diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 8fe0080707..714407c69e 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -430,3 +430,72 @@ describe('web e2e: agent-preset selection', () => { expect(tripwire.warnings).toEqual([]) }) }) + +it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without changing drafts or defaults', async (developerTools) => { + const scaffold = await launchWebScaffold({ developerTools, agentPresets: { default: 'standard' } }) + let browser: Browser | undefined + try { + browser = await chromium.launch() + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-creator')) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const creator = scaffold.ctx.agents.list()[0] + if (creator === undefined) throw new Error('Connecting the workspace did not create a Session') + expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('standard') + await page.getByRole('button', { name: 'Standard mode', exact: true }).waitFor() + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + const draft = 'Keep this unsent plugin idea.' + await writeComposerDraft(page, composer, draft) + + await page.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click() + await page.getByRole('button', { name: 'Choose how to add a plugin', exact: true }).click() + await Promise.all([ + page.waitForResponse('**/api/agentPresets/select'), + page.getByRole('menuitem', { name: /^Let the agent create a plugin/ }).click(), + ]) + const picker = page.getByTitle('Choose the agent preset for your new task', { exact: true }).filter({ hasText: 'Creator mode' }) + await picker.waitFor() + await composer.filter({ hasText: draft }).waitFor() + expect(await composer.innerText()).toBe(draft) + expect(await picker.getAttribute('aria-haspopup')).toBe('menu') + expect(await page.getByRole('dialog', { name: 'Add plugin', exact: true }).count()).toBe(0) + expect(scaffold.ctx.sessionProjections.stateOf(creator.session, 'agentPreset')).toBe('cordis') + expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('cordis') + expect(scaffold.ctx.tools.schemas(creator).map(tool => tool.name)) + .toEqual(expect.arrayContaining(['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])) + expect(creator.session.snapshotEvents().some(event => event.type === 'agent-preset/selected' + && event.data.agentPreset === 'cordis')).toBe(true) + expect(creator.session.snapshotEvents().some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false) + expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: developerTools }) + expect(scaffold.ctx.agentPresets.defaultId).toBe('standard') + + // Close a fixture turn on the real Creator Session without requesting a model. + await writeComposerDraft(page, composer, '') + creator.session.append('turn/start', { turn: 1 }) + creator.session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Creator fixture completed without a model call.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + creator.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(creator.session) + await page.getByText('Creator fixture completed without a model call.', { exact: true }).waitFor() + const newSession = page.getByRole('button', { name: 'New session', exact: true }).filter({ hasText: 'New Session' }) + await Promise.all([page.waitForResponse('**/api/session/create'), newSession.click()]) + expect(scaffold.ctx.agents.list().find(agent => agent.id !== creator.id)).toBeDefined() + const next = scaffold.ctx.agents.list().find(agent => agent.id !== creator.id)! + expect(next.id).not.toBe(creator.id) + expect(next.session.header.agentPreset).toBe('standard') + expect(scaffold.ctx.sessionProjections.stateOf(next.session, 'agentPreset')).toBe('standard') + expect(scaffold.ctx.agentPresets.composedPreset(next.ctx)).toBe('standard') + expect(scaffold.ctx.sessionProjections.stateOf(creator.session, 'agentPreset')).toBe('cordis') + await page.getByRole('button', { name: 'Standard mode', exact: true }).waitFor() + expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: developerTools }) + expect(scaffold.ctx.agentPresets.defaultId).toBe('standard') + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + await browser?.close() + await scaffold.close() + } +}) diff --git a/apps/web/tests/expected/plugin-config/official.expected.md b/apps/web/tests/expected/plugin-config/official.expected.md index 3906b58624..f4b2293eb0 100644 --- a/apps/web/tests/expected/plugin-config/official.expected.md +++ b/apps/web/tests/expected/plugin-config/official.expected.md @@ -2,7 +2,9 @@ - text: 安装、启用和配置插件 - button "插件说明" - button "刷新" -- button "添加插件" +- group "添加插件": + - button "添加插件" + - button "选择添加插件方式" - heading "官方" [level=3] - text: "8" - list: diff --git a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md index 23d74b2077..fa9fd12631 100644 --- a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md +++ b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md @@ -2,7 +2,9 @@ - text: 安装、启用和配置插件 - button "插件说明" - button "刷新" -- button "添加插件" +- group "添加插件": + - button "添加插件" + - button "选择添加插件方式" - heading "官方" [level=3] - text: "8" - list: diff --git a/apps/web/tests/expected/plugin-manager/loading.expected.md b/apps/web/tests/expected/plugin-manager/loading.expected.md index 9c6fea0d43..4cf8d9ea23 100644 --- a/apps/web/tests/expected/plugin-manager/loading.expected.md +++ b/apps/web/tests/expected/plugin-manager/loading.expected.md @@ -2,7 +2,9 @@ - text: 安装、启用和配置插件 - button "插件说明" - button "刷新" [disabled] -- button "添加插件" [disabled] +- group "添加插件": + - button "添加插件" [disabled] + - button "选择添加插件方式" [disabled] - status "正在读取插件…" 1680px: 4 rows; page/group headers, rows, icons, text lines and blank action spaces align within 0.1px diff --git a/apps/web/tests/expected/plugin-manager/manager.expected.md b/apps/web/tests/expected/plugin-manager/manager.expected.md index 7e126cd61b..89ca0d1416 100644 --- a/apps/web/tests/expected/plugin-manager/manager.expected.md +++ b/apps/web/tests/expected/plugin-manager/manager.expected.md @@ -2,7 +2,9 @@ - text: 安装、启用和配置插件 - button "插件说明" - button "刷新" -- button "添加插件" +- group "添加插件": + - button "添加插件" + - button "选择添加插件方式" - heading "官方" [level=3] - text: "8" - list: diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 6a0da11f0f..39ae03e691 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -124,7 +124,7 @@ describe('web e2e: plugin manager', () => { expect(await skeleton.getAttribute('aria-label')).toBe('正在读取插件…') expect(await panel.getAttribute('aria-busy')).toBe('true') const actions = panel.locator(':scope > header > div:last-child button') - expect(await actions.count()).toBe(2) + expect(await actions.count()).toBe(3) for (const action of await actions.all()) expect(await action.isDisabled()).toBe(true) expect(await panel.getByRole('button', { name: '插件说明' }).isEnabled()).toBe(true) const loadingAria = await captureStableAria(probe, '[data-plugin-panel]', scaffold.workspaceCwd) @@ -832,6 +832,16 @@ describe('web e2e: plugin manager', () => { const dialog = page.getByRole('dialog', { name: '添加插件' }) await dialog.waitFor({ timeout: 10_000 }) const field = dialog.getByRole('textbox', { name: '包名或地址' }) + expect(await page.getByRole('menu').count()).toBe(0) + await expect.poll(() => field.evaluate(element => document.activeElement === element)).toBe(true) + await dialog.getByRole('button', { name: '关闭', exact: true }).click() + await dialog.waitFor({ state: 'hidden' }) + await panel.getByRole('button', { name: '选择添加插件方式', exact: true }).click() + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: /^安装第三方插件/ }).click() + await menu.waitFor({ state: 'hidden' }) + await dialog.waitFor({ state: 'visible' }) + await expect.poll(() => field.evaluate(element => document.activeElement === element)).toBe(true) const install = dialog.getByRole('button', { name: '安装', exact: true }) expect(await install.isDisabled()).toBe(true) expect(await dialog.getByRole('note').textContent()).toContain('请确认插件来源可信') diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index a78b1185a1..aec206af8c 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/slots.md /web-client-slots: - en: bda026282132e290 - zh: 3e3faf96c72420d6 + en: 8d33b164230344fa + zh: 13a930ab96280744 /web-client-slots/declaration-and-lifecycle: en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index 13b47b7460..42da307ddd 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -8,6 +8,8 @@ This page documents slot ownership, component inputs, extension APIs, and the sh `plugins.bundle.config` supplies bundle detail configuration, keyed by npm package name. `plugins.bundle.activation` renders optional guidance after user-requested enablement, with owner callbacks to dismiss or open that bundle’s details. `conversation.input.activity` supplies one action between the model selector and Send, with toolbar expansion released on unmount. +The plugin catalog declares `plugins.add.actions`, a root-scoped list for `MenuItemButton` rows after installation in the Add plugin menu. Its owner supplies `onDismiss()` to close the menu before starting an action. The slot follows the owning Plugins page declaration lifetime. + ## Declaration and lifecycle `SlotMap` is the compile-time registry. A package declaration-merges the key, cardinality, scope, owner props, keyed props, and optional slot-level inject face. The runtime declaration is the matching `children` entry on the component that owns the render location. @@ -133,6 +135,7 @@ root │ ├─ settings.models.footer │ └─ settings.plugins.tab ├─ main +│ ├─ plugins.add.actions │ ├─ plugins.item │ ├─ plugins.bundle.config │ ├─ plugins.row.config diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 42bf724545..10e6338d0f 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -8,6 +8,8 @@ Slots 是 Web Client 的类型化 React 组合系统。[`dsh-client-ui-slots`](. `plugins.bundle.config` 以 npm 包名为 key,提供 Bundle 详情配置。`plugins.bundle.activation` 在用户显式启用后渲染可选引导,由拥有者提供关闭引导和打开该 Bundle 详情的回调。`conversation.input.activity` 提供模型选择器与发送按钮之间的单个活动控件,可展开工具栏并在卸载时释放展开状态。 +插件目录声明 `plugins.add.actions`,它是 root 作用域的 list,在添加插件菜单的安装项之后提供 `MenuItemButton` 行。owner 提供 `onDismiss()`,用于开始动作前关闭菜单。该 slot 遵循所属插件页面声明的生命周期。 + ## 声明与生命周期 `SlotMap` 是编译期注册表。包通过声明合并写入 key、cardinality(基数)、scope、owner props、keyed props 与可选的 slot 级 inject face。运行时声明则是拥有该渲染位置的组件在 `children` 中给出的对应条目。 @@ -133,6 +135,7 @@ root │ ├─ settings.models.footer │ └─ settings.plugins.tab ├─ main +│ ├─ plugins.add.actions │ ├─ plugins.item │ ├─ plugins.bundle.config │ ├─ plugins.row.config diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 14bb9ffa04..a1086951fe 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: b3ad7867f23dad1c /deepseek-ai-dsh-client-ui-agent-preset/use-this-package: - en: fb8633d84f7ae9df - zh: 85dddc83f4abe686 + en: abb24ddb24f5588d + zh: 2c58c8cd0e2a335e /deepseek-ai-dsh-client-ui-agent-preset/understand-the-implementation: - en: 7813f0063c15e241 - zh: 6eabc242edfc45ec + en: 4c88c83529317389 + zh: 5125122bdacfa3da /deepseek-ai-dsh-client-ui-agent-preset/further-exploration: en: bbae8d79844bc481 zh: 4302107fd1f460e6 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 3c8ed422c3..b66072911d 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -33,6 +33,10 @@ Turning Coding Tools off clears all unapplied choices through the existing Devel 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. +**Let the agent create a plugin** in the Plugins page's **Add plugin** arrow menu enters the same Creator flow as Settings. It submits no message and preserves unsent drafts. While the roster loads or Creator is unavailable, the menu item is disabled with an explanation. Both entries show a Toast with the reason if the Host refuses the preset switch. + +Entering Creator selects `cordis` for the receiving blank Session without changing the new-task default or Coding Tools setting. If no workspace or blank Session is bound yet, the choice waits for that binding. After the choice is applied, the Creator Session keeps its preset; a later newly created Session uses the configured default, such as Standard. + ## Understand the implementation @@ -41,6 +45,8 @@ Known shipped presets offer mode details and usage examples in a read-only dialo `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. +`CreatePluginMenuItem` contributes to `plugins.add.actions` using the shared roster store. Its selection calls the owner's `onDismiss()` before the same `startCreatorDraft` callback exposed to Settings as `creatorDraft`. That callback stages `cordis` through `AgentPresetSeatController` and opens the task through `uiWorkspace.startSession`; it can reuse a blank Session and applies the staged choice when a Session binding becomes available. The choice is consumed once applied. Both Coding Tools states use the same picker and selection store, and `AgentPresetSeat` renders refusals through the shared `Toast` component. + diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index a6f2d97f44..434b74e026 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -33,6 +33,10 @@ kind: "package-reference" 已知的内置预设提供只读的模式说明与使用示例对话框。各页签保留各自的滚动位置;关闭后焦点回到打开它的操作。帮助不会改变新任务默认值。默认徽标取代卡片的分组徽标,预设 id 显示在标题旁。指南文案与示例归本包所有。 +插件页**添加插件**箭头菜单中的**让 Agent 创建插件**进入与设置页相同的创造流程,不发送消息,并保留未发送的草稿。读取预设列表或创造模式不可用时,菜单项禁用并说明原因。Host 拒绝切换预设时,两处入口均通过 Toast 显示原因。 + +进入创造模式会为接收该选择的空白 Session 选择 `cordis`,不改变新任务默认值或代码工作工具设置。尚未绑定工作区或空白 Session 时,选择等待绑定完成后应用。应用后,创造 Session 保留该预设;之后真正创建的新 Session 使用配置的默认值,例如标准模式。 + ## 理解实现 @@ -41,6 +45,8 @@ kind: "package-reference" `agentPresets/list` 提供列表并标记当前默认值,`agentPresets/read` 为查看器提供一条声明的 YAML;默认值的修改写入 `agent-preset-registry` settings 命名空间。选择器、空白会话同步和只读会话标签使用记录的 preset 标识。连接重置和设置更新会刷新列表。 +`CreatePluginMenuItem` 使用共享的预设列表 store,向 `plugins.add.actions` 贡献菜单项。选择时先调用页面传入的 `onDismiss()`,再调用与设置页 `creatorDraft` 相同的 `startCreatorDraft` 回调。该回调通过 `AgentPresetSeatController` 暂存 `cordis`,再通过 `uiWorkspace.startSession` 打开任务;它可以复用空白 Session,并在 Session 绑定可用时应用暂存选择。暂存选择应用后即清除。代码工作工具开启或关闭时均使用同一个选择器和选择 store,`AgentPresetSeat` 通过共享的 `Toast` 组件显示拒绝原因。 + diff --git a/packages/client/ui-agent-preset/package.json b/packages/client/ui-agent-preset/package.json index be4ef13690..2f5bc155e6 100644 --- a/packages/client/ui-agent-preset/package.json +++ b/packages/client/ui-agent-preset/package.json @@ -58,6 +58,7 @@ "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", diff --git a/packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx b/packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx index afa2b5a2ad..07e4aa84c8 100644 --- a/packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx +++ b/packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx @@ -37,6 +37,8 @@ export interface AgentPresetSeatInjected { load: () => Promise /** Stage one preset for the next session; resolves to a refusal, or undefined. */ select: (id: string) => Promise + /** Acknowledge the refusal whose Toast finished. */ + dismissRefusal: (error: AgentPresetSeatState['error']) => void /** Clear the one-shot introduce cue once the chip has played it. */ introduced: () => void } @@ -74,10 +76,10 @@ export type AgentPresetSeatProps = /** * Render the new-session agent-preset chip. * @param props - composed slot props. - * @returns The chip, or null outside the main view or before the roster provides a preset choice. + * @returns The chip and any pending selection refusal, or null outside the main view. */ export function AgentPresetSeat({ - sessionId, useSessionRetainInfo, load, select, introduced, useAgentPresetSeat, useDeveloperTools, t, + sessionId, useSessionRetainInfo, load, select, dismissRefusal, introduced, useAgentPresetSeat, useDeveloperTools, t, }: AgentPresetSeatProps) { const developerTools = useDeveloperTools(value => value) const state = useAgentPresetSeat(snapshot => snapshot) @@ -87,7 +89,14 @@ export function AgentPresetSeat({ // The seq keys the banner, so picking the same broken preset twice replays // 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 [toast, setToast] = useState<{ seq: number; error: Exclude } | null>(null) + + useEffect(() => { + if (state.error !== null && typeof state.error === 'object') { + toastSeq.current += 1 + setToast({ seq: toastSeq.current, error: state.error }) + } else setToast(null) + }, [state.error]) useEffect(() => { void load() @@ -127,9 +136,8 @@ export function AgentPresetSeat({ return () => { window.clearTimeout(done) } }, [state.introduce, ready, label, introduced]) - // Nothing to choose between: the deployment composes no presets and every - // session shares the host composition. - if (!main || !ready) return null + // A refused initial composition still needs its Toast when there is no chip to show. + if (!main) 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. @@ -153,7 +161,7 @@ export function AgentPresetSeat({ return ( <> - 0} onClose={() => { setOpen(false) }} items={options.map((option) => { @@ -173,19 +181,7 @@ export function AgentPresetSeat({ selectedId={state.current} onSelect={(id) => { setOpen(false) - const picked = options.find(option => option.id === id) - // The fallback is for the row shape `find` cannot promise; the menu's - // items ARE `options`, so an emitted id is always one of them. - /* v8 ignore next */ - const name = picked === undefined ? id : presetDisplayText(picked, t).name - void select(id).then((refusal) => { - // Announced only for a pick a person just made: `apply()` also runs - // when a session becomes current, and a banner over that would - // report a refusal nobody asked for. - if (refusal === undefined) return - toastSeq.current += 1 - setToast({ seq: toastSeq.current, text: t('switchRefused', { name, reason: refusal }) }) - }) + void select(id) }} align="start" portal @@ -196,7 +192,7 @@ export function AgentPresetSeat({ className={css.seat} aria-haspopup="menu" aria-expanded={open && options.length > 0} - title={state.error ?? t('seatHint')} + title={(typeof state.error === 'object' ? state.error?.reason : state.error) ?? t('seatHint')} disabled={state.busy || options.length === 0} onClick={() => { setOpen(value => !value) }} > @@ -205,11 +201,11 @@ export function AgentPresetSeat({ )} - /> + />} {toast !== null && ( } holdMs={REFUSAL_HOLD_MS} // The composer card, which is the content column this chip sits @@ -217,7 +213,7 @@ export function AgentPresetSeat({ // Absent, the banner centers on the window, which is off-center // whenever the sidebar is open. anchor={document.querySelector('[data-composer-card]')} - onDone={() => { setToast(null) }} + onDone={() => { dismissRefusal(toast.error) }} /> )} diff --git a/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.module.css b/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.module.css new file mode 100644 index 0000000000..e2540e0861 --- /dev/null +++ b/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.module.css @@ -0,0 +1,19 @@ +.copy { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + white-space: normal; +} + +.description { + display: -webkit-box; + max-height: 36px; + overflow: hidden; + overflow-wrap: anywhere; + color: var(--dsw-alias-label-secondary); + font-size: 12px; + line-height: 18px; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} diff --git a/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.tsx b/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.tsx new file mode 100644 index 0000000000..e4bbf21d02 --- /dev/null +++ b/packages/client/ui-agent-preset/src/client/CreatePluginMenuItem.tsx @@ -0,0 +1,50 @@ +/** Create a plugin through the existing Creator flow from the Add plugin menu. */ +import { useEffect } from 'react' +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import { IconAgentPresetOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import type { AgentPresetSettingsState } from './settings-store.ts' +import css from './CreatePluginMenuItem.module.css' + +/** Roster and navigation supplied by the preset plugin. */ +export interface CreatePluginMenuItemInjected { + hooks: { + agentPresets: SnapshotStore + } + load: () => Promise + startCreatorDraft: () => void +} + +type CreatePluginMenuItemProps = PropsRuntime<'plugins.add.actions'> + & PropsLocale<'settings.agentPreset'> & InjectFace + +/** + * Close the Add plugin menu before opening Creator without sending a message. + * @param props - locale, roster, dismissal and navigation callbacks. + * @returns a stable menu item that explains why Creator is unavailable. + */ +export function CreatePluginMenuItem({ + t, useAgentPresets, load, onDismiss, startCreatorDraft, +}: CreatePluginMenuItemProps) { + const roster = useAgentPresets(state => state) + const enabled = roster.status === 'ready' && roster.options.some(option => option.id === 'cordis') + useEffect(() => { void load() }, [load]) + + let description = t('createPluginDescription') + if (roster.status === 'idle' || roster.status === 'loading') description = t('createPluginChecking') + else if (roster.status === 'error' || roster.status === 'unavailable') description = t('createPluginUnavailable') + else if (!enabled) description = t('createPluginMissing') + + return ( + } disabled={!enabled} onSelect={() => { + onDismiss() + startCreatorDraft() + }}> + + {t('createPlugin')} + {description} + + + ) +} diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index b2f0b1fd87..7869f9cf4d 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -31,8 +31,10 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' // Type-only: pulls the Workspace UI navigation service merge (ctx.uiWorkspace). import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' import { AgentPresetLabel } from './AgentPresetLabel.tsx' +import { CreatePluginMenuItem } from './CreatePluginMenuItem.tsx' import type { AgentPresetLabelInjected } from './AgentPresetLabel.tsx' import { AgentPresetSeat } from './AgentPresetSeat.tsx' import type { AgentPresetSeatInjected } from './AgentPresetSeat.tsx' @@ -186,6 +188,7 @@ export function apply(ctx: ClientContext): void { hooks: { agentPresetSeat: seat.store, developerTools: ctx.configForms.developerTools.enabled }, load: () => seat.load(), select: (id: string) => seat.select(id), + dismissRefusal: (error) => { seat.dismissRefusal(error) }, introduced: () => { seat.introduced() }, } } @@ -195,13 +198,15 @@ export function apply(ctx: ClientContext): void { load: () => controller.load(), }) + const startCreatorDraft = () => { + const seat = mainBlankSeat() ?? unboundSeat + seat.stage('cordis', true) + scope.uiWorkspace.startSession() + void seat.apply() + } + scope.effect(() => { - creatorDraft = () => { - const seat = mainBlankSeat() ?? unboundSeat - seat.stage('cordis', true) - scope.uiWorkspace.startSession() - void seat.apply() - } + creatorDraft = startCreatorDraft const chip = scope.slots.register({ name: 'conversation.hero.agentPreset', locale: 'settings.agentPreset', @@ -221,6 +226,17 @@ export function apply(ctx: ClientContext): void { label() } }, 'ui-agent-preset: new-session chip and header label') + + scope.slots.inject('plugins.add.actions', () => scope.slots.register({ + name: 'plugins.add.actions', + id: 'create-plugin', + locale: 'settings.agentPreset', + inject: () => ({ + hooks: { agentPresets: controller.store }, + load: () => controller.load(), + startCreatorDraft, + }), + }, CreatePluginMenuItem)) }) /** Capture the exact blank Session one Settings action may update. */ diff --git a/packages/client/ui-agent-preset/src/client/locales.ts b/packages/client/ui-agent-preset/src/client/locales.ts index 165e0cc556..1863c2e108 100644 --- a/packages/client/ui-agent-preset/src/client/locales.ts +++ b/packages/client/ui-agent-preset/src/client/locales.ts @@ -28,6 +28,11 @@ export type AgentPresetSettingsKey = | 'standardUnavailable' | 'close' | 'creatorDraft' + | 'createPlugin' + | 'createPluginDescription' + | 'createPluginChecking' + | 'createPluginUnavailable' + | 'createPluginMissing' /** English copy. */ export const en: Record = { @@ -66,6 +71,11 @@ export const en: Record = { close: 'Close', creatorDraft: 'Let the agent help me create a preset', + createPlugin: 'Let the agent create a plugin', + createPluginDescription: 'Enter Creator mode and make your own DSH plugin', + createPluginChecking: 'Checking whether Creator mode is available', + createPluginUnavailable: 'Temporarily unavailable. Reopen this menu to retry', + createPluginMissing: 'Creator mode is not included in this configuration', } @@ -102,6 +112,11 @@ export const zh: Record = { close: '关闭', creatorDraft: '让 Agent 帮我创建预设模式', + createPlugin: '让 Agent 创建插件', + createPluginDescription: '进入创造模式,制作属于你的 DSH 插件', + createPluginChecking: '正在确认创造模式是否可用', + createPluginUnavailable: '暂时不可用,请重新打开菜单重试', + createPluginMissing: '当前配置未提供创造模式', } diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index b24c7f2622..dfa2c69945 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -25,8 +25,8 @@ export interface AgentPresetSeatState { options: readonly AgentPresetOption[] /** The staged choice, empty until the roster loads. */ current: string - /** A rejected apply's message, cleared by the next attempt. */ - error: string | null + /** An error message; explicit selection failures also carry the preset for a Toast. */ + error: string | { readonly preset: AgentPresetOption; readonly reason: string } | null busy: boolean /** * One-shot cue that the chip should introduce itself (the creator-draft @@ -91,8 +91,10 @@ export class AgentPresetSeatController { const generation = ++this.loadGeneration const roster = await readRoster(this.ctx) if (generation !== this.loadGeneration) return + // A roster refresh can finish after a selection; leave its announcement for the chip. + const error = this.store.getSnapshot().error if (!roster.ok) { - this.set({ error: roster.error }) + if (typeof error !== 'object' || error === null) this.set({ error: roster.error }) return } const { presets } = roster.value @@ -107,7 +109,7 @@ export class AgentPresetSeatController { // once the flow's session is current, so the reply can arrive after // apply() already composed it. current: this.staged.id ?? (session === undefined ? this.fallback : presetOf(session) ?? ''), - error: null, + error: typeof error === 'object' ? error : null, introduce: this.staged.introduce, }) await this.apply() @@ -117,11 +119,8 @@ export class AgentPresetSeatController { * Stage one preset for the next session, applying it immediately when a * blank session is already current. * - * The refusal is returned as well as stored, because the two readers need - * different things from it: the chip's own label carries the standing state, - * while the caller that made this pick is the one that has to say why the - * label came back — and only it knows the pick was a person's, not the - * applier catching up with a session that just became current. + * The refusal is stored for the chip's announcement and returned to callers + * such as Settings that also report the result of their own write. * @param id - the preset to stage. * @returns the refusal text, or undefined once the pick settled. */ @@ -148,6 +147,15 @@ export class AgentPresetSeatController { this.set({ current: id, error: null, introduce }) } + /** Acknowledge a displayed refusal without dismissing a newer attempt. + * @param refusal - the selection error whose Toast finished. + */ + dismissRefusal(refusal: AgentPresetSeatState['error']): void { + if (refusal !== null && typeof refusal === 'object' && this.store.getSnapshot().error === refusal) { + this.set({ error: refusal.reason }) + } + } + /** * Capture the exact blank Session a Settings action may bring along. * @returns its id, or undefined outside a blank Session. @@ -210,26 +218,27 @@ export class AgentPresetSeatController { const completion = Promise.withResolvers() this.pendingSelection = completion.promise this.clearStage() + const refuse = (reason: string) => { + this.set({ + error: { reason, preset: this.store.getSnapshot().options.find(option => option.id === staged) ?? { id: staged } }, + current: this.staged.id ?? presetOf(session) ?? '', + }) + return reason + } try { this.set({ busy: true, error: null }) const result = await this.ctx.remote.agentPresets.select(session.id, staged) if (!result.ok) { const { error } = result + // Prefer the bare cause; the Toast already names the rejected preset. const refusal = 'reason' in error.details && typeof error.details.reason === 'string' ? error.details.reason : error.message - this.set({ - // A refusal carries its cause twice: `message` wraps it in the - // roster's own frame, which names the preset the surface reporting - // this already names, and a `reason` detail holds the same cause - // without it. Read by the detail rather than by the code, because - // every refusal that has a cause to give names it the same way. - error: refusal, - current: this.staged.id ?? presetOf(session) ?? '', - }) - return refusal + return refuse(refusal) } this.set({ current: this.staged.id ?? result.value }) + } catch (error) { + return refuse(error instanceof Error ? error.message : String(error)) } finally { this.pendingSelection = undefined this.set({ busy: false }) diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index 8c608faec6..459c4db863 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -22,6 +22,7 @@ import type { AgentPresetSectionInjected } from '../src/client/AgentPresetSectio import { AgentPresetSeat } from '../src/client/AgentPresetSeat.tsx' import type { AgentPresetSeatInjected } from '../src/client/AgentPresetSeat.tsx' import { AgentPresetSeatController } from '../src/client/seat-store.ts' +import { CreatePluginMenuItem, type CreatePluginMenuItemInjected } from '../src/client/CreatePluginMenuItem.tsx' import { AgentPresetSectionController } from '../src/client/section-store.ts' import { apply as hostApply } from '../src/index.ts' import type { AgentPresetRow } from '@deepseek-ai/dsh-agent-preset-registry/types' @@ -373,6 +374,46 @@ describe('ui-agent-preset apply', () => { await vi.waitFor(() => { expect(slots.entries('settings.section')).toHaveLength(1) }) }) + it('binds the Add plugin menu item to the roster and Creator flow and removes it with the feature', async () => { + const { ctx, slots, setDeveloperTools } = await bench() + try { + slots.register({ + name: 'root', + children: { + 'settings.section': { kind: 'list', scope: 'root' }, + conversation: { kind: 'single', scope: 'root' }, + 'plugins.add.actions': { kind: 'list', scope: 'root' }, + }, + } as never, () => null) + declareConversation(slots) + ctx.provide('conversation', {} as never) + ctx.provide('sessions', sessionsDouble(ctx, { byId: {} }) as never) + const uiWorkspace = uiWorkspaceDouble() + ctx.provide('uiWorkspace', uiWorkspace as never) + const feature = ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'uiWorkspace'], apply }) + await feature.await() + + const entry = slots.entries('plugins.add.actions')[0]! + expect(entry.component).toBe(CreatePluginMenuItem) + const action: Partial | undefined = entry.inject?.() + if (action?.load === undefined || action.hooks === undefined || action.startCreatorDraft === undefined) { + throw new Error('expected the injected Create plugin actions') + } + await action.load() + expect(action.hooks.agentPresets.getSnapshot().options).toEqual([{ id: 'standard' }]) + + await setDeveloperTools(false) + action.startCreatorDraft() + expect(uiWorkspace.starts).toHaveLength(1) + expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(false) + + await feature.dispose() + expect(slots.entries('plugins.add.actions')).toHaveLength(0) + } finally { + await ctx.fiber.dispose() + } + }) + it('hands the section its own store, live Coding Tools preference, and default write', async () => { const { ctx, slots, setDeveloperTools } = await bench() ctx.provide('sessions', sessionsDouble(ctx, { byId: {} }) as never) @@ -1099,8 +1140,9 @@ describe('ui-agent-preset apply', () => { conversation() }) - it('keeps the applied composition when the roster load lands late', async () => { - const { ctx, slots, calls } = await bench() + it.each([false, true])('keeps the bound Creator outcome when the roster load lands late (refused: %s)', async (refused) => { + const selection = Promise.withResolvers() + const { ctx, slots, calls } = await bench({ selectGate: selection.promise }) declareRoot(slots) const conversation = declareConversation(slots) ctx.provide('conversation', {} as never) @@ -1119,6 +1161,7 @@ describe('ui-agent-preset apply', () => { const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)() const injectSeat = slots.entries('conversation.hero.agentPreset')[0]! .inject as unknown as (sessionId?: SessionId) => AgentPresetSeatInjected + const unboundSeat = injectSeat() await section.load() section.startCreatorDraft?.() @@ -1126,18 +1169,28 @@ describe('ui-agent-preset apply', () => { state.byId['s1'] = { id: 's1', blank: true } sessions.notify() const boundSeat = injectSeat(SessionId('s1')) - await boundSeat.load() + const loading = boundSeat.load() await vi.waitFor(() => { expect(calls).toContain('select:cordis') }) + if (refused) selection.reject(new Error('Creator failed to mount')) + else selection.resolve(undefined) + await loading + await vi.waitFor(() => { expect(boundSeat.hooks.agentPresetSeat.getSnapshot().busy).toBe(false) }) // The chip mounts with the flow's session, so its roster load can land // AFTER the stage was consumed; the session's own composition is what // the display must keep — not the deployment default. state.byId['s1'] = { - id: 's1', blank: true, projectionValues: { agentPreset: 'cordis' }, + id: 's1', blank: true, projectionValues: { agentPreset: refused ? null : 'cordis' }, } await boundSeat.load() - expect(boundSeat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis') + expect(boundSeat.hooks.agentPresetSeat.getSnapshot()).toMatchObject({ + current: refused ? '' : 'cordis', + error: refused ? { preset: { id: 'cordis' }, reason: 'Creator failed to mount' } : null, + }) + expect(unboundSeat.hooks.agentPresetSeat.getSnapshot().error).toBeNull() + boundSeat.dismissRefusal(boundSeat.hooks.agentPresetSeat.getSnapshot().error) + expect(boundSeat.hooks.agentPresetSeat.getSnapshot().error).toBe(refused ? 'Creator failed to mount' : null) conversation() }) @@ -1189,7 +1242,7 @@ describe('AgentPresetSeatController reconciliation', () => { await expect(settings).resolves.toBe(refuseLatest ? 'selection refused' : undefined) expect(controller.store.getSnapshot()).toMatchObject({ current: refuseLatest ? 'standard' : 'cordis', busy: false, - error: refuseLatest ? 'selection refused' : null, + error: refuseLatest ? { preset: { id: 'cordis' }, reason: 'selection refused' } : null, }) }) @@ -1302,20 +1355,27 @@ describe('AgentPresetSeatController reconciliation', () => { expect(controller.store.getSnapshot().current).toBe('') }) - it('restores an empty current value after a refused switch for an uncomposed Session', async () => { - const select = () => Promise.resolve({ - ok: false as const, error: new RemoteError('gateway/internal', 'selection rejected', {}), - }) + it.each(['returned', 'thrown'] as const)('restores an uncomposed Session after a %s selection failure', async (failure) => { + const select = () => failure === 'thrown' + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise a transport rejection with a non-Error reason. + ? Promise.reject('selection rejected') + : Promise.resolve({ ok: false as const, error: new RemoteError('gateway/internal', 'selection rejected', {}) }) const controller = new AgentPresetSeatController({ ...developerTools(), - remote: { agentPresets: { select } }, + remote: { agentPresets: { + select, + list: () => Promise.resolve({ ok: true, value: { presets: [{ id: 'standard', isDefault: true }] } }), + } }, } as never, () => ({ id: SessionId('uncomposed'), blank: true })) await controller.select('minimal') expect(controller.store.getSnapshot()).toMatchObject({ - busy: false, current: '', error: 'selection rejected', + busy: false, current: '', error: { preset: { id: 'minimal' }, reason: 'selection rejected' }, }) + controller.dismissRefusal(controller.store.getSnapshot().error) + await controller.load() + expect(controller.store.getSnapshot()).toMatchObject({ current: '', error: null }) }) it('keeps the bare cause of a mount failure, not the frame that names the preset again', async () => { @@ -1324,6 +1384,7 @@ describe('AgentPresetSeatController reconciliation', () => { ...developerTools(), remote: { agentPresets: { + list: () => Promise.resolve({ ok: false as const, error: new RemoteError('gateway/internal', 'roster unavailable', {}) }), select: () => Promise.resolve({ ok: false as const, error: new RemoteError( @@ -1339,6 +1400,17 @@ describe('AgentPresetSeatController reconciliation', () => { // The surface reporting this names the preset itself, so carrying the // roster's own "preset X failed to mount" frame would say it twice. expect(await controller.select('broken')).toBe(reason) + const first = controller.store.getSnapshot().error + expect(first).toEqual({ preset: { id: 'broken' }, reason }) + await controller.select('broken') + const second = controller.store.getSnapshot().error + expect(second).toEqual(first) + expect(second).not.toBe(first) + await controller.load() + expect(controller.store.getSnapshot().error).toBe(second) + controller.dismissRefusal(first) + expect(controller.store.getSnapshot().error).toBe(second) + controller.dismissRefusal(second) expect(controller.store.getSnapshot().error).toBe(reason) }) }) diff --git a/packages/client/ui-agent-preset/tests/components.client.spec.tsx b/packages/client/ui-agent-preset/tests/components.client.spec.tsx index 006950507e..79cc930e01 100644 --- a/packages/client/ui-agent-preset/tests/components.client.spec.tsx +++ b/packages/client/ui-agent-preset/tests/components.client.spec.tsx @@ -57,7 +57,14 @@ function renderSeat( ) { const store = createSnapshotStore({ ...SEAT_READY, ...state }) const developerTools = createSnapshotStore(enabled) - const actions = { load: vi.fn(() => Promise.resolve()), select: vi.fn(select), introduced: vi.fn() } + const actions = { + load: vi.fn(() => Promise.resolve()), select: vi.fn(select), introduced: vi.fn(), + dismissRefusal: vi.fn((error: AgentPresetSeatState['error']) => { + if (store.getSnapshot().error === error && error !== null && typeof error === 'object') { + store.set({ ...store.getSnapshot(), error: error.reason }) + } + }), + } const props = { ...actions, sessionId: session === undefined ? undefined : SessionId(session.id), @@ -242,28 +249,34 @@ describe('the new-session chip', () => { }) describe('a refused switch', () => { - it('announces the reason instead of letting the label snap back in silence', async () => { + it('announces delayed and repeated refusals even without a composed preset or Coding Tools', () => { // The banner's own timer has to be a fake one from the start, or the // lifetime assertion below would wait out its real nine seconds. vi.useFakeTimers({ shouldAdvanceTime: true }) try { const reason = 'failed to import loader entry live-on-mac (@deepseek-ai/dsh-also-gone)' - renderSeat({}, () => Promise.resolve(reason)) - - fireEvent.click(screen.getByRole('button')) - fireEvent.click(screen.getByRole('menuitem', { name: /mine/ })) + const actions = renderSeat({ current: '' }, undefined, undefined, false) + const refusal = { preset: { id: 'cordis' }, reason } + act(() => { actions.store.set({ ...actions.store.getSnapshot(), error: refusal }) }) // The host refuses a mount discovery reported healthy, so this banner is // the only place the cause appears — the chip has already reverted and // the settings row shows the preset as fine. - const banner = await screen.findByRole('alert') + const banner = screen.getByRole('alert') expect(banner.textContent).toContain(reason) - expect(banner.textContent).toContain('mine') + expect(banner.textContent).toContain(en.presetCordisName) + expect(screen.queryByRole('button')).toBeNull() + + act(() => { vi.advanceTimersByTime(7000) }) + act(() => { actions.store.set({ ...actions.store.getSnapshot(), error: { ...refusal } }) }) + act(() => { vi.advanceTimersByTime(2001) }) + expect(screen.getByRole('alert').textContent).toContain(reason) // Transient by design: it holds long enough to read a cause that names // packages, then leaves rather than sitting over the screen. act(() => { vi.advanceTimersByTime(9001) }) expect(screen.queryByRole('alert')).toBeNull() + expect(actions.dismissRefusal).toHaveBeenCalledOnce() } finally { vi.useRealTimers() } diff --git a/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx new file mode 100644 index 0000000000..d1ecedaa66 --- /dev/null +++ b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx @@ -0,0 +1,118 @@ +// @vitest-environment jsdom +import { useState, type ComponentProps } from 'react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { Menu, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import { CreatePluginMenuItem } from '../src/client/CreatePluginMenuItem.tsx' +import type { AgentPresetSettingsState } from '../src/client/settings-store.ts' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) +const translations: ReadonlyMap = new Map(Object.entries(en)) + +function unusedHook(): never { + throw new Error('Create plugin does not read this slot source') +} + +function view(roster: Partial = {}, inMenu = false) { + const agentPresets = createSnapshotStore({ + status: 'ready', error: null, options: [{ id: 'standard' }, { id: 'cordis' }], ...roster, + }) + const calls: string[] = [] + const startCreatorDraft = vi.fn(() => { calls.push('start') }) + const onDismiss = vi.fn(() => { calls.push('dismiss') }) + const load = vi.fn(async () => {}) + const props: ComponentProps = { + t: key => translations.get(key) ?? key, + useAgentPresets: bindSnapshotSelector(agentPresets), + usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, + useSessionRetainInfo: unusedHook, useWorkspaces: unusedHook, useResource: unusedHook, + load, startCreatorDraft, onDismiss, + } + function TestMenu() { + const [open, setOpen] = useState(true) + return { setOpen(false) }} + anchor={}> + {}}>Install a third-party plugin + { onDismiss(); setOpen(false) }} /> + + } + render(inMenu ? : ) + return { agentPresets, load, startCreatorDraft, onDismiss, calls } +} + +function item(): HTMLElement { + return screen.getByRole('menuitem', { name: new RegExp(en.createPlugin) }) +} + +describe('Create plugin menu item', () => { + it('explains Creator and dismisses the menu before starting it exactly once', () => { + const actions = view({}, true) + expect(actions.load).toHaveBeenCalledOnce() + expect(item().textContent).toContain(en.createPluginDescription) + expect(screen.queryByRole('dialog')).toBeNull() + expect(actions.startCreatorDraft).not.toHaveBeenCalled() + fireEvent.click(item()) + expect(actions.calls).toEqual(['dismiss', 'start']) + expect(screen.queryByRole('menu')).toBeNull() + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('supports keyboard selection through the shared menu and closes before navigation', () => { + const actions = view({}, true) + const trigger = item() + trigger.focus() + fireEvent.keyDown(trigger, { key: 'Tab' }) + expect(actions.calls).toEqual(['dismiss', 'start']) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it.each(['idle', 'loading', 'error', 'unavailable'] as const)('keeps a disabled entry while the roster is %s', (status) => { + const actions = view({ status }) + expect(item()).toHaveProperty('disabled', true) + const description = status === 'idle' || status === 'loading' ? en.createPluginChecking : en.createPluginUnavailable + expect(item().textContent).toContain(description) + fireEvent.click(item()) + expect(actions.calls).toEqual([]) + }) + + it('disables the same entry when Creator leaves the roster', () => { + const actions = view() + const original = item() + act(() => { actions.agentPresets.set({ status: 'ready', error: null, options: [{ id: 'standard' }] }) }) + expect(item()).toBe(original) + expect(item()).toHaveProperty('disabled', true) + expect(item().textContent).toContain(en.createPluginMissing) + fireEvent.click(item()) + expect(actions.calls).toEqual([]) + }) + + it('keeps the same second menu item through ready, loading, and ready states', () => { + const actions = view({}, true) + const menu = screen.getByRole('menu') + const before = screen.getAllByRole('menuitem') + const original = item() + expect(before[1]).toBe(original) + expect(original).toHaveProperty('disabled', false) + + act(() => { actions.agentPresets.set({ ...actions.agentPresets.getSnapshot(), status: 'loading' }) }) + expect(screen.getByRole('menu')).toBe(menu) + expect(screen.getAllByRole('menuitem')).toEqual(before) + expect(item()).toBe(original) + expect(original).toHaveProperty('disabled', true) + expect(original.textContent).toContain(en.createPluginChecking) + fireEvent.click(original) + expect(actions.calls).toEqual([]) + + act(() => { actions.agentPresets.set({ ...actions.agentPresets.getSnapshot(), status: 'ready' }) }) + expect(screen.getByRole('menu')).toBe(menu) + expect(screen.getAllByRole('menuitem')).toEqual(before) + expect(item()).toBe(original) + expect(original).toHaveProperty('disabled', false) + expect(original.textContent).toContain(en.createPluginDescription) + fireEvent.click(original) + expect(actions.calls).toEqual(['dismiss', 'start']) + }) +}) diff --git a/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts b/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts index af82a0a7d7..73f412f564 100644 --- a/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts @@ -432,7 +432,9 @@ describe('the new-session chip controller', () => { // Showing `minimal` after a refusal would claim a composition the session // never got. - expect(controller.store.getSnapshot()).toMatchObject({ current: 'standard', error: 'already started' }) + expect(controller.store.getSnapshot()).toMatchObject({ + current: 'standard', error: { preset: { id: 'minimal' }, reason: 'already started' }, + }) }) it('ignores a pick while a switch is in flight', async () => { diff --git a/packages/client/ui-agent-preset/tsconfig.json b/packages/client/ui-agent-preset/tsconfig.json index dee5fb035d..564a0b82d9 100644 --- a/packages/client/ui-agent-preset/tsconfig.json +++ b/packages/client/ui-agent-preset/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../ui-primitives" }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, { "path": "../ui-renderer" }, diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index 47161fb20f..448bb52785 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -18,8 +18,8 @@ en: b7d2396da72ecac4 zh: 4ec8336478dd39c7 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/installing-a-bundle: - en: 7f4438da14f803bc - zh: 1728231acbd25d49 + en: c3fad003bf7f8a5a + zh: 89a22aa6e8bb2986 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-a-bundle: en: abc90531efa889d5 zh: 0562570f85e69c35 @@ -36,8 +36,8 @@ en: 8ca48e1365f18adf zh: 91eadd683d2d8b5b /deepseek-ai-dsh-client-ui-plugin-manager/understand-the-implementation/registration: - en: c5a1f14d37433d07 - zh: 75014f10a155fadb + en: 3d70281f082988a5 + zh: 17c6f595e3b57260 /deepseek-ai-dsh-client-ui-plugin-manager/understand-the-implementation/the-store: en: 21a0bbe8eb92229c zh: 096ff63db61992bb diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 0b9eddbc1d..d35f703d43 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -37,6 +37,15 @@ The **Refresh** button shows its tooltip after 500 ms of hovering or keyboard fo ### Installing a bundle +The **Add plugin** control has a main button and a separate arrow for choosing how to add a plugin. + +| Button or menu item | Result | +| --- | --- | +| **Add plugin** | Opens the installation dialog with focus in its package field. | +| Arrow: **Choose how to add a plugin** | Opens the menu of installation and plugin-contributed actions. | +| **Install a third-party plugin** | Closes the menu and opens the same dialog for a package name, Git repository, or local directory. | +| **Let the agent create a plugin** | When [ui-agent-preset](../ui-agent-preset/README.md#use-this-package) contributes this item, closes the menu and opens Creator to author a DSH plugin. | + On first use, when pnpm uses the unconfigured official npm registry and npmmirror is offered, the Host probes both registries in parallel. The first successful HTTPS ping response selects the initial source. The dialog preserves remembered choices, manual selections, explicit manager configuration, and custom or unknown pnpm registries. An install clicked during initial probing waits for that bounded operation; a late result cannot overwrite a manual choice or reopen a closed dialog. The Host sends GET requests to `https://registry.npmjs.org/-/ping` and `https://registry.npmmirror.com/-/ping` through its normal fetch proxy. A 2xx response wins; redirects and failures do not. The remaining request is cancelled, both response bodies are discarded, and cleanup completes before the result returns. The default deadline is 1500 ms and results, including unavailable results, are cached for five minutes. Configure `registryProbeTimeoutMs` and `registryProbeCacheTtlMs` on `ui-plugin-manager`; `registryProbeEnabled: false` disables probing. If both requests fail or time out, the existing default remains selected. No IP-location service or Session content is involved. @@ -99,6 +108,8 @@ The Host entry exposes `pluginRegistryProbe.fastest()` through the generated Rem The browser plugin registers the `plugins` sidebar entry and its `main` panel through `ctx.slots.inject()`, so both follow late slot declaration, locale changes and teardown. The page is global and belongs to no Session. Display text comes from package metadata and the page's dictionary. +The add control reuses `Button`, `Menu`, and `MenuItemButton`. Both installation actions call the same `openInstall` callback and use `InstallDialog` and `PluginManagerController`. The root-scoped list slot `plugins.add.actions` accepts contributed `MenuItemButton` rows after the install action; each contribution receives an `onDismiss()` callback to close the menu before starting its action. + ### The store `PluginManagerController` owns the bundle views, busy keys, notices, install progress and the uninstall confirmation. Each read asks the inventory whether the Host manages a profile, then joins `listBundles` with `listPlugins` into one view per bundle, whose rows carry the live entry's enablement and fiber phase. It coalesces overlapping reads, refreshes after operations, on `plugin-manager/changed`, and on reconnect, and ignores late results after disposal. Install output is grouped by job id. The install dialog moves `idle → checking → starting → running → done | failed`, with `cancelling` and `applying` as the Host reports them and `unconfirmed` when an installation or cancellation response is lost; confirmed `applying` progress never regresses. Recovery uses `waitForInstall`, settling to `unknown` if no active request remains; checking and every active phase use ongoing, while the final screens use done or error. The check runs under an `AbortController` that going back or closing aborts, and its settlement is dropped; a run is stopped only through `pluginManager.cancelInstall`. Closing hides a run without discarding its state. A cancellation that overtakes installation is retried when progress or output acknowledges the request. A change the Host could not apply, a restart it waits for, and an override by a higher layer become toasts that retire on their own. diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 1be7ed01bf..8e1734abc4 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -37,6 +37,15 @@ kind: "package-reference" ### 安装一个组合包 +**添加插件**控件包含主按钮和独立箭头,箭头用于选择添加方式。 + +| 按钮或菜单项 | 结果 | +| --- | --- | +| **添加插件** | 打开安装对话框并聚焦包名输入框。 | +| 箭头:**选择添加插件方式** | 打开包含安装及插件贡献动作的菜单。 | +| **安装第三方插件** | 关闭菜单,打开同一对话框,从包名、Git 仓库或本地目录安装。 | +| **让 Agent 创建插件** | 由 [ui-agent-preset](../ui-agent-preset/README.zh.md#use-this-package) 提供此项时,关闭菜单并进入创造模式,制作 DSH 插件。 | + 首次使用时,如果未显式配置安装源、pnpm 使用官方 npm 源,且列表提供 npmmirror,Host 会并发探测这两个源,选择最先成功响应 HTTPS ping 的源。已记住的选择、用户手选、管理器显式配置,以及自定义或未知的 pnpm 源均保留。在初次探测期间点击安装会等待这次有时限的操作;迟到结果不会覆盖手选或重新打开已关闭的对话框。 Host 通过普通 fetch 代理向 `https://registry.npmjs.org/-/ping` 和 `https://registry.npmmirror.com/-/ping` 发送 GET 请求,以最先返回 2xx 的源为结果;重定向和失败不参与选择。随后取消另一条请求、丢弃两个响应体,并在清理完成后返回。默认时限为 1500 毫秒,包括不可用结果在内的探测结果均缓存五分钟。在 `ui-plugin-manager` 上配置 `registryProbeTimeoutMs` 和 `registryProbeCacheTtlMs`;`registryProbeEnabled: false` 关闭探测。两条请求都失败或超时时保留现有默认源。不使用 IP 地区服务,也不发送 Session 内容。 @@ -99,6 +108,8 @@ Host 入口通过生成的 Remote 接口暴露 `pluginRegistryProbe.fastest()` 浏览器插件通过 `ctx.slots.inject()` 注册 `plugins` 侧栏入口与它的 `main` 面板,使两者跟随 slot 延迟声明、本地化变化与销毁。页面为全局页面,不属于任何 Session。显示文本来自包元信息与页面字典。 +添加控件复用 `Button`、`Menu` 和 `MenuItemButton`。两个安装入口调用同一个 `openInstall` 回调,使用 `InstallDialog` 与 `PluginManagerController`。root 作用域的 list slot `plugins.add.actions` 接受贡献的 `MenuItemButton` 行,放在安装项之后;每个贡献者接收 `onDismiss()` 回调,在开始动作前关闭菜单。 + ### store `PluginManagerController` 拥有组合包视图、忙碌键、提示、安装进度和卸载确认。每次读取先问清单 Host 是否管理着 profile,再把 `listBundles` 与 `listPlugins` 合成每个组合包一份视图,其行携带存活条目的启停状态与 fiber 阶段。它合并重叠读取,在操作后、收到 `plugin-manager/changed` 时以及重连后刷新,并在销毁后忽略晚到结果。安装输出按 job id 分组。安装对话框沿 `idle → checking → starting → running → done | failed` 推进,`cancelling` 与 `applying` 按 Host 的报告呈现,安装或取消响应丢失时进入 `unconfirmed`;已确认的 `applying` 阶段不会倒退。通过 `waitForInstall` 恢复结果,无活动请求时结束为 `unknown`;checking 与所有活动阶段使用 ongoing,最终页面使用 done 或 error。检查在一个 `AbortController` 下运行,返回编辑或关闭会中止它并丢弃其结果;运行只能通过 `pluginManager.cancelInstall` 停止。关闭会隐藏任务而保留其状态。如果取消请求先于安装到达,在进度或输出确认该请求后会再次请求取消。Host 无法应用的变更、要等重启的变更、被更高层覆盖的变更,都是会自行消失的 toast。 diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index 6af4a623fe..9e786b9f53 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -66,11 +66,43 @@ .toolbar { display: flex; + flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 16px; } +.addMenu { + width: 320px; + max-width: calc(100vw - 48px); +} + +.addMenu [role='menuitem'] { + height: 72px; + box-sizing: border-box; + gap: 10px; + padding: 6px 12px; +} + +.addMenuItem { + display: flex; + flex-direction: column; + gap: 2px; + white-space: normal; +} + +.addMenuDescription { + display: -webkit-box; + max-height: 36px; + overflow: hidden; + overflow-wrap: anywhere; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-secondary); + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} + .status, .failure p, .empty { @@ -368,7 +400,9 @@ } /* The toolbar's Add plugin action, one step up from the 28px sm capsule. */ -.addButton { +.addButton, +.addPrimary, +.addMore { height: 32px; font-size: 13px; line-height: 20px; @@ -376,6 +410,25 @@ border-radius: var(--dsw-radius-md); } +.addGroup { + display: inline-flex; + flex: none; + align-items: stretch; +} + +.addPrimary { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} + +.addMore { + width: 32px; + padding: 0; + border-left: 0.5px solid color-mix(in srgb, var(--dsw-alias-label-primary-foreground) 30%, transparent); + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} + .iconWrap { display: inline-flex; } diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index 9bd3992611..174e0b8ae8 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -15,8 +15,8 @@ import type { PluginInstallFailureKind, Registry } from '@deepseek-ai/dsh-api-re import { Button, IconCheckCircleFillRegular, IconChevronDownOutlineRegular, IconChevronLeftOutlineMedium, IconChevronRightOutlineRegular, IconCloseOutlineMedium, - IconInfoOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconTrashOutlineRegular, - IconWarningOutlineRegular, Input, Modal, pointerModality, + IconDownloadOutlineRegular, IconInfoOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconTrashOutlineRegular, + IconWarningOutlineRegular, Input, Menu, MenuItemButton, Modal, pointerModality, PluginArtworkDefault, PluginArtworkLoop, PluginArtworkSearch, PluginArtworkSubagent, PluginArtworkTerminal, StateDot, Switch, Tag, TerminalBlock, Toast, Tooltip, useAnchoredPosition, useDismissOnOutsidePointer, type IconProps, type StateDotState, type TerminalBlockLabels, @@ -41,6 +41,7 @@ export type PluginManagerPageProps = & PropsLocale<'pluginManager'> & PropsRenderSlots< | 'plugins.item' | 'plugins.bundle.config' | 'plugins.row.config' | 'plugins.bundle.activation' + | 'plugins.add.actions' | 'plugins.detail.actions' | 'plugins.detail.badge' | 'plugins.detail.section' > & InjectFace @@ -52,6 +53,44 @@ type ResolveText = PluginManagerFace['resolveText'] type RowPhase = NonNullable +/** The primary action installs; the adjacent menu offers every add-plugin path. */ +function AddPluginMenu({ t, disabled, openInstall, renderSlot }: { + readonly t: Translate + readonly disabled: boolean + readonly openInstall: () => void + readonly renderSlot: RenderConfig +}): ReactNode { + const [open, setOpen] = useState(false) + const onDismiss = (): void => { setOpen(false) } + return ( + + + { setOpen(value => !value) }} + onKeyDown={(event) => { + if (!open && event.key === 'ArrowDown') { event.preventDefault(); setOpen(true) } + }}> + + + ) +} + /** How long the list marks a package an install just enabled. */ const HIGHLIGHT_MS = 2_400 @@ -909,6 +948,7 @@ function InstallDialog({ - + {state.install.requestId === undefined + ? + : } ) diff --git a/packages/client/ui-plugin-manager/src/client/index.ts b/packages/client/ui-plugin-manager/src/client/index.ts index a568db4666..76802768f9 100644 --- a/packages/client/ui-plugin-manager/src/client/index.ts +++ b/packages/client/ui-plugin-manager/src/client/index.ts @@ -48,7 +48,8 @@ export type { ConfigLedger, OfficialItem } from './config-ledger.ts' export type { PluginManagerFace } from './manager-store.ts' export type { PluginManagerLocaleKey } from './locales.ts' export type { - ConfigPageForm, PluginActivationOwnerProps, PluginConfigViewProps, PluginDetailProps, PluginPackageRef, PluginRowRef, PluginsSubject, + ConfigPageForm, PluginActivationOwnerProps, PluginAddActionsProps, + PluginConfigViewProps, PluginDetailProps, PluginPackageRef, PluginRowRef, PluginsSubject, } from './slot-contract.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -116,6 +117,7 @@ export function apply(ctx: ClientContext): void { store, inject: () => face, children: { + 'plugins.add.actions': { kind: 'list', scope: 'root' }, 'plugins.item': { kind: 'list', scope: 'root' }, 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, diff --git a/packages/client/ui-plugin-manager/src/client/locales.ts b/packages/client/ui-plugin-manager/src/client/locales.ts index 4274937afa..5c5300b69c 100644 --- a/packages/client/ui-plugin-manager/src/client/locales.ts +++ b/packages/client/ui-plugin-manager/src/client/locales.ts @@ -20,6 +20,9 @@ export const zh = { refreshError: '刷新失败,请重试', empty: '还没有安装任何插件。', addPlugin: '添加插件', + chooseAddMethod: '选择添加插件方式', + installExisting: '安装第三方插件', + installExistingDescription: '支持 npm 包、Git 仓库和本地目录', restartNotice: '更改将在下次启动生效', overriddenNotice: '{name} 已保存,但被更高优先级的配置覆盖,当前未生效', bundlesTitle: '已安装', @@ -216,6 +219,9 @@ export const en = { refreshError: 'Refresh failed. Please try again.', empty: 'No plugins are installed yet.', addPlugin: 'Add plugin', + chooseAddMethod: 'Choose how to add a plugin', + installExisting: 'Install a third-party plugin', + installExistingDescription: 'Supports npm packages, Git repositories, and local directories', restartNotice: 'The change takes effect at the next start', overriddenNotice: '{name} was saved, but a higher-priority configuration overrides it, so it is not in effect', bundlesTitle: 'Installed', diff --git a/packages/client/ui-plugin-manager/src/client/slot-contract.ts b/packages/client/ui-plugin-manager/src/client/slot-contract.ts index 4c636813cb..e2dd229e78 100644 --- a/packages/client/ui-plugin-manager/src/client/slot-contract.ts +++ b/packages/client/ui-plugin-manager/src/client/slot-contract.ts @@ -72,8 +72,16 @@ export interface PluginActivationOwnerProps { readonly onOpenDetails: () => void } +/** Add-plugin menu actions, independent of any selected bundle or Session. */ +export interface PluginAddActionsProps { + /** Close the add-plugin menu before starting the contributed action. */ + readonly onDismiss: () => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { + /** Additional MenuItemButton rows after installation: 72px high, with a title and a description capped at two lines. */ + 'plugins.add.actions': { kind: 'list'; scope: 'root'; owner: PluginAddActionsProps } /** Optional guidance after the user enables a bundle from the list, keyed by npm package name. */ 'plugins.bundle.activation': { kind: 'keyed'; scope: 'root'; owner: PluginActivationOwnerProps } /** diff --git a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx index 155a15c69b..8d5be40efa 100644 --- a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx @@ -147,6 +147,7 @@ describe('ui-plugin-manager browser plugin', () => { expect(icon.locale).toBe(NS) expect(resolveSlotLabel(icon.options.label)).toBe('插件') // The page declares the slots a plugin's configuration arrives through, and binds their projection beside its state. + expect(b.slots.spec('plugins.add.actions')).toMatchObject({ kind: 'list', scope: 'root' }) expect(b.slots.spec('plugins.item')).toMatchObject({ kind: 'list', scope: 'root' }) expect(b.slots.spec('plugins.bundle.config')).toMatchObject({ kind: 'keyed', scope: 'root' }) expect(b.slots.spec('plugins.row.config')).toMatchObject({ kind: 'keyed', scope: 'root' }) diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index d8f0f51508..ee027c0be7 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -8,6 +8,7 @@ import type { PluginEntryId, PluginInstallRequestId } from '@deepseek-ai/dsh-api import { bindSnapshotSelector, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import type { ConfigForm, ConfigFormSnapshot, SettingsMirrorSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import { StrictMode, type ReactNode } from 'react' import { createNavigationStore } from '../src/client/navigation-store.ts' import { PluginManagerPage } from '../src/client/PluginManagerPage.tsx' @@ -16,7 +17,7 @@ import type { PluginManagerPageProps } from '../src/client/index.ts' import type { ConfigLedger } from '../src/client/config-ledger.ts' import { rowKey, type InstallState, type PackageRow, type PackageView, type PluginManagerState } from '../src/client/manager-store.ts' import { INSTALL_GIT_EXAMPLE, INSTALL_PATH_EXAMPLE, en, zh, type PluginManagerLocaleKey } from '../src/client/locales.ts' -import type { PluginActivationOwnerProps, PluginDetailProps, PluginsSubject } from '../src/client/slot-contract.ts' +import type { PluginActivationOwnerProps, PluginAddActionsProps, PluginDetailProps, PluginsSubject } from '../src/client/slot-contract.ts' afterEach(cleanup) @@ -81,7 +82,7 @@ const READY: PluginManagerState = { * (a list slot's cell is empty), the view asked for — `detail` for a detail * contribution — and the owner props. */ -type SlotBodies = Record ReactNode> +type SlotBodies = Record ReactNode> /** The subject a detail contribution was rendered with. */ function subjectOf(owner: unknown): PluginsSubject | undefined { @@ -158,6 +159,7 @@ function renderTab( const body = bodies[`${name}:${opts?.only ?? opts?.entryKey ?? ''}`] if (body === undefined) return null if (name === 'plugins.bundle.activation') return body('activation', owner) + if (name === 'plugins.add.actions') return body('add', owner) if (name.startsWith('plugins.detail.')) return body('detail', owner) if (!('view' in owner) || (owner.view !== 'summary' && owner.view !== 'page')) { throw new Error('Plugin configuration fixture requires a summary or page view') @@ -191,6 +193,88 @@ function renderTab( } describe('PluginManagerPage', () => { + it('opens the add-plugin menu with ArrowDown and returns focus to its trigger on Escape', () => { + const { actions } = renderTab({}, {}, { + 'plugins.add.actions:': (_view, owner) => { (owner as PluginAddActionsProps).onDismiss() }}>Create a plugin, + }) + const add = screen.getByRole('button', { name: en.chooseAddMethod }) + add.focus() + expect(fireEvent.keyDown(add, { key: 'Tab' })).toBe(true) + expect(screen.queryByRole('menu')).toBeNull() + fireEvent.keyDown(add, { key: 'ArrowDown' }) + const install = screen.getByRole('menuitem', { name: new RegExp(en.installExisting) }) + const create = screen.getByRole('menuitem', { name: 'Create a plugin' }) + expect(screen.getAllByRole('menuitem')).toEqual([install, create]) + expect(document.activeElement).toBe(install) + fireEvent.keyDown(install, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(create) + fireEvent.keyDown(create, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + expect(document.activeElement).toBe(add) + expect(actions.openInstall).not.toHaveBeenCalled() + }) + + it('opens the existing install dialog from the menu and keeps focus on its input', async () => { + const b = renderTab() + b.actions.openInstall.mockImplementation(() => { + b.set({ install: { ...IDLE_INSTALL, open: true } }) + }) + const add = screen.getByRole('button', { name: en.chooseAddMethod }) + add.focus() + fireEvent.click(add) + expect(b.actions.openInstall).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(screen.getByRole('menuitem', { name: new RegExp(en.installExisting) })) + }) + expect(b.actions.openInstall).toHaveBeenCalledOnce() + expect(screen.queryByRole('menu')).toBeNull() + expect(document.activeElement).toBe(screen.getByRole('textbox', { name: en.installSpecLabel })) + }) + + it('keeps primary installation and mouse-selected creation on separate buttons', () => { + const createPlugin = vi.fn() + const { actions } = renderTab({}, {}, { + 'plugins.add.actions:': (_view, owner) => { + (owner as PluginAddActionsProps).onDismiss() + createPlugin() + }}>Create a pluginDescribe it to the agent, + }) + const add = screen.getByRole('button', { name: en.addPlugin }) + const more = screen.getByRole('button', { name: en.chooseAddMethod }) + expect(add.getAttribute('aria-haspopup')).toBeNull() + expect(more.getAttribute('aria-haspopup')).toBe('menu') + fireEvent.pointerDown(add, { pointerType: 'mouse', button: 0 }) + fireEvent.pointerUp(add, { pointerType: 'mouse', button: 0 }) + fireEvent.click(add) + expect(actions.openInstall).toHaveBeenCalledOnce() + expect(screen.queryByRole('menu')).toBeNull() + actions.openInstall.mockClear() + for (const label of ['Create a plugin', 'Describe it to the agent']) { + fireEvent.pointerDown(more, { pointerType: 'mouse', button: 0 }) + fireEvent.pointerUp(more, { pointerType: 'mouse', button: 0 }) + fireEvent.click(more) + expect(more.getAttribute('aria-expanded')).toBe('true') + expect(actions.openInstall).not.toHaveBeenCalled() + const target = screen.getByText(label) + fireEvent.pointerDown(target, { pointerType: 'mouse', button: 0 }) + fireEvent.pointerUp(target, { pointerType: 'mouse', button: 0 }) + fireEvent.click(target) + expect(screen.queryByRole('menu')).toBeNull() + expect(more.getAttribute('aria-expanded')).toBe('false') + expect(actions.openInstall).not.toHaveBeenCalled() + } + expect(createPlugin).toHaveBeenCalledTimes(2) + fireEvent.click(more) + const install = screen.getByText(en.installExisting) + fireEvent.pointerDown(install, { pointerType: 'mouse', button: 0 }) + fireEvent.pointerUp(install, { pointerType: 'mouse', button: 0 }) + fireEvent.click(install) + expect(actions.openInstall).toHaveBeenCalledOnce() + expect(createPlugin).toHaveBeenCalledTimes(2) + expect(screen.queryByRole('menu')).toBeNull() + }) + it('opens the requested bundle after its inventory arrives and falls back when it is absent', () => { const b = renderTab({ status: 'loading' }) act(() => { b.navigation.actions.setView({ kind: 'package', name: 'dsh-better-sidebar' }) }) @@ -221,6 +305,7 @@ describe('PluginManagerPage', () => { expect(loading.querySelector('button, input, [data-state="ongoing"]')).toBeNull() expect(document.querySelector('[data-plugin-panel]')?.getAttribute('aria-busy')).toBe('true') expect(screen.getByRole('button', { name: en.addPlugin })).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: en.chooseAddMethod })).toHaveProperty('disabled', true) set({ status: 'unavailable' }) expect(screen.queryByRole('status', { name: en.loading })).toBeNull() expect(screen.getByRole('status').querySelector('[data-state="idle"]')).not.toBeNull() @@ -1786,6 +1871,8 @@ describe('PluginManagerPage', () => { ...IDLE_INSTALL, open: true, phase: 'unconfirmed', requestId: 'pending-install' as PluginInstallRequestId, failure: { reason: 'offline', uncertainty: 'cancellation' }, } }) + expect(screen.queryByRole('button', { name: en.chooseAddMethod })).toBeNull() + expect(screen.queryByRole('menu')).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.installViewTask })) expect(actions.openInstall).toHaveBeenCalledOnce() expect(screen.getByRole('status').textContent).toBe(en.installUnconfirmedTitle) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 7a15a2f5ef..34a751030e 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1801,6 +1801,56 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-conversation/src/client/contract/slots.ts:131', }, + { + key: 'plugins.add.actions', + kind: 'list', + scope: 'root', + summary: 'Additional MenuItemButton rows after installation: 72px high, with a title and a description capped at two lines.', + doc: 'Additional MenuItemButton rows after installation: 72px high, with a title and a description capped at two lines.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Add-plugin menu actions, independent of any selected bundle or Session. */\nexport interface PluginAddActionsProps {\n /** Close the add-plugin menu before starting the contributed action. */\n readonly onDismiss: () => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', + occupants: [ + 'client-ui-agent-preset CreatePluginMenuItem id \'create-plugin\'', + ], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.add.actions\', () => ctx.slots.register(\n { name: \'plugins.add.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:84', + }, { key: 'plugins.bundle.activation', kind: 'keyed', @@ -1837,7 +1887,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.bundle.activation\', () => ctx.slots.register(\n { name: \'plugins.bundle.activation\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:78', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:86', }, { key: 'plugins.bundle.config', @@ -1877,7 +1927,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.bundle.config\', () => ctx.slots.register(\n { name: \'plugins.bundle.config\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:94', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:102', }, { key: 'plugins.detail.actions', @@ -1927,7 +1977,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.actions\', () => ctx.slots.register(\n { name: \'plugins.detail.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:108', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:116', }, { key: 'plugins.detail.badge', @@ -1977,7 +2027,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.badge\', () => ctx.slots.register(\n { name: \'plugins.detail.badge\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:113', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:121', }, { key: 'plugins.detail.section', @@ -2027,7 +2077,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.section\', () => ctx.slots.register(\n { name: \'plugins.detail.section\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:120', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:128', }, { key: 'plugins.item', @@ -2082,7 +2132,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.item\', () => ctx.slots.register(\n { name: \'plugins.item\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:88', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:96', }, { key: 'plugins.row.config', @@ -2120,7 +2170,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.row.config\', () => ctx.slots.register(\n { name: \'plugins.row.config\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:102', + source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:110', }, { key: 'rightbar', diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index e916089552..ba36e88d34 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -1176,17 +1176,20 @@ describe('dsh-tool-subagent background mode', () => { }) describe('dsh-tool-subagent continuable background mode', () => { - const roots: string[] = [] - afterEach(() => { - for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) + const fixtures: { ctx: Context; root: string }[] = [] + afterEach(async () => { + for (const { ctx, root } of fixtures.splice(0)) { + await ctx.fiber.dispose() + rmSync(root, { recursive: true, force: true }) + } }) /** Boot the real continuable stack without any model-facing follow-up adapter. */ async function continuableSetup() { const ctx = new Context() - await mountAgentLoopTestDependencies(ctx) const root = mkdtempSync(path.join(tmpdir(), 'dsh-tool-subagent-continuable-')) - roots.push(root) + fixtures.push({ ctx, root }) + await mountAgentLoopTestDependencies(ctx) await ctx.plugin(JsonlSessionPersistence, { root }) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c7ce04c19..c807b5ae8e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3093,6 +3093,9 @@ importers: '@deepseek-ai/dsh-client-ui-conversation': specifier: workspace:* version: link:../ui-conversation + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:* + version: link:../ui-plugin-manager '@deepseek-ai/dsh-client-ui-primitives': specifier: workspace:* version: link:../ui-primitives