Merge pull request #5108 from deepseek-harness/feat/developer-mode-preset-selection

feat(web): 由开发者模式统一控制新任务模式选择
This commit is contained in:
lsdsjy authored and GitHub committed 2026-09-24 17:24:51 +08:00
commit c0f0bcf587
46 files changed
+433 -382

No files matched your search

@@ -33,8 +33,8 @@
en: c46c9ca54ea9eaad
zh: 918dc8eebff5edf3
/agent-note-client-session-references-reference-sources-and-ui-status/decision/presets-and-creation-flows:
en: 790eda215b64ee37
zh: a4b5d3a61cc80cbc
en: 70ef26a3cd399b14
zh: 5c81515ff896f91a
/agent-note-client-session-references-reference-sources-and-ui-status/decision/host-event-context-ownership-and-typert:
en: eb3be89cf9431c44
zh: bfc26899286b37ad
@@ -166,7 +166,7 @@ Workspace connection preserves its navigation guards and panel-switch invalidati
Preset directories and deployment defaults may be shared. A bound Session's preset is read or changed through its Provider binding; preset controllers are cached by `SessionBinding` rather than managed by one root current-Session follower. The hero preset seat uses the `session-maybe` Provider: it shows the creation-flow choice without a Session and operates on the exact bound blank Session after one arrives. Header labels read the same Provider-bound Session projection.
A preset chosen before Session creation remains in the main Conversation's `session-maybe` preset surface. After Workspace creation or reuse establishes the main Provider over a blank Session, that surface applies the choice to its Provider-bound Session. When Settings changes the default preset or picker setting, the preset service selects the blank Session whose established Provider binding carries `mainView` ownership and updates that Session. Non-blank main Sessions, independent Sidebar Providers, and other background references remain unchanged; preset subtrees do not read the main reference or use a global current follower to find their target.
A preset chosen before Session creation remains in the main Conversation's `session-maybe` preset surface. After Workspace creation or reuse establishes the main Provider over a blank Session, that surface applies the choice to its Provider-bound Session. When Settings changes the default preset, the preset service selects the blank Session whose established Provider binding carries `mainView` ownership and updates that Session. Non-blank main Sessions, independent Sidebar Providers, and other background references remain unchanged; preset subtrees do not read the main reference or use a global current follower to find their target.
### Host-event Context ownership and Typert
@@ -166,7 +166,7 @@ Workspace 连接保持既有导航检查与面板切换失效规则。侧边栏
预设目录与部署默认值可以共享。已绑定 Session 的预设通过 Provider 的 binding 读取或修改;预设控制器按 `SessionBinding` 缓存,不由根级 current-Session 跟随器管理。Hero 的 preset seat 使用 `session-maybe` Provider:没有 Session 时显示创建流程选择,绑定空白 Session 后操作该确切 Session。标题标签读取同一 Provider 绑定 Session 的投影。
Session 创建前选择的 preset 保留在主 Conversation 的 `session-maybe` preset surface 中。Workspace 创建或复用空白 Session 并建立主 Provider 后,该 surface 将选择应用到 Provider 绑定的 Session。设置页修改默认 preset 或 picker 设置时,preset 服务从 Provider 已建立的 binding 缓存中选择带 `mainView` 所有权标记的空白 Session,并更新该 Session。非空白主 Session、Sidebar 的独立 Provider 与其他后台引用均不受该设置动作影响;preset 子树不读取主引用,也不通过全局 current follower 寻找目标。
Session 创建前选择的 preset 保留在主 Conversation 的 `session-maybe` preset surface 中。Workspace 创建或复用空白 Session 并建立主 Provider 后,该 surface 将选择应用到 Provider 绑定的 Session。设置页修改默认 preset 时,preset 服务从 Provider 已建立的 binding 缓存中选择带 `mainView` 所有权标记的空白 Session,并更新该 Session。非空白主 Session、Sidebar 的独立 Provider 与其他后台引用均不受该设置动作影响;preset 子树不读取主引用,也不通过全局 current follower 寻找目标。
### Host 事件 Context 所有权与 Typert
@@ -9,8 +9,8 @@
en: 725f773bb350218e
zh: dd8fbc09ef48208d
/agent-note-declarative-agent-presets-and-retained-revisions/decision:
en: fa2ac428de2ba3d0
zh: c75da98e1cf076ef
en: 2a2489303fc76fc0
zh: 1a760e9a5edfccc8
/agent-note-declarative-agent-presets-and-retained-revisions/alternatives-considered:
en: 09f40eab4659e9f6
zh: 7a70da0d0ae6845b
@@ -16,7 +16,7 @@ The registry owns each revision's scope and Loader tree. Agents link their own s
The Web editor and `agent_preset` tool accept only child plugin YAML. Saving writes the active profile's user patch, preserving display metadata and unrelated configuration. Revision checks and profile locking prevent overwriting concurrent saves; validation rejects a higher-priority override that would defeat the edit. Persistence and activation outcomes are reported separately. Tool writes require approval or full access because configuration executes in the Host.
Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition. Old executable revisions are process-local, not serialized. The existing chooser policy and blank-session selection remain: hiding the chooser uses the deployment default without deleting the saved user preference.
Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition. Old executable revisions are process-local, not serialized. The saved user default and blank-session selection remain; `selectedDefault` is what an unnamed new session resolves, and the Client's Developer tools preference decides only whether the choice is shown.
## Alternatives considered
@@ -16,7 +16,7 @@ Preset 目录重复承担 Cordis 配置的所有权。独立的发现、元数
Web 编辑器与 `agent_preset` 工具只接受子插件 YAML。保存写入当前 profile 的用户补丁,保留显示元数据和无关配置。版本检查和 profile 锁防止覆盖并发保存;验证拒绝会使编辑失效的更高优先级覆盖。持久化与激活结果分别报告。配置在 Host 中执行,因此工具写入需要批准或完全访问权限。
会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复。旧的可执行代际仅保留在进程内,不会序列化。现有选择器策略和空白会话选择保持不变:隐藏选择器使用部署默认值,但不删除保存的用户偏好。
会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复。旧的可执行代际仅保留在进程内,不会序列化。保存的用户默认值与空白会话选择保持不变:未指定 preset 的新会话解析 `selectedDefault`,客户端的开发者工具偏好只决定是否展示这项选择。
## Alternatives considered
@@ -9,8 +9,8 @@
en: e22ee243b1503319
zh: b53c1a932d547f55
/agent-note-shared-developer-tool-settings/decision:
en: 3fc14af35b025970
zh: 8359262a5c5d3805
en: 62f71b49af7b9971
zh: f0f12da4cb0c7fc0
/agent-note-shared-developer-tool-settings/alternatives-considered:
en: df1b80e5b8d2a178
zh: 0136d16fc44d57bf
@@ -12,9 +12,9 @@ Diagnostic views, preset selection and changed-file summaries add complexity to
The settings-owned `ctx.configForms.developerTools` preference uses a shared entry form and exposes one accepted `ui-settings.enabled` preference. The initial default-off choice reduces routine-task complexity; [Developer tools default on after preference resolution](2026-09-20-developer-tools-default-on.md) supersedes that default and owns startup enablement. General Settings offers the same switch on Web and desktop. The existing settings transport owns validation, ordered writes, persistence and recovery; loopback Web and desktop follow Host acceptance. Remote Web owns one browser-local observable shared by all consumers until reload, with no Host writes.
Off hides the Trajectory View, hides tool Inspect actions when no visible View declares tool-call inspection, hides the conversation View tab bar while fewer than two Views are available, hides the new-session preset chip and the settings row that allows switching Agent modes, and omits the changed-files card and its summary read. Views registered by other plugins stay available. Turning it off while Trajectory is active activates Chat. The preset composition, saved default, Session events and explicit delivery cards remain unchanged. This preference is presentation policy, not Host authorization.
Off hides the Trajectory View, hides tool Inspect actions when no visible View declares tool-call inspection, hides the conversation View tab bar while fewer than two Views are available, hides the new-session preset chip and refuses the Agent-preset cards' selection, and omits the changed-files card and its summary read. Views registered by other plugins stay available. Turning it off while Trajectory is active activates Chat. The preset composition, saved default, Session events and explicit delivery cards remain unchanged. This preference is presentation policy, not Host authorization.
Plugin assembly translates the shared preference into component-specific capabilities (`showCodeDiff`, `showPresetPicker`, and `interactivePreview`). Conversation supplies the inspection callback using the visible target's `toolCallFocus`; Chat does not name the target. The builtin HTML renderer uses DOMPurify for complete-document sanitization and parser-mutation defenses. Off preserves root styling, removes active documents, resource hints, SVG animation and all `href` attributes, and mounts an iframe with no sandbox permissions and a CSP denying scripts and external resources. It reads no related files. On retains the opaque scripted Blob renderer and its bounded related-file reads. Switching modes replaces the browsing context and disposes pending reads. The [document-preview decision](../architecture/2026-09-08-document-preview-operations.md) and [filesystem-read authority](../architecture/2026-09-09-workspace-file-read-authority.md) remain authoritative for advanced rendering and Host read access.
Plugin assembly translates the shared preference into component-specific capabilities (`showCodeDiff`, the Agent-preset surfaces' `developerTools`, and `interactivePreview`). Conversation supplies the inspection callback using the visible target's `toolCallFocus`; Chat does not name the target. The builtin HTML renderer uses DOMPurify for complete-document sanitization and parser-mutation defenses. Off preserves root styling, removes active documents, resource hints, SVG animation and all `href` attributes, and mounts an iframe with no sandbox permissions and a CSP denying scripts and external resources. It reads no related files. On retains the opaque scripted Blob renderer and its bounded related-file reads. Switching modes replaces the browsing context and disposes pending reads. The [document-preview decision](../architecture/2026-09-08-document-preview-operations.md) and [filesystem-read authority](../architecture/2026-09-09-workspace-file-read-authority.md) remain authoritative for advanced rendering and Host read access.
## Alternatives considered
@@ -12,9 +12,9 @@ Status: implemented
设置域内的 `ctx.configForms.developerTools` 偏好对象使用共享条目表单,提供一个已接受的 `ui-settings.enabled` 偏好。最初默认关闭的选择用于降低日常任务的复杂度;[偏好解析后默认开启开发者工具](2026-09-20-developer-tools-default-on.zh.md)取代该默认值并负责启动时的启用策略。Web 和桌面端的通用设置提供同一个开关。现有设置传输负责验证、有序写入、持久化和恢复;回环 Web 和桌面端跟随 Host 接受的状态。远程 Web 持有一个所有消费者共享的浏览器本地可观察值,刷新后重置,不发送 Host 写入。
关闭时隐藏 Trajectory View,在没有可见 View 声明工具调用检查能力时隐藏 Inspect 操作,可见 View 少于两个时隐藏会话 View 标签栏,隐藏新会话预设入口和「允许切换 agent 模式」设置行,并省略改动文件卡片及其摘要读取。其他插件注册的 View 保持可用。在 Trajectory 中关闭开关会激活 Chat。预设组合、保存的默认值、Session 事件和显式交付卡片保持不变。此偏好是展示策略,不是 Host 授权。
关闭时隐藏 Trajectory View,在没有可见 View 声明工具调用检查能力时隐藏 Inspect 操作,可见 View 少于两个时隐藏会话 View 标签栏,隐藏新会话预设入口并拒绝 Agent 预设卡片的选择操作,并省略改动文件卡片及其摘要读取。其他插件注册的 View 保持可用。在 Trajectory 中关闭开关会激活 Chat。预设组合、保存的默认值、Session 事件和显式交付卡片保持不变。此偏好是展示策略,不是 Host 授权。
插件组装层将共享偏好转换为组件自身的能力(`showCodeDiff`、`showPresetPicker` 和 `interactivePreview`)。Conversation 根据可见目标的 `toolCallFocus` 提供检查回调;Chat 不再指定目标名称。内置 HTML 渲染器使用 DOMPurify 清理完整文档并防护解析变异。关闭时保留根节点样式,移除主动文档、资源提示、SVG 动画及所有 `href` 属性,再放入不授予沙箱权限的 iframe,并通过 CSP 禁止脚本和外部资源。不读取关联文件。开启时保留不透明源的脚本 Blob 渲染器及其有界关联文件读取。切换模式会替换浏览上下文并清理待处理读取。[文档预览决策](../architecture/2026-09-08-document-preview-operations.zh.md)和[文件系统读取权限](../architecture/2026-09-09-workspace-file-read-authority.zh.md)继续定义高级渲染与 Host 读取访问。
插件组装层将共享偏好转换为组件自身的能力(`showCodeDiff`、Agent 预设各界面读取的 `developerTools`,以及 `interactivePreview`)。Conversation 根据可见目标的 `toolCallFocus` 提供检查回调;Chat 不再指定目标名称。内置 HTML 渲染器使用 DOMPurify 清理完整文档并防护解析变异。关闭时保留根节点样式,移除主动文档、资源提示、SVG 动画及所有 `href` 属性,再放入不授予沙箱权限的 iframe,并通过 CSP 禁止脚本和外部资源。不读取关联文件。开启时保留不透明源的脚本 Blob 渲染器及其有界关联文件读取。切换模式会替换浏览上下文并清理待处理读取。[文档预览决策](../architecture/2026-09-08-document-preview-operations.zh.md)和[文件系统读取权限](../architecture/2026-09-09-workspace-file-read-authority.zh.md)继续定义高级渲染与 Host 读取访问。
## Alternatives considered
+38 -1
View File
@@ -853,7 +853,6 @@ describe('a delegated child', () => {
describe('the default preset as a user setting', () => {
it('composes an unnamed session from the stored default, not the composed one', async () => {
expect((await ctx.agentPresets.remoteExportList()).modeSelectionEnabled).toBe(true)
expect(ctx.agentPresets.defaultId).toBe('standard')
await ctx.settings.update(SETTINGS_NAMESPACE, { selectedDefault: 'minimal' })
@@ -882,6 +881,44 @@ describe('the default preset as a user setting', () => {
})
})
describe('a profile patch stored before Developer tools owned preset selection', () => {
let legacy: Context
let legacyHome: string
beforeAll(async () => {
legacyHome = await mkdtemp(join(tmpdir(), 'dsh-web-presets-legacy-'))
// A stored configuration from before the switch moved to Developer tools:
// it carries the retired key beside the default the user had saved. The
// Loader resolves the declared fields and leaves the extra one alone.
legacy = await bootWeb(legacyHome, [{
id: SETTINGS_NAMESPACE,
config: { default: 'standard', selectedDefault: 'minimal', modeSelectionEnabled: false },
}])
}, 120_000)
afterAll(async () => {
await legacy?.fiber.dispose()
await rm(legacyHome, { recursive: true, force: true })
})
it('starts, keeps the retired key inert and composes new sessions from the saved default', async () => {
expect(legacy.agentPresets.defaultId).toBe('minimal')
expect((await legacy.agentPresets.remoteExportList()).presets.find(row => row.id === 'minimal')?.isDefault).toBe(true)
// Settings projects the declared fields, so the retired key is neither
// shown nor rewritten; the user's saved default is.
expect(legacy.settings.describe().find(row => row.ns === SETTINGS_NAMESPACE)?.value)
.toEqual({ selectedDefault: 'minimal' })
const handle = await legacy.agents.create({
sessionId: SessionId('preset-legacy-patch'),
setup: agentCtx => legacy.agentPresets.mount(agentCtx).then(() => undefined),
})
try {
expect(toolNames(legacy, handle.agent)).toEqual(['bash'])
} finally {
await handle.dispose()
}
})
})
describe('a session keeps the preset it was created with', () => {
it('refuses to adopt a live session under a different preset', async () => {
const handle = await ctx.agents.create({
+14 -14
View File
@@ -249,7 +249,7 @@ describe('web e2e: agent-preset selection', () => {
await rm(fixtureRoot, { recursive: true, force: true })
})
it('starts with mode selection shown on the Standard default', async () => {
it('starts on the Standard default with the roster editable in Settings', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-hero'))
await connectFreshWorkspace(page, scaffold.workspaceCwd)
await page.getByRole('button', { name: 'Standard mode', exact: true }).waitFor({ timeout: 10_000 })
@@ -257,9 +257,9 @@ describe('web e2e: agent-preset selection', () => {
await openSettings(page, 'en')
const dialog = page.getByRole('dialog', { name: 'Settings' })
await dialog.getByRole('button', { name: 'Agent presets' }).click()
const toggle = dialog.getByRole('switch', { name: 'Choose a mode for new tasks' })
await dialog.getByRole('button', { name: 'New task default: Standard mode' }).waitFor({ timeout: 10_000 })
expect(await toggle.getAttribute('aria-checked')).toBe('true')
expect(await dialog.getByRole('switch').count()).toBe(0)
await dialog.getByRole('button', { name: 'Set as new task default: Minimal mode' }).waitFor({ timeout: 10_000 })
await dialog.getByRole('button', { name: 'Close' }).last().click()
const snapshot = await captureStableAria(page, '[class*="heroWorkspaceRow"]', scaffold.workspaceCwd)
@@ -343,7 +343,7 @@ describe('web e2e: agent-preset selection', () => {
await writeComposerDraft(page, composer, '')
}, 90_000)
it('aligns the current blank task and restores its saved default when re-enabled', async () => {
it('keeps the saved default composing sessions while Developer tools only gate the choice', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-disabled'))
await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('standard')
@@ -353,23 +353,23 @@ describe('web e2e: agent-preset selection', () => {
await dialog.getByRole('button', { name: 'Set as new task default: Minimal mode' }).click()
await dialog.getByRole('button', { name: 'New task default: Minimal mode' }).waitFor({ timeout: 10_000 })
await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal')
const toggle = dialog.getByRole('switch', { name: 'Choose a mode for new tasks' })
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
await dialog.getByRole('button', { name: 'Application default: Standard mode' }).waitFor({ timeout: 10_000 })
await dialog.getByRole('button', { name: 'General', exact: true }).click()
const developerTools = dialog.getByRole('switch', { name: 'Developer tools' })
await developerTools.click()
await expect.poll(() => developerTools.getAttribute('aria-checked')).toBe('false')
await dialog.getByRole('button', { name: 'Close' }).last().click()
// The gate hides the choice; the blank task keeps its saved composition.
await expect.poll(() => page.getByRole('button', { name: / mode$/ }).count()).toBe(0)
await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('standard')
await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal')
// The switch controls availability only: re-enabling restores the saved
// default and aligns this same still-blank task with it.
await openSettings(page, 'en')
const reopened = page.getByRole('dialog', { name: 'Settings' })
await reopened.getByRole('button', { name: 'General', exact: true }).click()
const reopenedDeveloperTools = reopened.getByRole('switch', { name: 'Developer tools' })
await reopenedDeveloperTools.click()
await expect.poll(() => reopenedDeveloperTools.getAttribute('aria-checked')).toBe('true')
await reopened.getByRole('button', { name: 'Agent presets' }).click()
const reopenedToggle = reopened.getByRole('switch', { name: 'Choose a mode for new tasks' })
await reopenedToggle.click()
await expect.poll(() => reopenedToggle.getAttribute('aria-checked')).toBe('true')
await reopened.getByRole('button', { name: 'New task default: Minimal mode' }).waitFor({ timeout: 10_000 })
await reopened.getByRole('button', { name: 'Close' }).last().click()
await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal')
+11 -9
View File
@@ -25,16 +25,18 @@ it('persists developer tools in the Host settings document and restores the acce
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
await page.getByRole('button', { name: 'Agent presets', exact: true }).click()
const pickerToggle = page.getByRole('switch', { name: 'Choose a mode for new tasks' })
await expect.poll(() => page.getByRole('heading', { name: 'Agent presets', exact: true }).count()).toBe(1)
expect(await pickerToggle.count()).toBe(0)
// The page owns no selection switch: only the General one gates the choice.
const section = page.locator('section')
.filter({ has: page.getByRole('heading', { name: 'Agent presets', exact: true }) })
const refused = section.getByRole('button', { name: /^Turn on Developer tools in General settings to choose a default: / })
expect(await section.getByRole('switch').count()).toBe(0)
await expect.poll(() => refused.count()).toBeGreaterThan(0)
await scaffold.ctx.settings.update('ui-settings', { enabled: true })
await expect.poll(() => pickerToggle.count()).toBe(1)
await expect.poll(() => pickerToggle.isEnabled()).toBe(true)
const pickerEnabled = await pickerToggle.getAttribute('aria-checked')
await expect.poll(() => section.getByRole('button', { name: 'Set as new task default: Minimal mode' }).count()).toBe(1)
await expect.poll(() => refused.count()).toBe(0)
expect(await section.getByRole('switch').count()).toBe(0)
await scaffold.ctx.settings.update('ui-settings', { enabled: false })
await expect.poll(() => pickerToggle.count()).toBe(0)
await scaffold.ctx.settings.update('ui-settings', { enabled: true })
await expect.poll(() => pickerToggle.isEnabled()).toBe(true)
await expect.poll(() => pickerToggle.getAttribute('aria-checked')).toBe(pickerEnabled)
await expect.poll(() => refused.count()).toBeGreaterThan(0)
expect(await section.getByRole('switch').count()).toBe(0)
})
@@ -9,9 +9,6 @@
- button "关闭"
- heading "Agent 预设" [level=2]
- paragraph: 选择 Agent 的工具和工作方式。日常任务用「标准模式」,扩展 DSH 的能力用「创造模式」。
- text: 新任务可选择模式 实验性
- paragraph: 开启后,可为每个新任务选择模式,并在这里设置默认值。关闭后,新任务使用应用配置的默认预设。已有任务不受影响。
- switch "新任务可选择模式" [checked]
- heading "内置" [level=3]
- list:
- listitem:
+1 -2
View File
@@ -181,8 +181,7 @@
"trust": "user",
"isDefault": false
}
],
"modeSelectionEnabled": true
]
}
},
"commands": {
+1 -3
View File
@@ -148,10 +148,8 @@ export type Config = PresetDefinition
export interface Config {
/** Deployment default when the caller omits a preset. */
default: string
/** User-selected default while the chooser is shown; edited through Settings. */
/** User-selected default; edited through Settings. */
selectedDefault: Volatile<string | undefined>
/** Whether new-session surfaces expose preset selection and the saved default applies. */
modeSelectionEnabled: Volatile<boolean>
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-agent-preset-registry -->
+1 -3
View File
@@ -150,10 +150,8 @@ export type Config = PresetDefinition
export interface Config {
/** Deployment default when the caller omits a preset. */
default: string
/** User-selected default while the chooser is shown; edited through Settings. */
/** User-selected default; edited through Settings. */
selectedDefault: Volatile<string | undefined>
/** Whether new-session surfaces expose preset selection and the saved default applies. */
modeSelectionEnabled: Volatile<boolean>
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-agent-preset-registry -->
+1 -1
View File
@@ -9,7 +9,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac
| Event | Mode | Declared in | Dispatchers | Listeners |
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:71`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`schedule`](../packages/schedule/schedule), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:270`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+1 -1
View File
@@ -11,7 +11,7 @@
| Event | Mode | Declared in | Dispatchers | Listeners |
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:71`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), [`schedule`](../packages/schedule/schedule), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:270`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+2 -2
View File
@@ -499,8 +499,8 @@ async register(definition: PresetDefinition): Promise<() => Promise<void>>
*/
async list(): Promise<AgentPreset[]>
/** Read the selection roster and chooser policy.
* @returns Current presets, default and chooser policy.
/** Read the selection roster.
* @returns Current presets, each marked when it is the default.
*/
@Remote('list') async remoteExportList(): Promise<AgentPresetRoster>
+2 -2
View File
@@ -509,8 +509,8 @@ async register(definition: PresetDefinition): Promise<() => Promise<void>>
*/
async list(): Promise<AgentPreset[]>
/** Read the selection roster and chooser policy.
* @returns Current presets, default and chooser policy.
/** Read the selection roster.
* @returns Current presets, each marked when it is the default.
*/
@Remote('list') async remoteExportList(): Promise<AgentPresetRoster>
@@ -15,11 +15,11 @@
en: d152484eb41ac6b4
zh: b3ad7867f23dad1c
/deepseek-ai-dsh-client-ui-agent-preset/use-this-package:
en: eb4171068bfe0915
zh: 7992c69bc30d1929
en: 1b1af8f5a2ac6b01
zh: 5ad3daeead8040df
/deepseek-ai-dsh-client-ui-agent-preset/understand-the-implementation:
en: 28a422a4be17b4f9
zh: 92c1695c078b861c
en: 7813f0063c15e241
zh: 6eabc242edfc45ec
/deepseek-ai-dsh-client-ui-agent-preset/further-exploration:
en: bbae8d79844bc481
zh: 4302107fd1f460e6
+2 -2
View File
@@ -27,7 +27,7 @@ Choose Agent presets and the new-task default in Web, read what each mode does a
Settings shows the built-in and custom card groups with default highlighting and card-body selection; a group without presets is omitted, except the custom group, which keeps its Creator entry on screen. Every card offers “View configuration”, which opens the preset's declared plugin list as read-only YAML in the Loader's own dialect (`!!js` conditions included); a failed preset stays readable because its diagnostic points into that YAML. Escape closes only the viewer and returns focus to its card; leaving Settings clears the viewer, and a late read does not reopen it. The page edits nothing: the Creator entry starts a Creator-mode task that authors or overrides a preset as a bundle, offered while the `cordis` preset is on the roster and a conversation flow exists.
The “Choose a mode for new tasks” switch controls whether the saved user default is active. Hiding selection uses the deployment default; showing it restores the user preference. Choosing a healthy default also synchronizes the blank session on the current new-task surface. Creator starts a new task using the `cordis` preset. The new-session picker additionally requires Developer tools in General Settings.
Developer tools in General Settings decide whether a mode can be chosen at all: with them off the new-session picker disappears and the cards refuse selection, while the saved default keeps composing new tasks. Choosing a healthy default also synchronizes the blank session on the current new-task surface. Creator starts a new task using the `cordis` preset.
Known shipped presets offer mode details and usage examples in a read-only dialog. Its tabs preserve each page's scroll position; closing returns focus to the opening action. Help does not change the new-task default. The default badge replaces the card's group badge, and the preset id appears beside the title. Guide copy and examples belong to this package.
@@ -37,7 +37,7 @@ Known shipped presets offer mode details and usage examples in a read-only dialo
<details>
<summary>Implementation internals — click to expand</summary>
`agentPresets/list` supplies the roster and the chooser policy, and `agentPresets/read` one declaration's YAML for the viewer; default and visibility changes write the `agent-presets` settings namespace. The picker, blank-session synchronization and read-only session label use recorded preset identities. Connection resets and settings updates refresh the roster.
`agentPresets/list` supplies the roster and marks the current default, and `agentPresets/read` one declaration's YAML for the viewer; default changes write the `agent-preset-registry` settings namespace. The picker, blank-session synchronization and read-only session label use recorded preset identities. Connection resets and settings updates refresh the roster.
</details>
+2 -2
View File
@@ -27,7 +27,7 @@ kind: "package-reference"
设置页显示内置与自定义卡片分组、默认项高亮和点击卡片选择;没有 preset 的分组不显示,但自定义分组会保留其创造入口。每张卡片都提供「查看配置」,以只读 YAML 打开该 preset 声明的插件列表,使用 Loader 自己的方言(含 `!!js` 条件);加载失败的 preset 同样可读,因为其诊断信息正指向这份 YAML。Escape 只关闭查看器并将焦点还给卡片;离开设置页会清空查看器,迟到的读取结果不会重新打开它。本页不编辑任何内容:创造入口启动一个创造模式任务,以 bundle 形式创建或覆盖 preset;当 `cordis` preset 在列表中且存在会话流程时提供。
「新任务可选择模式」开关控制保存的用户默认值是否生效。关闭时使用部署默认值,重新开启则恢复用户偏好。选择健康定义作为默认值也会同步当前新任务页面的空白会话。Creator 入口开启一个使用 `cordis` preset 的新任务。新会话选择器还要求通用设置开启开发者工具。
通用设置中的开发者工具决定能否选择模式:关闭后新会话选择器消失、卡片拒绝选择,而已保存的默认值继续用于新任务。选择健康定义作为默认值也会同步当前新任务页面的空白会话。Creator 入口开启一个使用 `cordis` preset 的新任务。
已知的内置预设提供只读的模式说明与使用示例对话框。各页签保留各自的滚动位置;关闭后焦点回到打开它的操作。帮助不会改变新任务默认值。默认徽标取代卡片的分组徽标,预设 id 显示在标题旁。指南文案与示例归本包所有。
@@ -37,7 +37,7 @@ kind: "package-reference"
<details>
<summary>实现细节 — 点击展开</summary>
`agentPresets/list` 提供列表和选择器策略,`agentPresets/read` 为查看器提供一条声明的 YAML;默认值与可见性的修改写入 `agent-presets` settings 命名空间。选择器、空白会话同步和只读会话标签使用记录的 preset 标识。连接重置和设置更新会刷新列表。
`agentPresets/list` 提供列表并标记当前默认值,`agentPresets/read` 为查看器提供一条声明的 YAML;默认值的修改写入 `agent-preset-registry` settings 命名空间。选择器、空白会话同步和只读会话标签使用记录的 preset 标识。连接重置和设置更新会刷新列表。
</details>
@@ -27,8 +27,8 @@ import css from './AgentPresetSeat.module.css'
/** Registration-side business face for the hero chip. */
export interface AgentPresetSeatInjected {
hooks: {
/** Whether this entry offers preset selection. */
showPresetPicker: ObservableSnapshot<boolean>
/** Shared Developer tools preference; off hides the chip. */
developerTools: ObservableSnapshot<boolean>
/** Seat snapshot bound by the renderer as useAgentPresetSeat. */
agentPresetSeat: SnapshotStore<AgentPresetSeatState>
}
@@ -73,12 +73,13 @@ export type AgentPresetSeatProps =
/**
* Render the new-session agent-preset chip.
* @param props - composed slot props.
* @returns the chip, or null when the deployment composes no presets.
* @returns The chip, or null outside the main view, with Developer tools off,
* or before the roster provides a preset choice.
*/
export function AgentPresetSeat({
sessionId, useSessionRetainInfo, load, select, introduced, useAgentPresetSeat, useShowPresetPicker, t,
sessionId, useSessionRetainInfo, load, select, introduced, useAgentPresetSeat, useDeveloperTools, t,
}: AgentPresetSeatProps) {
const showPresetPicker = useShowPresetPicker(value => value)
const developerTools = useDeveloperTools(value => value)
const state = useAgentPresetSeat(snapshot => snapshot)
const main = useSessionRetainInfo(info => sessionId === undefined
|| (info?.retainedBy.mainView ?? 0) > 0)
@@ -87,9 +88,8 @@ export function AgentPresetSeat({
// it rather than leaving the first one silently in place.
const toastSeq = useRef(0)
const [toast, setToast] = useState<{ seq: number; text: string } | null>(null)
const visible = showPresetPicker && state.showPicker
const pickerVisible = useRef(visible)
pickerVisible.current = visible
const pickerVisible = useRef(developerTools)
pickerVisible.current = developerTools
useEffect(() => {
void load()
@@ -99,10 +99,10 @@ export function AgentPresetSeat({
// state explicitly; otherwise an external off/on edit can revive an old
// menu or refusal banner.
useEffect(() => {
if (visible) return
if (developerTools) return
setOpen(false)
setToast(null)
}, [visible])
}, [developerTools])
const chosen = state.options.find(option => option.id === state.current)
const chosenText = chosen === undefined ? undefined : presetDisplayText(chosen, t)
@@ -131,7 +131,7 @@ export function AgentPresetSeat({
// Nothing to choose between: the deployment composes no presets and every
// session shares the host composition.
if (!main || !visible || !ready) return null
if (!main || !developerTools || !ready) return null
// One wrapper span: the chip is a flex row with a gap, so loose character
// spans would each pick up the gap between them.
@@ -18,43 +18,6 @@
color: var(--dsw-alias-label-tertiary);
}
.pickerPreference {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
padding: 14px 16px;
border: 0.5px solid var(--dsw-alias-settings-card-stroke);
border-radius: var(--dsw-radius-xl);
background: var(--dsw-alias-settings-card-fill);
}
.pickerPreferenceCopy {
display: grid;
gap: 4px;
min-width: 0;
}
.pickerPreferenceTitleRow {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.pickerPreferenceTitle {
font-size: 14px;
font-weight: 600;
line-height: 1.5;
}
.pickerPreferenceDescription {
margin: 0;
font-size: 12px;
line-height: 1.5;
color: var(--dsw-alias-label-tertiary);
}
/* Cards, not rows: a preset is a thing you pick, and the description is the
part that tells them apart — a row would bury it beside the actions. */
.group {
@@ -2,7 +2,7 @@
import type { ReactNode } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import {
Button, IconBrowseOutlineRegular, IconPlusOutlineRegular, Modal, Switch, Tag, Tooltip,
Button, IconBrowseOutlineRegular, IconPlusOutlineRegular, Modal, Tag, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
@@ -15,8 +15,8 @@ import css from './AgentPresetSection.module.css'
export interface AgentPresetSectionInjected {
hooks: {
agentPresetSection: SnapshotStore<AgentPresetSectionState>
/** Shared preference controlling the picker-policy row. */
showPickerPolicy: ObservableSnapshot<boolean>
/** Shared Developer tools preference; off hides every selection action. */
developerTools: ObservableSnapshot<boolean>
}
/** Stage the `cordis` preset and start a Creator-mode task; absent without a conversation flow. */
startCreatorDraft?: () => void
@@ -26,7 +26,6 @@ export interface AgentPresetSectionInjected {
/** Close the read-only viewer. */
closeView: () => void
makeDefault: (id: string) => Promise<void>
setPickerVisible: (visible: boolean) => Promise<void>
}
/** Props assembled by the settings renderer. */
export type AgentPresetSectionProps = PropsRuntime<'settings.section'> & PropsLocale<'settings.agentPreset'> & InjectFace<AgentPresetSectionInjected>
@@ -62,11 +61,11 @@ function CardDescription({ text }: { text: string }): ReactNode {
* @returns The preset settings section.
*/
export function AgentPresetSection({
useAgentPresetSection, load, view, closeView, makeDefault, setPickerVisible, startCreatorDraft,
close: closeSettings, useShowPickerPolicy, t,
useAgentPresetSection, load, view, closeView, makeDefault, startCreatorDraft,
close: closeSettings, useDeveloperTools, t,
}: AgentPresetSectionProps) {
const state = useAgentPresetSection(value => value)
const showPickerPolicy = useShowPickerPolicy(enabled => enabled)
const developerTools = useDeveloperTools(enabled => enabled)
const [guide, setGuide] = useState<{
content: NonNullable<ReturnType<typeof presetGuide>>
page: PresetGuidePage
@@ -91,8 +90,8 @@ export function AgentPresetSection({
<button
type="button"
className={css.creatorButton}
disabled={!state.showPicker || state.policySaving}
title={state.showPicker ? undefined : t('enablePickerToCreate')}
disabled={!developerTools || state.saving}
title={developerTools ? undefined : t('enableDevToolsToCreate')}
onClick={() => { creator(); closeSettings() }}
>
<IconPlusOutlineRegular size={14} />
@@ -102,19 +101,6 @@ export function AgentPresetSection({
return <section className={css.section}>
<h2 className={css.title}>{t('nav')}</h2>
<p className={css.intro}>{t('sectionIntro')}</p>
{showPickerPolicy && (
<div className={css.pickerPreference}>
<div className={css.pickerPreferenceCopy}>
<span className={css.pickerPreferenceTitleRow}>
<span className={css.pickerPreferenceTitle}>{t('showPicker')}</span>
<Tag>{t('showPickerBeta')}</Tag>
</span>
<p className={css.pickerPreferenceDescription}>{t('showPickerDescription')}</p>
</div>
<Switch checked={state.showPicker} disabled={state.status !== 'ready' || state.policySaving}
onChange={(value) => { void setPickerVisible(value) }} label={t('showPicker')} />
</div>
)}
{state.error === null ? null : <p className={css.error} role="alert">{state.error}</p>}
{([true, false] as const).map((builtIn) => {
const rows = state.rows.filter(row => isBuiltInPreset(row) === builtIn)
@@ -127,15 +113,15 @@ export function AgentPresetSection({
const display = presetDisplayText(row, t)
const help = presetGuide(row.id, builtIn ? 'system' : 'user')
const selectionAction = row.broken !== undefined ? t('brokenBadge')
: row.isDefault ? t(state.showPicker ? 'inUse' : 'selectionOffDefault')
: t(state.showPicker ? 'setDefault' : 'enablePickerToSetDefault')
: row.isDefault ? t('inUse')
: t(developerTools ? 'setDefault' : 'enableDevToolsToSetDefault')
return <li key={row.id} data-agent-preset-id={row.id} className={[
css.card, row.broken === undefined ? undefined : css.cardBroken,
row.isDefault ? css.cardActive : undefined,
!state.showPicker && row.broken === undefined && !row.isDefault ? css.cardSelectionDisabled : undefined,
!developerTools && row.broken === undefined && !row.isDefault ? css.cardSelectionDisabled : undefined,
].filter(Boolean).join(' ')}>
<button type="button" className={css.cardMain} aria-pressed={row.isDefault}
disabled={row.isDefault || (row.broken === undefined && (!state.showPicker || state.policySaving))}
disabled={row.isDefault || (row.broken === undefined && (!developerTools || state.saving))}
aria-disabled={row.broken !== undefined} aria-label={`${selectionAction}: ${display.name}`} title={selectionAction}
onClick={() => { if (row.broken === undefined) void makeDefault(row.id) }}>
<span className={css.cardHead}>
@@ -145,7 +131,7 @@ export function AgentPresetSection({
{t('brokenBadge')}<span className={css.brokenTip} aria-hidden="true">{row.broken}</span>
</span>}
<Tag tone={row.isDefault ? 'solid' : 'outline'}>
{row.isDefault ? t(state.showPicker ? 'inUse' : 'selectionOffDefault') : t(builtIn ? 'builtInGroup' : 'customGroup')}
{row.isDefault ? t('inUse') : t(builtIn ? 'builtInGroup' : 'customGroup')}
</Tag>
</span>
<code className={css.cardId} title={row.id}>{row.id}</code>
@@ -11,6 +11,10 @@
* header only reports what a session already runs. The default preset is
* edited where the roster is visible — the settings section's "make default"
* — so General settings carries no duplicate control for the same field.
*
* Developer tools (General settings) are the single gate over selection: with
* them off the chip disappears and the card actions are disabled, while the
* saved default keeps composing new sessions.
*/
// Type-only: pulls the Session Controller service merge (ctx.sessions).
@@ -96,6 +100,15 @@ export function apply(ctx: ClientContext): void {
return seat
}
const section = new AgentPresetSectionController(ctx)
// Turning Developer tools off clears the shared stage before any apply can compose it.
const developerTools = ctx.configForms.developerTools.enabled
ctx.effect(() => developerTools.subscribe(() => {
if (developerTools.getSnapshot()) return
staged.id = undefined
staged.introduce = false
void unboundSeat.apply()
for (const seat of seats.values) void seat.apply()
}), 'ui-agent-preset: Developer tools gate')
const mainBlankSeat = (): AgentPresetSeatController | undefined => {
const summary = Object.values(ctx.sessions.list.getSnapshot().byId)
.find((session) => {
@@ -142,7 +155,7 @@ export function apply(ctx: ClientContext): void {
const binding = sessionId === undefined ? undefined : ctx.sessions.binding(sessionId)
const seat = binding === undefined ? unboundSeat : seatFor(binding)
return {
hooks: { agentPresetSeat: seat.store, showPresetPicker: ctx.configForms.developerTools.enabled },
hooks: { agentPresetSeat: seat.store, developerTools: ctx.configForms.developerTools.enabled },
load: () => seat.load(),
select: (id: string) => seat.select(id),
introduced: () => { seat.introduced() },
@@ -156,7 +169,6 @@ export function apply(ctx: ClientContext): void {
scope.effect(() => {
creatorDraft = () => {
if (!section.store.getSnapshot().showPicker) return
const seat = mainBlankSeat() ?? unboundSeat
seat.stage('cordis', true)
scope.uiWorkspace.startSession()
@@ -198,13 +210,12 @@ export function apply(ctx: ClientContext): void {
}
const sectionInjected = (): AgentPresetSectionInjected => ({
hooks: { agentPresetSection: section.store, showPickerPolicy: ctx.configForms.developerTools.enabled },
hooks: { agentPresetSection: section.store, developerTools: ctx.configForms.developerTools.enabled },
load: () => section.load(),
view: (id: string) => section.view(id),
closeView: () => { section.closeView() },
...creatorDraft === undefined ? {} : { startCreatorDraft: creatorDraft },
makeDefault: (id: string) => section.makeDefault(id, captureBlankSessionSync()),
setPickerVisible: (showPicker: boolean) => section.setPickerVisible(showPicker, captureBlankSessionSync()),
})
// Ordered after Models: choosing a model is routine, and composing an
@@ -22,17 +22,13 @@ export type AgentPresetSettingsKey =
| 'presetCordisName'
| 'presetCordisDescription'
| 'inUse'
| 'selectionOffDefault'
| 'noDescription'
| 'brokenBadge'
| 'switchRefused'
| 'close'
| 'creatorDraft'
| 'showPicker'
| 'showPickerBeta'
| 'showPickerDescription'
| 'enablePickerToSetDefault'
| 'enablePickerToCreate'
| 'enableDevToolsToSetDefault'
| 'enableDevToolsToCreate'
/** English copy. */
export const en: Record<AgentPresetSettingsKey, string> = {
@@ -61,7 +57,6 @@ export const en: Record<AgentPresetSettingsKey, string> = {
'Customize DSH through conversation. Let the agent write plugins that add features or UI, or combine tools and prompts to create your own mode.',
inUse: 'New task default',
selectionOffDefault: 'Application default',
noDescription: 'No description.',
brokenBadge: 'Failed to load',
@@ -72,12 +67,8 @@ export const en: Record<AgentPresetSettingsKey, string> = {
creatorDraft: 'Let the agent help me create a preset',
showPicker: 'Choose a mode for new tasks',
showPickerBeta: 'Experimental',
showPickerDescription:
'When enabled, each new task can choose a mode and the default is set here. When disabled, new tasks use the application default preset. Existing tasks are unaffected.',
enablePickerToSetDefault: 'Turn on mode selection for new tasks to choose a default',
enablePickerToCreate: 'Turn on mode selection for new tasks to start Creator mode',
enableDevToolsToSetDefault: 'Turn on Developer tools in General settings to choose a default',
enableDevToolsToCreate: 'Turn on Developer tools in General settings to start Creator mode',
}
/** Simplified Chinese copy. */
@@ -103,7 +94,6 @@ export const zh: Record<AgentPresetSettingsKey, string> = {
presetCordisDescription: '用对话定制 DSH:让 Agent 编写插件,添加新功能或界面;也能组合工具和提示词,创建自己的模式。',
inUse: '新任务默认',
selectionOffDefault: '应用默认',
noDescription: '暂无描述。',
brokenBadge: '加载失败',
@@ -114,11 +104,8 @@ export const zh: Record<AgentPresetSettingsKey, string> = {
creatorDraft: '让 Agent 帮我创建预设模式',
showPicker: '新任务可选择模式',
showPickerBeta: '实验性',
showPickerDescription: '开启后,可为每个新任务选择模式,并在这里设置默认值。关闭后,新任务使用应用配置的默认预设。已有任务不受影响。',
enablePickerToSetDefault: '请先开启新任务模式选择,再设置默认值',
enablePickerToCreate: '请先开启新任务模式选择,再启动创造模式',
enableDevToolsToSetDefault: '请先在通用设置中开启开发者工具,再设置默认值',
enableDevToolsToCreate: '请先在通用设置中开启开发者工具,再启动创造模式',
}
// The resolution itself is the shared fold in `dsh-agent-preset-registry/display`,
@@ -13,6 +13,8 @@
import type { Context as ClientContext } from '@deepseek-ai/cordis'
// Type-only: pulls the ctx.remote merge into this program.
import type {} from '@deepseek-ai/dsh-api-remotes/client'
// Type-only: pulls the Developer tools preference (ctx.configForms) into this program.
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type {} from '@deepseek-ai/dsh-agent-preset-registry/types'
@@ -21,8 +23,6 @@ import type { AgentPresetOption } from './settings-store.ts'
/** Hero-chip snapshot. */
export interface AgentPresetSeatState {
/** Whether the new-session surface exposes preset selection. */
showPicker: boolean
/** Presets the deployment supplies; empty means the chip renders nothing. */
options: readonly AgentPresetOption[]
/** The staged choice, empty until the roster loads. */
@@ -39,7 +39,7 @@ export interface AgentPresetSeatState {
}
const INITIAL: AgentPresetSeatState = {
showPicker: false, options: [], current: '', error: null, busy: false, introduce: false,
options: [], current: '', error: null, busy: false, introduce: false,
}
/** Mutable one-shot preset choice shared across Provider-bound seat controllers. */
@@ -85,6 +85,11 @@ export class AgentPresetSeatController {
this.staged.introduce = false
}
/** Developer tools are the single gate over preset selection. */
private selectionAvailable(): boolean {
return this.ctx.configForms.developerTools.enabled.getSnapshot()
}
/**
* Read the roster and open the chip on the Host-effective default.
* @returns once the snapshot reflects the host.
@@ -97,14 +102,12 @@ export class AgentPresetSeatController {
this.set({ error: roster.error })
return
}
const { presets, modeSelectionEnabled } = roster.value
if (!modeSelectionEnabled) {
this.clearStage()
}
const { presets } = roster.value
// A stage outlives the screen that made it; Developer tools may have gone off since.
if (!this.selectionAvailable()) this.clearStage()
this.fallback = presets.find(preset => preset.isDefault)?.id ?? presets[0]?.id ?? ''
const session = this.currentSession()
this.set({
showPicker: modeSelectionEnabled,
options: presetOptions(presets),
// Staged pick first, then the composition the current session
// already carries, then the Host-effective default. The middle term is
@@ -114,7 +117,7 @@ export class AgentPresetSeatController {
// apply() already composed it.
current: this.staged.id ?? (session === undefined ? this.fallback : presetOf(session) ?? ''),
error: null,
introduce: modeSelectionEnabled && this.staged.introduce,
introduce: this.staged.introduce,
})
await this.apply()
}
@@ -198,11 +201,18 @@ export class AgentPresetSeatController {
*/
async apply(): Promise<string | undefined> {
if (this.store.getSnapshot().busy) return
const available = this.selectionAvailable()
// A stage made while Developer tools were on must not outlive them.
if (!available) this.clearStage()
const staged = this.staged.id
const session = this.currentSession()
if (staged === undefined) {
const current = session === undefined ? this.fallback : presetOf(session) ?? ''
if (current !== this.store.getSnapshot().current) this.set({ current })
const shown = this.store.getSnapshot()
// Hiding the chip also withdraws the introduction cue armed for it;
// ordinary list movement leaves that cue to the chip that plays it.
if (!available && shown.introduce) this.set({ current, introduce: false })
else if (current !== shown.current) this.set({ current })
return
}
if (session === undefined) return
@@ -1,9 +1,9 @@
/** Preset roster, selection policy and the read-only composition viewer for the settings section. */
/** Preset roster, the new-task default and the read-only composition viewer for the settings section. */
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-api-remotes/client'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { AgentPresetRow } from '@deepseek-ai/dsh-agent-preset-registry/types'
import { writeDefaultPreset, writeModeSelectionEnabled } from './settings-store.ts'
import { writeDefaultPreset } from './settings-store.ts'
/** The read-only composition viewer over one preset. */
export interface PresetView {
@@ -18,16 +18,15 @@ export interface PresetView {
export interface AgentPresetSectionState {
status: 'idle' | 'loading' | 'ready' | 'error'
error: string | null
showPicker: boolean
policySaving: boolean
saving: boolean
rows: readonly AgentPresetRow[]
/** The open viewer, or null. */
view: PresetView | null
}
const INITIAL: AgentPresetSectionState = { status: 'idle', error: null, showPicker: true, policySaving: false, rows: [], view: null }
const INITIAL: AgentPresetSectionState = { status: 'idle', error: null, saving: false, rows: [], view: null }
const message = (error: unknown): string => error instanceof Error ? error.message : String(error)
/** Loads the roster, writes the default and chooser policy, and reads one composition at a time. */
/** Loads the roster, writes the default, and reads one composition at a time. */
export class AgentPresetSectionController {
/** Observable roster, selection and viewer state. */
readonly store: SnapshotStore<AgentPresetSectionState> = createSnapshotStore(INITIAL)
@@ -47,7 +46,7 @@ export class AgentPresetSectionController {
try {
const result = await this.ctx.remote.agentPresets.list()
if (!result.ok) throw new Error(result.error.message)
this.set({ status: 'ready', error: null, rows: result.value.presets, showPicker: result.value.modeSelectionEnabled })
this.set({ status: 'ready', error: null, rows: result.value.presets })
} catch (error) { this.set({ status: 'error', error: message(error) }) }
}
@@ -75,20 +74,11 @@ export class AgentPresetSectionController {
* @returns Once saved and refreshed.
*/
async makeDefault(id: string, sync?: (id: string) => Promise<string | undefined>): Promise<void> {
if (!this.store.getSnapshot().showPicker) return
await this.policy(() => writeDefaultPreset(this.ctx, id), sync)
await this.save(() => writeDefaultPreset(this.ctx, id), sync)
}
/** Change chooser visibility.
* @param visible Whether the chooser is visible.
* @param sync Blank-session synchronization callback.
* @returns Once saved and refreshed.
*/
async setPickerVisible(visible: boolean, sync?: (id: string) => Promise<string | undefined>): Promise<void> {
await this.policy(() => writeModeSelectionEnabled(this.ctx, visible), sync)
}
private async policy(write: () => Promise<string | undefined>, sync?: (id: string) => Promise<string | undefined>): Promise<void> {
if (this.store.getSnapshot().policySaving) return
this.set({ policySaving: true, error: null })
private async save(write: () => Promise<string | undefined>, sync?: (id: string) => Promise<string | undefined>): Promise<void> {
if (this.store.getSnapshot().saving) return
this.set({ saving: true, error: null })
try {
const error = await write()
await this.load()
@@ -99,6 +89,6 @@ export class AgentPresetSectionController {
if (error !== undefined) throw new Error(error)
}
} catch (error) { this.set({ error: message(error) }) }
finally { this.set({ policySaving: false }) }
finally { this.set({ saving: false }) }
}
}
@@ -15,15 +15,6 @@ import type { AgentPresetRoster } from '@deepseek-ai/dsh-agent-preset-registry/t
/** The agent-preset settings namespace on the host wire. */
export const AGENT_PRESET_SETTINGS_NS = 'agent-preset-registry'
/** Write only the named agent-preset settings fields. */
async function writeAgentPresetSettings(
ctx: ClientContext,
patch: { selectedDefault?: string; modeSelectionEnabled?: boolean },
): Promise<string | undefined> {
const response = await ctx.remote.settings.update(AGENT_PRESET_SETTINGS_NS, patch, undefined)
return response.ok ? undefined : response.error.message
}
/**
* Persist one preset as the default for sessions created later.
*
@@ -34,24 +25,12 @@ async function writeAgentPresetSettings(
* @param id - the preset to make default.
* @returns the failure message, or undefined once the write landed.
*/
export function writeDefaultPreset(
export async function writeDefaultPreset(
ctx: ClientContext,
id: string,
): Promise<string | undefined> {
return writeAgentPresetSettings(ctx, { selectedDefault: id })
}
/**
* Persist whether new-session surfaces expose preset selection.
* @param ctx - the browser plugin context carrying the Remote namespaces.
* @param enabled - whether the picker should be exposed.
* @returns the failure message, or undefined once the write landed.
*/
export function writeModeSelectionEnabled(
ctx: ClientContext,
enabled: boolean,
): Promise<string | undefined> {
return writeAgentPresetSettings(ctx, { modeSelectionEnabled: enabled })
const response = await ctx.remote.settings.update(AGENT_PRESET_SETTINGS_NS, { selectedDefault: id }, undefined)
return response.ok ? undefined : response.error.message
}
/** One selectable preset. */
@@ -70,7 +49,7 @@ export type RosterPreset = AgentPresetRoster['presets'][number]
/** The roster, or the message to show in its place. */
export type RosterRead = { ok: true; value: AgentPresetRoster } | { ok: false; error: string }
const EMPTY_ROSTER: AgentPresetRoster = { presets: [], modeSelectionEnabled: false }
const EMPTY_ROSTER: AgentPresetRoster = { presets: [] }
/**
* Read the roster, turning a refusal into the message every surface shows.
@@ -10,6 +10,7 @@ import { describe, expect, it, vi } from 'vitest'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import { SessionId } from '@deepseek-ai/dsh-session'
import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client'
@@ -27,11 +28,15 @@ import { apply as hostApply } from '../src/index.ts'
// so browser-language detection never runs and a fresh LocaleRuntime opens on
// FALLBACK_LOCALE (en); each bench stages zh explicitly on the locale instead.
/** The Developer tools half of `ctx.configForms`, which gates all selection. */
function developerTools(enabled = true): { configForms: { developerTools: { enabled: ObservableSnapshot<boolean> } } } {
return { configForms: { developerTools: { enabled: createSnapshotStore(enabled) } } }
}
const ROSTER_ONE = {
ok: true as const,
value: {
presets: [{ id: 'standard', isDefault: true }],
modeSelectionEnabled: true,
},
}
@@ -43,7 +48,6 @@ const ROSTER_AUTHORED = {
{ id: 'standard', isDefault: true },
{ id: 'mine', isDefault: false },
],
modeSelectionEnabled: true,
},
}
@@ -55,16 +59,6 @@ const ROSTER_MOVED = {
{ id: 'standard', isDefault: false },
{ id: 'minimal', isDefault: true },
],
modeSelectionEnabled: true,
},
}
/** The deployment after reconnect, with mode selection disabled. */
const ROSTER_HIDDEN = {
ok: true as const,
value: {
presets: [{ id: 'standard', isDefault: true }],
modeSelectionEnabled: false,
},
}
@@ -76,7 +70,7 @@ async function bench(options: {
const ctx = new Context()
// The host's answer, mutable so a spec can move the default the way the
// settings surface does and watch who re-reads it.
let ROSTER: typeof ROSTER_ONE | typeof ROSTER_MOVED | typeof ROSTER_AUTHORED | typeof ROSTER_HIDDEN = ROSTER_ONE
let ROSTER: typeof ROSTER_ONE | typeof ROSTER_MOVED | typeof ROSTER_AUTHORED = ROSTER_ONE
const moveDefault = (): void => { ROSTER = ROSTER_MOVED }
await ctx.plugin(SlotRegistry).await()
const locale = new LocaleRuntime(ctx)
@@ -84,7 +78,7 @@ async function bench(options: {
ctx.provide('locale', locale)
const calls: string[] = []
let savedDefault = 'standard'
let selectionEnabled = true
let developerToolsEnabled = true
let settingsSaved = false
const settingsRosterStarted = Promise.withResolvers<undefined>()
// The row reads `describe` to learn whether this browser may write at all,
@@ -92,9 +86,23 @@ async function bench(options: {
const settings = {
describe: () => Promise.resolve({
ok: true as const,
value: { writable: true, hasDocument: true, namespaces: [] },
value: {
writable: true,
hasDocument: true,
// The shared Developer tools preference the surfaces read: this browser
// has it on, so the roster is editable.
namespaces: [{
ns: 'ui-settings',
schema: { type: 'object', dict: { enabled: { type: 'boolean' } } },
value: { enabled: developerToolsEnabled },
autoGenerate: false,
applies: 'live',
secrets: [],
revision: 0,
}],
},
}),
update: (_ns: string, patch: { selectedDefault?: unknown; modeSelectionEnabled?: unknown }) => {
update: (_ns: string, patch: { selectedDefault?: unknown }) => {
calls.push(`settings:${JSON.stringify(patch)}`)
if (options.failSettingsUpdate === true) {
return Promise.resolve({
@@ -105,12 +113,7 @@ async function bench(options: {
if (typeof patch.selectedDefault === 'string') {
savedDefault = patch.selectedDefault
}
if (typeof patch.modeSelectionEnabled === 'boolean') {
selectionEnabled = patch.modeSelectionEnabled
}
ROSTER = !selectionEnabled
? ROSTER_HIDDEN
: savedDefault === 'minimal' ? ROSTER_MOVED : ROSTER_ONE
ROSTER = savedDefault === 'minimal' ? ROSTER_MOVED : ROSTER_ONE
settingsSaved = true
return Promise.resolve({ ok: true as const, value: {} })
},
@@ -150,7 +153,18 @@ async function bench(options: {
ctx.provide('remote.agentPresets', agentPresets as never)
Object.assign(remote, { agentPresets })
await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await()
return { ctx, slots: ctx.get('slots') as SlotRegistry, calls, moveDefault, remote, settingsRosterStarted: settingsRosterStarted.promise }
// Every spec below starts from the accepted "Developer tools on" value.
await vi.waitFor(() => { expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(true) })
/** Publish a new Developer tools choice the way the settings mirror does. */
const setDeveloperTools = async (enabled: boolean): Promise<void> => {
developerToolsEnabled = enabled
remote.emit('settings/document-updated', ['ui-settings', 1])
await vi.waitFor(() => { expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(enabled) })
}
return {
ctx, slots: ctx.get('slots') as SlotRegistry, calls, moveDefault, remote,
settingsRosterStarted: settingsRosterStarted.promise, setDeveloperTools,
}
}
function declareRoot(slots: SlotRegistry): () => void {
@@ -264,7 +278,6 @@ async function settingsWithoutChip(initialPreset: string, settingsRosterGate?: P
describe('ui-agent-preset apply', () => {
const settingsActions = [
{ action: 'makeDefault', initial: 'standard', selected: 'minimal', run: (section: AgentPresetSectionInjected) => section.makeDefault('minimal') },
{ action: 'setPickerVisible', initial: 'minimal', selected: 'standard', run: (section: AgentPresetSectionInjected) => section.setPickerVisible(false) },
]
it.each(settingsActions)('synchronizes $action before the chip mounts', async ({ initial, selected, run }) => {
@@ -604,31 +617,15 @@ describe('ui-agent-preset apply', () => {
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('minimal')
sessionState.byId.s1.projectionValues.agentPreset = 'minimal'
await section.setPickerVisible(false)
expect(calls.filter(call => call.startsWith('select:'))).toEqual([
'select:minimal', 'select:standard',
])
expect(section.hooks.agentPresetSection.getSnapshot().showPicker).toBe(false)
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('standard')
sessionState.byId.s1.projectionValues.agentPreset = 'standard'
await section.setPickerVisible(true)
expect(calls.filter(call => call.startsWith('select:'))).toEqual([
'select:minimal', 'select:standard', 'select:minimal',
])
expect(section.hooks.agentPresetSection.getSnapshot().showPicker).toBe(true)
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('minimal')
sessionState.byId.s1.projectionValues.agentPreset = 'minimal'
sessionState.byId.s1.blank = false
await section.makeDefault('standard')
expect(calls.filter(call => call.startsWith('select:'))).toEqual([
'select:minimal', 'select:standard', 'select:minimal',
])
expect(calls.filter(call => call.startsWith('select:'))).toEqual(['select:minimal'])
conversation()
})
it('reloads Host truth after a picker-policy save failure', async () => {
it('reloads Host truth after a default save failure', async () => {
const { ctx, slots, calls } = await bench({ failSettingsUpdate: true })
ctx.provide('sessions', sessionsDouble(ctx, { byId: {} }) as never)
declareRoot(slots)
@@ -636,13 +633,14 @@ describe('ui-agent-preset apply', () => {
const section = (slots.entries('settings.section')[0]!
.inject as unknown as () => AgentPresetSectionInjected)()
await section.load()
expect(section.hooks.agentPresetSection.getSnapshot().showPicker).toBe(true)
expect(section.hooks.agentPresetSection.getSnapshot().rows)
.toEqual([{ id: 'standard', isDefault: true }])
await section.setPickerVisible(false)
await section.makeDefault('minimal')
expect(calls.filter(call => call === 'list')).toHaveLength(2)
expect(section.hooks.agentPresetSection.getSnapshot()).toMatchObject({
showPicker: true, policySaving: false, error: 'settings write disconnected',
saving: false, error: 'settings write disconnected',
})
})
@@ -737,6 +735,67 @@ describe('ui-agent-preset apply', () => {
expect(calls.filter(call => call === 'select:minimal')).toHaveLength(spent)
})
it('drops a cross-screen stage when Developer tools turn off, and releases its subscription with the fiber', async () => {
const { ctx, slots, calls, setDeveloperTools } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
const state: {
current?: string
byId: Record<string, { id: string; blank: boolean; projectionValues?: { agentPreset?: string | null } }>
} = {
current: 's0',
byId: {
s0: { id: 's0', blank: false, projectionValues: { agentPreset: 'standard' } },
s1: { id: 's1', blank: true, projectionValues: { agentPreset: 'standard' } },
},
}
const sessions = sessionsDouble(ctx, state)
ctx.provide('sessions', sessions as never)
ctx.provide('uiWorkspace', uiWorkspaceDouble() as never)
// The gate's seat sweep runs over live Provider bindings; s1's binding is
// not the main view yet, so its seat keeps a stage it cannot apply.
let released = 0
const dispatch = ctx.configForms.developerTools.enabled.subscribe.bind(ctx.configForms.developerTools.enabled)
vi.spyOn(ctx.configForms.developerTools.enabled, 'subscribe').mockImplementation((listener) => {
const dispose = dispatch(listener)
return () => { released += 1; dispose() }
})
const feature = ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'uiWorkspace'], apply })
await feature.await()
const injectSeat = slots.entries('conversation.hero.agentPreset')[0]!
.inject as (sessionId?: SessionId) => AgentPresetSeatInjected & Record<string, unknown>
const chip = injectSeat(SessionId('s1'))
await chip.load()
await chip.select('minimal')
expect(chip.hooks.agentPresetSeat.getSnapshot()).toMatchObject({ current: 'minimal', introduce: false })
// The preference turns off with no seat load, so only the gate's own sweep
// can reconcile this live bound seat back to the roster default.
await setDeveloperTools(false)
await vi.waitFor(() => {
expect(chip.hooks.agentPresetSeat.getSnapshot()).toMatchObject({ current: 'standard', introduce: false })
})
expect(calls.filter(call => call.startsWith('select:'))).toEqual([])
// Turning back on must not resurrect the dropped stage when this blank
// Session becomes the main view's current one.
await setDeveloperTools(true)
state.current = 's1'
sessions.notify()
await chip.load()
expect(calls.filter(call => call.startsWith('select:'))).toEqual([])
expect(chip.hooks.agentPresetSeat.getSnapshot().current).toBe('standard')
const settled = chip.hooks.agentPresetSeat.getSnapshot()
await feature.dispose()
await setDeveloperTools(false)
expect(chip.hooks.agentPresetSeat.getSnapshot()).toBe(settled)
expect(released).toBe(1)
conversation()
})
it('loads the header label from the shared roster store', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
@@ -768,10 +827,6 @@ describe('ui-agent-preset apply', () => {
const seat = injectSeat()
await section.load()
await section.setPickerVisible(false)
section.startCreatorDraft?.()
expect(uiWorkspace.starts).toHaveLength(0)
await section.setPickerVisible(true)
section.startCreatorDraft?.()
// The pick is staged on the chip's own controller — the session the
@@ -888,6 +943,7 @@ describe('AgentPresetSeatController reconciliation', () => {
const requests: { preset: string; outcome: ReturnType<typeof Promise.withResolvers<Outcome>> }[] = []
const session = { id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } }
const controller = new AgentPresetSeatController({
...developerTools(),
remote: { agentPresets: { select: (_id: SessionId, preset: string) => {
const outcome = Promise.withResolvers<Outcome>()
requests.push({ preset, outcome })
@@ -919,7 +975,7 @@ describe('AgentPresetSeatController reconciliation', () => {
const select = vi.fn((_id: SessionId, preset: string) => preset === 'minimal'
? firstReply.promise
: Promise.resolve({ ok: true as const, value: preset }))
const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never,
const controller = new AgentPresetSeatController({ ...developerTools(), remote: { agentPresets: { select } } } as never,
() => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } }))
const first = controller.select('minimal')
controller.stage('cordis', true)
@@ -938,6 +994,7 @@ describe('AgentPresetSeatController reconciliation', () => {
const requests: { preset: string; outcome: ReturnType<typeof Promise.withResolvers<Outcome>> }[] = []
const session = { id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } }
const controller = new AgentPresetSeatController({
...developerTools(),
remote: { agentPresets: { select: (_id: SessionId, preset: string) => {
const outcome = Promise.withResolvers<Outcome>()
requests.push({ preset, outcome })
@@ -963,7 +1020,7 @@ describe('AgentPresetSeatController reconciliation', () => {
const reply = Promise.withResolvers<{ ok: true; value: string }>()
const select = vi.fn(() => reply.promise)
let current = { id: SessionId('first'), blank: true, projectionValues: { agentPreset: 'standard' } }
const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never, () => current)
const controller = new AgentPresetSeatController({ ...developerTools(), remote: { agentPresets: { select } } } as never, () => current)
const first = controller.select('minimal')
const settings = controller.syncBlankSession(current.id, 'cordis')
current = { ...current, id: SessionId('replacement') }
@@ -974,7 +1031,7 @@ describe('AgentPresetSeatController reconciliation', () => {
})
it('does not capture a non-blank Session', () => {
const controller = new AgentPresetSeatController({} as never, () => ({
const controller = new AgentPresetSeatController({ ...developerTools() } as never, () => ({
id: SessionId('started'), blank: false,
}))
@@ -987,6 +1044,7 @@ describe('AgentPresetSeatController reconciliation', () => {
id: SessionId('first'), blank: true, projectionValues: { agentPreset: 'standard' },
}
const controller = new AgentPresetSeatController({
...developerTools(),
remote: { agentPresets: { select } },
} as never, () => current)
const captured = controller.blankSessionId()
@@ -1003,6 +1061,7 @@ describe('AgentPresetSeatController reconciliation', () => {
it('uses the deployment default without a Session and clears it for an uncomposed Session', async () => {
const state: { current?: { id: SessionId; blank: boolean } } = {}
const controller = new AgentPresetSeatController({
...developerTools(),
remote: {
agentPresets: {
list: () => Promise.resolve(ROSTER_ONE),
@@ -1024,6 +1083,7 @@ describe('AgentPresetSeatController reconciliation', () => {
ok: false as const, error: new RemoteError('gateway/internal', 'selection rejected', {}),
})
const controller = new AgentPresetSeatController({
...developerTools(),
remote: { agentPresets: { select } },
} as never, () => ({ id: SessionId('uncomposed'), blank: true }))
@@ -1037,6 +1097,7 @@ describe('AgentPresetSeatController reconciliation', () => {
it('keeps the bare cause of a mount failure, not the frame that names the preset again', async () => {
const reason = 'failed to import loader entry ctx (@deepseek-ai/dsh-gone): Cannot find package'
const controller = new AgentPresetSeatController({
...developerTools(),
remote: {
agentPresets: {
select: () => Promise.resolve({
@@ -29,7 +29,6 @@ const ROSTER_READY: AgentPresetSettingsState = {
}
const SEAT_READY: AgentPresetSeatState = {
showPicker: true,
current: 'standard',
options: [
{ id: 'standard' },
@@ -54,20 +53,22 @@ function renderSeat(
state: Partial<AgentPresetSeatState> = {},
select: () => Promise<string | undefined> = () => Promise.resolve(undefined),
session?: { id: string; retainInfo: SessionRetainInfo | undefined },
enabled = true,
) {
const store = createSnapshotStore<AgentPresetSeatState>({ ...SEAT_READY, ...state })
const developerTools = createSnapshotStore(true)
const developerTools = createSnapshotStore(enabled)
const actions = { load: vi.fn(() => Promise.resolve()), select: vi.fn(select), introduced: vi.fn() }
render(<AgentPresetSeat {...({
const props = {
...actions,
sessionId: session === undefined ? undefined : SessionId(session.id),
useShowPresetPicker: bindSnapshotSelector(developerTools),
useDeveloperTools: bindSnapshotSelector(developerTools),
useAgentPresetSeat: bindSnapshotSelector(store),
useSessionRetainInfo: session === undefined
? useSessionRetainInfo
: <Selected,>(selector: (value: SessionRetainInfo | undefined) => Selected) => selector(session.retainInfo),
t: translate,
} as unknown as AgentPresetSeatProps)} />)
} as AgentPresetSeatProps
render(<AgentPresetSeat {...props} />)
return { ...actions, developerTools }
}
@@ -92,8 +93,8 @@ function renderLabel(
}
describe('the new-session chip', () => {
it('renders nothing while the picker is disabled', () => {
renderSeat({ showPicker: false })
it('renders nothing while Developer tools are off', () => {
renderSeat({}, undefined, undefined, false)
expect(screen.queryByRole('button')).toBeNull()
})
@@ -3,7 +3,7 @@ import { AgentPresetSectionController } from '../src/client/section-store.ts'
function fixture() {
const remote = { agentPresets: {
list: vi.fn(async () => ({ ok: true as const, value: { presets: [{ id: 'standard', isDefault: true }], modeSelectionEnabled: true } })),
list: vi.fn(async () => ({ ok: true as const, value: { presets: [{ id: 'standard', isDefault: true }] } })),
read: vi.fn(async (id: string) => ({ ok: true as const, value: { agentPreset: id, name: 'Standard', content: '- name: fs\n' } })),
}, settings: { update: vi.fn(async () => ({ ok: true as const, value: {} })) } }
const controller = new AgentPresetSectionController({ remote } as never)
@@ -15,7 +15,7 @@ describe('the preset roster', () => {
const { controller, remote, state } = fixture()
await Promise.all([controller.load(), controller.load()])
expect(remote.agentPresets.list).toHaveBeenCalledOnce()
expect(state()).toMatchObject({ status: 'ready', rows: [{ id: 'standard', isDefault: true }], showPicker: true, view: null })
expect(state()).toMatchObject({ status: 'ready', rows: [{ id: 'standard', isDefault: true }], view: null })
remote.agentPresets.list.mockRejectedValueOnce(new Error('offline'))
await controller.load()
expect(state()).toMatchObject({ status: 'error', error: 'offline' })
@@ -70,28 +70,32 @@ describe('the preset roster', () => {
await controller.makeDefault('standard', sync)
expect(remote.settings.update).toHaveBeenCalledWith('agent-preset-registry', { selectedDefault: 'standard' }, undefined)
expect(sync).toHaveBeenCalledWith('standard')
await controller.setPickerVisible(false)
expect(remote.settings.update).toHaveBeenLastCalledWith('agent-preset-registry', { modeSelectionEnabled: false }, undefined)
remote.settings.update.mockRejectedValueOnce(new Error('read only'))
await controller.setPickerVisible(true)
expect(state()).toMatchObject({ policySaving: false, error: 'read only' })
await controller.makeDefault('minimal')
expect(state()).toMatchObject({ saving: false, error: 'read only' })
})
it('prevents a second policy write and reports blank-session synchronization failures', async () => {
it('prevents a second default write and reports blank-session synchronization failures', async () => {
const { controller, remote, state } = fixture()
let release!: () => void
const wait = new Promise<void>((resolve) => { release = resolve })
remote.settings.update.mockImplementationOnce(async () => { await wait; return { ok: true, value: {} } })
const pending = controller.makeDefault('standard', async () => 'Session already started')
await controller.setPickerVisible(false)
await controller.makeDefault('standard')
expect(remote.settings.update).toHaveBeenCalledOnce()
release()
await pending
expect(state().error).toBe('Session already started')
remote.agentPresets.list.mockResolvedValueOnce({ ok: true, value: { presets: [], modeSelectionEnabled: false } })
await controller.setPickerVisible(false)
const writes = remote.settings.update.mock.calls.length
await controller.makeDefault('standard')
expect(remote.settings.update).toHaveBeenCalledTimes(writes)
})
it('skips blank-session synchronization when the roster marks no default', async () => {
const { controller, remote } = fixture()
const sync = vi.fn(async () => undefined)
remote.agentPresets.list.mockResolvedValueOnce({ ok: true, value: { presets: [{ id: 'standard', isDefault: false }] } })
await controller.makeDefault('standard', sync)
expect(remote.settings.update).toHaveBeenCalledOnce()
expect(sync).not.toHaveBeenCalled()
})
})
@@ -12,19 +12,19 @@ const translations: ReadonlyMap<string, string> = new Map(Object.entries(en))
function unusedHook(): never {
throw new Error('This section does not read global slot sources')
}
function view(partial: Partial<AgentPresetSectionState> = {}, startCreatorDraft?: () => void, showPickerPolicy = true,
function view(partial: Partial<AgentPresetSectionState> = {}, startCreatorDraft?: () => void, developerTools = true,
outerClose?: () => void) {
const store = createSnapshotStore<AgentPresetSectionState>({ status: 'ready', error: null,
showPicker: true, policySaving: false, rows: [{ id: 'standard', isDefault: true }, { id: 'mine', name: 'Mine', isDefault: false }],
saving: false, rows: [{ id: 'standard', isDefault: true }, { id: 'mine', name: 'Mine', isDefault: false }],
view: null, ...partial })
const actions = { load: vi.fn(async () => {}), view: vi.fn(async () => {}), closeView: vi.fn(), makeDefault: vi.fn(async () => {}),
setPickerVisible: vi.fn(async () => {}), close: vi.fn() }
close: vi.fn() }
const props: AgentPresetSectionProps = { ...actions,
...(startCreatorDraft === undefined ? {} : { startCreatorDraft }),
usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook,
useWorkspaces: unusedHook, useResource: unusedHook,
useAgentPresetSection: bindSnapshotSelector(store),
useShowPickerPolicy: bindSnapshotSelector(createSnapshotStore(showPickerPolicy)),
useDeveloperTools: bindSnapshotSelector(createSnapshotStore(developerTools)),
t: key => translations.get(key) ?? key }
render(outerClose === undefined ? <AgentPresetSection {...props} />
: <Modal open onClose={outerClose} title="Settings" closeLabel="Close"><AgentPresetSection {...props} /></Modal>)
@@ -35,11 +35,11 @@ function rowFor(id: string): HTMLElement {
if (row === null) throw new Error(`no card for ${id}`)
return row
}
it('hides the complete picker-policy row while developer tools are off', () => {
it('offers no selection switch and disables the card actions while Developer tools are off', () => {
view({}, undefined, false)
expect(screen.queryByRole('switch', { name: en.showPicker })).toBeNull()
expect(screen.queryByText(en.showPickerDescription)).toBeNull()
expect(screen.queryByText(en.showPickerBeta)).toBeNull()
expect(screen.queryByRole('switch')).toBeNull()
expect(screen.getByRole<HTMLButtonElement>('button', { name: `${en.enableDevToolsToSetDefault}: Mine` }).disabled).toBe(true)
})
it('reads the roster once and sets a default from the card body', async () => {
const actions = view()
@@ -82,12 +82,12 @@ it('offers no Creator entry without the conversation flow or the cordis preset',
view({}, vi.fn())
expect(screen.queryByRole('button', { name: en.creatorDraft })).toBeNull()
})
it('disables the Creator entry when mode selection is hidden', () => {
it('disables the Creator entry while Developer tools are off', () => {
const launch = vi.fn()
view({ showPicker: false, rows: [{ id: 'cordis', isDefault: true }] }, launch)
view({ rows: [{ id: 'cordis', isDefault: true }] }, launch, false)
const button = screen.getByRole<HTMLButtonElement>('button', { name: en.creatorDraft })
expect(button.disabled).toBe(true)
expect(button.title).toBe(en.enablePickerToCreate)
expect(button.title).toBe(en.enableDevToolsToCreate)
fireEvent.click(button)
expect(launch).not.toHaveBeenCalled()
})
@@ -137,15 +137,14 @@ it('clears an open viewer when the settings section unmounts', () => {
cleanup()
expect(actions.closeView).toHaveBeenCalledOnce()
})
it('shows roster errors while the policy switch stays usable', () => {
const actions = view({ error: 'Roster stale', rows: [{ id: 'broken', isDefault: false, broken: 'Missing plugin' }] })
it('shows roster errors without hiding the roster', () => {
const actions = view({ error: 'Roster stale', rows: [
{ id: 'broken', isDefault: false, broken: 'Missing plugin' },
{ id: 'mine', name: 'Mine', isDefault: false },
] })
expect(screen.getAllByRole('alert').map(node => node.textContent)).toEqual(['Roster stale', 'Missing plugin'])
fireEvent.click(screen.getByRole('switch'))
expect(actions.setPickerVisible).toHaveBeenCalledWith(false)
})
it('identifies the effective default when the picker is hidden', () => {
view({ showPicker: false })
expect(screen.getByRole<HTMLButtonElement>('button', { name: `${en.selectionOffDefault}: ${en.presetStandardName}` }).disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: `${en.setDefault}: Mine` }))
expect(actions.makeDefault).toHaveBeenCalledWith('mine')
})
it('keeps a broken card focusable for diagnostics and refuses to select it', () => {
const actions = view({ rows: [{ id: 'broken', isDefault: false, broken: 'Missing plugin' }] })
@@ -226,11 +225,11 @@ it('does not attach built-in claims to named or unknown presets', () => {
expect(screen.queryByRole('button', { name: new RegExp(en.modeExplanation) })).toBeNull()
expect(screen.queryByRole('button', { name: new RegExp(en.howToUse) })).toBeNull()
})
it('leaves help usable when mode selection is disabled', () => {
const actions = view({ showPicker: false })
it('leaves help usable while Developer tools are off', () => {
const actions = view({}, undefined, false)
fireEvent.click(within(rowFor('standard')).getByRole('button', { name: `${en.howToUse}: ${en.presetStandardName}` }))
expect(screen.getByRole('dialog', { name: en.presetStandardName })).toBeTruthy()
expect(actions.setPickerVisible).not.toHaveBeenCalled()
expect(actions.makeDefault).not.toHaveBeenCalled()
})
it('closes help even when the browser reports no previously focused element', () => {
const descriptor: TypedPropertyDescriptor<Element | null> = Object.getOwnPropertyDescriptor(Document.prototype, 'activeElement')!
@@ -11,9 +11,10 @@ import type { RemoteErrorCode } from '@deepseek-ai/dsh-api-remotes/client'
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import {
AGENT_PRESET_SETTINGS_NS, AgentPresetSettingsController,
writeDefaultPreset, writeModeSelectionEnabled,
writeDefaultPreset,
} from '../src/client/settings-store.ts'
/** The roster store over a scripted context. */
@@ -33,10 +34,9 @@ function fakeRoster(
failList?: string
failListCode?: RemoteErrorCode
settings?: object
showPicker?: boolean
} = {},
): ClientContext {
return {
const partial = {
remote: {
...options.settings === undefined ? {} : { settings: options.settings },
agentPresets: {
@@ -44,9 +44,7 @@ function fakeRoster(
return Promise.resolve(options.failList === undefined
? {
ok: true as const,
value: {
presets, modeSelectionEnabled: options.showPicker ?? true,
},
value: { presets },
}
: {
ok: false as const,
@@ -55,7 +53,8 @@ function fakeRoster(
},
},
},
} as unknown as ClientContext
}
return partial as ClientContext
}
/** A context whose roster and settings write outcome the test controls. */
@@ -68,7 +67,7 @@ function fakeApi(
} = {},
): ClientContext {
const settings = {
update: (ns: string, patch: { selectedDefault?: unknown; modeSelectionEnabled?: unknown }) => {
update: (ns: string, patch: { selectedDefault?: unknown }) => {
options.writes?.push({ ns, ops: patch })
if (options.failWrite !== undefined) {
return Promise.resolve({ ok: false as const, error: new RemoteError('gateway/internal', options.failWrite, {}) })
@@ -175,16 +174,6 @@ describe('the agent-preset roster store', () => {
expect(await writeDefaultPreset(ctx, 'minimal')).toBe('read-only settings')
})
it('writeModeSelectionEnabled writes only the picker policy field', async () => {
const writes: Recorded[] = []
expect(await writeModeSelectionEnabled(fakeApi([], { writes }), false)).toBeUndefined()
expect(writes).toEqual([{
ns: AGENT_PRESET_SETTINGS_NS,
ops: { modeSelectionEnabled: false },
}])
})
it('surfaces a roster failure without claiming the deployment has no presets', async () => {
const controller = derivedController(fakeApi([], { failList: 'host down' }))
@@ -217,20 +206,19 @@ describe('the new-session chip controller', () => {
failSelect?: string
failList?: string
failListCode?: RemoteErrorCode
showPicker?: boolean
developerTools?: ObservableSnapshot<boolean>
list?: () => Promise<ReturnType<typeof remoteRoster>>
} = {},
): AgentPresetSeatController {
const ctx = {
const partial = {
configForms: { developerTools: { enabled: options.developerTools ?? createSnapshotStore(true) } },
remote: {
agentPresets: {
list: options.list ?? (() => {
return Promise.resolve(options.failList === undefined
? {
ok: true as const,
value: {
presets, modeSelectionEnabled: options.showPicker ?? true,
},
value: { presets },
}
: {
ok: false as const,
@@ -250,7 +238,8 @@ describe('the new-session chip controller', () => {
},
},
},
} as unknown as ClientContext
}
const ctx = partial as ClientContext
return new AgentPresetSeatController(
ctx,
typeof current === 'function' ? current : () => current,
@@ -276,7 +265,7 @@ describe('the new-session chip controller', () => {
])
})
it('takes picker visibility from the newest Host roster truth', async () => {
it('publishes only the newest overlapping roster read', async () => {
const first = Promise.withResolvers<ReturnType<typeof remoteRoster>>()
const second = Promise.withResolvers<ReturnType<typeof remoteRoster>>()
const replies = [first.promise, second.promise]
@@ -284,13 +273,13 @@ describe('the new-session chip controller', () => {
const older = controller.load()
const newer = controller.load()
second.resolve(remoteRoster(false))
second.resolve(remoteRoster('mine'))
await newer
first.resolve(remoteRoster(true))
first.resolve(remoteRoster('standard'))
await older
expect(controller.store.getSnapshot()).toMatchObject({
showPicker: false, current: 'standard', error: null,
current: 'mine', error: null,
})
})
@@ -477,13 +466,14 @@ describe('the new-session chip controller', () => {
expect(controller.store.getSnapshot().current).toBe('minimal')
})
it('clears an unconsumed stage when the Host hides the picker', async () => {
it('clears an unconsumed stage when Developer tools are off', async () => {
const writes: Recorded[] = []
const developerTools = createSnapshotStore(false)
const controller = chip(ROSTER, {
id: 's1' as SessionId,
blank: false,
projectionValues: { agentPreset: 'standard' },
}, { writes, showPicker: false })
}, { writes, developerTools })
controller.stage('minimal', true)
await controller.load()
@@ -491,12 +481,56 @@ describe('the new-session chip controller', () => {
expect(writes).toEqual([])
expect(controller.store.getSnapshot()).toMatchObject({
showPicker: false,
current: 'standard',
introduce: false,
})
})
it('drops a stage made while Developer tools were on once they turn off', async () => {
const writes: Recorded[] = []
const developerTools = createSnapshotStore(true)
const session = {
id: 's1' as SessionId,
blank: true,
projectionValues: { agentPreset: 'standard' },
}
const controller = chip(ROSTER, session, { writes, developerTools })
await controller.load()
// The blank session keeps the composition its own screen already names.
controller.stage('minimal', true)
developerTools.set(false)
await controller.apply()
expect(writes).toEqual([])
expect(controller.store.getSnapshot()).toMatchObject({
current: 'standard',
introduce: false,
})
})
it('leaves the introduction cue to the chip while Developer tools stay on', async () => {
const developerTools = createSnapshotStore(true)
const session = {
id: 's1' as SessionId,
blank: true,
// Already composed from the staged preset, so applying the stage is a
// no-op that leaves the cue for the chip to play.
projectionValues: { agentPreset: 'minimal' },
}
const controller = chip(ROSTER, session, { developerTools })
await controller.load()
controller.stage('minimal', true)
await controller.apply()
await controller.apply()
expect(controller.store.getSnapshot().introduce).toBe(true)
expect(controller.store.getSnapshot().current).toBe('minimal')
controller.introduced()
expect(controller.store.getSnapshot().introduce).toBe(false)
})
it('reports a refused roster read without emptying the chip', async () => {
const controller = chip(ROSTER, undefined, { failList: 'host down' })
@@ -507,12 +541,14 @@ describe('the new-session chip controller', () => {
})
function remoteRoster(modeSelectionEnabled: boolean) {
function remoteRoster(defaultId: string) {
return {
ok: true as const,
value: {
presets: [{ id: 'standard', isDefault: true }],
modeSelectionEnabled,
presets: [
{ id: 'standard', isDefault: defaultId === 'standard' },
{ id: 'mine', isDefault: defaultId === 'mine' },
],
},
}
}
@@ -149,9 +149,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: '@Remote(\'list\') async remoteExportList(): Promise<AgentPresetRoster>',
description: 'Read the selection roster and chooser policy.',
description: 'Read the selection roster.',
parameters: [],
returns: 'Current presets, default and chooser policy.',
returns: 'Current presets, each marked when it is the default.',
},
{
signature: 'async resolve(id?: string): Promise<AgentPreset>',
@@ -4419,7 +4419,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'AgentPresetRoster',
declaration: 'export interface AgentPresetRoster {\n readonly presets: readonly AgentPresetRow[];\n readonly modeSelectionEnabled: boolean;\n}',
declaration: 'export interface AgentPresetRoster {\n readonly presets: readonly AgentPresetRow[];\n}',
},
{
name: 'AgentPresetRow',
@@ -18,8 +18,8 @@
en: bbff250eba0f1b89
zh: b20a47f82d8ab6e0
/deepseek-ai-dsh-agent-preset-registry/use-this-package/minimal-configuration:
en: 981929e49dca14b0
zh: 4969893ca131039b
en: cd28d9b4f46c46a8
zh: 4921d853f98469fe
/deepseek-ai-dsh-agent-preset-registry/understand-the-implementation:
en: 11a1a4847ffc68b4
zh: 9e1ca14d642b43ac
@@ -43,7 +43,7 @@ Choose an Agent’s tools, prompt sections and skills through declarative preset
|---|---|---|
| `default` | required | Preset ID used when none is requested |
The Web definitions come from the `dsh-web-app` bundle. Definitions are ordinary plugin rows; the registry neither scans directories nor accepts preset paths. The `selectedDefault` and `modeSelectionEnabled` volatile fields of the `agent-preset-registry` entry retain the user default and the chooser visibility; hiding the chooser uses the deployment `default`.
The Web definitions come from the `dsh-web-app` bundle. Definitions are ordinary plugin rows; the registry neither scans directories nor accepts preset paths. The `selectedDefault` volatile field of the `agent-preset-registry` entry retains the user default, which new sessions resolve over the deployment `default`. A profile patch may still carry the retired `modeSelectionEnabled` field; the registry declares no such field and neither reads nor rewrites it.
The registry writes no declarations. The `read` Remote renders one declaration’s child list back as entry-list YAML (`!!js` conditions included) so a client can show what a preset composes; nothing accepts YAML back. A new preset or an override of a shipped one is a bundle patch: an `insert` of a `@deepseek-ai/dsh-agent-preset` row, or a patch keyed by that row’s id, installed into the profile with `plugin_manager`; Creator mode authors such bundles in conversation.
@@ -43,7 +43,7 @@ kind: "package-reference"
|---|---|---|
| `default` | 必填 | 未显式指定时使用的 preset ID |
Web 内置定义来自 `dsh-web-app` bundle。定义使用普通插件行;注册表不扫描目录,也不接受 preset 路径。`agent-preset-registry` 条目的 volatile 字段 `selectedDefault` 与 `modeSelectionEnabled` 保留用户默认值和选择器可见性;隐藏选择器时使用部署 `default`。
Web 内置定义来自 `dsh-web-app` bundle。定义使用普通插件行;注册表不扫描目录,也不接受 preset 路径。`agent-preset-registry` 条目的 volatile 字段 `selectedDefault` 保留用户默认值,新会话优先使用它而不是部署 `default`。profile patch 仍可能带有已废弃的 `modeSelectionEnabled` 字段;注册表未声明该字段,既不读取也不重写它。
注册表不写入任何声明。`read` Remote 把一条声明的子插件列表按 entry-list YAML 方言(含 `!!js` 条件)渲染回来,供客户端展示 preset 的组成;没有任何接口接受 YAML 写回。新建 preset 或覆盖内置 preset 都是 bundle 补丁:插入一行 `@deepseek-ai/dsh-agent-preset`,或按该行 id 写覆盖补丁,再用 `plugin_manager` 安装到 profile;创造模式在对话中编写这类 bundle。
@@ -53,7 +53,6 @@ export class AgentPresetRegistry extends TypertRemoteService {
static Config = z.object({
default: z.string().required(),
selectedDefault: z.string().volatile(),
modeSelectionEnabled: z.boolean().default(true).volatile(),
})
private readonly owner: Context
private readonly definitions = new Map<string, Definition>()
@@ -72,12 +71,7 @@ export class AgentPresetRegistry extends TypertRemoteService {
}
/** Default preset for a subsequently created session. */
get defaultId(): string { return this.policy().defaultId }
private policy(): { enabled: boolean; defaultId: string } {
const enabled = this.config.modeSelectionEnabled.get()
return { enabled, defaultId: enabled ? this.config.selectedDefault.get() ?? this.config.default : this.config.default }
}
get defaultId(): string { return this.config.selectedDefault.get() ?? this.config.default }
/** Register and eagerly load a definition; activation failure remains visible in the roster.
* @param definition Parsed configuration supplied by the declaring plugin.
@@ -170,14 +164,13 @@ export class AgentPresetRegistry extends TypertRemoteService {
return rows.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity) || a.id.localeCompare(b.id))
}
/** Read the selection roster and chooser policy.
* @returns Current presets, default and chooser policy.
/** Read the selection roster.
* @returns Current presets, each marked when it is the default.
*/
@Remote('list')
async remoteExportList(): Promise<AgentPresetRoster> {
const policy = this.policy()
return { presets: (await this.list()).map(row => ({ ...row, isDefault: row.id === policy.defaultId })),
modeSelectionEnabled: policy.enabled }
const defaultId = this.defaultId
return { presets: (await this.list()).map(row => ({ ...row, isDefault: row.id === defaultId })) }
}
/** Resolve an identity without starting an Agent.
@@ -13,8 +13,6 @@ export interface AgentPreset {
export interface Config {
/** Deployment default when the caller omits a preset. */
default: string
/** User-selected default while the chooser is shown; edited through Settings. */
/** User-selected default; edited through Settings. */
selectedDefault: Volatile<string | undefined>
/** Whether new-session surfaces expose preset selection and the saved default applies. */
modeSelectionEnabled: Volatile<boolean>
}
@@ -22,8 +22,6 @@ export interface AgentPresetRow {
export interface AgentPresetRoster {
/** Every current declaration, including activation failures. */
readonly presets: readonly AgentPresetRow[]
/** Whether visible mode selection is enabled for unnamed new sessions. */
readonly modeSelectionEnabled: boolean
}
/** One preset's declared composition, rendered for reading. */
@@ -74,7 +74,6 @@ describe('declarative preset revisions', () => {
await expect(ctx.agentPresets.mount(scope.ctx, 'broken')).rejects.toThrow()
expect(await ctx.agentPresets.mount(scope.ctx)).toEqual({ id: 'standard' })
const roster = await ctx.agentPresets.remoteExportList()
expect(roster.modeSelectionEnabled).toBe(true)
expect(roster.presets.find(row => row.id === 'standard')?.isDefault).toBe(true)
})
@@ -217,20 +216,30 @@ it('allows an isolated service and resolves it through the Agent composition', a
expect(ctx.agentPresets.serviceFor({ ctx: scope.ctx }, 'loader')).toBeUndefined()
})
it('keeps policy preferences while hiding and restoring the chooser', async () => {
it('resolves the saved default over the deployment default, and drops a removed override', async () => {
const ctx = await harness({ live: true })
contexts.push(ctx)
const live = liveRegistries.get(ctx)!
await live.update({ selectedDefault: 'minimal', modeSelectionEnabled: true })
expect(ctx.agentPresets.defaultId).toBe('minimal')
await live.update({ modeSelectionEnabled: false })
expect(ctx.agentPresets.defaultId).toBe('standard')
await live.update({ modeSelectionEnabled: true })
await live.update({ selectedDefault: 'minimal' })
expect(ctx.agentPresets.defaultId).toBe('minimal')
await live.replace({ default: 'standard' })
expect(ctx.agentPresets.defaultId).toBe('standard')
})
it('ignores a retired modeSelectionEnabled field in the user patch', async () => {
const ctx = await harness({ live: true })
contexts.push(ctx)
const live = liveRegistries.get(ctx)!
await declare(ctx, contribution('minimal'))
// A patch written before Developer tools became the only gate still carries
// this key; the Loader's declared fields simply do not include it.
await live.update({ selectedDefault: 'minimal', modeSelectionEnabled: false })
expect(ctx.agentPresets.defaultId).toBe('minimal')
expect((await ctx.agentPresets.remoteExportList()).presets.find(row => row.id === 'minimal')?.isDefault).toBe(true)
// Neither read nor rewritten: the raw entry keeps the key it was loaded with.
expect(live.entry.options.config).toMatchObject({ selectedDefault: 'minimal', modeSelectionEnabled: false })
})
it('keeps its own instance off the generated Settings pages', () => omitsGeneratedPage(async (ctx) => {
await ctx.plugin(Loader)
await ctx.plugin(SessionProjectionRegistry)
@@ -25,7 +25,7 @@ export const remoteDefaultResponses: RemoteTable = {
failures: [],
}),
// ui-agent-preset hero chip and header label on first mount.
'agentPresets/list': ok({ presets: [], modeSelectionEnabled: true }),
'agentPresets/list': ok({ presets: [] }),
// cordis-client-runner `ClientCordisInspectRegistry.sync` at apply and on `connection/reset`.
'dynamicCordisRunner/syncInspectManifest': ok(null),
// ui-cordis inventory at apply and on `connection/reset`.
-5
View File
@@ -457,13 +457,8 @@
"ddca8a18cd7755688ea48674c48c3c8a6107186815ea91f516424bbed0e1c518": 1
},
"packages/client/ui-agent-preset/tests/components.client.spec.tsx": {
"0df95ae2a37a0b3403599b7478d4d59fa2611cb1189b67e8b3fd0f4fcbf500e1": 1,
"6c63f71c0aeb1a9a97ec28a3242f77eef021ecfcee48238f17592eb2f1040c09": 1
},
"packages/client/ui-agent-preset/tests/settings-store.client.spec.ts": {
"74d9d12b6f146dcd600e84c9fde4d8e9e3d4e66aa485cc598ef4e763188b0eac": 1,
"8dc4dd33a728f8be87bedb987dacefe36155443f0d2e0cc58da9716947d85920": 1
},
"packages/client/ui-approval/tests/ui-approval.client.spec.tsx": {
"3e392ff0165a51a6ac716515b99af35ec152f89607cff72080cb9afbcff63f46": 1,
"d3a081f97422a352526b7014a6aa4c6c8f78cb27587568bc4150232db2037198": 1