Files
deepseek-harness/packages/api/settings-controller/tests/settings-controller.host.spec.ts
T
Turtle d1e22a7e24 feat(preset): declare Agent compositions in profile YAML (#4569)
* feat(preset): declare Agent compositions in profile YAML

* fix(preset): share scope binding cleanup and refresh module graph

* fix(preset): use host syntax colors in the YAML editor

* fix(preset): write new profile declarations as block YAML

* fix(preset): align eager activation with browser and worker surfaces

* fix(ui-agent-preset): retain the existing preset card layout

* fix(preset): keep rows waiting for a Host service mounted and re-audit after settlement

A preset row whose Host provider was still activating at declaration time
was reported as waiting for a missing service, and the registry recorded the
definition as broken for the rest of the process. Split the mount audit into
failed and pending rows: failures and root-realm leaks still reject the
mount, while pending rows stay mounted and every read and binding re-audits
them after the Host Loader tree settles.

Remove the accidental self-dependency of @deepseek-ai/dsh-web-app and its
lockfile self-link. Archive the copy-only preset authoring note, which the
declarative-preset note fully supersedes, and update the ralph note's
restore recipe to the profile-patch mechanism.

* chore(lint): re-key and prune the unknown-cast baseline after the master merge

* refactor(web-app): ship each Agent preset as its own bundle patch file

`dsh.bundle.patch` accepts an ordered file list, so the four shipped preset
declarations move out of the 1000-line web patch into
`presets/<id>.patch.yml`, one insert per file, applied after the host patch.
The host patch keeps the preset registry row. Gates and test scaffolds that
read the web layer resolve every patch file through `bundlePatchPaths`
instead of one hardcoded path.

* refactor(preset): drop the save notice injected into live Agents

The notice duplicated the save result the Web editor already shows, and
after the producer-owned message sources it would have needed its own
persisted source kind. Saving now only persists and reports the activation
diagnostic; the persistence catalog is unchanged from master.

* docs: regenerate the module graph after dropping the registry's llm dependency

* test(ui-agent-preset): cover the guide dialog's keyboard handling on the declarative section

* fix(preset): address the remaining review comments

Apply the lowercase id rule only when creating a declaration, so presets
declared with other ids stay editable. Export `isBuiltInPreset` from the
display fold and key the client card groups on it. Remove the dead `error`
and `retry` locale keys, the JSDoc orphaned by the `trust` removal, the
`trust` fields in the plugin-inventory test fixtures, and the stale
`dsh-agent-presets` package name in comments and READMEs.

* refactor(preset): make the Web preset page view-and-select only

Remove the child-plugin YAML editor, the `agent_preset` tool and the
registry's read/save Remote methods. Presets are declared and changed only by
bundle patches; the settings page keeps the roster, the new-task default and
the mode help, and its question icon explains that and offers to start a
Creator-mode task. The `editing-cordis-compositions` skill and the Creator
persona describe the bundle-based path, and the authored skill-load Session
and Web snapshots are refreshed for it.

* docs(skill): make the composition skill self-sufficient for preset authoring

State where the shipped declarations live, list every declaration field,
inline a complete minimal bundle and an override example, and name the
verification calls, so Creator mode no longer reads DSH package sources to
infer the format. Refresh the authored skill-load Session for the new text.

* test(tools): drop the removed agent_preset tool from the catalog expectation
2026-09-21 08:24:18 +00:00

331 lines
14 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { SettingsDescriptor } from '@deepseek-ai/dsh-settings'
import { remoteErrorOf, remoteMethods } from '@deepseek-ai/dsh-typert-protocol'
import SettingsController from '../src/index.ts'
import { MemorySettings } from '../../../settings/settings/tests/memory.ts'
const NS = 'ui-test'
const Profile = z.object({
preference: z.union(['light', 'dark']).default('light'),
apiKey: z.string().role('secret'),
})
/** A provider that reports a local document, for the `hasDocument` fact. */
class DocumentSettings extends MemorySettings {
override get documentPath(): string | undefined {
return '/deployment/settings.yaml'
}
}
/** A provider whose read forgets the namespace its write just committed. */
class VanishingSettings extends MemorySettings {
override describe(): SettingsDescriptor[] {
return []
}
}
/**
* A provider whose descriptor omits the secret-slot list. `secrets` is optional
* on the descriptor, so a foreign provider may leave it out even under
* `redactSecrets`, and the view still has to declare an empty list.
*/
class SlotlessSettings extends MemorySettings {
override describe(): SettingsDescriptor[] {
return [{
ns: NS,
schema: Profile.toJSON(),
value: { preference: 'light' },
applies: 'live',
revision: 0,
} as unknown as SettingsDescriptor]
}
}
/** A provider that refuses every write the way a read-only backing store would. */
class RefusingSettings extends MemorySettings {
override mutate(): Promise<void> {
return Promise.reject(new Error('settings are read-only in this deployment'))
}
}
/** A provider that refuses with a bare string, the way some storage clients do. */
class LiteralRefusingSettings extends MemorySettings {
override async mutate(): Promise<void> {
throw 'the document is locked'
}
}
async function boot(
provider: typeof MemorySettings = MemorySettings,
options: { doc?: Record<string, unknown>; base?: { preference: 'light' | 'dark' } } = {},
): Promise<{ controller: SettingsController; ctx: Context }> {
const ctx = new Context()
await ctx.plugin(provider, options.doc === undefined ? {} : { doc: options.doc })
ctx.settings.register(NS, Profile, options.base === undefined ? {} : { base: options.base })
await ctx.plugin(SettingsController)
return { controller: ctx.settingsController, ctx }
}
describe('the settings Remote namespace a configuration page calls', () => {
it('publishes the settings namespace from its own service key', async () => {
const { controller } = await boot()
expect(controller.typertRemote.serviceKey).toBe('settingsController')
expect(controller.typertRemote.namespace).toBe('settings')
expect(remoteMethods(controller)).toEqual([
{ method: 'describe', invocation: { kind: 'direct' } },
{ method: 'update', invocation: { kind: 'direct' } },
{ method: 'replace', invocation: { kind: 'direct' } },
{ method: 'mutate', invocation: { kind: 'direct' } },
{ method: 'openSettingsDocument', invocation: { kind: 'direct' } },
])
})
it('reports the actionable configuration error while no settings provider is mounted', async () => {
const ctx = new Context()
await ctx.plugin(SettingsController)
const calls: Array<() => unknown> = [
() => ctx.settingsController.describe(),
() => ctx.settingsController.update('ui-test', {}, undefined),
() => ctx.settingsController.replace('ui-test', {}, undefined),
() => ctx.settingsController.mutate('ui-test', [], undefined),
() => ctx.settingsController.openSettingsDocument(new AbortController().signal),
]
for (const call of calls) {
const failure = await Promise.resolve().then(call).catch((error: unknown) => error)
expect(remoteErrorOf(failure)).toMatchObject({
code: 'gateway/internal',
message: 'settings service is absent: this deployment does not mount a settings provider (e.g. @deepseek-ai/dsh-settings-file) in its composition',
details: {},
})
}
})
it('mounts the credentials namespace beside its own', async () => {
const ctx = new Context()
await ctx.plugin(MemorySettings)
ctx.settings.register(NS, Profile)
const fiber = ctx.plugin(SettingsController)
await fiber.await()
expect(ctx.get('credentialsController')).toBeDefined()
await fiber.dispose()
expect(ctx.get('settingsController')).toBeUndefined()
expect(ctx.get('credentialsController')).toBeUndefined()
})
it('describes every namespace redacted, with the deployment facts around them', async () => {
const { controller } = await boot(DocumentSettings, { doc: { 'ui-test': { apiKey: 'sk-stored' } } })
const value = controller.describe()
expect(value).toMatchObject({ writable: true, hasDocument: true })
const [view] = value.namespaces
expect(view?.ns).toBe('ui-test')
// The secret never rides; its slot reports only that one is stored.
expect(JSON.stringify(value)).not.toContain('sk-stored')
expect(view?.secrets).toEqual([{ path: ['apiKey'], set: true }])
// Redaction removes the field rather than replacing it, so the layer that
// stored a secret comes back empty instead of carrying a placeholder.
expect(view?.user).toEqual({})
})
it('reports a read-only provider and omits the layers it has none of', async () => {
const { controller } = await boot(class extends MemorySettings {
override get writable(): boolean {
return false
}
})
const value = controller.describe()
expect(value).toMatchObject({ writable: false, hasDocument: false })
const [view] = value.namespaces
// No composition base was declared and no user section is stored, so
// neither optional layer appears at all.
expect(view && 'base' in view).toBe(false)
expect(view && 'user' in view).toBe(false)
})
it('declares an empty slot list when the provider names no secrets', async () => {
const { controller } = await boot(SlotlessSettings)
const [view] = controller.describe().namespaces
expect(view?.secrets).toEqual([])
})
it('carries the composition base layer when the registrant declared one', async () => {
const { controller } = await boot(MemorySettings, { base: { preference: 'dark' } })
const [view] = controller.describe().namespaces
expect(view?.base).toEqual({ preference: 'dark' })
})
it('applies path-addressed edits and answers with the namespace it just wrote', async () => {
const { controller } = await boot()
const view = await controller.mutate('ui-test', [{ op: 'set', path: ['preference'], value: 'dark' }], undefined)
expect(view).toMatchObject({ ns: 'ui-test', user: { preference: 'dark' } })
expect(view.revision).toBeGreaterThan(0)
})
it('supports merge updates and wholesale replacement on the Remote namespace', async () => {
const { controller } = await boot(MemorySettings, {
doc: { 'ui-test': { preference: 'dark', apiKey: 'sk-stored' } },
})
const updated = await controller.update('ui-test', { preference: 'light' }, undefined)
expect(updated.user).toEqual({ preference: 'light' })
expect(updated.secrets).toEqual([{ path: ['apiKey'], set: true }])
const replaced = await controller.replace('ui-test', {}, updated.revision)
expect(replaced.value).toEqual({ preference: 'light' })
expect(replaced.user).toEqual({})
expect(replaced.secrets).toEqual([{ path: ['apiKey'], set: false }])
})
it('refuses a stale write as settings/conflict carrying both revisions', async () => {
const { controller } = await boot()
const held = controller.describe().namespaces[0]!.revision
await controller.mutate('ui-test', [{ op: 'set', path: ['preference'], value: 'dark' }], held)
const failure = await controller
.mutate('ui-test', [{ op: 'set', path: ['preference'], value: 'light' }], held)
.catch((error: unknown) => error)
const { code, details } = remoteErrorOf(failure) ?? {}
expect(code).toBe('settings/conflict')
expect(details).toMatchObject({ ns: 'ui-test', expected: held })
})
it('answers a malformed namespace exactly as an unregistered one', async () => {
const { controller } = await boot()
for (const ns of ['Not A Namespace', 'unregistered']) {
const failure = await controller.mutate(ns, [{ op: 'unset', path: ['preference'] }], undefined)
.catch((error: unknown) => error)
expect(remoteErrorOf(failure)).toMatchObject({
code: 'settings/rejected',
details: { ns },
})
}
})
it('reports an empty namespace as bad-request', async () => {
const { controller } = await boot()
for (const call of [
() => controller.update('', {}, undefined),
() => controller.replace('', {}, undefined),
() => controller.mutate('', [], undefined),
]) {
const failure = await call().catch((error: unknown) => error)
expect(remoteErrorOf(failure)).toMatchObject({ code: 'gateway/bad-request' })
}
})
it('reports a refused write as settings/rejected carrying the seam message', async () => {
const { controller } = await boot(RefusingSettings)
const failure = await controller.mutate('ui-test', [{ op: 'unset', path: ['preference'] }], undefined)
.catch((error: unknown) => error)
const { code, message } = remoteErrorOf(failure) ?? {}
expect(code).toBe('settings/rejected')
expect(message).toContain('read-only in this deployment')
})
it('stringifies a refusal that is not an Error', async () => {
const { controller } = await boot(LiteralRefusingSettings)
const failure = await controller.mutate('ui-test', [{ op: 'unset', path: ['preference'] }], undefined)
.catch((error: unknown) => error)
expect(remoteErrorOf(failure)?.message).toBe('the document is locked')
})
it('reports a namespace disposed between the write and its read-back', async () => {
const { controller } = await boot(VanishingSettings)
const failure = await controller.mutate('ui-test', [{ op: 'set', path: ['preference'], value: 'dark' }], undefined)
.catch((error: unknown) => error)
const { code, message } = remoteErrorOf(failure) ?? {}
expect(code).toBe('gateway/internal')
expect(message).toContain('was disposed after the mutate')
})
it('prepares and opens the provider-owned settings document', async () => {
const ctx = new Context()
await ctx.plugin(DocumentSettings)
const prepare = vi.spyOn(ctx.settings, 'prepareDocument').mockResolvedValue('/tmp/settings.yaml')
const openTextFile = vi.fn((_path: string, _signal: AbortSignal) => Promise.resolve())
const controller = new SettingsController(ctx, { openTextFile })
const signal = new AbortController().signal
await expect(controller.openSettingsDocument(signal)).resolves.toEqual({ opened: true })
expect(prepare).toHaveBeenCalledOnce()
expect(openTextFile).toHaveBeenCalledWith('/tmp/settings.yaml', signal)
})
it('preserves settings-document absence, failure, and cancellation', async () => {
const absent = await boot()
const missingDocument = absent.controller.openSettingsDocument(new AbortController().signal)
await expect(missingDocument).rejects.toMatchObject({ code: 'gateway/internal' })
await expect(missingDocument).rejects.toThrow('no local document')
const failed = await boot(DocumentSettings)
vi.spyOn(failed.ctx.settings, 'prepareDocument').mockRejectedValue(new Error('read failed'))
const failedRead = failed.controller.openSettingsDocument(new AbortController().signal)
await expect(failedRead).rejects.toMatchObject({ code: 'gateway/internal' })
await expect(failedRead).rejects.toThrow('read failed')
const cancelled = new AbortController()
cancelled.abort(new Error('cancelled'))
const prepare = vi.spyOn(failed.ctx.settings, 'prepareDocument')
prepare.mockClear()
await expect(failed.controller.openSettingsDocument(cancelled.signal))
.rejects.toMatchObject({ code: 'gateway/cancelled' })
expect(prepare).not.toHaveBeenCalled()
})
it('does not open a settings document cancelled during preparation', async () => {
const ctx = new Context()
await ctx.plugin(DocumentSettings)
const prepared = Promise.withResolvers<string | undefined>()
vi.spyOn(ctx.settings, 'prepareDocument').mockReturnValue(prepared.promise)
const openTextFile = vi.fn((_path: string, _signal: AbortSignal) => Promise.resolve())
const controller = new SettingsController(ctx, { openTextFile })
const abort = new AbortController()
const opening = controller.openSettingsDocument(abort.signal)
abort.abort(new Error('cancelled'))
prepared.resolve('/tmp/settings.yaml')
await expect(opening).rejects.toMatchObject({ code: 'gateway/cancelled' })
expect(openTextFile).not.toHaveBeenCalled()
})
it('maps native settings-document opener failures', async () => {
const ctx = new Context()
await ctx.plugin(DocumentSettings)
vi.spyOn(ctx.settings, 'prepareDocument').mockResolvedValue('/tmp/settings.yaml')
const controller = new SettingsController(ctx, {
openTextFile: () => Promise.reject(new Error('no default editor')),
})
await expect(controller.openSettingsDocument(new AbortController().signal))
.rejects.toMatchObject({ code: 'gateway/internal', message: 'path open failed: no default editor' })
})
it('classifies cancellation while preparing or opening the settings document', async () => {
const preparing = new Context()
await preparing.plugin(DocumentSettings)
const prepareAbort = new AbortController()
vi.spyOn(preparing.settings, 'prepareDocument').mockImplementation(async () => {
prepareAbort.abort(new Error('cancelled'))
throw new Error('preparation stopped')
})
const preparingController = new SettingsController(preparing)
await expect(preparingController.openSettingsDocument(prepareAbort.signal))
.rejects.toMatchObject({ code: 'gateway/cancelled' })
const opening = new Context()
await opening.plugin(DocumentSettings)
vi.spyOn(opening.settings, 'prepareDocument').mockResolvedValue('/tmp/settings.yaml')
const openAbort = new AbortController()
const openingController = new SettingsController(opening, {
openTextFile: async () => {
openAbort.abort(new Error('cancelled'))
throw new Error('opening stopped')
},
})
await expect(openingController.openSettingsDocument(openAbort.signal))
.rejects.toMatchObject({ code: 'gateway/cancelled' })
})
})