From 94829d14f37e99dba7a4aecf5c6286841633c707 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Wed, 4 Nov 2026 19:17:37 +0800 Subject: [PATCH 01/68] feat(ui): add inline reasoning controls to model picker Keep model and effort selection in the first-level menu, move Team settings into a detail page, and preserve keyboard focus during selection and pending saves. Add localized effort tooltips, theme-stable slider thumbs, and focused keyboard and browser regression coverage. --- apps/web/tests/agent-team-panel.e2e.ts | 230 +++++--- apps/web/tests/declared-reasoning.e2e.ts | 281 +++++++--- .../tests/deepseek-messages-settings.e2e.ts | 17 +- apps/web/tests/default-model.e2e.ts | 40 +- .../pointer-menu.expected.md | 2 +- .../declared-reasoning/ui.expected.md | 9 +- .../picker.expected.md | 2 +- .../expected/default-model/search.expected.md | 2 +- apps/web/tests/model-menu-observer.e2e.ts | 55 +- apps/web/tests/plugin-manager.e2e.ts | 1 + .../collaboration.zh.expected.md | 5 +- .../agent-team-panel/info.expected.md | 13 +- .../client/ui-agent-team/README.i18n.yaml | 8 +- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.module.css | 78 ++- .../src/client/TeamModeToggle.tsx | 80 ++- .../ui-agent-team/src/client/locales.ts | 24 +- .../client/ui-agent-team/src/client/mount.ts | 9 +- .../tests/browser-plugin.client.spec.ts | 22 +- .../tests/team-mode.client.spec.tsx | 177 +++--- .../ui-model-selection/README.i18n.yaml | 20 +- packages/client/ui-model-selection/README.md | 22 +- .../client/ui-model-selection/README.zh.md | 22 +- .../src/client/EffortSlider.module.css | 141 +++++ .../src/client/EffortSlider.tsx | 122 +++++ .../src/client/ModelSelect.module.css | 75 ++- .../src/client/ModelSelect.tsx | 275 +++++----- .../ui-model-selection/src/client/index.ts | 1 + .../ui-model-selection/src/client/locales.ts | 16 + .../ui-model-selection/src/client/slots.ts | 34 +- .../tests/effort-slider.client.spec.tsx | 214 ++++++++ .../tests/model-menu-tab.client.spec.tsx | 187 +++++++ .../tests/model-select.client.spec.tsx | 508 +++++++++++++----- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/Switch.tsx | 11 +- .../tests/switch.client.spec.tsx | 33 ++ .../ui-theme/src/styles/design-platform.css | 4 + .../src/client/slot-catalog.ts | 59 +- 41 files changed, 2148 insertions(+), 667 deletions(-) create mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.module.css create mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.tsx create mode 100644 packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx create mode 100644 packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index a68c1908a7..e8477cfba4 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -39,6 +39,19 @@ const RECEIPT_LOCALES = [ type ReceiptLocale = typeof RECEIPT_LOCALES[number] +async function openTeamSettings(page: Page, chinese = false): Promise { + const trigger = page.getByRole('button', { name: chinese ? /^选择模型/u : /^Select model/u }) + await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('true') + await page.getByRole('menuitem', { name: chinese ? /^智能体团队协作 /u : /^Agent teamwork /u }).click() +} + +async function closeModelMenu(page: Page): Promise { + const trigger = page.getByRole('button', { name: /^(Select model|选择模型)/u }) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') +} + async function seedTeamConversation(page: Page, scaffold: WebScaffold): Promise { const agent = scaffold.ctx.agents.list()[0] if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') @@ -114,81 +127,148 @@ describe('web e2e: agent teamwork panel', () => { await scaffold?.close() }) - it('explains agent teamwork on hover and focus without changing the Session selection', async () => { + it('shows the explanation and switch only on the second page and returns to the summary', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) - await page.getByRole('button', { name: /^Select model/u }).click() - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const tooltip = page.getByRole('tooltip') - await info.hover() - await tooltip.waitFor({ state: 'visible' }) - await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), await captureStableAria(page, '[role="tooltip"]', scaffold.workspaceCwd), MODE) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.getByRole('button', { name: /^Select model/u }).hover() - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Shift') - await info.focus() - await tooltip.waitFor({ state: 'visible' }) - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await toggle.isVisible()).toBe(true) - await info.click() - await tooltip.waitFor({ state: 'visible' }) - expect(await info.getAttribute('aria-describedby')).toBe(await tooltip.getAttribute('id')) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Escape') - expect(tripwire.pageErrors).toEqual([]) + const trigger = page.getByRole('button', { name: /^Select model/u }) + await trigger.click() + const menu = page.getByRole('menu') + const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) + await summary.waitFor() + // The route-only fixture supplies no reasoning capability, so no range is invented. + expect(await menu.getByRole('slider', { name: 'Effort', exact: true }).count()).toBe(0) + expect(await menu.getByRole('switch').count()).toBe(0) + expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) + const rootSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const original = await menu.elementHandle() + if (original === null) throw new Error('Model menu is missing') + try { + await summary.click() + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.waitFor() + expect(await original.evaluate(element => element.isConnected)).toBe(true) + await menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + const settingsSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), + `## Root\n\n${rootSnapshot}\n\n## Team settings\n\n${settingsSnapshot}`, MODE) + await page.keyboard.press('Escape') + await expect.poll(() => summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(await menu.getByRole('switch').count()).toBe(0) + await summary.press('Enter') + await toggle.waitFor() + await page.keyboard.press('Escape') + await summary.waitFor() + expect(await summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentTeams.isEnabled(scaffold.ctx.agents.list()[0]!)).toBe(false) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await original.dispose() + } }) - it('toggles from the row label and empty space while keeping the information button independent', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-team-row')) - await page.getByRole('button', { name: /^Select model/u }).click() - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const label = page.getByText('Enable agent teamwork', { exact: true }) - const labelBounds = await label.boundingBox() - if (labelBounds === null) throw new Error('Team label is not visible') - const labelPoint = { x: labelBounds.x + labelBounds.width / 2, y: labelBounds.y + labelBounds.height / 2 } - await page.mouse.move(labelPoint.x, labelPoint.y) - expect(await toggle.evaluate((element) => { - const row = element.parentElement! - return getComputedStyle(row).backgroundColor !== 'rgba(0, 0, 0, 0)' - })).toBe(true) - await page.mouse.click(labelPoint.x, labelPoint.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await info.click() - await page.getByRole('tooltip').waitFor({ state: 'visible' }) - expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') - const gap = await toggle.evaluate((element) => { - const control = element.getBoundingClientRect() - const help = element.parentElement!.querySelector('button:not([role="switch"])')!.getBoundingClientRect() - return { x: (help.right + control.left) / 2, y: control.top + control.height / 2 } + it('keeps explanatory text noninteractive and the settings page inside wide and narrow viewports', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-settings-page')) + const viewport = page.viewportSize()! + try { + await openTeamSettings(page) + const menu = page.getByRole('menu') + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + const description = menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }) + await description.click() + expect(await menu.isVisible()).toBe(true) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + for (const size of [viewport, { width: 390, height: 700 }]) { + await page.setViewportSize(size) + await expect.poll(() => menu.evaluate((element) => { + const bounds = element.getBoundingClientRect() + return bounds.left >= 12 && bounds.right <= innerWidth - 12 + && bounds.top >= 12 && bounds.bottom <= innerHeight - 12 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + } + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + await menu.getByRole('menuitem', { name: 'Agent teamwork On', exact: true }).click() + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await page.setViewportSize(viewport) + } + }) + + it('keeps keyboard focus on the Team switch through pending writes and rejects repeated activation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-keyboard-pending')) + const service = scaffold.ctx.agentTeams + const setEnabled = service.setEnabled.bind(service) + const agent = scaffold.ctx.agents.list()[0]! + const initial = service.isEnabled(agent) + onTestFinished(async () => { + await closeModelMenu(page) + await setEnabled(agent, initial) }) - await page.mouse.click(gap.x, gap.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') - expect(await page.getByRole('tooltip').count()).toBe(0) - await page.keyboard.press('Escape') + await openTeamSettings(page) + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + for (const enabled of [true, false]) { + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let inFlight: Promise | undefined + const write = vi.spyOn(service, 'setEnabled').mockImplementation((...args) => { + inFlight = (async () => { + entered.resolve(undefined) + await release.promise + await setEnabled(...args) + })() + return inFlight + }) + try { + await toggle.focus() + await page.keyboard.press('Space') + await entered.promise + await expect.poll(() => toggle.getAttribute('aria-busy')).toBe('true') + expect(await toggle.evaluate(element => (element as HTMLButtonElement).disabled)).toBe(false) + expect(await toggle.getAttribute('aria-disabled')).toBe('true') + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await page.keyboard.press('Space') + expect(write).toHaveBeenCalledTimes(1) + expect(await toggle.getAttribute('aria-checked')).toBe(String(!enabled)) + release.resolve(undefined) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) + await expect.poll(() => toggle.getAttribute('aria-busy')).toBeNull() + expect(await toggle.getAttribute('aria-disabled')).toBeNull() + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) + } finally { + release.resolve(undefined) + try { await inFlight } finally { write.mockRestore() } + } + } expect(tripwire.pageErrors).toEqual([]) }) it('defaults off and saves a Session selection in the model menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode')) expect(await page.locator('[data-subagent-action]').count()).toBe(0) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.waitFor() expect(await toggle.getAttribute('aria-checked')).toBe('false') await toggle.focus() - await page.keyboard.press('ArrowUp') - expect(await toggle.evaluate(element => element === document.activeElement)).toBe(false) - await page.keyboard.press('ArrowDown') + await page.keyboard.press('Shift+Tab') + expect(await page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + expect(await toggle.count()).toBe(0) + await openTeamSettings(page) expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Space') await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) const agent = scaffold.ctx.agents.list()[0]! expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) @@ -198,10 +278,10 @@ describe('web e2e: agent teamwork panel', () => { await other.dispose() const beforeReload = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) acknowledgeReloadConnectionLoss(tripwire, beforeReload) }, 60_000) @@ -210,11 +290,11 @@ describe('web e2e: agent teamwork panel', () => { const input = page.locator('[data-composer-input]').first() const agent = scaffold.ctx.agents.list()[0]! for (const enabled of [false, true]) { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) - await page.keyboard.press('Escape') + await closeModelMenu(page) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) await expect.poll(() => input.textContent()).toBe('') await page.getByRole('button', { name: 'Account menu', exact: true }).focus() @@ -434,22 +514,22 @@ describe('web e2e: agent teamwork panel', () => { }, 60_000) it('hides the board while disabled and restores its tasks when re-enabled', async () => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') expect(await page.locator('[data-subagent-action]').count()).toBe(1) - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click() await page.getByRole('treeitem', { name: /Researcher/u }).waitFor() expect(await page.locator('[data-team-panel]').count()).toBe(0) expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360) expect(await page.locator('[data-subagent-section-header]').count()).toBe(0) await page.keyboard.press('Escape') - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click() await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor() await page.keyboard.press('Escape') @@ -784,14 +864,15 @@ describe('web e2e: agent teamwork panel', () => { agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) const openConfirmation = async (): Promise => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }).waitFor() } await openConfirmation() const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) await assertWarningDialogLayout(dialog) - expect(await page.getByRole('menu', { name: 'Model and reasoning effort', exact: true }).count()).toBe(0) + expect(await page.getByRole('menu', { name: 'Agent teamwork', exact: true }).count()).toBe(0) + expect(await page.getByRole('button', { name: /^Select model/u }).getAttribute('aria-expanded')).toBe('false') expect(await dialog.getByRole('checkbox').count()).toBe(0) expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'disable-confirmation.expected.md'), @@ -810,11 +891,11 @@ describe('web e2e: agent teamwork panel', () => { await dialog.waitFor({ state: 'hidden' }) await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) expect(await dialog.count()).toBe(0) - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([]) expect(tripwire.pageErrors).toEqual([]) }) @@ -891,14 +972,14 @@ it.each(RECEIPT_LOCALES)('toggles teamwork in $language without command records await expect.poll(captureLayout).toEqual(recordedLayout) } for (const enabled of [true, false]) { - await page.getByRole('button', { name: locale.modelButton }).click() + await openTeamSettings(page, locale.code === 'zh') const toggle = page.getByRole('switch', { name: locale.toggle, exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) expect(commandEvents()).toEqual([]) - await page.keyboard.press('Escape') + await closeModelMenu(page) await assertChatUnchanged() } await scaffold.ctx.sessions.flush(agent.session) @@ -1003,10 +1084,11 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', if (selection === undefined) throw new Error('Chinese Team fixture has no model') agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) - await page.getByRole('button', { name: /^选择模型/u }).click() + await openTeamSettings(page, true) const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.getByRole('button', { name: '关于智能体团队协作', exact: true }).waitFor() + await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await toggle.click() diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 27619f0bf1..95b6244e3b 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -1,12 +1,12 @@ // Web e2e scenario: a hand-declared model's `reasoningEfforts` reaches the -// composer's effort pane — the levels a settings profile declares are exactly +// composer's inline effort slider — the levels a settings profile declares are exactly // what the picker offers, and picking one records it with the Agent default. // Zero model calls: declaring, describing, and switching are settings/llm // traffic only, so there is no fixture and a stray stream would fail loud. import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import type { Browser, Page, Request } from 'playwright' +import type { Browser, Locator, Page, Request } from 'playwright' import { chromium, webkit } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' import { @@ -49,7 +49,9 @@ describe.skipIf(MODE === 'record').each([ { id: 'acme-lite', name: 'Acme Lite' }, ].map(model => ({ ...model, - reasoningEfforts: { off: null, high: 'high', max: 'ultra' }, + reasoningEfforts: model.id === 'acme-lite' + ? { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' } + : { off: null, high: 'high', max: 'ultra' }, })), }, }, @@ -70,68 +72,119 @@ describe.skipIf(MODE === 'record').each([ } }) - it('offers exactly the declared levels and records the picked one', async () => { + it('uses Tab only for focus while Enter and Space open model and Team pages', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-model-tab-${engine.name()}`)) + let selections = 0 + const countSelection = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ + } + page.on('request', countSelection) + onTestFinished(() => { page.off('request', countSelection) }) + const previous = scaffold.ctx.agentDefaultModel.currentSelection() + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + const team = page.locator('[data-model-menu-page="agent-team"]') + const focused = async (locator: Locator): Promise => { + await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) + } + await trigger.click() + await page.keyboard.press('Tab'); await focused(rootModel) + expect(await page.getByRole('menuitemradio').count()).toBe(0) + await page.keyboard.press('Tab'); await focused(slider) + await page.keyboard.press('Tab'); await focused(team) + expect(await page.getByRole('switch').count()).toBe(0) + await page.keyboard.press('Shift+Tab'); await focused(slider) + await page.keyboard.press('Shift+Tab'); await focused(rootModel) + await page.keyboard.press('Enter') + const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) + await search.waitFor(); await focused(search) + await page.mouse.move(0, 0) + await page.keyboard.press('Escape'); await focused(rootModel) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + await page.keyboard.press('Space'); await focused(search) + await page.keyboard.press('Tab') + await focused(page.locator('[role="menuitemradio"][tabindex="0"]')) + expect(selections).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + await page.keyboard.press('Shift+Tab'); await focused(search) + await page.keyboard.press('Shift+Tab'); await focused(trigger) + expect(await search.count()).toBe(0) + await page.keyboard.press('Enter') + await page.keyboard.press('Tab'); await focused(rootModel) + await page.keyboard.press('Space'); await search.waitFor() + await page.keyboard.press('Tab') + await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) + await page.keyboard.press('Space'); await focused(rootModel) + await page.keyboard.press('Tab'); await focused(slider) + await page.keyboard.press('Tab'); await focused(team) + await page.keyboard.press('Space') + const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await toggle.waitFor(); await focused(toggle) + const checked = await toggle.getAttribute('aria-checked') + await page.keyboard.press('Shift+Tab'); await focused(trigger) + expect(await toggle.count()).toBe(0) + await page.keyboard.press('Enter') + await team.click(); await focused(toggle) + expect(await toggle.getAttribute('aria-checked')).toBe(checked) + expect(await page.getByRole('button', { name: '返回', exact: true }).count()).toBe(0) + await page.keyboard.press('Escape'); await focused(team) + await page.keyboard.press('Tab') + await page.locator('[data-model-menu-root]').waitFor({ state: 'detached' }) + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(false) + expect(selections).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) await trigger.waitFor({ timeout: 15_000 }) + onTestFinished(async () => { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + }) await trigger.click() - await page.getByRole('menuitem', { name: /推理等级/ }).click() - - // Declared levels, nothing else: the provider-default entry (the route - // configures no `reasoning`), then Off/High/Max — minimal, low, medium, - // and xhigh were not declared and must not be offered. - const levels = page.getByRole('menuitemradio') - await expect.poll(async () => levels.allTextContents(), { timeout: 10_000 }) - .toEqual(['Default', 'Off', 'High', 'Max']) + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') + expect(await levels.count()).toBe(0) + expect(await slider.getAttribute('min')).toBe('0') + expect(await slider.getAttribute('max')).toBe('3') + expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('Default', { exact: true }) + expect(await tag.evaluate(element => ({ + cursor: getComputedStyle(element).cursor, + userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), + tabIndex: element.tabIndex, + }))).toEqual({ cursor: 'default', userSelect: 'none', tabIndex: -1 }) + expect(await page.getByRole('menuitem', { name: /推理等级/ }).count()).toBe(0) const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) - - // Keyboard: the clicked cell unmounts with its pane, so the drilled pane's - // checked row takes the focus it left behind. ↑↓ walk the rows from there - // and Tab settles the focused one exactly as Enter would. - await expect.poll( - () => levels.nth(0).evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) - await page.keyboard.press('ArrowDown') - await expect.poll( - () => levels.nth(1).evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) - await page.keyboard.press('ArrowDown') - await expect.poll( - () => levels.nth(2).evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) - - // Settling with Tab is the same gesture that saves the default selection, so - // the effort lands in the Agent default Settings section beside provider/model. - await page.keyboard.press('Tab') - await expect.poll(() => levels.count(), { timeout: 10_000 }).toBe(0) + const previous = scaffold.ctx.agentDefaultModel.currentSelection() + await slider.focus() + try { + await page.keyboard.down('ArrowRight') + await expect.poll(() => slider.inputValue()).toBe('1') + await page.keyboard.down('ArrowRight') + await expect.poll(() => slider.inputValue()).toBe('2') + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) + } finally { + await page.keyboard.up('ArrowRight') + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) await expect.poll( async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 10_000 }, ).toContain('reasoningEffort: high') - await expect.poll(() => trigger.getAttribute('aria-label'), { timeout: 10_000 }) - .toBe('选择模型,当前 Acme Think,推理等级 High') - - // Reopening the drilled pane parks the keyboard on the level in use, and - // Shift+Tab walks back out like Escape: to the drilled cell, then closed. - await trigger.click() - await page.getByRole('menuitem', { name: /推理等级/ }).click() - const high = page.getByRole('menuitemradio', { name: 'High' }) - await expect.poll( - () => high.evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) + await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 High') + expect(await slider.getAttribute('aria-valuetext')).toBe('High') + await slider.focus() await page.keyboard.press('Shift+Tab') - await expect.poll( - () => page.getByRole('menuitem', { name: /推理等级/ }) - .evaluate(element => element === document.activeElement), - { timeout: 10_000 }, - ).toBe(true) + await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) + .evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.getByRole('menu').count(), { timeout: 10_000 }).toBe(0) + await expect.poll(() => page.getByRole('menu').count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) @@ -139,7 +192,7 @@ describe.skipIf(MODE === 'record').each([ onTestFailed(() => saveFailureShot(page, `web-e2e-model-trigger-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) const menu = page.getByRole('menu') - for (const pane of ['root', 'model', 'effort']) { + for (const pane of ['root', 'model', 'slider']) { await page.locator('[data-composer-input][contenteditable="true"]').focus() await trigger.click() await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) @@ -148,10 +201,11 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) .evaluate(element => element === document.activeElement)).toBe(true) } else { - await page.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }).click() + if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() const focused = pane === 'model' ? page.getByRole('searchbox', { name: '搜索模型…' }) - : page.locator('[role="menuitemradio"][aria-checked="true"]') + : page.getByRole('slider', { name: '推理等级', exact: true }) + if (pane === 'slider') await focused.focus() await expect.poll(() => focused.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) } await trigger.click() @@ -171,6 +225,9 @@ describe.skipIf(MODE === 'record').each([ onTestFinished(() => { page.off('request', countSelection) }) const trigger = page.getByRole('button', { name: /^选择模型/ }) const menu = page.getByRole('menu') + onTestFinished(async () => { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + }) await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() const current = page.getByRole('menuitemradio', { name: 'Acme Think', exact: true }) @@ -203,15 +260,28 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() await target.getByText('Acme Swift', { exact: true }).click() - await menu.waitFor({ state: 'detached' }) + await page.locator('[data-model-menu-root]').waitFor() expect(selections).toBe(1) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model, { timeout: 10_000 }) .toBe('acme-swift') - await trigger.click() - await page.getByRole('menuitem', { name: /推理等级/ }).click() - await page.getByRole('menuitemradio', { name: 'Max', exact: true }).click() - await menu.waitFor({ state: 'detached' }) + const rootModel = page.getByRole('menuitem', { name: /^模型/ }) + await expect.poll(() => rootModel.evaluate(element => element === document.activeElement)).toBe(true) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + await rootModel.hover() + await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') + await page.mouse.move(0, 0) + await page.keyboard.press('Tab') + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) + expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') + expect(selections).toBe(1) + const rangeBounds = await slider.boundingBox() + if (rangeBounds === null) throw new Error('Reasoning slider is not visible') + await page.mouse.click(rangeBounds.x + rangeBounds.width - 8, rangeBounds.y + rangeBounds.height / 2) + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') expect(selections).toBe(2) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') @@ -228,7 +298,6 @@ describe.skipIf(MODE === 'record').each([ }, }) }, { times: 1 }) - await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) @@ -236,12 +305,15 @@ describe.skipIf(MODE === 'record').each([ await page.getByRole('alert').waitFor() expect(selections).toBe(3) await compareOrRefreshGolden(POINTER_EXPECTED, - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), MODE) - await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Tab') + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), MODE) + const focusedRow = page.locator('[role="menuitemradio"][tabindex="0"]') + await expect.poll(() => focusedRow.evaluate(element => element === document.activeElement)).toBe(true) + expect(await target.getAttribute('aria-checked')).toBe('true') + expect(scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-swift') + await page.keyboard.press('Shift+Tab') await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) - await search.press('ArrowUp') + await search.fill('Acme Think') + await search.press('ArrowDown') expect(await search.getAttribute('aria-activedescendant')).toBe(await current.getAttribute('id')) expect(await search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) await page.keyboard.press('Escape') @@ -250,7 +322,11 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.locator('[data-composer-input][contenteditable="true"]').focus() + await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true) + const composer = page.locator('[data-composer-input][contenteditable="true"]') + // Native focus supplies relatedTarget; Playwright's contentEditable focus first blurs to null. + await composer.evaluate((element) => { element.focus() }) + await expect.poll(() => composer.evaluate(element => element === document.activeElement)).toBe(true) await menu.waitFor({ state: 'detached' }) await trigger.click() await page.mouse.click(0, 0) @@ -258,6 +334,75 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) }) + it('shows six stops including Default and commits only after releasing a drag outside the range', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-six-effort-drag-${engine.name()}`)) + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const viewport = page.viewportSize()! + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-lite') + let selections = 0 + const countSelection = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ + } + page.on('request', countSelection) + onTestFinished(() => { page.off('request', countSelection) }) + try { + await page.setViewportSize({ width: 390, height: 700 }) + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const group = menu.getByRole('group', { name: '推理等级', exact: true }) + const slider = group.getByRole('slider', { name: '推理等级', exact: true }) + expect(await group.getByRole('button').count()).toBe(0) + expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + expect(await slider.getAttribute('max')).toBe('5') + await expect.poll(() => menu.evaluate((element) => { + const rect = element.getBoundingClientRect() + return rect.left >= 12 && rect.right <= innerWidth - 12 && rect.top >= 12 && rect.bottom <= innerHeight - 12 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await slider.hover() + const bounds = await slider.boundingBox() + if (bounds === null) throw new Error('Reasoning slider is not visible') + const y = bounds.y + bounds.height / 2 + await page.mouse.move(bounds.x + 8, y) + await page.mouse.down() + try { + await page.mouse.move(bounds.x + bounds.width * .4, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width * .6, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width - 8, y, { steps: 4 }) + await page.mouse.move(bounds.x + bounds.width + 24, y, { steps: 4 }) + expect(await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.matches('input[type="range"]'), + { x: bounds.x + bounds.width + 24, y })).not.toBe(true) + expect(selections).toBe(0) + expect(await menu.isVisible()).toBe(true) + await expect.poll(() => slider.evaluate(input => ({ + value: (input as HTMLInputElement).value, + label: input.getAttribute('aria-valuetext'), + busy: input.getAttribute('aria-busy'), + disabled: (input as HTMLInputElement).disabled, + }))).toEqual({ value: '5', label: 'Max', busy: 'false', disabled: false }) + } catch (error) { + await page.screenshot({ path: fileURLToPath(new URL( + `../../../.artifacts/model-picker-master-sync/drag-${engine.name()}-regression.png`, import.meta.url, + )) }) + throw error + } finally { + await page.mouse.up() + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect(await menu.isVisible()).toBe(true) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(selections).toBe(1) + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'pointer-menu.expected.md']) }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 6033c8f06f..a842669c01 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -120,13 +120,18 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await page.getByRole('menuitem', { name: /模型/ }).click() await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'picker.expected.md'), - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), webSnapshotMode()) await page.keyboard.press('Escape') - await page.getByRole('menuitem', { name: /推理等级/ }).click() - const effortWeights = await page.getByRole('menuitemradio').evaluateAll(rows => rows.map(row => - getComputedStyle(row.querySelector('span span')!).fontWeight, - )) - expect(new Set(effortWeights)).toEqual(new Set(['400'])) + const effort = page.getByRole('group', { name: '推理等级', exact: true }) + await effort.getByRole('slider', { name: '推理等级', exact: true }).waitFor() + expect(await effort.getByRole('button').count()).toBe(0) + const slider = effort.getByRole('slider') + expect(await slider.getAttribute('min')).toBe('0') + expect(await slider.getAttribute('max')).toBe('3') + expect(await slider.getAttribute('aria-valuetext')).toBe('High') + const tag = effort.getByText('High', { exact: true }) + expect(await tag.evaluate(element => getComputedStyle(element).fontWeight)).toBe('500') + expect(await tag.evaluate(element => element.tabIndex)).toBe(-1) expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index afd89b3c77..78c45f1bb0 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -116,20 +116,23 @@ describe('web e2e: the composer model switch is the default for later sessions', JSON.stringify(await readLabels(menu), null, 2), webSnapshotMode(), ) + await page.keyboard.press('Escape') + await expect.poll(() => cell.evaluate(element => element === document.activeElement)).toBe(true) + expect(await page.getByRole('menuitemradio').count()).toBe(0) } finally { await page.keyboard.press('Escape') await page.keyboard.press('Escape') } }) - it.each(['root', 'model'])('reanchors the %s menu when a label grows and shrinks without a window resize', async (pane) => { + it.each(['root', 'model'])('keeps the %s menu aligned as a label grows and shrinks without a window resize', async (pane) => { const viewport = page.viewportSize()! const trigger = page.getByRole('button', { name: /^选择模型/ }) try { await page.setViewportSize({ width: 390, height: 844 }) await trigger.click() if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() - const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: '模型与推理等级', exact: true }) + const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: pane === 'model' ? '模型' : '模型与推理等级', exact: true }) const label = surface.locator('[data-provider-id="origin-gateway"][data-model-id="origin-large"]') await label.waitFor() const original = await surface.boundingBox() @@ -141,7 +144,9 @@ describe('web e2e: the composer model switch is the default for later sessions', badge.textContent = ' — Provider identification badge with a long channel name' node.appendChild(badge) }) - await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + expect(original!.width).toBe(260) + await expect.poll(async () => (await surface.boundingBox())!.width).toBeCloseTo(original!.width) + expect(await surface.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) await expect.poll(async () => { const box = (await surface.boundingBox())! return box.x >= 12 && box.x + box.width <= 378 @@ -272,6 +277,10 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(() => model.evaluate(element => document.activeElement === element)).toBe(true) await observeFocus('Enter model pane') await devicePage.keyboard.press('ArrowDown') + const next = devicePage.getByRole('menuitemradio', { name: 'Acme Large', exact: true }) + await expect.poll(() => next.evaluate(element => document.activeElement === element)).toBe(true) + expect(await devicePage.locator('[role="menuitemradio"][tabindex="0"]').count()).toBe(1) + await devicePage.keyboard.press('Shift+Tab') const search = devicePage.getByRole('searchbox', { name: '搜索模型…' }) expect(await search.evaluate(input => getComputedStyle(input).fontSize)).toBe('16px') await expect.poll(() => search.evaluate(element => document.activeElement === element)).toBe(true) @@ -320,7 +329,7 @@ describe('web e2e: the composer model switch is the default for later sessions', try { await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const menu = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const menu = page.getByRole('group', { name: '模型', exact: true }) const menuSearch = page.getByRole('searchbox', { name: '搜索模型…' }) const order = await readGroups(menu, 'menuitemradio') const sticky = await checkSticky(menu, menu.getByRole('menu', { name: '模型', exact: true })) @@ -368,8 +377,11 @@ describe('web e2e: the composer model switch is the default for later sessions', for (let index = 0; index < 4; index++) await page.keyboard.press('ArrowDown') expect(await page.evaluate(() => document.activeElement?.id)).toBe(currentId) await page.keyboard.press('Enter') - await expect.poll(() => trigger.evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) - expect(await trigger.evaluate(node => getComputedStyle(node).boxShadow)).toBe('none') + await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) + .evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + await page.keyboard.press('Escape') + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') await page.getByRole('button', { name: '添加文件或调用指令', exact: true }).click() await page.getByRole('option', { name: /^模型/ }).click() const commandSearch = page.getByRole('textbox', { name: '筛选选项', exact: true }) @@ -398,11 +410,12 @@ describe('web e2e: the composer model switch is the default for later sessions', platform: document.documentElement.getAttribute('data-platform'), theme: document.body.getAttribute('data-ds-dark-theme'), })) - const surface = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const surface = page.getByRole('group', { name: '模型', exact: true }) const trigger = page.getByRole('button', { name: /^选择模型/ }) const search = page.getByRole('searchbox', { name: '搜索模型…' }) try { - await page.setViewportSize({ width: 1680, height: 220 }) + // Keep multiple provider groups scrollable beneath the search field. + await page.setViewportSize({ width: 1680, height: 280 }) await trigger.click() await page.getByRole('menuitem', { name: /模型/ }).click() const scroller = page.getByRole('menu', { name: '模型', exact: true }) @@ -442,6 +455,7 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(readPinned).toEqual([true, false, false]) await search.fill('Origin Large') await expect.poll(() => headings.count()).toBe(1) + await expect.poll(() => scroller.evaluate(element => element.scrollHeight <= element.clientHeight)).toBe(true) await expect.poll(readPinned).toEqual([false]) await page.getByRole('button', { name: '清除搜索', exact: true }).click() await expect.poll(readPinned).toEqual([false, false, false]) @@ -534,7 +548,7 @@ describe('web e2e: the composer model switch is the default for later sessions', getComputedStyle(row.querySelector('span span')!).fontWeight, )) expect(new Set(modelWeights)).toEqual(new Set(['400'])) - const headingPalettes = await page.getByRole('group', { name: '模型与推理等级', exact: true }).evaluate((menu) => { + const headingPalettes = await page.getByRole('group', { name: '模型', exact: true }).evaluate((menu) => { const html = menu.ownerDocument.documentElement const body = menu.ownerDocument.body const previousPlatform = html.getAttribute('data-platform') @@ -582,7 +596,7 @@ describe('web e2e: the composer model switch is the default for later sessions', expect(await page.getByRole('group', { name: 'Origin Gateway', exact: true }).count()).toBe(0) await compareOrRefreshGolden( fileURLToPath(new URL('./expected/default-model/search.expected.md', import.meta.url)), - await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), + await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), webSnapshotMode(), ) const entered = Promise.withResolvers() @@ -600,9 +614,11 @@ describe('web e2e: the composer model switch is the default for later sessions', await page.keyboard.press('Enter') await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') await expect.poll(() => trigger.textContent()).toContain('Acme Large') - await expect.poll(() => trigger.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await trigger.evaluate(element => getComputedStyle(element).boxShadow)).toBe('none') + await expect.poll(() => modelCell.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) + expect(await trigger.getAttribute('aria-expanded')).toBe('true') expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: START_ROUTE, model: START_MODEL }) + await page.keyboard.press('Escape') + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') const aria = await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/default-model/background-save.expected.md', import.meta.url)), aria, webSnapshotMode()) } finally { diff --git a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md index 2a5271a974..007884ec01 100644 --- a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md +++ b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - searchbox "搜索模型…" - menu "模型": - group "DeepSeek": diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index 2b18a73716..a56dedf7d1 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,5 +1,6 @@ - menu "模型与推理等级": - - menuitemradio "Default" [checked] - - menuitemradio "Off" - - menuitemradio "High" - - menuitemradio "Max" + - menuitem "模型 Acme Think" + - group "推理等级": + - text: Default + - slider "推理等级": "0" + - menuitem "智能体团队协作 关" diff --git a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md index f256339fcd..5b8cc4753a 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - menu "模型": - group "DeepSeek": - text: DeepSeek diff --git a/apps/web/tests/expected/default-model/search.expected.md b/apps/web/tests/expected/default-model/search.expected.md index 9b2d48e3c8..2379835f56 100644 --- a/apps/web/tests/expected/default-model/search.expected.md +++ b/apps/web/tests/expected/default-model/search.expected.md @@ -1,4 +1,4 @@ -- group "模型与推理等级": +- group "模型": - searchbox "搜索模型…": ACMLG - button "清除搜索" - menu "模型": diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index 7bd5720bc5..d0a1cab304 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -150,7 +150,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ for (const entry of ['button', 'command'] as const) { const composer = page.locator('[data-composer-input]').first() const surface = entry === 'button' - ? page.getByRole('group', { name: '模型与推理等级', exact: true }) + ? page.getByRole('group', { name: '模型', exact: true }) : page.locator('[aria-label="/model 选项"]') const viewport = entry === 'button' ? surface.getByRole('menu', { name: '模型', exact: true }) @@ -296,7 +296,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await page.setViewportSize({ width: 402, height: 874 }) await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const panel = page.getByRole('group', { name: '模型与推理等级', exact: true }) + const panel = page.getByRole('group', { name: '模型', exact: true }) for (const height of [874, 500]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) @@ -398,66 +398,67 @@ describe.skipIf(webSnapshotMode() === 'record').each([ } }) - it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without list overflow', async () => { + it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without root overflow', async () => { const cdp = await page.context().newCDPSession(page) try { - for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 350, scrolls: true }]) { + for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 220, scrolls: true }]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) await page.getByRole('button', { name: /^选择模型/ }).click() - await page.getByRole('menuitem', { name: /^推理等级/ }).click() const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - await menu.getByRole('menuitemradio').first().click() + const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBeUndefined() - await page.getByRole('button', { name: /^选择模型/ }).click() - await page.getByRole('menuitem', { name: /^推理等级/ }).click() - const last = menu.getByRole('menuitemradio').last() - await expect.poll(() => last.getAttribute('aria-checked')).toBe('false') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) - expect(await menu.getByRole('menuitemradio').count()).toBeGreaterThanOrEqual(7) - await expect.poll(() => last.evaluate((row) => { - const scroller = row.parentElement! + expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) + expect(await menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button').count()).toBe(0) + await expect.poll(() => slider.evaluate((range) => { + const scroller = range.closest('[data-model-menu-root]')! scroller.scrollTop = scroller.scrollHeight return { overflow: getComputedStyle(scroller).overflowY, overflows: scroller.scrollHeight > scroller.clientHeight, moved: scroller.scrollTop > 0 } })).toEqual({ overflow: 'auto', overflows: scrolls, moved: scrolls }) - await expect.poll(() => last.evaluate((row) => { - const rect = row.getBoundingClientRect() - const viewport = row.parentElement!.getBoundingClientRect() + await expect.poll(() => slider.evaluate((range) => { + const rect = range.getBoundingClientRect() + const viewport = range.closest('[data-model-menu-root]')!.getBoundingClientRect() return rect.top >= viewport.top - 1 && rect.bottom <= viewport.bottom + 1 })).toBe(true) - const target = await last.evaluate((row) => { - const rect = row.getBoundingClientRect() + const target = await slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! return { - left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.left + rect.width / 2 - viewport.width / 2)), + left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.right - 8 - viewport.width / 2)), top: Math.max(0, Math.min(window.innerHeight - viewport.height, rect.top + rect.height / 2 - viewport.height / 2)), offsetLeft: viewport.offsetLeft, offsetTop: viewport.offsetTop, } }) - // Pan from the page margin so wheel input cannot scroll the list instead. + // Pan from the page margin so wheel input cannot scroll the menu instead. await cdp.send('Input.synthesizeScrollGesture', { x: 1, y: 1, xDistance: target.offsetLeft - target.left, yDistance: target.offsetTop - target.top, gestureSourceType: 'mouse', speed: 800, }) - await expect.poll(() => last.evaluate((row) => { - const rect = row.getBoundingClientRect() + await expect.poll(() => slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! - const x = rect.left + rect.width / 2 - viewport.offsetLeft + const x = rect.right - 8 - viewport.offsetLeft const y = rect.top + rect.height / 2 - viewport.offsetTop return x >= 0 && x < viewport.width && y >= 0 && y < viewport.height })).toBe(true) - // Dispatch touch without locator auto-scrolling the last row into view. - const point = await last.evaluate((row) => { - const rect = row.getBoundingClientRect() + // Native touch must select the last stop without locator auto-scrolling. + const point = await slider.evaluate((range) => { + const rect = range.getBoundingClientRect() const viewport = window.visualViewport! - return { x: rect.left + rect.width / 2 - viewport.offsetLeft, + return { x: rect.right - 8 - viewport.offsetLeft, y: rect.top + rect.height / 2 - viewport.offsetTop } }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) + expect(await menu.isVisible()).toBe(true) + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await page.keyboard.press('Escape') await menu.waitFor({ state: 'detached' }) } } finally { diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 66bd3cfb1d..3c606b7624 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -1191,6 +1191,7 @@ describe('web e2e: plugin manager', () => { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) await teamPage.getByRole('button', { name: /^选择模型/u }).click() + await teamPage.getByRole('menuitem', { name: '智能体团队协作 关', exact: true }).click() const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) await mode.waitFor() expect(await mode.getAttribute('aria-checked')).toBe('false') diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index 07a6ac96dc..0522d13274 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,10 +1,9 @@ ## Menu -- menu "模型与推理等级": - - menuitem "模型 DeepSeek-V4-Flash" +- menu "智能体团队协作": - text: 启用智能体团队协作 - - button "关于智能体团队协作" - switch "启用智能体团队协作" [checked] + - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 ## Confirmation diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md index 5e675607a5..d1171d7e32 100644 --- a/apps/web/tests/snapshots/agent-team-panel/info.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -1 +1,12 @@ -- tooltip "Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs." +## Root + +- menu "Model and reasoning effort": + - menuitem "Model DeepSeek-V4-Flash" + - menuitem "Agent teamwork Off" + +## Team settings + +- menu "Agent teamwork": + - text: Enable agent teamwork + - switch "Enable agent teamwork" + - paragraph: Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs. diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 3f894b097c..a438e29119 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: d502ab38773eef34 - zh: e1f9c4edbc74c38f + en: 1bb905cfddfc8686 + zh: f3996e9b43e2b06b /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 /deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: - en: 9b0b6a8505a9ebbf - zh: beb5d89f80463b3e + en: 7eda4383f70987f8 + zh: 84de71637336d63c /deepseek-ai-dsh-client-ui-agent-team/further-exploration: en: 4d9214370681b02e zh: 4acb21b9ecf25e85 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index 7e87010dcb..bd556a4873 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, turn on **Enable agent teamwork**. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire Team row highlights on hover and toggles the selection when clicked, except for its independent information button. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The adjacent information button explains shared-task coordination and additional token use on hover, keyboard focus, or click/tap without changing the selection. Escape or an outside press dismisses the explanation. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Saving uses the [Switch pending state](../ui-primitives/README.md#component-catalog), so a keyboard-activated switch keeps focus without accepting another change. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. @@ -47,7 +47,7 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
Implementation internals — click to expand -The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. Disposing the plugin fiber removes its registrations. +The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns page navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.page` with key `agent-team`. Disposing the plugin fiber removes its registrations. The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index c0db84fe78..115fb82e4c 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中打开**启用智能体团队协作**。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。团队设置整行在悬停时高亮,点击可切换状态,但独立的信息按钮除外。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。旁边的信息按钮可通过悬停、键盘聚焦或点击/轻触查看共享任务协作与额外 token 消耗的说明,不改变开关状态。按 Escape 或点击外部可关闭说明。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。保存时使用 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog),因此键盘激活的开关保留焦点,但不接受再次切换。 会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 @@ -47,7 +47,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
实现细节——点击展开 -Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。销毁插件 fiber 会移除这些注册。 +Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责页面导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.page` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 75eedfb3e7..44916c8f26 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -1,3 +1,63 @@ +.summary { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + width: 100%; + min-height: 34px; + padding: 7px 8px; + border: 0; + border-radius: var(--dsw-radius-md); + background: transparent; + color: var(--dsw-alias-label-primary); + font-family: inherit; + font-size: 13px; + font-weight: 400; + line-height: 20px; + text-align: start; + cursor: pointer; +} + +.summary:disabled { + opacity: 0.5; + cursor: default; +} + +.summary:focus-visible { + outline: none; + background: var(--dsw-alias-interactive-bg-hover); +} + +.summaryLabel { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.state, +.chevron { + flex: none; + color: var(--dsw-alias-label-secondary); +} + +.page { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.description { + margin: 0; + padding: 4px 8px; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; + overflow-wrap: anywhere; +} + .row { position: relative; display: flex; @@ -13,25 +73,14 @@ } .label { - display: inline-flex; - align-items: center; - gap: 4px; min-width: 0; + overflow-wrap: anywhere; } -.infoButton { - position: relative; - z-index: 1; - flex: none; - width: 20px; - height: 20px; - padding: 0; - color: var(--dsw-alias-label-caption); -} - -/* Extend the native switch hit target without nesting the information button. */ +/* The switch owns the whole row's pointer target. */ .row .toggle { position: static; + flex: none; } .toggle::after { @@ -46,6 +95,7 @@ } @media (hover: hover) { + .summary:not(:disabled):hover, .row:has(.toggle:not(:disabled)):hover { background: var(--dsw-alias-interactive-bg-hover); } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index cd0d3dcafa..15f6c93cae 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -1,7 +1,7 @@ -/** Session-owned Agent Teams selection in the model and reasoning menu. */ +/** Session-owned Agent Teams summary and settings inside the model menu. */ import { useState } from 'react' -import { Button, IconInfoOutlineRegular, Switch, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconChevronRightOutlineRegular, Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import type {} from '@deepseek-ai/dsh-agent-team/client' @@ -9,40 +9,75 @@ import type {} from '@deepseek-ai/dsh-agent' import type { NS } from './locales.ts' import css from './TeamModeToggle.module.css' -/** Session selection callbacks supplied by the Client plugin. */ -export interface TeamModeToggleInjected { +/** Session selection callbacks supplied to the Team settings page. */ +export interface TeamModePageInjected { /** Save the selection; null means success, otherwise the string describes the failure. */ selectTeamMode: (enabled: boolean) => Promise /** Open a Session-targeted confirmation outside this menu. */ requestDisableConfirmation: () => void } -/** Full props of the model-menu Team switch. */ -export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> - & PropsLocale & TeamModeToggleInjected +/** Full props of the model-menu Team summary. */ +export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> & PropsLocale + +/** Full props of the model-menu Team settings page. */ +export type TeamModePageProps = PropsRuntime<'conversation.input.model.page'> + & PropsLocale & TeamModePageInjected /** - * Render the saved selection without an optimistic update. - * @param props - Session projection, menu state, localized copy, and selection callback. - * @returns the Team switch when the capability projection is available. + * Show the saved Team state and open its settings without changing the mode. + * @param props - Session projection, page navigation, and locale. + * @returns the summary when Team mode is available on a root Session. */ export function TeamModeToggle(props: TeamModeToggleProps) { const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') if (addressedChild || listedChild) return null - return + return +} + +function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { + const mode = useProjection('agentTeam') + if (mode === undefined) return null + return ( + + ) +} + +/** + * Present the explanation and persisted Team switch for a root Session. + * @param props - Session projections, mode operations, menu dismissal, and locale. + * @returns the Team settings content when its projection is available. + */ +export function TeamModePage(props: TeamModePageProps) { + const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) + const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') + if (addressedChild || listedChild) return null + return } /** Read and change the selection only for root Sessions. */ -function RootTeamModeToggle({ +function RootTeamModePage({ useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, -}: TeamModeToggleProps) { +}: TeamModePageProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { + if (locked || pending || modelSelection === undefined) return + if (!enabled && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() return @@ -55,16 +90,13 @@ function RootTeamModeToggle({ }).finally(() => { setPending(false) }) } return ( -
- - {t('mode.label')} - - - - - +
+
+ {t('mode.label')} + +
+

{t('mode.description')}

) } diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index 0c5b29a4fb..8f4ed615a6 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -15,7 +15,8 @@ export const zh = { 'command.failedReason': '执行失败:{reason}', trigger: '任务板', 'mode.label': '启用智能体团队协作', - 'mode.infoLabel': '关于智能体团队协作', + 'mode.on': '开', + 'mode.off': '关', 'mode.description': '通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', 'mode.failed': '无法确认智能体团队协作设置已保存,请重试:{message}', 'disable.title': '确认停用智能体团队协作?', @@ -52,7 +53,8 @@ export const en = { 'command.failedReason': 'Failed: {reason}', trigger: 'Task board', 'mode.label': 'Enable agent teamwork', - 'mode.infoLabel': 'About agent teamwork', + 'mode.on': 'On', + 'mode.off': 'Off', 'mode.description': 'Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', 'mode.failed': 'Could not confirm the agent teamwork setting was saved. Try again: {message}', 'disable.title': 'Disable agent teamwork?', @@ -85,7 +87,8 @@ export const ja = { 'command.failed': '実行失敗', 'command.failedReason': '実行失敗: {reason}', 'mode.label': 'エージェント連携を有効にする', - 'mode.infoLabel': 'エージェント連携について', + 'mode.on': 'オン', + 'mode.off': 'オフ', 'mode.description': '共有タスクボードで複数のエージェントの分担と進捗を調整します。複雑なタスクでより良い結果が得られますが、その分トークンのコストも高くなります。', 'mode.failed': 'エージェント連携の設定が保存されたことを確認できませんでした。再試行してください: {message}', 'disable.title': 'エージェント連携を無効にしますか?', @@ -119,7 +122,8 @@ export const es = { 'command.failed': 'Error', 'command.failedReason': 'Error: {reason}', 'mode.label': 'Activar colaboración entre agentes', - 'mode.infoLabel': 'Acerca de la colaboración entre agentes', + 'mode.on': 'Activada', + 'mode.off': 'Desactivada', 'mode.description': 'Coordina el trabajo y el progreso de varios agentes mediante un tablero de tareas compartido, con mejores resultados en tareas complejas y un coste de tokens proporcionalmente mayor.', 'mode.failed': 'No se pudo confirmar que se guardó la configuración de colaboración entre agentes. Inténtalo de nuevo: {message}', 'disable.title': '¿Desactivar la colaboración entre agentes?', @@ -153,7 +157,8 @@ export const fr = { 'command.failed': 'Échec', 'command.failedReason': 'Échec : {reason}', 'mode.label': 'Activer la collaboration entre agents', - 'mode.infoLabel': 'À propos de la collaboration entre agents', + 'mode.on': 'Activée', + 'mode.off': 'Désactivée', 'mode.description': 'Coordonnez la répartition du travail et la progression de plusieurs agents via un tableau de tâches partagé, pour de meilleurs résultats sur les tâches complexes, avec un coût en tokens plus élevé en contrepartie.', 'mode.failed': 'Impossible de confirmer l’enregistrement du réglage de collaboration entre agents. Réessayez : {message}', 'disable.title': 'Désactiver la collaboration entre agents ?', @@ -187,7 +192,8 @@ export const de = { 'command.failed': 'Fehlgeschlagen', 'command.failedReason': 'Fehlgeschlagen: {reason}', 'mode.label': 'Agentenzusammenarbeit aktivieren', - 'mode.infoLabel': 'Über Agentenzusammenarbeit', + 'mode.on': 'Ein', + 'mode.off': 'Aus', 'mode.description': 'Koordiniert die Arbeitsteilung und den Fortschritt mehrerer Agenten über eine gemeinsame Aufgabenübersicht. Erzielt bessere Ergebnisse bei komplexen Aufgaben, bei entsprechend höheren Tokenkosten.', 'mode.failed': 'Das Speichern der Einstellung zur Agentenzusammenarbeit konnte nicht bestätigt werden. Erneut versuchen: {message}', 'disable.title': 'Agentenzusammenarbeit deaktivieren?', @@ -221,7 +227,8 @@ export const ru = { 'command.failed': 'Ошибка', 'command.failedReason': 'Ошибка: {reason}', 'mode.label': 'Включить совместную работу агентов', - 'mode.infoLabel': 'О совместной работе агентов', + 'mode.on': 'Вкл.', + 'mode.off': 'Выкл.', 'mode.description': 'Координируйте распределение работы и прогресс нескольких агентов с помощью общей доски задач: лучшие результаты в сложных задачах при соответственно более высоких затратах на токены.', 'mode.failed': 'Не удалось подтвердить сохранение настройки совместной работы агентов. Повторите попытку: {message}', 'disable.title': 'Отключить совместную работу агентов?', @@ -255,7 +262,8 @@ export const pt = { 'command.failed': 'Falha', 'command.failedReason': 'Falha: {reason}', 'mode.label': 'Ativar colaboração entre agentes', - 'mode.infoLabel': 'Sobre a colaboração entre agentes', + 'mode.on': 'Ativada', + 'mode.off': 'Desativada', 'mode.description': 'Coordene a divisão do trabalho e o progresso de vários agentes com um quadro de tarefas compartilhado, para melhores resultados em tarefas complexas, com custos de tokens proporcionalmente maiores.', 'mode.failed': 'Não foi possível confirmar que a configuração de colaboração entre agentes foi salva. Tente novamente: {message}', 'disable.title': 'Desativar a colaboração entre agentes?', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 833267e39e..8f22910564 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -11,7 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' -import { TeamModeToggle, type TeamModeToggleInjected } from './TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from './TeamModeToggle.tsx' import { TeamBoard } from './TeamBoard.tsx' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -58,11 +58,14 @@ export function registerAgentTeamUi(ctx: ClientContext): void { name: 'conversation.input.model.options', id: 'agent-team', locale: NS, - inject: (sessionId): TeamModeToggleInjected => ({ + }, TeamModeToggle)) + yield scope.slots.inject('conversation.input.model.page', () => scope.slots.register({ + name: 'conversation.input.model.page', key: 'agent-team', locale: NS, + inject: (sessionId): TeamModePageInjected => ({ selectTeamMode: enabled => selectTeamMode(sessionId, enabled), requestDisableConfirmation: () => { disableRequest.set({ sessionId }) }, }), - }, TeamModeToggle)) + }, TeamModePage)) }) }) ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index ba964a033f..c5bab1fe0a 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleInjected } from '../src/client/TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { TeamBoard } from '../src/client/TeamBoard.tsx' @@ -62,21 +62,30 @@ describe('task-board browser plugin', () => { await b.fiber.dispose() }) - it('registers the mode switch when Agent Teams arrives and reports each execution outcome', async () => { + it('registers the summary and settings page when Agent Teams arrives and reports each execution outcome', async () => { const b = await bench() b.ctx.slots.register({ name: 'conversation.input.model', - children: { 'conversation.input.model.options': { kind: 'list', scope: 'session' } }, + children: { + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, + }, } as never, () => null) const entry = () => b.ctx.slots.entries('conversation.input.model.options') .find(candidate => candidate.component === TeamModeToggle) + const page = () => b.ctx.slots.entries('conversation.input.model.page') + .find(candidate => candidate.component === TeamModePage) expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() const setEnabled = vi.fn() new TestRemote(b.ctx, { agentTeams: { setEnabled } }) - await vi.waitFor(() => { expect(entry()).toBeDefined() }) - const injected = entry()!.inject as (sessionId: SessionId) => Record + await vi.waitFor(() => { expect(entry()).toBeDefined(); expect(page()).toBeDefined() }) + expect(entry()).toMatchObject({ options: { id: 'agent-team' }, locale: 'agent-team' }) + expect(entry()!.inject).toBeUndefined() + expect(page()).toMatchObject({ options: { key: 'agent-team' }, locale: 'agent-team' }) + const injected = page()!.inject as (sessionId: SessionId) => Record const value: object = injected(SessionId('chosen-session')) - const mode = value as TeamModeToggleInjected + const mode = value as TeamModePageInjected setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) await expect(mode.selectTeamMode(true)).resolves.toBeNull() expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', true) @@ -104,6 +113,7 @@ describe('task-board browser plugin', () => { mode.requestDisableConfirmation() await b.fiber.dispose() expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() expect(overlayEntry()).toBeUndefined() expect(request.getSnapshot()).toBeNull() }) diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 13a1da8450..9fa08dacc9 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -1,18 +1,17 @@ // @vitest-environment jsdom -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { SessionId } from '@deepseek-ai/dsh-session' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { TeamModePage, TeamModeToggle, type TeamModePageProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) +afterEach(cleanup) -function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TeamModeToggleProps { +type TestProps = TeamModePageProps & TeamModeToggleProps + +function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TestProps { return { sessionId: SessionId('root'), useSession: (select: (value: { subagent: object | null }) => unknown) => select({ subagent: child === 'addressed' ? {} : null }), @@ -20,69 +19,112 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), - } as TeamModeToggleProps + } as TestProps } -it('renders only available mode and waits for persisted state before displaying a new selection', async () => { - let finish!: (result: string | null) => void - const select = vi.fn(() => new Promise((resolve) => { finish = resolve })) - const view = render() +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => + [false, true].map(enabled => ({ locale, dictionary, enabled })), +))('opens Team settings from the $locale summary without changing mode (enabled: $enabled)', ({ dictionary, enabled }) => { + const input = props(enabled) + render() + const summary = screen.getByRole('menuitem', { name: new RegExp(dictionary['command.title']) }) + expect(summary.textContent).toBe(dictionary['command.title'] + dictionary[enabled ? 'mode.on' : 'mode.off']) + expect(summary.getAttribute('data-model-menu-page')).toBe('agent-team') expect(screen.queryByRole('switch')).toBeNull() - view.rerender() + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByText(dictionary['mode.description'])).toBeNull() + fireEvent.click(summary) + expect(input.openPage).toHaveBeenCalledExactlyOnceWith({ key: 'agent-team', title: dictionary['command.title'] }) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() +}) + +it('keeps summary state projection-owned and blocks navigation while locked', () => { + const input = props(false) + const view = render() + expect(screen.getByText('关')).toBeTruthy() + const lockedInput = props(true) + view.rerender() + expect(screen.getByText('开')).toBeTruthy() + const summary = screen.getByRole('menuitem') + expect(summary.hasAttribute('disabled')).toBe(true) + fireEvent.click(summary) + expect(lockedInput.openPage).not.toHaveBeenCalled() +}) + +it('allows reading settings from the summary while model history loads', () => { + const input = props(false, undefined, undefined, 'loading') + render() + fireEvent.click(screen.getByRole('menuitem')) + expect(input.openPage).toHaveBeenCalledOnce() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it.each([false, true])('retains focus and blocks repeated writes while waiting for persisted mode (enabled: %s)', async (enabled) => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const select = vi.fn(() => pending.promise) + const view = render() const toggle = screen.getByRole('switch', { name: '启用智能体团队协作' }) + toggle.focus() fireEvent.click(toggle) - expect(select).toHaveBeenCalledWith(true) - expect(toggle.getAttribute('aria-checked')).toBe('false') - expect(toggle.hasAttribute('disabled')).toBe(true) - await act(async () => { finish(null) }) - view.rerender() - expect(toggle.getAttribute('aria-checked')).toBe('true') + expect(select).toHaveBeenCalledExactlyOnceWith(!enabled) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) + expect(toggle.hasAttribute('disabled')).toBe(false) + expect(toggle.getAttribute('aria-disabled')).toBe('true') + expect(toggle.getAttribute('aria-busy')).toBe('true') + expect(document.activeElement).toBe(toggle) + fireEvent.click(toggle) + fireEvent.click(toggle) + expect(select).toHaveBeenCalledTimes(1) + await act(async () => { pending.resolve(null) }) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) + expect(toggle.getAttribute('aria-disabled')).toBeNull() + expect(toggle.getAttribute('aria-busy')).toBeNull() + view.rerender() + expect(toggle.getAttribute('aria-checked')).toBe(String(!enabled)) + expect(document.activeElement).toBe(toggle) }) it.each(['returned', 'error', 'string'])('reports rejected mode writes through the menu host (%s)', async (failure) => { - const p = props(false, vi.fn(async () => { + const input = props(false, vi.fn(async () => { if (failure === 'error') throw new Error('offline') if (failure === 'string') throw 'offline' return 'offline' })) - render() - await act(async () => { fireEvent.click(screen.getByRole('switch')) }) - expect(p.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) + render() + const toggle = screen.getByRole('switch') + toggle.focus() + await act(async () => { fireEvent.click(toggle) }) + expect(document.activeElement).toBe(toggle) + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(input.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false) }) it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => [false, true].map(locked => ({ locale, dictionary, locked })), -))('opens the $locale explanation without changing Team mode (locked: $locked)', ({ dictionary, locked }) => { - vi.stubGlobal('ResizeObserver', class { - observe() {} - unobserve() {} - disconnect() {} - }) +))('shows the full $locale explanation in the settings page (locked: $locked)', ({ dictionary, locked }) => { const input = props(false) - render() - const info = screen.getByRole('button', { name: dictionary['mode.infoLabel'] }) - expect(info.hasAttribute('disabled')).toBe(false) - fireEvent.click(info) - const tooltip = screen.getByRole('tooltip', { hidden: true }) - expect(tooltip.textContent).toBe(dictionary['mode.description']) - expect(info.getAttribute('aria-describedby')).toBe(tooltip.id) - expect(document.body.contains(tooltip)).toBe(true) - expect(input.selectTeamMode).not.toHaveBeenCalled() - expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') - fireEvent.keyDown(info, { key: 'Escape' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - fireEvent.click(info) - fireEvent.pointerDown(document.body) + render() + const description = screen.getByText(dictionary['mode.description'], { exact: true }) + expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByRole('button')).toBeNull() + const toggle = screen.getByRole('switch', { name: dictionary['mode.label'] }) + expect(toggle.compareDocumentPosition(description) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(toggle.hasAttribute('disabled')).toBe(locked) + expect(toggle.getAttribute('aria-checked')).toBe('false') expect(input.selectTeamMode).not.toHaveBeenCalled() }) -it('requests confirmation before disabling after a recorded model request', () => { +it('dismisses the menu before requesting disable confirmation after a recorded model request', () => { const input = props(true, undefined, undefined, true) - render() + render() fireEvent.click(screen.getByRole('switch')) expect(input.dismiss).toHaveBeenCalledOnce() expect(input.dismiss).toHaveBeenCalledBefore(vi.mocked(input.requestDisableConfirmation)) @@ -93,39 +135,52 @@ it('requests confirmation before disabling after a recorded model request', () = it.each([false, true])('enables directly regardless of model history (requested: %s)', async (requested) => { const input = props(false, undefined, undefined, requested) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(true) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) it('disables directly when a model is selected but no request has been recorded', async () => { const input = props(true) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(false) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) -it('waits for model history before allowing the switch to change', () => { +it('waits for model history before allowing the settings switch to change', () => { const input = props(true, undefined, undefined, 'loading') - render() + render() expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) fireEvent.click(screen.getByRole('switch')) expect(input.selectTeamMode).not.toHaveBeenCalled() expect(input.requestDisableConfirmation).not.toHaveBeenCalled() }) -it('disables selection while the Session is locked', () => { - render() - expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings page', Component: TeamModePage }, +])('hides the $name until the Team projection is available', ({ Component }) => { + const { container } = render() + expect(container.textContent).toBe('') + expect(screen.queryByRole('menuitem')).toBeNull() + expect(screen.queryByRole('switch')).toBeNull() }) -it.each(['addressed', 'listed'] as const)('hides the switch on a child Session (%s)', (source) => { - const input = props(false, undefined, source) - const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) - render() - expect(screen.queryByRole('switch')).toBeNull() - expect(useProjection).not.toHaveBeenCalled() - expect(input.selectTeamMode).not.toHaveBeenCalled() -}) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings page', Component: TeamModePage }, +].flatMap(entry => (['addressed', 'listed'] as const).map(child => ({ ...entry, child }))))( + 'hides the $name on a $child child Session', ({ Component, child }) => { + const input = props(false, undefined, child) + const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) + const { container } = render() + expect(container.textContent).toBe('') + expect(useProjection).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.openPage).not.toHaveBeenCalled() + }, +) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index f0b4774867..3d37eb7f75 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 0e2230da6a2214a1 - zh: 0452e7556c9175f2 + en: 8caa289a6b9a3987 + zh: 4e68187154ad7a01 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: cead8d55a9508a8f - zh: d1ef63a880cbec55 + en: 7444798cb92d0f38 + zh: 03edcc1070554437 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 @@ -27,11 +27,11 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 80fc237fa5c829f7 - zh: ecff5c8526f45996 + en: 393aae0df60e2abd + zh: f989d6108a047160 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: - en: c1d14a925c92950f - zh: f80f8169bc283c60 + en: feab134e75f5b2f7 + zh: 66bd58568f58ed4f /deepseek-ai-dsh-client-ui-model-selection/further-exploration: en: 14acd4692e923480 zh: ff89aed852aa0da8 @@ -42,8 +42,8 @@ en: 68e54c00412a40d1 zh: 0ac96f57fd194d96 /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work: - en: 7003aff3aa57e40c - zh: 450d88a5e9332f05 + en: 01a55381300a60c5 + zh: 3561ca742b9272ca /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index ec0aba0d4e..55adbc748d 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -29,22 +29,24 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses DeepSeek account and API-key routes appear as separate provider groups, each exposing the same configured model catalog. -When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. +When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape closes it. Tab and Shift+Tab traverse its controls and leave the menu at either end. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. -Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown on desktop devices; otherwise it focuses the current model or effort row, or the first enabled row when none is selected. Going back focuses the cell that opened the pane. Phones and tablets leave search unfocused until the user taps it or uses keyboard navigation. The composer shows the catalog name while the selected model is available. Removing a model or provider, including account sign-out, preserves the stored provider, model, and reasoning effort without displaying their IDs. Restoring the catalog entry restores its name and effort caption. +Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab move to the adjacent control. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes the menu and returns focus there. Root rows and the search-clear button show the same fill for keyboard focus and hover, without a native outline. Selecting a model or effort returns focus to the trigger without a focus ring; leaving the trigger or reopening the menu restores its normal focus indication. While a selection from either entry is pending, focus stays on the trigger, the trigger shows a spinner in place of its chevron, and each row whose value the selection carries shows one in place of its check; a rejected selection leaves the menu open. Tab returns to model search with the current model highlighted when search is shown, otherwise to the current row. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort keeps the menu and slider focus in place. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; an effort save also keeps slider focus. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. ### Model and effort -The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups; Enter or Tab selects it. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. +The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups. In the composer menu, Enter selects the result and Tab moves focus without selecting it; the `/model` popup retains its command-menu keyboard behavior. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. -Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. +Model names use weight 400 (regular); the current effort tag uses weight 500. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. -Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. +Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the reasoning slider absent; there is no arbitrary effort input. The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. +The 260px-wide root menu places the model name above a centered effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag uses the default cursor and its text cannot be selected; hovering still shows the localized “Reasoning effort: {effort}” tooltip without adding a Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. A `Default` stop appears only when the adapter has no configured default effort and submits no explicit effort; it is not a promise of a fixed provider strength. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. + ### Model label extensions `conversation.input.model.label` is a session-scoped, inline `single` slot for the composer trigger (`placement: 'trigger'`), the root menu's current value (`'menu'`), and each model option (`'option'`). Its owner props provide `provider: { id, name }`, the exact catalog `model`, `placement`, and `selected`. Provider names are localized display names; match channels by `provider.id`, and identify a model by the provider/model ID pair. Connection URLs and credentials are not passed to the slot. @@ -61,18 +63,18 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends controls below model and reasoning selection. Owner props expose `locked`, `reportFailure(message)`, and `dismiss()`, which closes the menu and synchronously focuses its trigger before another overlay opens; contributions read their own projections and supply narrow commands. Enabled switch buttons participate in the menu’s keyboard navigation. +The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. ----- ## Understand the implementation -Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. Model and reasoning-effort lists scroll vertically within the panel height limit. -
Implementation internals — click to expand +Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. The root controls, model list, and settings pages have their own scroll area inside the panel height limit. + The composer `ModelSelect` and `/model` option builder share [provider ordering](src/client/provider-order.ts), while both searches use `rankByName` within each provider. The command supplies optional groups and `searchMode: 'fuzzy-label'` through the [popupSelect API](../ui-commands/README.md#use-this-package); both entries use `MenuGroup` and rebuild its sticky observer when the rendered groups change. The command popup fills the composer overlay, while the button retains its compact menu. Two entries over ONE per-session directory owned by `ModelDirectoryResolver` (`ctx.modelDirectories`): the `/model` popupSelect contribution (registered through `ctx.commandUi`) and the composer's named `conversation.input.model` seat both load the session's available directory through `session.models` and submit through `session.selectModel` via the same `ModelDirectory` instance, so a switch made in either entry is what the other shows next. Directory loads and selections share a generation counter so an older response never overwrites a newer one. The directory publishes the latest submitted selection as `pending` until it settles or a connection reset invalidates it; a connection reset drops every resident projection and repulls the Host-restored selection before display. Directories are per-session, resolved lazily, and disposed with the session scope; addressed subagent sessions expose neither entry. Every resident directory refetches directly on forwarded `llm/adapters-updated`, `llm/models-updated`, `settings/document-updated`, and credential update events. @@ -110,7 +112,7 @@ These limits define the current model surface. They are current package constrai - **No create-time or addressed-subagent selection** — both entries require an existing ordinary session's Agent; there is no draft-phase model choice to fold into session creation, and subagent continuation deliberately exposes no independent model-selection contract. - **Directory names are presentation-only** — selection and persistence use provider/model/effort ids; a provider whose catalog or exact-model metadata lookup fails lists as an unselectable failure row until reload. -- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the Effort row absent. +- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the reasoning slider absent. - **Badges label the composer seat only** — `/model` popup rows, the trigger's accessible name, and its tooltip keep the plain catalog name. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 864d3ea9ff..f92ff2ffdd 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -29,22 +29,24 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示相同的已配置模型目录。 -未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” +未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 关闭列表。Tab 和 Shift+Tab 遍历列表内的控件,到达两端时离开菜单。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时,桌面设备在显示模型搜索框时聚焦搜索框;其他情况聚焦当前模型或推理强度行,没有选中项时聚焦首个可用行。返回时聚焦打开该面板的格子。手机和平板在用户主动点按搜索框或使用键盘导航前,不会聚焦搜索框。所选模型可用时,composer 显示目录中的模型名称。模型或提供方被删除时(包括账号退登),保留已保存的提供方、模型和推理强度,但不展示其 ID。目录条目恢复后重新显示名称和推理强度。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 移至相邻控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击触发按钮会关闭菜单并把焦点还给它。根菜单行和搜索清除按钮的键盘焦点与悬停使用相同底色,不显示原生焦点轮廓。选定模型或推理等级后,焦点返回触发按钮但不显示焦点环;焦点离开按钮或重新打开菜单后恢复正常焦点提示。等待任一入口发起的选择结果时,焦点停在触发按钮,触发按钮以加载图标代替下拉箭头,该选择包含的值所在行以加载图标代替勾选标记;选择被拒绝后菜单保持打开。显示模型搜索框时,Tab 返回搜索框并高亮当前模型,否则返回当前选中行。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级后保持菜单打开和滑块焦点。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存期间也保留滑块焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 ### 模型与推理强度 -按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框;Enter 或 Tab 选定高亮项。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 +按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框。composer 菜单用 Enter 选定高亮项,Tab 只移动焦点而不选定;`/model` 弹窗保留命令菜单的键盘行为。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 -composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 +composer 菜单中的模型名称使用 400(regular)字重;当前推理等级标签使用 500 字重。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 -两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 +两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示推理滑块;不存在任意推理强度输入。 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 +260px 宽的一级菜单将模型名放在上方,下方显示居中的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签使用默认鼠标指针,文字不可选中;悬停仍显示本地化的“推理等级:{effort}”提示,不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。仅当适配器未配置默认强度时出现 `Default` 刻度,它不提交显式强度,也不承诺提供方会使用固定档位。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 + ### 模型名称扩展 `conversation.input.model.label` 是会话作用域的内联 `single` slot,覆盖 composer 触发按钮(`placement: 'trigger'`)、根菜单中的当前值(`'menu'`)和各模型选项(`'option'`)。owner props 提供 `provider: { id, name }`、准确的目录 `model`、`placement` 和 `selected`。提供方名称是本地化显示名称;按 `provider.id` 匹配渠道,按提供方与模型 ID 的组合识别模型。slot 不接收连接 URL 或凭据。 @@ -61,18 +63,18 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。Owner props 提供 `locked`、`reportFailure(message)` 和 `dismiss()`,后者关闭菜单并同步聚焦触发按钮,供贡献方随后打开其他浮层;贡献方读取自身投影并提供专用命令。启用的开关按钮参与菜单键盘导航。 +会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 ----- ## 理解实现 -菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。模型与推理等级列表在面板高度限制内纵向滚动。 -
实现细节——点击展开 +菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。一级控件、模型列表和设置二级页均在面板高度限制内使用各自的滚动区域。 + composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](src/client/provider-order.ts),两个搜索框均在每个提供方内使用 `rankByName`。命令通过 [popupSelect API](../ui-commands/README.zh.md#use-this-package) 提供可选分组与 `searchMode: 'fuzzy-label'`;两个入口均使用 `MenuGroup`,并在渲染分组变化时重建其吸顶观察器。命令弹窗撑满 composer 浮层,按钮则保留紧凑菜单。 两个入口共用一份由 `ModelDirectoryResolver`(`ctx.modelDirectories`)持有的会话级目录:`/model` popupSelect 贡献项(经 `ctx.commandUi` 注册)与 composer 的具名 `conversation.input.model` 位都经 `session.models` 加载会话的可用目录、经 `session.selectModel` 通过同一个 `ModelDirectory` 实例提交,因此任一入口所做的切换正是另一个入口接下来显示的。目录加载与选择共享一个代次计数器,旧响应不会覆盖新结果。目录把最近一次提交的选择发布为 `pending`,直到它完成或被连接重置作废;连接重置丢弃所有常驻投影,并在显示前重新拉取 Host 恢复的选择。目录按会话惰性解析,随会话作用域一并 dispose(资源释放);已寻址 subagent 会话不公开任一入口。每份常驻目录都会直接在转发的 `llm/adapters-updated`、`llm/models-updated`、`settings/document-updated` 与凭据更新事件上重拉。 @@ -110,7 +112,7 @@ composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](s - **无创建期或已寻址 subagent 选择**——两个入口都要求既有普通会话的 agent(智能体);没有可纳入会话创建的草稿阶段模型选择,subagent 继续执行也有意不公开独立的模型选择约定。 - **目录名仅供呈现**——选择与持久化使用提供方/模型/推理强度 id;目录查询或确切模型元数据查询失败的提供方以不可选失败行列出,重新加载前保持原样。 -- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示 Effort 行。 +- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示推理滑块。 - **角标只出现在 composer 模型位**——`/model` 弹窗各行、触发按钮的无障碍名称及其提示仍只显示目录名称。 diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css new file mode 100644 index 0000000000..645a5f5b61 --- /dev/null +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -0,0 +1,141 @@ +.root { + display: contents; + --effort-thumb-size: 20px; + --effort-track-size: 16px; +} + +.heading { + grid-row: 2; + display: flex; + justify-content: center; + height: 22px; + margin: 10px 14px 0; +} + +.value { + max-width: 100%; + padding: 1px 10px; + border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); + border-radius: 999px; + corner-shape: round; + background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); + color: var(--dsw-alias-state-business-primary); + font-size: 13px; + line-height: 18px; + font-weight: 500; + text-align: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + cursor: default; + -webkit-user-select: none; + user-select: none; +} + +.rail { + grid-row: 3; + position: relative; + margin: 0 8px 2px; +} + +.range { + appearance: none; + display: block; + box-sizing: border-box; + width: 100%; + height: 40px; + margin: 0; + padding: 0; + border: 0; + background: transparent; + cursor: pointer; + touch-action: pan-y; +} + +.range::-webkit-slider-runnable-track { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: + linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent) 0, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent) var(--effort-progress), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) var(--effort-progress), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) 100%), + color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.range::-moz-range-track { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.range::-moz-range-progress { + height: var(--effort-track-size); + border-radius: 999px; + corner-shape: round; + background: linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); +} + + + +.range::-webkit-slider-thumb { + appearance: none; + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + margin-top: calc((var(--effort-track-size) - var(--effort-thumb-size)) / 2); + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); + box-shadow: var(--dsw-elevation-panel); +} + +.range::-moz-range-thumb { + box-sizing: border-box; + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); + box-shadow: var(--dsw-elevation-panel); +} + +.range:focus-visible { + outline: 2px solid var(--dsw-alias-state-business-primary); + outline-offset: 1px; + border-radius: var(--dsw-radius-sm); +} + +.range:disabled { + opacity: 0.5; + cursor: default; +} + +.ticks { + position: absolute; + inset: 0 calc(var(--effort-thumb-size) / 2); + display: flex; + align-items: center; + justify-content: space-between; + pointer-events: none; +} + +.tick, +.tickActive { + width: 4px; + height: 4px; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-label-caption); + opacity: 0.6; +} + +.ticks [data-current] { + visibility: hidden; +} diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx new file mode 100644 index 0000000000..301055506f --- /dev/null +++ b/packages/client/ui-model-selection/src/client/EffortSlider.tsx @@ -0,0 +1,122 @@ +import { useState, type CSSProperties } from 'react' +import { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import css from './EffortSlider.module.css' + +/** One adapter-advertised stop; undefined selects the adapter's default behavior. */ +export interface EffortChoice { + key: string + effort: string | undefined + label: string +} + +/** Data and localized chrome supplied by the model selector. */ +export interface EffortSliderProps { + choices: readonly EffortChoice[] + value: string | undefined + label: string + currentLabel: string + /** Localized tooltip text for the currently displayed effort name. */ + formatTooltip: (effort: string) => string + disabled: boolean + /** A selection is being saved; keep its displayed value and keyboard focus. */ + pending: boolean + onSelect: (effort: string | undefined) => void +} + +type Gesture = { kind: 'pointer' | 'keyboard' | 'cancelled'; source: string; index: number } +const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) + +/** + * Preview a discrete selection locally and submit once when the gesture finishes. + * @param props - Exact-model choices, persisted value, and selection callback. + * @returns A native discrete range with a live value label. + */ +export function EffortSlider({ choices, value, label, currentLabel, formatTooltip, disabled, pending, onSelect }: EffortSliderProps) { + const selectedIndex = choices.findIndex(choice => choice.effort === value) + const source = JSON.stringify([choices.map(choice => [choice.key, choice.effort]), value]) + const [gesture, setGesture] = useState(null) + const preview = gesture?.source === source && gesture.kind !== 'cancelled' ? gesture.index : selectedIndex + const index = Math.max(0, preview) + const current = choices[preview] + const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 + const commit = (nextIndex: number): void => { + const choice = choices[nextIndex] + setGesture(null) + if (!disabled && !pending && choice !== undefined) onSelect(choice.effort) + } + const finish = (kind: Gesture['kind'], nextIndex: number): void => { + if (gesture?.kind === kind && gesture.source === source) commit(nextIndex) + else setGesture(null) + } + return ( +
1 ? index / (choices.length - 1) * 100 : 0}%`, + } as CSSProperties} + > +
+ + {current?.label ?? currentLabel} + +
+
+ { + if (pending) { event.preventDefault(); return } + setGesture({ kind: 'pointer', source, index }) + }} + onChange={(event) => { + if (pending || disabled) return + const nextIndex = event.currentTarget.valueAsNumber + if (gesture === null) commit(nextIndex) + else if (gesture.source === source && gesture.kind !== 'cancelled') setGesture({ ...gesture, index: nextIndex }) + }} + onPointerUp={(event) => { finish('pointer', event.currentTarget.valueAsNumber) }} + onPointerCancel={() => { setGesture(null) }} + onLostPointerCapture={() => { setGesture(null) }} + onBlur={() => { setGesture(null) }} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return + if (pending && ADJUST_KEYS.has(event.key)) { + event.preventDefault() + event.stopPropagation() + return + } + if (event.key === 'Escape' && gesture !== null) { + event.preventDefault() + event.stopPropagation() + setGesture({ ...gesture, kind: 'cancelled' }) + } else if (ADJUST_KEYS.has(event.key)) { + event.stopPropagation() + if (gesture === null) setGesture({ kind: 'keyboard', source, index }) + } + }} + onKeyUp={(event) => { + if (ADJUST_KEYS.has(event.key)) { + event.stopPropagation() + finish('keyboard', event.currentTarget.valueAsNumber) + } + }} + /> + +
+
+ ) +} diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index 9ef7fc2e80..802871af67 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -106,13 +106,14 @@ z-index: 1100; display: flex; flex-direction: column; - /* Rows size the card up to its visible bounds; longer names ellipsize. */ - width: fit-content; + /* Every pane shares one width so drilling in cannot resize the card. */ + width: min(260px, calc(100vw - 24px)); height: fit-content; - min-width: min(240px, calc(100vw - 24px)); - max-width: min(420px, calc(100vw - 24px)); + min-width: 0; + max-width: min(260px, calc(100vw - 24px)); max-height: min(360px, calc(100dvh - 96px)); overflow: hidden; + outline: none; padding: 4px; /* Surface tokens match the Menu primitive card (ui-primitives * Menu.module.css) so every dropdown reads as the same material. */ @@ -129,6 +130,65 @@ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } + + +.rootPage { + display: flex; + flex-direction: column; + min-height: 0; + overflow-y: auto; +} + +.rootPage > * { + flex-shrink: 0; +} + +.reasoningPage { + display: grid; + grid-template-columns: minmax(0, 1fr); +} + +.reasoningPage .modelHeadline { + grid-row: 1; + justify-self: center; + justify-content: center; + width: fit-content; + min-width: 0; + max-width: 100%; + height: 34px; + margin: 4px 0 0; + padding: 0 6px; + gap: 2px; + border-radius: var(--dsw-radius-sm); +} + +.reasoningPage .modelHeadline .cellChevron { + width: 10px; + height: 10px; +} + +.modelHeadline .cellLabel { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); +} + +.modelHeadline .cellValue { + flex: 0 1 auto; + text-align: center; + font-size: 14px; + color: var(--dsw-alias-label-secondary); +} + +.pageBody { + width: 100%; + min-width: 0; + min-height: 0; + overflow-y: auto; +} + .status, .empty { padding: 8px; @@ -362,11 +422,16 @@ } @media (hover: hover) { - .cell:hover { + .cell:hover:not(.modelHeadline), + .reasoningPage .modelHeadline:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } } +.rootPage .cell[data-return-focus]:is(:hover, :focus-visible) { + background: transparent; +} + .cellLabel { flex: 0 0 auto; white-space: nowrap; diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 3eea3e37ad..0ae454ffed 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -1,31 +1,6 @@ /** - * ModelSelect: the composer's named model seat (`conversation.input.model`). - * Two-level selection per figma 496:26454's MenuDropdown: the root menu is - * the Model / Effort row pair (label + current value + a right chevron), - * each drilling into its own list — the provider-grouped model list over - * the shared directory, and the effort levels. The trigger (313:14108's - * ToggleButton) shows both: model name + effort in the caption tone. - * Model catalogs above four entries show search, which retains focus while - * ↑/↓ cycle the highlighted result; Enter and Tab accept it. Smaller model - * catalogs, root panes, and effort panes move focus between rows. Escape and Shift+Tab leave a drilled pane first and otherwise close - * back to the trigger. A drilled pane focuses the current effort or model - * search field. Provider headings paint their background only while pinned - * by scrolling. Clearing a query restores the full list and search focus. - * Selecting restores trigger focus without a ring until the trigger loses focus - * or the menu reopens. Mobile devices restore button focus when opening or - * drilling; model search takes focus only after explicit user input. - * Model names match a case-insensitive ordered subsequence - * within each provider group, ranked by - * prefix, alignment score, then catalog order. Returning to the root pane - * hands focus back to the cell that opened it. Data and submission ride the - * same per-session ModelDirectory as the /model popup; exact-model reasoning - * metadata and the selected effort come from the Host rather than a - * client-owned vocabulary. A rejected selection announces through the shared - * transient Toast anchored to the composer card; the in-menu strip with - * Retry remains the catalog-load surface. While the directory's pending - * selection is unsettled, the trigger shows a spinner in place of its - * chevron, and each row whose value that selection carries shows one in place - * of its check mark. + * Session model menu with inline reasoning stops and keyed settings pages. + * Model choices and submissions share the same directory as the /model command. */ import { MenuGroup, MenuSurface, observeStickyMenuGroups } from '@deepseek-ai/dsh-client-ui-primitives' import { @@ -36,23 +11,18 @@ import { createPortal } from 'react-dom' import clsx from 'clsx' import type { ModelReasoningEffort, ModelSelection } from '@deepseek-ai/dsh-api-remotes/client' import { - IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, + IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, + IconCloseFillRegular, IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuPage, ModelSelectInjected } from './slots.ts' +import { EffortSlider, type EffortChoice } from './EffortSlider.tsx' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ -type Pane = 'root' | 'model' | 'effort' - -/** One dynamic effort row; undefined means preserve the provider default. */ -interface EffortChoice { - key: string - effort: string | undefined - label: string -} +/** The root controls, all models, or a keyed plugin-owned settings page. */ +type Pane = 'root' | 'model' | ModelMenuPage /** * Render the composer model seat. @@ -63,7 +33,7 @@ interface EffortChoice { export function ModelSelect( { locked, available, directory, load, select, resolveText, t, renderSlot }: ModelSelectInjected & Pick, 'locked'> & PropsLocale<'model'> - & Omit, 'SessionProvider'>, + & Omit, 'SessionProvider'>, ) { const state = useSyncExternalStore( fn => directory.subscribe(fn), @@ -74,6 +44,7 @@ export function ModelSelect( const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) + const [modelReturnFocus, setModelReturnFocus] = useState(false) // The in-menu error strip serves catalog loads (its Retry re-runs the // load); a rejected SELECTION announces through the transient toast // instead, so the strip renders only while the latest failure-capable @@ -176,15 +147,25 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | 'effort' | null>(null) + const paneFocus = useRef<'drill' | 'model' | 'effort' | ModelMenuPage | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) + if (intent === 'effort' && busy) return paneFocus.current = null if (!open || intent === null) return + if (intent === 'effort') { + menuRef.current?.querySelector('input[type="range"]:not([disabled])')?.focus() + return + } if (intent === 'drill') { + if (typeof pane === 'object') { + const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') + ;(first ?? menuRef.current ?? triggerRef.current)?.focus() + return + } if (pane === 'model' && showSearch && !isMobileDevice()) { searchRef.current?.focus() return @@ -198,9 +179,11 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = itemRefs.current[intent === 'effort' ? 1 : 0] + const cell = intent === 'model' ? itemRefs.current[0] + : Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) + .find(button => button.dataset.modelMenuPage === intent.key) ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() - }, [open, pane, showSearch]) + }, [open, pane, showSearch, selectionFocus, busy]) useEffect(() => { const viewport = groupsRef.current @@ -218,6 +201,7 @@ export function ModelSelect( const show = (): void => { setSelectionFocus(false) + setModelReturnFocus(false) triggerRef.current?.focus() setQuery('') setHighlightedIndex(null) @@ -238,11 +222,6 @@ export function ModelSelect( if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - const closeAfterSelection = (): void => { - setSelectionFocus(true) - close(true) - } - const drill = (next: Pane): void => { setQuery('') setHighlightedIndex(null) @@ -252,13 +231,14 @@ export function ModelSelect( /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ const back = (from: Exclude): void => { + setModelReturnFocus(from === 'model') paneFocus.current = from setPane('root') } const moveFocus = (offset: number): void => { - const items = Array.from(menuRef.current?.querySelectorAll( - 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', + const items = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled]), input[type="range"]:not([disabled])', ) ?? []) if (items.length === 0) return const active = items.findIndex(item => item === document.activeElement) @@ -275,63 +255,60 @@ export function ModelSelect( if (event.nativeEvent.isComposing) return if (event.key === 'Escape' && open) { event.preventDefault() + event.stopPropagation() // Escape backs out of a drilled pane first, then closes. - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (typeof pane === 'object' || (pane === 'model' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (event.key === 'Tab') { + const menu = menuRef.current + const trigger = triggerRef.current + if (menu === null || trigger === null) return + const stops = Array.from(menu.querySelectorAll('button, input, select, textarea, a[href], [tabindex]')) + .filter(item => item.tabIndex >= 0 && !item.matches(':disabled') && item.closest('[hidden], [inert]') === null) + const focused = document.activeElement + if (focused === trigger || focused === menu) { + if (event.shiftKey) { + close() + if (focused === menu) { event.preventDefault(); trigger.focus() } + } else { + event.preventDefault() + ;(stops[0] ?? trigger).focus() + } + return + } + const index = stops.findIndex(item => item === focused) + if (index < 0) return + const next = stops[index + (event.shiftKey ? -1 : 1)] + if (next !== undefined) { + event.preventDefault() + next.focus() + } else { + // Forward Tab continues from the trigger into the composer, not from the body portal. + if (event.shiftKey) event.preventDefault() + close() + trigger.focus() + } + return + } + if (pane === 'model' && showSearch && event.target === searchRef.current + && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 setHighlightedIndex((activeModelIndex + direction + visibleModels.length) % visibleModels.length) - searchRef.current?.focus() + searchRef.current.focus() } return } - if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement - && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { - if (event.key === 'Tab' && visibleModels.length === 0) return + if (pane === 'model' && showSearch && event.target === searchRef.current && event.key === 'Enter') { event.preventDefault() const highlighted = visibleModels[activeModelIndex] if (!busy && highlighted !== undefined) choose(highlighted) return } - // Tab settles like Enter and Shift+Tab leaves like Escape, so the menu's - // keys mean what they mean in the composer. Both are consumed: the card - // keeps the browser's focus traversal out while it is open. - if (event.key === 'Tab') { - if (event.shiftKey) { - event.preventDefault() - if (pane !== 'root' && currentChoice !== undefined) back(pane) - else close(true) - return - } - // Settling activates the row the keyboard is on; with focus still on the - // trigger, Tab enters the menu at the value in use instead. Any other - // control inside the card (a retry button) keeps the browser's traversal, - // so the keystroke stays unconsumed there. - const focused = document.activeElement - const rows = Array.from(menuRef.current?.querySelectorAll( - 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', - ) ?? []) - if (focused instanceof HTMLButtonElement && rows.includes(focused)) { - event.preventDefault() - focused.click() - return - } - if (focused !== triggerRef.current) return - event.preventDefault() - if (pane === 'model' && showSearch) { - setHighlightedIndex(null) - searchRef.current?.focus() - return - } - const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])') - ;(checked ?? rows.find(item => !item.disabled))?.focus() - return - } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault() moveFocus(event.key === 'ArrowDown' ? 1 : -1) @@ -339,6 +316,9 @@ export function ModelSelect( } const onBlur = (event: FocusEvent): void => { + // Non-focusable menu text and native range dragging can temporarily clear DOM focus. + // Outside pointer presses are handled separately; close only for a known outside focus target. + if (event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -346,12 +326,17 @@ export function ModelSelect( close() } - const settleSelection = (result: Awaited>): void => { + const settleSelection = (result: Awaited>, origin: 'model' | 'effort'): void => { if (result === undefined) return - if (result.ok) { - if (rootRef.current !== null) closeAfterSelection() - return + if (menuRef.current !== null) { + paneFocus.current = origin + if (result.ok) { + setModelReturnFocus(origin === 'model') + setPane('root') + } + setSelectionFocus(false) } + if (result.ok) return const { error } = result toastSeq.current += 1 setToast({ @@ -362,34 +347,31 @@ export function ModelSelect( }) } - const submit = (selection: ModelSelection): void => { + const submit = (selection: ModelSelection, origin: 'model' | 'effort'): void => { lastActionRef.current = 'select' - // Disabled option rows cannot retain focus while a selection is pending. + // Model rows may unmount; the inline slider keeps focus while its value is saved. setSelectionFocus(true) - triggerRef.current?.focus() - void select(selection).then(settleSelection) + if (origin === 'model') triggerRef.current?.focus() + void select(selection).then((result) => { settleSelection(result, origin) }) } const choose = (selection: ModelSelection): void => { if (state.current?.provider === selection.provider && state.current.model === selection.model) { - closeAfterSelection() + back('model') return } - submit(selection) + submit(selection, 'model') } const chooseEffort = (effort: string | undefined): void => { - if (state.current === null) return - if (effectiveEffort === effort) { - closeAfterSelection() - return - } + if (state.current === null || locked || busy) return + if (effectiveEffort === effort || (effort === undefined && state.current.reasoningEffort === undefined)) return const selection: ModelSelection = { provider: state.current.provider, model: state.current.model, ...effort === undefined ? {} : { reasoningEffort: effort }, } - submit(selection) + submit(selection, 'effort') } const waiting = currentChoice === undefined && state.status === 'loading' @@ -479,38 +461,53 @@ export function ModelSelect( {open && createPortal( {pane === 'root' && ( - <> - - {reasoning !== undefined && ( - + {currentChoice !== undefined && reasoning !== undefined && ( + t('effort.tooltip', { effort })} + disabled={locked} + pending={busy} + onSelect={chooseEffort} + /> )} {renderSlot('conversation.input.model.options', { locked: locked || busy, + openPage: (page) => { drill(page) }, dismiss: () => { close() triggerRef.current?.focus() }, reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, })} - +
)} {pane === 'model' && ( @@ -580,7 +577,7 @@ export function ModelSelect( role="menuitemradio" aria-checked={selected} id={`${id}-model-${index}`} - tabIndex={showSearch ? -1 : 0} + tabIndex={showSearch && index !== activeModelIndex ? -1 : 0} onFocus={() => { setHighlightedIndex(index) }} data-highlighted={index === activeModelIndex ? '' : undefined} className={clsx( @@ -616,41 +613,17 @@ export function ModelSelect( )} - {pane === 'effort' && ( - <> - {state.error !== null && lastActionRef.current === 'load' && ( -
- {t('error.action', { message: state.error })} - -
- )} -
- {effortChoices.length === 0 - ?
{t('empty.efforts')}
- : effortChoices.map(level => ( - - ))} -
- + {typeof pane === 'object' && ( +
+ {renderSlot('conversation.input.model.page', { + locked: locked || busy, + dismiss: () => { + close() + triggerRef.current?.focus() + }, + reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, + }, { entryKey: pane.key })} +
)} , document.body, diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index 224990e848..7a567a4c30 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -175,6 +175,7 @@ export function apply(ctx: ClientContext): void { children: { 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, }, inject: (sessionId): ModelSelectInjected => { const directory = models.directoryFor(sessionId) diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index cb2749f9a9..b7b81ff772 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -10,6 +10,8 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'effort.tooltip': '推理等级:{effort}', + 'menu.back': '返回', 'provider.account': 'DeepSeek 账号', 'command.label': '模型', 'command.description': '选择本会话使用的模型', @@ -40,6 +42,8 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'effort.tooltip': 'Reasoning effort: {effort}', + 'menu.back': 'Back', 'provider.account': 'DeepSeek Account', 'command.label': 'Model', 'command.description': 'Select the model for this conversation', @@ -67,6 +71,8 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { + 'effort.tooltip': '推論強度:{effort}', + 'menu.back': '戻る', 'provider.account': 'DeepSeek アカウント', 'command.label': 'モデル', 'command.description': 'この会話で使用するモデルを選択', @@ -94,6 +100,8 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { + 'effort.tooltip': 'Esfuerzo de razonamiento: {effort}', + 'menu.back': 'Volver', 'provider.account': 'Cuenta DeepSeek', 'command.label': 'modelo', 'command.description': 'Selecciona el modelo para esta conversación', @@ -121,6 +129,8 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { + 'effort.tooltip': 'Effort de raisonnement : {effort}', + 'menu.back': 'Retour', 'provider.account': 'Compte DeepSeek', 'command.label': 'Modèle', 'command.description': 'Sélectionnez le modèle pour cette conversation', @@ -148,6 +158,8 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { + 'effort.tooltip': 'Denkaufwand: {effort}', + 'menu.back': 'Zurück', 'provider.account': 'DeepSeek-Konto', 'command.label': 'Modell', 'command.description': 'Wählen Sie das Modell für dieses Gespräch aus', @@ -175,6 +187,8 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { + 'effort.tooltip': 'Уровень рассуждений: {effort}', + 'menu.back': 'Назад', 'provider.account': 'DeepSeek Аккаунт', 'command.label': 'Модель', 'command.description': 'Выберите модель для этого разговора', @@ -202,6 +216,8 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { + 'effort.tooltip': 'Esforço de raciocínio: {effort}', + 'menu.back': 'Voltar', 'provider.account': 'DeepSeek Conta', 'command.label': 'Modelo', 'command.description': 'Selecione o modelo para esta conversa', diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 39a31b673f..7e62e9710c 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,21 +17,41 @@ export interface ModelLabelOwner { selected: boolean } +/** A keyed contribution displayed as a second page of the model menu. */ +export interface ModelMenuPage { + /** Registration key in conversation.input.model.page; also marks its root button's data-model-menu-page. */ + key: string + /** Localized accessible name of the detail page. */ + title: string +} + +/** Selection state and feedback shared by menu option entries and detail pages. */ +export interface ModelMenuControls { + /** Whether the composer currently refuses selection changes. */ + locked: boolean + /** Close the menu and focus its trigger synchronously before opening another overlay. */ + dismiss: () => void + /** Report a failed selection through the menu owner's persistent toast. */ + reportFailure: (message: string) => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session options appended after model and reasoning controls in the root menu. */ 'conversation.input.model.options': { kind: 'list' scope: 'session' - owner: { - /** Whether the composer currently refuses selection changes. */ - locked: boolean - /** Close the menu and focus its trigger synchronously before opening another overlay. */ - dismiss: () => void - /** Report a failed selection through the menu owner's persistent toast. */ - reportFailure: (message: string) => void + owner: ModelMenuControls & { + /** Open a keyed detail page inside this menu; its root button supplies data-model-menu-page for focus return. */ + openPage: (page: ModelMenuPage) => void } } + /** Plugin-owned content displayed as a model-menu detail page. */ + 'conversation.input.model.page': { + kind: 'keyed' + scope: 'session' + owner: ModelMenuControls + } /** * Non-interactive inline model label; selection controls remain owner-managed. * Without a contribution, the badge precedes the catalog name in the trigger diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx new file mode 100644 index 0000000000..5ff0e2bb20 --- /dev/null +++ b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx @@ -0,0 +1,214 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' + +afterEach(() => { + cleanup() + vi.useRealTimers() + vi.unstubAllGlobals() +}) +const choices = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effort, label: effort })) +function props(overrides: Partial = {}): EffortSliderProps { + return { + choices, value: 'high', label: 'Effort', currentLabel: 'high', disabled: false, pending: false, + formatTooltip: effort => `Reasoning effort: ${effort}`, onSelect: vi.fn(), ...overrides, + } +} +function range(): HTMLInputElement { + return screen.getByRole('slider') as HTMLInputElement +} + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag tooltip (%s)', (_locale, dictionary) => { + vi.useFakeTimers() + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query === '(hover: hover)' || query === '(any-hover: hover)', media: query, onchange: null, + addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, + })) + vi.stubGlobal('ResizeObserver', class { + observe() {} + unobserve() {} + disconnect() {} + }) + const t = makeTranslate(dictionary) + const inputProps = props({ + choices: [{ key: 'default', effort: undefined, label: 'Default' }, { key: 'high', effort: 'high', label: 'High' }], + formatTooltip: effort => t('effort.tooltip', { effort }), + }) + const view = render() + const tag = screen.getByText('High') + expect(tag.tabIndex).toBe(-1) + fireEvent.pointerEnter(tag, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + const tooltip = screen.getByRole('tooltip', { hidden: true }) + expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'High')) + view.rerender() + expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'Default')) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('shows exact advertised stops and the selected value', () => { + render() + expect(range().max).toBe('3') + expect(range().value).toBe('2') + expect(range().getAttribute('aria-valuetext')).toBe('high') + expect(range().min).toBe('0') + expect(range().step).toBe('1') + expect(screen.getByText('high').tabIndex).toBe(-1) + expect(screen.queryByRole('button')).toBeNull() +}) + +it('previews a drag but submits only its final stop on release', () => { + const inputProps = props() + render() + const input = range() + fireEvent.pointerDown(input, { pointerId: 1 }) + fireEvent.change(input, { target: { value: '1' } }) + fireEvent.change(input, { target: { value: '3' } }) + expect(input.getAttribute('aria-valuetext')).toBe('max') + expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.pointerUp(input, { pointerId: 1 }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('max') +}) + +it.each(['pointerCancel', 'lostPointerCapture', 'blur'] as const)('cancels a drag on %s', (event) => { + const inputProps = props() + render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + fireEvent[event](input) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('2') +}) + +it('Escape discards the drag and ignores further movement until release', () => { + const inputProps = props() + const parentKey = vi.fn() + render(
) + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + fireEvent.keyDown(input, { key: 'Escape' }) + fireEvent.change(input, { target: { value: '0' } }) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(parentKey).not.toHaveBeenCalled() + expect(input.value).toBe('2') +}) + +it('commits keyboard changes on key release without forwarding adjustment keys', () => { + const inputProps = props() + const parentKey = vi.fn() + render(
) + const input = range() + fireEvent.keyDown(input, { key: 'ArrowLeft' }) + fireEvent.change(input, { target: { value: '1' } }) + fireEvent.keyDown(input, { key: 'ArrowLeft', repeat: true }) + fireEvent.change(input, { target: { value: '0' } }) + expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.keyUp(input, { key: 'ArrowLeft' }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('off') + expect(parentKey).not.toHaveBeenCalled() +}) + +it('lets Tab and an idle Escape reach the owning menu', () => { + const parentKey = vi.fn() + render(
) + fireEvent.keyDown(range(), { key: 'Tab' }) + fireEvent.keyDown(range(), { key: 'Escape' }) + fireEvent.keyUp(range(), { key: 'Tab' }) + expect(parentKey).toHaveBeenCalledTimes(2) +}) + +it('handles a direct assistive-technology change without a preceding pointer or keyboard gesture', () => { + const inputProps = props() + render() + fireEvent.change(range(), { target: { value: '1' } }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('keeps Default distinct from Off and submits an absent effort', () => { + const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices] }) + render() + expect(range().max).toBe('4') + fireEvent.change(range(), { target: { value: '0' } }) + expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith(undefined) +}) + +it('does not submit a gesture started before the persisted selection changes', () => { + const inputProps = props() + const view = render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + view.rerender() + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('1') +}) + +it('blocks selection while locked', () => { + const inputProps = props({ disabled: true }) + render() + expect(range().disabled).toBe(true) + fireEvent.change(range(), { target: { value: '3' } }) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('does not commit when another selection locks the control during a gesture', () => { + const inputProps = props() + const view = render() + const input = range() + fireEvent.pointerDown(input) + fireEvent.change(input, { target: { value: '3' } }) + view.rerender() + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('leaves IME composition keys untouched', () => { + const inputProps = props() + const key = vi.fn() + render(
) + fireEvent.keyDown(range(), { key: 'ArrowRight', isComposing: true }) + expect(key).toHaveBeenCalledOnce() + expect(inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('does not pretend an unknown stored effort matches the first supported stop', () => { + render() + expect(range().disabled).toBe(true) + expect(range().getAttribute('aria-valuetext')).toBe('retired') + expect(screen.getByText('retired')).toBeTruthy() + expect(screen.queryByRole('button')).toBeNull() +}) + +it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragging with fewer than two choices', ({ levels }) => { + render() + expect(range().disabled).toBe(true) + expect(range().max).toBe('0') +}) + +it('keeps the pending target focusable while blocking pointer, keyboard and direct changes', () => { + const inputProps = props({ value: 'max', pending: true }) + render() + const input = range() + input.focus() + expect(input.disabled).toBe(false) + expect(input.getAttribute('aria-disabled')).toBe('true') + expect(input.getAttribute('aria-busy')).toBe('true') + expect(input.value).toBe('3') + expect(input.getAttribute('aria-valuetext')).toBe('max') + expect(fireEvent.pointerDown(input)).toBe(false) + expect(fireEvent.keyDown(input, { key: 'ArrowLeft' })).toBe(false) + fireEvent.change(input, { target: { value: '0' } }) + fireEvent.keyUp(input, { key: 'ArrowLeft' }) + fireEvent.pointerUp(input) + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(input.value).toBe('3') + expect(document.activeElement).toBe(input) +}) diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx new file mode 100644 index 0000000000..7c3ae849d4 --- /dev/null +++ b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx @@ -0,0 +1,187 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ComponentProps } from 'react' +import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' +import { ModelSelect } from '../src/client/ModelSelect.tsx' +import type { ModelDirectoryState } from '../src/client/directory.ts' +import { en } from '../src/client/locales.ts' + +beforeEach(() => { + const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') + Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }) + onTestFinished(() => { + if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, 'scrollIntoView') + else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) + }) +}) +afterEach(cleanup) + +function setup(count = 2, hasReasoning = true) { + const select = vi.fn(async () => ({ ok: true as const, value: undefined })) + const toggle = vi.fn() + const directory = createSnapshotStore({ + current: { provider: 'sample', model: 'model-1' }, routable: true, + groups: [{ id: 'sample', name: 'Sample', models: Array.from({ length: count }, (_, index) => ({ + id: `model-${index + 1}`, name: `Model ${index + 1}`, + ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } : {}, + })) }], failures: [], status: 'ready', pending: null, error: null, + }) + const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as OwnerOf<'conversation.input.model.options'> + return <> + + + + } + if (name === 'conversation.input.model.page') return + return options?.fallback ?? null + } + render(<> typeof text === 'string' ? text : text.en} select={select} renderSlot={renderSlot} t={makeTranslate(en)} />) + const trigger = screen.getByRole('button', { name: /^Select model, current/ }) + fireEvent.click(trigger) + const model = () => screen.getByRole('menuitem', { name: /Model.*Model 1/ }) + const team = () => screen.getByRole('menuitem', { name: 'Agent teamwork' }) + return { select, toggle, directory, trigger, model, team } +} +function tab(shiftKey = false) { + const event = new KeyboardEvent('keydown', { key: 'Tab', shiftKey, bubbles: true, cancelable: true }) + fireEvent(document.activeElement!, event) + return event +} + +it('Tab moves from the trigger through root controls without opening a page or selecting a value', () => { + const view = setup() + tab() + expect(document.activeElement).toBe(view.model()) + tab() + expect(document.activeElement).toBe(screen.getByRole('slider', { name: 'Effort' })) + tab() + expect(document.activeElement).toBe(view.team()) + tab(true) + expect(document.activeElement).toBe(screen.getByRole('slider')) + tab(true) + expect(document.activeElement).toBe(view.model()) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.queryByRole('switch')).toBeNull() + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('Shift+Tab from the first root control returns to its trigger instead of activating it', () => { + const view = setup() + tab() + expect(tab(true).defaultPrevented).toBe(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab at the final root control closes the portal and leaves native forward traversal enabled', () => { + const view = setup() + view.team().focus() + expect(tab().defaultPrevented).toBe(false) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('skips a reasoning control when the model does not advertise one', () => { + const view = setup(2, false) + tab(); tab() + expect(document.activeElement).toBe(view.team()) + expect(screen.queryByRole('slider')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab and Shift+Tab traverse small model lists without choosing any model', () => { + const view = setup() + fireEvent.click(view.model()) + const rows = screen.getAllByRole('menuitemradio') + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + expect(document.activeElement).toBe(rows[0]) + tab() + expect(document.activeElement).toBe(rows[1]) + tab(true) + expect(document.activeElement).toBe(rows[0]) + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab leaves search without committing; Shift+Tab returns through search to the trigger', () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.keyDown(search, { key: 'ArrowDown' }) + tab() + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(view.select).not.toHaveBeenCalled() + expect(screen.getAllByRole('menuitemradio').filter(row => row.tabIndex === 0)).toHaveLength(1) + tab(true) + expect(document.activeElement).toBe(search) + tab(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('searchbox')).toBeNull() +}) + +it('includes the search clear button in Tab order and keeps Space native in search', () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.change(search, { target: { value: 'Model 2' } }) + const space = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }) + fireEvent(search, space) + expect(space.defaultPrevented).toBe(false) + tab() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Clear search' })) + tab() + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(view.select).not.toHaveBeenCalled() +}) + +it('Enter still selects a highlighted search result', async () => { + const view = setup(6) + fireEvent.click(view.model()) + const search = screen.getByRole('searchbox') + fireEvent.change(search, { target: { value: 'Model 2' } }) + await act(async () => { fireEvent.keyDown(search, { key: 'Enter' }) }) + await waitFor(() => { + expect(view.select).toHaveBeenCalledExactlyOnceWith({ provider: 'sample', model: 'model-2' }) + }) +}) + +it.each([2, 6])('returns from %i model choices with Escape, then closes the root with Escape', async (count) => { + const view = setup(count) + fireEvent.click(view.model()) + expect(screen.queryByText('Model', { exact: true })).toBeNull() + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(screen.getByRole('slider')).toBeTruthy() + expect(document.activeElement).toBe(view.model()) + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + await waitFor(() => { expect(document.activeElement).toBe(view.trigger) }) + expect(screen.queryByRole('menu')).toBeNull() + expect(view.select).not.toHaveBeenCalled() +}) + +it('Tab leaves the Team page without toggling, while Escape returns to its root entry', () => { + const view = setup() + fireEvent.click(view.team()) + const toggle = screen.getByRole('switch') + expect(screen.getByRole('menu', { name: 'Team settings' })).toBeTruthy() + expect(screen.queryByText('Team settings')).toBeNull() + expect(document.activeElement).toBe(toggle) + expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() + tab(true) + expect(document.activeElement).toBe(view.trigger) + expect(screen.queryByRole('switch')).toBeNull() + expect(view.toggle).not.toHaveBeenCalled() + fireEvent.click(view.trigger) + fireEvent.click(view.team()) + fireEvent.keyDown(screen.getByRole('switch'), { key: 'Escape' }) + expect(screen.queryByRole('switch')).toBeNull() + expect(view.team()).toBe(document.activeElement) +}) diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index 7990890cec..af1861f0a8 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import * as uiPrimitives from '@deepseek-ai/dsh-client-ui-primitives' -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { RemoteError, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { SessionId } from '@deepseek-ai/dsh-session/types' @@ -100,6 +100,7 @@ describe('ModelSelect label slot', () => { await runtime.root.declare({ 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, }, ({ renderSlot, SessionProvider }) => @@ -129,15 +130,14 @@ describe('ModelSelect label slot', () => { expect(external.querySelector('div')).toBeNull() fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'trusted: Same model' }), { key: 'ArrowDown' }) expect(document.activeElement).toBe(external) - fireEvent.keyDown(external, { key: 'Tab' }) + fireEvent.click(external) await waitFor(() => { expect(screen.getByTestId('trigger-external')).toBeTruthy() }) expect(select).toHaveBeenCalledWith({ provider: 'external', model: 'same-model' }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) await act(async () => { await plugin.dispose() }) expect(runtime.slots.entries('conversation.input.model.label')).toHaveLength(0) expect(trigger.textContent).toBe('Same model') expect(trigger.querySelector('[data-provider-id="external"][data-model-id="same-model"]')).toBeTruthy() - fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.getAllByRole('menuitemradio').map(row => row.textContent)).toEqual(['Same model', 'Same model']) }) @@ -226,12 +226,17 @@ describe('ModelSelect reasoning effort', () => { name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', }) fireEvent.click(trigger) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) - .toEqual(['Off', 'High', 'Max']) + const efforts = within(screen.getByRole('group', { name: '推理等级' })) + expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') + expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('High') + expect(efforts.getByText('High').tabIndex).toBe(-1) + expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() expect(screen.queryByText('Largest budget')).toBeNull() - fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) + const slider = efforts.getByRole('slider') + slider.focus() + fireEvent.change(slider, { target: { value: '2' } }) await waitFor(() => { expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', @@ -239,7 +244,8 @@ describe('ModelSelect reasoning effort', () => { reasoningEffort: 'max', }) expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 Max') - expect(document.activeElement).toBe(trigger) + expect(document.activeElement).toBe(slider) + expect(screen.getByRole('menu')).toBeTruthy() }) }) @@ -268,9 +274,66 @@ describe('ModelSelect reasoning effort', () => { fireEvent.click(screen.getByRole('button', { name: '选择模型,当前 Model,推理等级 Default', })) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) - .toEqual(['Default', 'Standard']) + const efforts = within(screen.getByRole('group', { name: '推理等级' })) + expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('slider').getAttribute('max')).toBe('1') + expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('Default') + }) + + it('submits the Default stop by omitting effort instead of sending a display label', async () => { + const current = { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } + const groups = state().groups.map(group => ({ ...group, models: group.models.map(model => ({ + ...model, reasoning: { efforts: reasoning.efforts }, + })) })) + const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '0' } }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('slider')) }) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('submits the final dragged stop once and keeps the committed trigger caption until acceptance', async () => { + const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) + render() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + fireEvent.click(trigger) + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + fireEvent.pointerDown(slider, { pointerId: 1 }) + fireEvent.change(slider, { target: { value: '0' } }) + fireEvent.change(slider, { target: { value: '2' } }) + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 High') + expect(select).not.toHaveBeenCalled() + fireEvent.pointerUp(slider, { pointerId: 1 }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) + await waitFor(() => { expect(document.activeElement).toBe(slider) }) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('keeps the committed effort and allows retry after a rejected inline selection', async () => { + const select = vi.fn().mockResolvedValue({ ok: false, error: new RemoteError('session/model-unavailable', 'effort unavailable', { + provider: 'deepseek-official', model: 'deepseek-v4-flash', + }) }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) + expect((await screen.findByRole('alert')).textContent).toContain('effort unavailable') + expect(screen.getByRole('menu')).toBeTruthy() + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(slider.getAttribute('aria-valuetext')).toBe('High') + expect(slider.hasAttribute('disabled')).toBe(false) + expect(document.activeElement).toBe(slider) + await act(async () => { fireEvent.change(slider, { target: { value: '0' } }) }) + expect(select).toHaveBeenLastCalledWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'off' }) }) it('opens model choices without exposing a saved route absent from the catalog', () => { @@ -298,7 +361,7 @@ describe('ModelSelect reasoning effort', () => { expect(select).not.toHaveBeenCalled() expect(directory.getSnapshot().current).toEqual({ provider: 'deepseek-official', model: 'removed-model' }) fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }), { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it.each(['model', 'provider'])('hides the saved id and effort when the selected %s disappears', (removed) => { @@ -316,7 +379,7 @@ describe('ModelSelect reasoning effort', () => { fireEvent.click(trigger) expect(screen.getByRole('status').textContent).toBe(zh['empty.models']) fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it.each([null, state().current])('shows loading until the catalog and Session projection are both ready (%j)', async (current) => { @@ -378,15 +441,17 @@ describe('ModelSelect reasoning effort', () => { fireEvent.mouseMove(rejected) fireEvent.click(rejected) const toast = await screen.findByRole('alert') - expect(document.activeElement).toBe(trigger) + const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) + expect(document.activeElement).toBe(selected) expect(toast.textContent).toBe(sessionInUse ? zh['error.sessionInUse'] : '模型操作失败:session/model-unavailable: session already contains images') // The selection failure does not render the in-menu load strip (no Retry). expect(screen.queryByRole('button', { name: '重试' })).toBeNull() - fireEvent.keyDown(trigger, { key: 'Tab' }) + fireEvent.keyDown(selected, { key: 'Tab' }) expect(screen.queryByRole('searchbox')).toBeNull() - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) + expect(document.activeElement).toBe(rejected) + expect(select).toHaveBeenCalledTimes(1) }) it('spins on the trigger and the chosen model row until the selection settles, across pane changes', async () => { @@ -433,21 +498,66 @@ describe('ModelSelect reasoning effort', () => { expect(trigger.getAttribute('aria-busy')).toBe('false') }) - it('spins on the chosen effort row only', () => { + it('announces the pending target while retaining slider focus and blocking duplicate submissions', async () => { const directory = createSnapshotStore(state()) + const pending = Promise.withResolvers<{ ok: true; value: undefined }>() + onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) const select = vi.fn((selection: ModelSelection) => { directory.set(state({ status: 'selecting', pending: selection })) - return new Promise(() => {}) + return pending.promise }) render() - fireEvent.click(screen.getByRole('button', { name: /选择模型|当前/ })) - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) - expect(screen.getAllByRole('menuitemradio') - .filter(row => row.querySelector('[data-state="ongoing"]') !== null) - .map(row => row.textContent)).toEqual(['Max']) + const trigger = screen.getByRole('button', { name: /选择模型|当前/ }) + fireEvent.click(trigger) + const slider = screen.getByRole('slider', { name: '推理等级' }) + screen.getByRole('slider').focus() + fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) + expect(trigger.getAttribute('aria-busy')).toBe('true') + expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(slider.hasAttribute('disabled')).toBe(false) + expect(slider.getAttribute('aria-disabled')).toBe('true') + expect(slider.getAttribute('aria-busy')).toBe('true') + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(document.activeElement).toBe(slider) + fireEvent.change(slider, { target: { value: '0' } }) + expect(select).toHaveBeenCalledExactlyOnceWith({ + provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', + }) + await act(async () => { + directory.set(state({ current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) + pending.resolve({ ok: true, value: undefined }) + }) + expect(screen.getByRole('menu')).toBeTruthy() + expect(trigger.getAttribute('aria-busy')).toBe('false') + expect(slider.getAttribute('aria-disabled')).toBe('false') + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(document.activeElement).toBe(slider) + }) + + it('keeps transient focus loss inside the menu but closes on a known outside focus target', () => { + render(<>) + const trigger = screen.getByRole('button', { name: /选择模型/ }) + fireEvent.click(trigger) + fireEvent.blur(trigger, { relatedTarget: null }) + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.blur(trigger, { relatedTarget: screen.getByRole('button', { name: 'Outside' }) }) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('closes the portaled model list when focus moves from search to an outside editor', () => { + render(<>
) + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + expect(document.activeElement).toBe(screen.getByRole('searchbox')) + const editor = screen.getByLabelText('Outside editor') + act(() => { editor.focus() }) + expect(document.activeElement).toBe(editor) + expect(screen.queryByRole('menu')).toBeNull() }) it('anchors the body portal with CSS and closes only on truly-outside mousedown', () => { @@ -541,31 +651,23 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(trigger) const modelCell = screen.getByRole('menuitem', { name: /^模型/ }) - const effortCell = screen.getByRole('menuitem', { name: /推理等级/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) fireEvent.keyDown(trigger, { key: 'ArrowDown' }) fireEvent.keyDown(modelCell, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(effortCell) - fireEvent.keyDown(effortCell, { key: 'Tab' }) - const high = screen.getByRole('menuitemradio', { name: 'High' }) - const max = screen.getByRole('menuitemradio', { name: /Max/ }) - expect(document.activeElement).toBe(high) - fireEvent.keyDown(high, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(max) - fireEvent.keyDown(max, { key: 'Escape' }) - - const restoredEffortCell = screen.getByRole('menuitem', { name: /推理等级/ }) - expect(document.activeElement).toBe(restoredEffortCell) - fireEvent.keyDown(restoredEffortCell, { key: 'ArrowUp' }) - const restoredModelCell = screen.getByRole('menuitem', { name: /^模型/ }) - expect(document.activeElement).toBe(restoredModelCell) - fireEvent.keyDown(restoredModelCell, { key: 'Tab' }) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'ArrowDown' })).toBe(true) + expect(document.activeElement).toBe(slider) + expect(screen.queryByRole('searchbox')).toBeNull() + fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true }) + expect(document.activeElement).toBe(modelCell) + fireEvent.click(modelCell) const model = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(model) if (modelCount > 4) { const search = screen.getByRole('searchbox') expect(document.activeElement).not.toBe(search) fireEvent.keyDown(model, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(search) + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) } else { expect(screen.queryByRole('searchbox')).toBeNull() } @@ -578,63 +680,69 @@ describe('ModelSelect keyboard walk', () => { }, ) - it.each(['model', 'effort'])('prevents button mousedown defaults in the %s pane without selecting it', (pane) => { + it.each(['model', 'inline effort'])('does not select on button mousedown and mouseup alone in %s controls', (kind) => { const select = mountOpen() - const cell = screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }) + const cell = screen.getByRole('menuitem', { name: /^模型/ }) expect(fireEvent.mouseDown(cell.firstElementChild!)).toBe(false) - fireEvent.click(cell) - const rows = screen.getAllByRole('menuitemradio') + if (kind === 'model') fireEvent.click(cell) + const target = kind === 'model' + ? screen.getAllByRole('menuitemradio')[0]! + : screen.getByRole('slider') const focused = document.activeElement - expect(fireEvent.mouseDown(rows[0]!.firstElementChild!)).toBe(false) + expect(fireEvent.mouseDown(target)).toBe(kind === 'inline effort') fireEvent.mouseUp(screen.getByRole('menu')) expect(select).not.toHaveBeenCalled() - fireEvent.keyDown(focused!, { key: 'Escape' }) - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ })) + expect(document.activeElement).toBe(focused) + if (kind === 'inline effort') { + expect(fireEvent.mouseDown(screen.getByRole('slider'))).toBe(true) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('High') + } else { + fireEvent.keyDown(focused!, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) + } }) - it('↑↓ walk the rows of the shown pane, wrapping, and stay open', () => { - mountOpen() - // The trigger holds focus while the menu opens: the first forward step - // enters at the first cell instead of skipping it. false = preventDefault ran. - const cells = screen.getAllByRole('menuitem') - expect(fireEvent.keyDown(cells[0]!, { key: 'ArrowDown' })).toBe(false) - expect(document.activeElement).toBe(cells[0]) - - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - expect(rows.map(row => row.textContent)).toEqual(['Off', 'High', 'Max']) - // The pane opens on its checked row, so walking starts from High. - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(rows[2]) - fireEvent.keyDown(rows[2]!, { key: 'ArrowDown' }) // wraps to the top - expect(document.activeElement).toBe(rows[0]) - fireEvent.keyDown(rows[0]!, { key: 'ArrowUp' }) // wraps to the bottom - expect(document.activeElement).toBe(rows[2]) - expect(screen.getByRole('menu')).toBeTruthy() - }) - - it('Tab settles the focused row like Enter and closes the menu', async () => { + it('walks between root controls while leaving adjustment arrows to the native range', () => { const select = mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) // High → Max - expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ + const model = screen.getByRole('menuitem', { name: /^模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(fireEvent.keyDown(model, { key: 'ArrowDown' })).toBe(false) + expect(document.activeElement).toBe(model) + fireEvent.keyDown(model, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'ArrowRight' })).toBe(true) + expect(document.activeElement).toBe(slider) + expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(model) + fireEvent.keyDown(model, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(slider) + expect(screen.getByRole('menu')).toBeTruthy() + expect(select).not.toHaveBeenCalled() + }) + + it('commits a range keyboard gesture once with the model route and retains slider focus', async () => { + const select = mountOpen() + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + fireEvent.keyDown(slider, { key: 'End' }) + // jsdom does not perform the native range value change for a keyboard event. + fireEvent.change(slider, { target: { value: '2' } }) + expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(select).not.toHaveBeenCalled() + fireEvent.keyUp(slider, { key: 'End' }) + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) + await waitFor(() => { expect(document.activeElement).toBe(slider) }) + expect(screen.getByRole('menu')).toBeTruthy() }) - it('Shift+Tab leaves a drilled pane and then closes, like Escape', () => { + it('Shift+Tab from the first model closes the menu and returns to the trigger', () => { mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - expect(fireEvent.keyDown(rows[0]!, { key: 'Tab', shiftKey: true })).toBe(false) - // Back on the drilled cell, then closed on the second press. - const cells = screen.getAllByRole('menuitem') - expect(document.activeElement).toBe(cells[1]) - expect(screen.getByRole('menu')).toBeTruthy() - fireEvent.keyDown(cells[1]!, { key: 'Tab', shiftKey: true }) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) + expect(fireEvent.keyDown(selected, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) expect(screen.queryByRole('menu')).toBeNull() }) @@ -658,26 +766,30 @@ describe('ModelSelect keyboard walk', () => { it('a backward step from outside the list enters at the last row, and a closed menu leaves Tab native', () => { mountOpen() - const [modelRow, effortRow] = screen.getAllByRole('menuitem') - expect(fireEvent.keyDown(modelRow!, { key: 'ArrowUp' })).toBe(false) - expect(document.activeElement).toBe(effortRow) + const modelRow = screen.getByRole('menuitem', { name: /^模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + expect(fireEvent.keyDown(modelRow, { key: 'ArrowUp' })).toBe(false) + expect(document.activeElement).toBe(slider) const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.keyDown(trigger, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(true) }) - it('hands a drilled pane the focus its unmounted cell left behind, on the value in use', () => { - mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - // The fixture's model defaults to the High effort: the checked row is where - // the keyboard lands, not the top of the list. - expect(rows[1]!.getAttribute('aria-checked')).toBe('true') - expect(document.activeElement).toBe(rows[1]) - // The walk continues from there. - fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(rows[2]) + it('returns from all models to the committed effort without submitting another selection', () => { + const select = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + expect(screen.queryByRole('slider')).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + expect(screen.queryByRole('button', { name: 'Max' })).toBeNull() + expect(select).not.toHaveBeenCalled() }) it('keeps the card navigable when a pane has no rows, and leaves a retry its Tab', () => { @@ -702,12 +814,12 @@ describe('ModelSelect keyboard walk', () => { expect(fireEvent.mouseDown(retry)).toBe(false) fireEvent.click(retry) expect(load).toHaveBeenCalledTimes(2) - expect(screen.getByRole('group', { name: '模型与推理等级' })).toBeTruthy() + expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() retry.focus() // A control that is not a row keeps the browser's traversal. expect(fireEvent.keyDown(retry, { key: 'Tab' })).toBe(true) fireEvent.keyDown(retry, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() }) it('focuses the checked model in a small catalog', () => { @@ -719,19 +831,15 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(rows[0]) }) - it('Escape returns to the root pane with the keyboard on the cell that drilled in', () => { - mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) - const rows = screen.getAllByRole('menuitemradio') - fireEvent.keyDown(rows[0]!, { key: 'Escape' }) - // The root pane is back with its two cells. - const cells = screen.getAllByRole('menuitem') - // Back on the drilled cell, so the next keystroke still reaches the menu. - expect(document.activeElement).toBe(cells[1]) - expect(screen.getByRole('menu')).toBeTruthy() - // A second Escape closes back to the trigger. - fireEvent.keyDown(cells[1]!, { key: 'Escape' }) + it('Escape from an unchanged inline slider closes the root menu and restores trigger focus', async () => { + const select = mountOpen() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + const slider = screen.getByRole('slider', { name: '推理等级' }) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Escape' })).toBe(false) expect(screen.queryByRole('menu')).toBeNull() + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + expect(select).not.toHaveBeenCalled() }) it('Escape from the model list lands back on the model cell', () => { @@ -776,7 +884,7 @@ describe('ModelSelect catalog size', () => { expect(search).toBeInstanceOf(HTMLInputElement) expect(document.activeElement).toBe(search) expect(search.getAttribute('aria-activedescendant')).toBe(rows[1]!.id) - expect(rows.every(row => row.tabIndex === -1)).toBe(true) + expect(rows.filter(row => row.tabIndex === 0)).toEqual([rows[1]]) } else { expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(count === 0 ? trigger : rows[count > 1 ? 1 : 0]) @@ -827,7 +935,7 @@ describe('ModelSelect catalog size', () => { .toBe(screen.getAllByRole('menuitemradio')[checked ? 2 : 0]!.id) }) - it('moves actual row focus with arrows, leaves Enter native, and selects with Tab in a small catalog', async () => { + it('moves actual row focus with arrows and Tab without choosing, then activates a small-catalog row', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render( { expect(document.activeElement).toBe(rows[2]) expect(select).not.toHaveBeenCalled() expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + expect(document.activeElement).toBe(rows[3]) + expect(select).not.toHaveBeenCalled() + fireEvent.click(rows[3]!) + expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-4' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() }) - it('keeps Tab selection available after hovering a small-catalog row', async () => { + it('moves Tab focus without selecting after hovering a small-catalog row', () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render() @@ -870,8 +981,8 @@ describe('ModelSelect catalog size', () => { expect(document.activeElement).toBe(row) expect(row.hasAttribute('data-highlighted')).toBe(true) expect(fireEvent.keyDown(row, { key: 'Tab' })).toBe(false) - expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) - await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 4' })) + expect(select).not.toHaveBeenCalled() }) it.each(['Escape', 'Tab'])('leaves a small model pane with %s and returns to its root cell', (key) => { @@ -882,10 +993,14 @@ describe('ModelSelect catalog size', () => { fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const row = screen.getAllByRole('menuitemradio')[0]! expect(fireEvent.keyDown(row, { key, shiftKey: key === 'Tab' })).toBe(false) - const cell = screen.getByRole('menuitem', { name: /^模型/ }) - expect(document.activeElement).toBe(cell) expect(select).not.toHaveBeenCalled() - fireEvent.keyDown(cell, { key, shiftKey: key === 'Tab' }) + if (key === 'Escape') { + const cell = screen.getByRole('menuitem', { name: /^模型/ }) + expect(document.activeElement).toBe(cell) + fireEvent.keyDown(cell, { key }) + } else { + expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) + } expect(screen.queryByRole('menu')).toBeNull() }) }) @@ -901,7 +1016,7 @@ describe('ModelSelect search', () => { expect(document.activeElement).toBe(search) fireEvent.change(search, { target: { value: 'zzzz' } }) fireEvent.keyDown(search, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() fireEvent.click(trigger) expect(screen.getByRole('searchbox').getAttribute('value')).toBe('') expect(document.activeElement).toBe(screen.getByRole('searchbox')) @@ -922,7 +1037,7 @@ describe('ModelSelect search', () => { expect(screen.getByRole('status').closest('[role="menu"]')).toBeNull() }) - it.each(['Enter', 'Tab'])('returns focus silently after %s accepts the current model, without suppressing later focus', async (key) => { + it('returns to the root model after Enter accepts the current model, without suppressing later focus', async () => { const select = vi.fn() render(<> @@ -932,9 +1047,9 @@ describe('ModelSelect search', () => { const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /模型/ })) - fireEvent.keyDown(screen.getByRole('searchbox'), { key }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Enter' }) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(trigger.hasAttribute('data-selection-focus')).toBe(false) expect(select).not.toHaveBeenCalled() act(() => { screen.getByRole('button', { name: 'Outside' }).focus() }) expect(trigger.hasAttribute('data-selection-focus')).toBe(false) @@ -942,7 +1057,7 @@ describe('ModelSelect search', () => { expect(trigger.hasAttribute('data-selection-focus')).toBe(false) }) - it.each(['Enter', 'Tab'])('keeps typing focus while arrows wrap across groups and %s accepts the highlight', async (key) => { + it('keeps typing focus while arrows wrap across groups and Enter accepts the highlight', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) const directory = createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'beta' }, @@ -985,19 +1100,19 @@ describe('ModelSelect search', () => { expect(search.hasAttribute('aria-activedescendant')).toBe(false) fireEvent.keyDown(search, { key: 'Enter' }) expect(select).not.toHaveBeenCalled() - expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(true) + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: '清除搜索' })) fireEvent.click(screen.getByRole('button', { name: '清除搜索' })) const restored = screen.getAllByRole('menuitemradio') expect(search.getAttribute('aria-activedescendant')).toBe(restored[0]!.id) fireEvent.mouseMove(restored[4]!) expect(search.getAttribute('aria-activedescendant')).toBe(restored[4]!.id) expect(document.activeElement).toBe(search) - fireEvent.keyDown(search, { key }) + fireEvent.keyDown(search, { key: 'Enter' }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gamma' }) - await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) - const trigger = screen.getByRole('button', { name: /选择模型/ }) - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(trigger.hasAttribute('data-selection-focus')).toBe(true) + await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + expect(screen.queryByRole('menuitemradio')).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() }) it('filters model names fuzzily, hides empty groups, clears on reopening, and selects a result', async () => { @@ -1045,8 +1160,8 @@ describe('ModelSelect search', () => { fireEvent.keyDown(reopened, { key: 'ArrowDown' }) expect(document.activeElement).toBe(reopened) expect(reopened.getAttribute('aria-activedescendant')).toBe(row.id) - fireEvent.keyDown(reopened, { key: 'Tab' }) - await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) + fireEvent.keyDown(reopened, { key: 'Enter' }) + await waitFor(() => { expect(screen.queryByRole('menuitemradio')).toBeNull() }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gemini' }) }) }) @@ -1066,7 +1181,7 @@ it('hides the inherited effort until a listed model is selected', async () => { const row = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(row) fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型' })).toBeNull() fireEvent.click(trigger) expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) @@ -1120,6 +1235,117 @@ it('restores the account model name after login without changing the saved route }) +describe('ModelSelect contributed pages', () => { + function mountPage(locked = false, withSwitch = true) { + const toggle = vi.fn() + const select = vi.fn() + const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as OwnerOf<'conversation.input.model.options'> + return + } + if (name === 'conversation.input.model.page') { + if (options?.entryKey !== 'fixture-settings') throw new Error('Unexpected detail page key') + const controls = owner as OwnerOf<'conversation.input.model.page'> + return <> +

用于解释该设置的完整说明

+ {withSwitch && } + + + + } + return options?.fallback ?? null + } + const directory = createSnapshotStore(state()) + const view = render() + const trigger = screen.getByRole('button', { name: /^选择模型/ }) + if (!locked) fireEvent.click(trigger) + return { directory, view, trigger, renderSlot, toggle, select } + } + + it('opens only the keyed detail controls and returns to the invoking entry with Escape', () => { + const { toggle, select } = mountPage() + expect(screen.queryByRole('switch')).toBeNull() + expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + fireEvent.click(entry) + const toggleButton = screen.getByRole('switch', { name: '启用示例设置' }) + expect(document.activeElement).toBe(toggleButton) + expect(screen.queryByText('示例设置')).toBeNull() + expect(screen.getByRole('menu', { name: '示例设置' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '返回' })).toBeNull() + expect(screen.getByText('用于解释该设置的完整说明')).toBeTruthy() + expect(screen.queryByRole('slider')).toBeNull() + expect(screen.queryByRole('menuitem', { name: /^模型/ })).toBeNull() + fireEvent.click(toggleButton) + expect(toggle).toHaveBeenCalledOnce() + expect(select).not.toHaveBeenCalled() + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.keyDown(toggleButton, { key: 'Escape' }) + expect(screen.queryByRole('switch')).toBeNull() + expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() + expect(screen.getByRole('slider', { name: '推理等级' })).toBeTruthy() + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: '设置 关' })) + }) + + it('moves Tab from the inline range to a contributed entry and Shift+Tab back without changing effort', () => { + const { select } = mountPage() + const slider = screen.getByRole('slider', { name: '推理等级' }) + const model = screen.getByRole('menuitem', { name: /^模型/ }) + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(entry) + slider.focus() + expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) + expect(document.activeElement).toBe(model) + expect(select).not.toHaveBeenCalled() + }) + + it('focuses the keyed page when it has no switch and Tabs through its controls', () => { + mountPage(false, false) + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + const page = screen.getByRole('menu', { name: '示例设置' }) + expect(document.activeElement).toBe(page) + expect(fireEvent.keyDown(page, { key: 'Tab' })).toBe(false) + const report = screen.getByRole('button', { name: '报告失败' }) + expect(document.activeElement).toBe(report) + expect(fireEvent.keyDown(report, { key: 'Tab' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('button', { name: '关闭设置' })) + expect(screen.getByRole('menu')).toBeTruthy() + }) + + it('passes pending selection locking into the keyed page while keeping Escape navigation available', () => { + const { directory, toggle } = mountPage() + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + act(() => { directory.set(state({ status: 'selecting', pending: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) }) + const switchButton = screen.getByRole('switch', { name: '启用示例设置' }) + expect(switchButton.hasAttribute('disabled')).toBe(true) + fireEvent.click(switchButton) + expect(toggle).not.toHaveBeenCalled() + fireEvent.keyDown(switchButton, { key: 'Escape' }) + expect(screen.getByRole('slider').hasAttribute('disabled')).toBe(false) + expect(screen.getByRole('slider').getAttribute('aria-disabled')).toBe('true') + }) + + it('retains detail controls after reported failure and lets the contribution dismiss with trigger focus', () => { + const { trigger } = mountPage() + fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) + fireEvent.click(screen.getByRole('button', { name: '报告失败' })) + expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') + expect(screen.getByRole('switch', { name: '启用示例设置' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: '关闭设置' })) + expect(screen.queryByRole('menu')).toBeNull() + expect(document.activeElement).toBe(trigger) + expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') + }) +}) + it('dismisses contributed options with focus on the trigger before opening another overlay', () => { const renderSlot = vi.fn((_name: string, _owner: object) => null) render(-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f90076add7..ec24f5b701 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。可选的 `pending` 拒绝新变更并设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`,因此保存期间保留焦点,除非 `disabled` 同时为 true。`label` 必填,控件不可能在没有名称的情况下发布。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 980a08f6be..3a48484f76 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -9,17 +9,18 @@ import css from './Switch.module.css' * @param props.checked - the current state; the control is fully controlled. * @param props.onChange - called with the state the click asks for. * @param props.label - localized accessible name, owned by the render site. - * @param props.disabled - whether the control refuses input; owners also set it - * while a write is in flight, not only when a deployment locks the toggle. + * @param props.disabled - whether the control is unavailable and excluded from keyboard focus. + * @param props.pending - a write is in flight; refuse further changes while preserving focus. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, pending = false, title, className }: { checked: boolean onChange: (next: boolean) => void label: string disabled?: boolean + pending?: boolean title?: string | undefined // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). @@ -33,8 +34,10 @@ export function Switch({ checked, onChange, label, disabled = false, title, clas aria-label={label} title={title} disabled={disabled} + aria-disabled={disabled || pending || undefined} + aria-busy={pending || undefined} className={clsx(css.switch, className)} - onClick={() => { onChange(!checked) }} + onClick={() => { if (!pending) onChange(!checked) }} > diff --git a/packages/client/ui-primitives/tests/switch.client.spec.tsx b/packages/client/ui-primitives/tests/switch.client.spec.tsx index a80eae48d3..6aef86cc3e 100644 --- a/packages/client/ui-primitives/tests/switch.client.spec.tsx +++ b/packages/client/ui-primitives/tests/switch.client.spec.tsx @@ -33,6 +33,39 @@ describe('Switch', () => { expect(onChange).not.toHaveBeenCalled() }) + it.each([false, true])('keeps focus while pending and refuses repeated activation (checked: %s)', (checked) => { + const onChange = vi.fn() + const { rerender } = render() + const control = screen.getByRole('switch') as HTMLButtonElement + control.focus() + rerender() + expect(control.disabled).toBe(false) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + expect(control.getAttribute('aria-checked')).toBe(String(checked)) + expect(document.activeElement).toBe(control) + fireEvent.click(control) + fireEvent.click(control) + expect(onChange).not.toHaveBeenCalled() + rerender() + expect(control.getAttribute('aria-disabled')).toBeNull() + expect(control.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(control) + fireEvent.click(control) + expect(onChange).toHaveBeenCalledExactlyOnceWith(!checked) + }) + + it('keeps a locked switch natively disabled while pending', () => { + const onChange = vi.fn() + render() + const control = screen.getByRole('switch') as HTMLButtonElement + expect(control.disabled).toBe(true) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + fireEvent.click(control) + expect(onChange).not.toHaveBeenCalled() + }) + it('carries a lock reason as the hover title when the owner names one', () => { render( {}} />) expect(screen.getByRole('switch').getAttribute('title')).toBe('Managed by policy') diff --git a/packages/client/ui-theme/src/styles/design-platform.css b/packages/client/ui-theme/src/styles/design-platform.css index 6c53a267a7..e17e4fbfbc 100644 --- a/packages/client/ui-theme/src/styles/design-platform.css +++ b/packages/client/ui-theme/src/styles/design-platform.css @@ -274,6 +274,8 @@ body { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-100); + --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); + --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-00); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-800); --dsw-alias-toast-label: var(--dsw-static-neutral-bluish-00); @@ -398,6 +400,8 @@ body[data-ds-dark-theme] { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-900); + --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); + --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-400); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-750); --dsw-alias-toast-label: var(--dsw-static-neutral-bluish-00); 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 04eeacf67a..83879bec56 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1545,7 +1545,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:70', }, { key: 'conversation.input.model.options', @@ -1573,7 +1573,10 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 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: [], + ownerProps: [ + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', + ], ownerPropsReferences: [], standardProps: [ 'useRemoteAccess: (action: RemoteEndpoint) => boolean', @@ -1605,7 +1608,57 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:23', + source: 'packages/client/ui-model-selection/src/client/slots.ts:41', + }, + { + key: 'conversation.input.model.page', + kind: 'keyed', + scope: 'session', + summary: 'Plugin-owned content displayed as a model-menu detail page.', + doc: 'Plugin-owned content displayed as a model-menu detail page.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [ + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: agent-team', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.input.model\' (client-ui-model-selection), so it exists while that entry is mounted', + occupants: [ + 'client-ui-agent-team TeamModePage key \'agent-team\'', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-model-selection/src/client/slots.ts:50', }, { key: 'conversation.input.overlay', From 603c26a9d796e90dd05f19d367842dd95208d3b6 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Thu, 5 Nov 2026 15:47:19 +0800 Subject: [PATCH 02/68] feat(ui): refine model picker motion and localized effort controls Add localized effort labels and default explanations, animate the blue thumb center, and preserve focus and opacity while selections save. --- apps/web/tests/declared-reasoning.e2e.ts | 525 +++++++++++++++++- .../tests/deepseek-messages-settings.e2e.ts | 4 +- .../declared-reasoning/ui.expected.md | 3 +- apps/web/tests/model-menu-observer.e2e.ts | 6 +- .../client/ui-agent-team/README.i18n.yaml | 4 +- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.module.css | 6 +- .../src/client/TeamModeToggle.tsx | 12 +- .../tests/team-mode.client.spec.tsx | 79 ++- .../ui-model-selection/README.i18n.yaml | 12 +- packages/client/ui-model-selection/README.md | 12 +- .../client/ui-model-selection/README.zh.md | 12 +- .../src/client/EffortSlider.module.css | 218 ++++++-- .../src/client/EffortSlider.tsx | 192 +++++-- .../src/client/ModelSelect.tsx | 35 +- .../src/client/effort-label.ts | 24 + .../ui-model-selection/src/client/locales.ts | 88 ++- .../ui-model-selection/src/client/slots.ts | 4 +- .../tests/effort-label.client.spec.ts | 30 + .../tests/effort-slider.client.spec.tsx | 258 ++++++++- .../tests/model-menu-tab.client.spec.tsx | 90 ++- .../tests/model-select.client.spec.tsx | 109 +++- .../src/client/slot-catalog.ts | 10 +- 24 files changed, 1546 insertions(+), 195 deletions(-) create mode 100644 packages/client/ui-model-selection/src/client/effort-label.ts create mode 100644 packages/client/ui-model-selection/tests/effort-label.client.spec.ts diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 95b6244e3b..c697d3dd84 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import type { Browser, Locator, Page, Request } from 'playwright' +import type { Browser, Locator, Page, Request, Route } from 'playwright' import { chromium, webkit } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' import { @@ -22,6 +22,57 @@ const UI_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/ui.expe const POINTER_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/pointer-menu.expected.md', import.meta.url)) const MODE = webSnapshotMode() +async function readEffortMotion(slider: Locator) { + return slider.evaluate((element) => { + const input = element as HTMLInputElement + const group = input.closest('[role="group"]')! + const thumb = group.querySelector('[data-effort-thumb]')! + const scale = group.querySelector('[data-effort-thumb-scale]')! + const fill = group.querySelector('[data-effort-fill]')! + const label = group.querySelector('[data-effort-label]')! + const rangeRect = input.getBoundingClientRect() + const thumbRect = thumb.getBoundingClientRect() + const fillRect = fill.getBoundingClientRect() + const labelRect = label.parentElement!.getBoundingClientRect() + const thumbSize = Number.parseFloat(getComputedStyle(thumb).width) + const ratio = (input.valueAsNumber - Number(input.min)) / (Number(input.max) - Number(input.min)) + return { + value: input.valueAsNumber, dragging: input.parentElement!.hasAttribute('data-dragging'), + nativeWidth: rangeRect.width, nativeHeight: rangeRect.height, + left: rangeRect.left, right: rangeRect.right, y: rangeRect.top + rangeRect.height / 2, + center: thumbRect.left + thumbRect.width / 2, centerY: thumbRect.top + thumbRect.height / 2, + expectedCenter: rangeRect.left + thumbSize / 2 + (rangeRect.width - thumbSize) * ratio, + thumbSize, visualWidth: scale.getBoundingClientRect().width, fillRight: fillRect.right, + dotWidth: Number.parseFloat(getComputedStyle(scale, '::after').width), + dotDuration: getComputedStyle(scale, '::after').transitionDuration, + dotEasing: getComputedStyle(scale, '::after').transitionTimingFunction, + labelCenter: labelRect.left + labelRect.width / 2, + thumbDuration: getComputedStyle(thumb).transitionDuration, + thumbEasing: getComputedStyle(thumb).transitionTimingFunction, + fillDuration: getComputedStyle(fill).transitionDuration, + tickDuration: getComputedStyle(group.querySelector('[data-effort-tick]')!).transitionDuration, + ticks: [...group.querySelectorAll('[data-effort-tick]')].map((tick) => { + const rect = tick.getBoundingClientRect() + return { center: rect.left + rect.width / 2, width: rect.width, + hovered: tick.hasAttribute('data-hovered'), visibility: getComputedStyle(tick).visibility } + }), + } + }) +} + +async function assertSettledEffort(slider: Locator) { + await expect.poll(async () => { + const view = await readEffortMotion(slider) + return Math.max(Math.abs(view.center - view.expectedCenter), Math.abs(view.fillRight - view.center)) + }).toBeLessThan(1) + const view = await readEffortMotion(slider) + expect(view.nativeHeight).toBe(40) + expect(view.thumbSize).toBe(20) + expect(Math.abs(view.centerY - view.y)).toBeLessThan(1) + expect(Math.abs(view.labelCenter - (view.left + view.right) / 2)).toBeLessThan(1) + return view +} + describe.skipIf(MODE === 'record').each([ { name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }, @@ -85,16 +136,19 @@ describe.skipIf(MODE === 'record').each([ const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const team = page.locator('[data-model-menu-page="agent-team"]') + const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) const focused = async (locator: Locator): Promise => { await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) } await trigger.click() await page.keyboard.press('Tab'); await focused(rootModel) expect(await page.getByRole('menuitemradio').count()).toBe(0) + await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) expect(await page.getByRole('switch').count()).toBe(0) await page.keyboard.press('Shift+Tab'); await focused(slider) + await page.keyboard.press('Shift+Tab'); await focused(info) await page.keyboard.press('Shift+Tab'); await focused(rootModel) await page.keyboard.press('Enter') const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) @@ -116,6 +170,7 @@ describe.skipIf(MODE === 'record').each([ await page.keyboard.press('Tab') await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) await page.keyboard.press('Space'); await focused(rootModel) + await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) await page.keyboard.press('Space') @@ -137,6 +192,76 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('reads default information by mouse and keyboard without selecting or closing the menu', async () => { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + let requests = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ + } + page.on('request', count) + try { + await trigger.click() + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) + const info = menu.getByRole('button', { name: '默认推理等级说明', exact: true }) + const explanation = '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理' + const defaultHeight = await menu.evaluate(element => element.getBoundingClientRect().height) + await menu.locator('[data-effort-label]').click() + expect(await slider.inputValue()).toBe('0') + await info.click() + const tooltip = page.getByRole('tooltip') + await tooltip.waitFor() + expect(await tooltip.textContent()).toBe(explanation) + expect(await menu.isVisible()).toBe(true) + await info.click() + await tooltip.waitFor({ state: 'hidden' }) + await trigger.focus() + await page.keyboard.press('Tab') + await page.keyboard.press('Tab') + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Space') + await tooltip.waitFor() + await page.keyboard.press('Tab') + await tooltip.waitFor({ state: 'hidden' }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(0) + await slider.press('ArrowRight') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('off') + expect(await slider.getAttribute('aria-valuetext')).toBe('关闭') + expect(await menu.locator('[data-effort-label]').textContent()).toBe('推理等级:关闭') + expect(await info.count()).toBe(0) + expect(await menu.evaluate(element => element.getBoundingClientRect().height)).toBe(defaultHeight) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ + provider: 'acme-gateway', model: 'acme-think', + }) + expect(await info.count()).toBe(1) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(2) + expect(tripwire.pageErrors).toEqual([]) + } finally { + page.off('request', count) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } + }) + it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) @@ -147,11 +272,12 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') - expect(await levels.count()).toBe(0) + expect(await levels.count()).toBe(1) + expect(await levels.getAttribute('aria-label')).toBe('默认推理等级说明') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('Default') - const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('Default', { exact: true }) + expect(await slider.getAttribute('aria-valuetext')).toBe('默认') + const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('推理等级:默认', { exact: true }) expect(await tag.evaluate(element => ({ cursor: getComputedStyle(element).cursor, userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), @@ -177,8 +303,8 @@ describe.skipIf(MODE === 'record').each([ async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 10_000 }, ).toContain('reasoningEffort: high') - await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 High') - expect(await slider.getAttribute('aria-valuetext')).toBe('High') + await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 高') + expect(await slider.getAttribute('aria-valuetext')).toBe('高') await slider.focus() await page.keyboard.press('Shift+Tab') await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) @@ -272,16 +398,21 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') await page.mouse.move(0, 0) await page.keyboard.press('Tab') + const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') const slider = page.getByRole('slider', { name: '推理等级', exact: true }) expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') + expect(await info.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') expect(selections).toBe(1) const rangeBounds = await slider.boundingBox() if (rangeBounds === null) throw new Error('Reasoning slider is not visible') await page.mouse.click(rangeBounds.x + rangeBounds.width - 8, rangeBounds.y + rangeBounds.height / 2) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') expect(selections).toBe(2) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') @@ -353,8 +484,9 @@ describe.skipIf(MODE === 'record').each([ const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) const group = menu.getByRole('group', { name: '推理等级', exact: true }) const slider = group.getByRole('slider', { name: '推理等级', exact: true }) - expect(await group.getByRole('button').count()).toBe(0) - expect(await slider.getAttribute('aria-valuetext')).toBe('Default') + expect(await group.getByRole('button').count()).toBe(1) + expect(await group.getByRole('button').getAttribute('aria-label')).toBe('默认推理等级说明') + expect(await slider.getAttribute('aria-valuetext')).toBe('默认') expect(await slider.getAttribute('max')).toBe('5') await expect.poll(() => menu.evaluate((element) => { const rect = element.getBoundingClientRect() @@ -382,7 +514,7 @@ describe.skipIf(MODE === 'record').each([ label: input.getAttribute('aria-valuetext'), busy: input.getAttribute('aria-busy'), disabled: (input as HTMLInputElement).disabled, - }))).toEqual({ value: '5', label: 'Max', busy: 'false', disabled: false }) + }))).toEqual({ value: '5', label: '最高', busy: 'false', disabled: false }) } catch (error) { await page.screenshot({ path: fileURLToPath(new URL( `../../../.artifacts/model-picker-master-sync/drag-${engine.name()}-regression.png`, import.meta.url, @@ -403,6 +535,379 @@ describe.skipIf(MODE === 'record').each([ } }) + it('keeps visual motion aligned with native dragging, hover targets and pending saves at 390px', async () => { + onTestFailed(() => saveFailureShot(page, `web-e2e-effort-motion-${engine.name()}`)) + const viewport = page.viewportSize()! + const trigger = page.getByRole('button', { name: /^选择模型/ }) + try { + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + await page.setViewportSize({ width: 390, height: 700 }) + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await slider.hover() + await page.mouse.move(0, 0) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + const rest = await assertSettledEffort(slider) + await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + expect(rest.dotWidth).toBeCloseTo(8, 1) + expect(rest.thumbDuration).toBe('0.3s') + expect(rest.fillDuration).toBe('0.3s') + expect(rest.thumbEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1)') + expect(rest.dotDuration.split(',').map(value => value.trim())).toEqual(['0.14s', '0.14s']) + expect(rest.dotEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1), cubic-bezier(0.23, 1, 0.32, 1)') + expect(rest.tickDuration).toBe('0.12s') + await page.mouse.move(rest.center, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) + const expanded = await readEffortMotion(slider) + expect(expanded.visualWidth).toBeCloseTo(20, 1) + expect(Math.abs(expanded.center - rest.center)).toBeLessThan(1) + const tick = rest.ticks[2]! + await page.mouse.move(tick.center + 7, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(8, 1) + const hovered = await readEffortMotion(slider) + expect(hovered.ticks.filter(point => point.hovered)).toHaveLength(1) + expect(Math.abs(hovered.ticks[2]!.center - tick.center)).toBeLessThan(1) + await page.mouse.move(tick.center + 9, rest.y) + await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) + const release = Promise.withResolvers() + let requests = 0 + let forwarding: Promise | undefined + const holdSelection = (route: Route): Promise => { + requests++ + forwarding = (async () => { await release.promise; await route.continue() })() + return forwarding + } + await page.route('**/api/session/selectModel', holdSelection) + try { + const grabOffset = 6 + await page.mouse.move(rest.center + grabOffset, rest.y) + await page.mouse.down() + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) + expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + const step = (rest.nativeWidth - rest.thumbSize) / 5 + const between = rest.center + step * 0.3 + await page.mouse.move(between + grabOffset, rest.y, { steps: 3 }) + const tracking = await readEffortMotion(slider) + expect(tracking.value).toBe(0) + expect(Math.abs(tracking.center - between)).toBeLessThan(1) + expect(Math.abs(tracking.fillRight - tracking.center)).toBeLessThan(1) + expect(tracking.ticks.every(point => point.visibility === 'visible')).toBe(true) + expect(tracking.thumbDuration).toBe('0s') + expect(tracking.fillDuration).toBe('0s') + expect(Math.abs(tracking.labelCenter - rest.labelCenter)).toBeLessThan(1) + await page.mouse.move(tick.center + grabOffset, rest.y, { steps: 4 }) + const dragging = await readEffortMotion(slider) + expect(dragging.ticks.every(point => !point.hovered)).toBe(true) + expect(dragging.ticks.every(point => Math.abs(point.width - 4) < 0.1)).toBe(true) + await page.mouse.move(rest.right + 24, rest.y, { steps: 8 }) + expect(requests).toBe(0) + await page.mouse.up() + await expect.poll(() => requests).toBe(1) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('true') + const pending = await assertSettledEffort(slider) + expect(pending.value).toBe(5) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(await slider.evaluate(element => (element as HTMLInputElement).disabled)).toBe(false) + await slider.press('ArrowLeft') + expect((await readEffortMotion(slider)).value).toBe(5) + expect(requests).toBe(1) + release.resolve(undefined) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const saved = await assertSettledEffort(slider) + expect(Math.abs(saved.center - pending.center)).toBeLessThan(1) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(1) + } finally { + release.resolve(undefined) + await page.mouse.up() + await forwarding + await page.unroute('**/api/session/selectModel', holdSelection) + } + await page.mouse.move(rest.ticks[2]!.center, rest.y) + await page.mouse.down() + try { + await expect.poll(() => slider.inputValue()).toBe('2') + const clicked = await readEffortMotion(slider) + expect(clicked.dragging).toBe(false) + expect(clicked.thumbDuration).toBe('0.3s') + expect(clicked.fillDuration).toBe('0.3s') + } finally { + await page.mouse.up() + } + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect((await assertSettledEffort(slider)).value).toBe(2) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + expect((await assertSettledEffort(slider)).value).toBe(0) + await page.emulateMedia({ reducedMotion: 'reduce' }) + await slider.press('End') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const reduced = await assertSettledEffort(slider) + expect(reduced.value).toBe(5) + expect(reduced.thumbDuration).toBe('0s') + expect(reduced.fillDuration).toBe('0s') + expect(reduced.dotDuration).toBe('0s') + expect(reduced.tickDuration).toBe('0s') + await page.mouse.move(reduced.center, reduced.y) + expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + expect((await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + await page.mouse.move(reduced.ticks[2]!.center, reduced.y) + expect((await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.mouse.up() + await page.emulateMedia({ reducedMotion: null }) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + await page.setViewportSize(viewport) + } + }) + + it('does not leave thumb or tick hover enlarged after a native touch tap', async () => { + const touch = await browser.newPage({ + viewport: { width: 390, height: 700 }, locale: ZH_BROWSER_LOCALE, hasTouch: true, isMobile: true, + }) + const consoleWatch = watchConsole(touch) + try { + await touch.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspaceZh(touch, scaffold.workspaceCwd) + await touch.getByRole('button', { name: /^选择模型/ }).click() + await touch.getByRole('menuitem', { name: /^模型/ }).click() + await touch.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const slider = touch.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const before = await assertSettledEffort(slider) + expect(before.value).toBe(0) + expect(await touch.evaluate(() => matchMedia('(hover: hover) and (pointer: fine)').matches)).toBe(false) + let requests = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ + } + touch.on('request', count) + try { + const info = touch.getByRole('button', { name: '默认推理等级说明', exact: true }) + const bounds = await info.boundingBox() + if (bounds === null) throw new Error('Default information is not visible') + await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + const tooltip = touch.getByRole('tooltip') + await tooltip.waitFor() + expect(await tooltip.textContent()).toBe('未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理') + expect(await slider.inputValue()).toBe('0') + expect(requests).toBe(0) + await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + await tooltip.waitFor({ state: 'hidden' }) + expect(await info.isVisible()).toBe(true) + await touch.touchscreen.tap(before.right - 10, before.y) + await expect.poll(() => slider.inputValue()).toBe('5') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await assertSettledEffort(slider) + await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) + await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) + expect(await touch.locator('[data-effort-thumb-scale][data-expanded]').count()).toBe(0) + expect((await readEffortMotion(slider)).ticks.every(tick => !tick.hovered && Math.abs(tick.width - 4) < 0.1)).toBe(true) + expect(requests).toBe(1) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + touch.off('request', count) + } + } finally { + await touch.close() + } + }) + + it('keeps the compact Spanish caption and default information readable at 390px', async () => { + const probe = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'es-ES' }) + const consoleWatch = watchConsole(probe) + try { + await probe.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await probe.getByRole('button', { name: 'Agregar espacio de trabajo', exact: true }).click() + const directory = probe.getByRole('dialog', { name: 'Seleccionar carpeta de trabajo', exact: true }) + await directory.getByRole('button', { name: 'Editar ruta', exact: true }).click() + const path = directory.getByRole('textbox', { name: 'Editar ruta', exact: true }) + await path.fill(join(scaffold.workspaceCwd, 'workspace')) + await path.press('Enter') + await directory.getByRole('button', { name: 'Abrir', exact: true }).click() + await probe.locator('[data-composer-input][contenteditable="true"]').waitFor() + await probe.getByRole('button', { name: /^Seleccionar modelo/ }).click() + await probe.getByRole('menuitem', { name: /^modelo/ }).click() + await probe.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const menu = probe.getByRole('menu', { name: 'Esfuerzo de modelo y razonamiento.', exact: true }) + const slider = menu.getByRole('slider', { name: 'Esfuerzo', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await probe.setViewportSize({ width: 390, height: 700 }) + const label = menu.locator('[data-effort-label]') + const info = menu.getByRole('button', { name: 'Acerca del esfuerzo de razonamiento predeterminado', exact: true }) + await info.waitFor() + const layout = await info.evaluate((button) => { + const tag = button.parentElement! + const text = tag.querySelector('[data-effort-label]')! + const name = text.querySelector('[data-effort-name]')! + const prefix = name.previousElementSibling! + const bounds = button.getBoundingClientRect() + const tagBounds = tag.getBoundingClientRect() + const nameBounds = name.getBoundingClientRect() + const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2) + return { width: bounds.width, height: bounds.height, textWidth: text.clientWidth, + textGap: bounds.left - text.getBoundingClientRect().right, endInset: tagBounds.right - bounds.right, + clipped: prefix.scrollWidth > prefix.clientWidth, ellipsis: getComputedStyle(prefix).textOverflow, + nameText: name.textContent, nameFits: name.scrollWidth <= name.clientWidth, + nameVisible: nameBounds.width > 0 && nameBounds.left >= tagBounds.left && nameBounds.right <= bounds.left, + contained: bounds.left >= tagBounds.left && bounds.right <= tagBounds.right, + reachable: hit?.closest('button') === button } + }) + expect(layout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', + nameText: 'Predeterminado', nameFits: true, nameVisible: true, contained: true, reachable: true }) + expect(layout.textWidth).toBeGreaterThan(0) + expect(layout.textGap).toBeCloseTo(2, 1) + expect(layout.endInset).toBeCloseTo(2, 1) + expect(await label.textContent()).toBe('Esfuerzo: Predeterminado') + await label.hover() + const tooltip = probe.getByRole('tooltip') + expect(await tooltip.count()).toBe(0) + await info.click() + await expect.poll(() => tooltip.allTextContents()).toEqual([ + 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', + ]) + expect(await menu.isVisible()).toBe(true) + expect(await slider.inputValue()).toBe('0') + await probe.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await menu.isVisible()).toBe(true) + await info.focus() + await probe.keyboard.press('Enter') + await tooltip.waitFor() + await probe.keyboard.press('Tab') + await tooltip.waitFor({ state: 'hidden' }) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(await slider.inputValue()).toBe('0') + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await probe.close() + } + }) + + it.each(['success', 'failure'] as const)('keeps Team undimmed and guarded through a pending effort %s', async (outcome) => { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const release = Promise.withResolvers() + let selections = 0 + let teamWrites = 0 + let forwarding: Promise | undefined + const countTeamWrites = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/agentTeams/setEnabled')) teamWrites++ + } + const holdSelection = (route: Route): Promise => { + selections++ + forwarding = (async () => { + await release.promise + if (outcome === 'success') { await route.continue(); return } + const envelope = route.request().postDataJSON() as { rpcId: string } + await route.fulfill({ json: { type: 'server-response', rpcId: envelope.rpcId, result: { + ok: false, error: { code: 'session/writer-held', message: 'held', details: { sessionId: 'team-pending-fixture' } }, + } } }) + })() + return forwarding + } + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('Home') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await page.keyboard.down('ArrowRight') + await page.keyboard.down('ArrowRight') + await page.keyboard.down('ArrowRight') + await page.keyboard.up('ArrowRight') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('high') + await page.mouse.move(0, 0) + const menuLocator = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const teamLocator = page.locator('[data-model-menu-page="agent-team"]') + const menu = await menuLocator.elementHandle() + const root = await page.locator('[data-model-menu-root]').elementHandle() + const team = await teamLocator.elementHandle() + if (menu === null || root === null || team === null) throw new Error('Missing pending Team controls') + const sample = () => page.evaluate(({ menu, root, team }) => { + const rect = (element: Element) => { + const value = element.getBoundingClientRect() + return { x: value.x, y: value.y, width: value.width, height: value.height } + } + return { + same: { + menu: menu === document.querySelector('[role="menu"][aria-label="模型与推理等级"]'), + root: root === document.querySelector('[data-model-menu-root]'), + team: team === document.querySelector('[data-model-menu-page="agent-team"]'), + }, + connected: menu.isConnected && root.isConnected && team.isConnected, + rect: { menu: rect(menu), root: rect(root), team: rect(team) }, + disabled: (team as HTMLButtonElement).disabled, opacity: getComputedStyle(team).opacity, + ariaDisabled: team.getAttribute('aria-disabled'), ariaBusy: team.getAttribute('aria-busy'), + focus: document.activeElement === team ? 'team' : document.activeElement === root.querySelector('input[type="range"]') ? 'range' : 'other', + } + }, { menu, root, team }) + page.on('request', countTeamWrites) + try { + const before = await sample() + expect(before).toMatchObject({ same: { menu: true, root: true, team: true }, connected: true, + disabled: false, opacity: '1', ariaDisabled: null, ariaBusy: null, focus: 'range' }) + await page.route('**/api/session/selectModel', holdSelection) + await page.keyboard.down('ArrowLeft') + await page.keyboard.down('ArrowLeft') + await page.keyboard.up('ArrowLeft') + await expect.poll(() => selections).toBe(1) + await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBe('true') + const during = await sample() + expect(during).toEqual({ ...before, ariaDisabled: 'true', ariaBusy: 'true' }) + const bounds = during.rect.team + await page.mouse.click(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) + expect(await menuLocator.getByRole('switch').count()).toBe(0) + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await page.keyboard.press('Space') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + expect(await menuLocator.getByRole('switch').count()).toBe(0) + expect(teamWrites).toBe(0) + expect(selections).toBe(1) + release.resolve(undefined) + await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBeNull() + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + const after = await sample() + expect(after).toEqual({ ...before, focus: 'team' }) + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe(outcome === 'success' ? 'low' : 'high') + if (outcome === 'failure') await page.getByRole('alert').waitFor() + expect(selections).toBe(1) + expect(teamWrites).toBe(0) + const lockedOpacity = await team.evaluate((element) => { + const button = element as HTMLButtonElement + try { button.disabled = true; return getComputedStyle(button).opacity } finally { button.disabled = false } + }) + expect(lockedOpacity).toBe('0.5') + await page.keyboard.press('Tab') + expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) + await teamLocator.click() + await page.getByRole('switch', { name: '启用智能体团队协作', exact: true }).waitFor() + expect(teamWrites).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + release.resolve(undefined) + await forwarding + await page.unroute('**/api/session/selectModel', holdSelection) + page.off('request', countTeamWrites) + await menu.dispose() + await root.dispose() + await team.dispose() + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'pointer-menu.expected.md']) }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index a842669c01..5a5c6727cc 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -128,8 +128,8 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const slider = effort.getByRole('slider') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('High') - const tag = effort.getByText('High', { exact: true }) + expect(await slider.getAttribute('aria-valuetext')).toBe('高') + const tag = effort.getByText('推理等级:高', { exact: true }) expect(await tag.evaluate(element => getComputedStyle(element).fontWeight)).toBe('500') expect(await tag.evaluate(element => element.tabIndex)).toBe(-1) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index a56dedf7d1..4ad2a55d90 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,6 +1,7 @@ - menu "模型与推理等级": - menuitem "模型 Acme Think" - group "推理等级": - - text: Default + - text: 推理等级:默认 + - button "默认推理等级说明" - slider "推理等级": "0" - menuitem "智能体团队协作 关" diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index d0a1cab304..5dfc2d06d3 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -413,7 +413,9 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) - expect(await menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button').count()).toBe(0) + const information = menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') + expect(await information.count()).toBe(1) + expect(await information.getAttribute('aria-label')).toBe('默认推理等级说明') await expect.poll(() => slider.evaluate((range) => { const scroller = range.closest('[data-model-menu-root]')! scroller.scrollTop = scroller.scrollHeight @@ -457,7 +459,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) expect(await menu.isVisible()).toBe(true) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('Max') + await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') await page.keyboard.press('Escape') await menu.waitFor({ state: 'detached' }) } diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index a438e29119..e7ab86a3a4 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: 1bb905cfddfc8686 - zh: f3996e9b43e2b06b + en: 5485135ed71fbbf5 + zh: 37112168c8785012 /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index bd556a4873..f94c571c56 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,9 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Saving uses the [Switch pending state](../ui-primitives/README.md#component-catalog), so a keyboard-activated switch keeps focus without accepting another change. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The settings switch combines model-menu pending state with its own save state through the [Switch pending state](../ui-primitives/README.md#component-catalog). Either pending save blocks another Team change while keeping keyboard focus; it does not bypass the disable confirmation. + +During a model or reasoning-effort save, the root Team row keeps its opacity and focus and refuses activation. It reports `aria-disabled` and `aria-busy` without setting native `disabled`. An actual composer lock still sets native `disabled` and retains the disabled appearance. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index 115fb82e4c..e906b386f7 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,9 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。保存时使用 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog),因此键盘激活的开关保留焦点,但不接受再次切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。设置页将模型菜单的 pending 状态与自身保存状态合并为 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog)。任一保存进行中都会阻止再次切换 Team,同时保留键盘焦点;这不会绕过关闭确认。 + +模型或推理等级保存期间,一级 Team 行保持原有不透明度和焦点,并拒绝激活。它设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`。输入区真正锁定时,仍设置原生 `disabled` 并保留禁用外观。 会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 44916c8f26..5071a9c00b 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -45,7 +45,7 @@ .page { display: flex; flex-direction: column; - gap: 8px; + gap: 4px; min-width: 0; } @@ -53,8 +53,8 @@ margin: 0; padding: 4px 8px; color: var(--dsw-alias-label-secondary); - font-size: 13px; - line-height: 20px; + font-size: 12px; + line-height: 18px; overflow-wrap: anywhere; } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index 15f6c93cae..a1b4b52dd6 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -36,7 +36,7 @@ export function TeamModeToggle(props: TeamModeToggleProps) { return } -function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { +function RootTeamModeSummary({ useProjection, locked, pending, openPage, t }: TeamModeToggleProps) { const mode = useProjection('agentTeam') if (mode === undefined) return null return ( @@ -46,7 +46,9 @@ function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeTog className={css.summary} data-model-menu-page="agent-team" disabled={locked} - onClick={() => { openPage({ key: 'agent-team', title: t('command.title') }) }} + aria-disabled={locked || pending || undefined} + aria-busy={pending || undefined} + onClick={() => { if (!locked && !pending) openPage({ key: 'agent-team', title: t('command.title') }) }} > {t('command.title')} {t(mode.enabled ? 'mode.on' : 'mode.off')} @@ -69,14 +71,14 @@ export function TeamModePage(props: TeamModePageProps) { /** Read and change the selection only for root Sessions. */ function RootTeamModePage({ - useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, + useProjection, locked, pending: modelPending, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, }: TeamModePageProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (locked || pending || modelSelection === undefined) return + if (locked || modelPending || pending || modelSelection === undefined) return if (!enabled && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() @@ -94,7 +96,7 @@ function RootTeamModePage({
{t('mode.label')} + pending={modelPending || pending} label={t('mode.label')} onChange={select} />

{t('mode.description')}

diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 9fa08dacc9..82029d9af2 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -19,7 +19,8 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + locked: false, pending: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), + selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), } as TestProps } @@ -55,6 +56,82 @@ it('keeps summary state projection-owned and blocks navigation while locked', () expect(lockedInput.openPage).not.toHaveBeenCalled() }) +it.each([false, true])('keeps the summary node focused and natively enabled during a model save (enabled: %s)', (enabled) => { + const input = props(enabled) + const view = render() + const summary = screen.getByRole('menuitem') + summary.focus() + view.rerender() + expect(screen.getByRole('menuitem')).toBe(summary) + expect(summary.isConnected).toBe(true) + expect(summary.hasAttribute('disabled')).toBe(false) + expect(summary.getAttribute('aria-disabled')).toBe('true') + expect(summary.getAttribute('aria-busy')).toBe('true') + expect(document.activeElement).toBe(summary) + fireEvent.click(summary) + expect(input.openPage).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() + view.rerender() + expect(screen.getByRole('menuitem')).toBe(summary) + expect(summary.getAttribute('aria-disabled')).toBeNull() + expect(summary.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(summary) + fireEvent.click(summary) + expect(input.openPage).toHaveBeenCalledOnce() +}) + +it.each([false, true])('blocks Team writes and confirmation without dropping switch focus during a model save (enabled: %s)', (enabled) => { + const input = props(enabled, undefined, undefined, true) + const view = render() + const toggle = screen.getByRole('switch') + toggle.focus() + view.rerender() + expect(screen.getByRole('switch')).toBe(toggle) + expect(toggle.hasAttribute('disabled')).toBe(false) + expect(toggle.getAttribute('aria-disabled')).toBe('true') + expect(toggle.getAttribute('aria-busy')).toBe('true') + fireEvent.click(toggle) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() + expect(document.activeElement).toBe(toggle) + view.rerender() + expect(toggle.getAttribute('aria-disabled')).toBeNull() + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(toggle) +}) + +it.each([TeamModeToggle, TeamModePage])('keeps a genuine lock natively disabled while a model write is pending', (Component) => { + const input = props(false) + render() + const control = screen.queryByRole('menuitem') ?? screen.getByRole('switch') + expect(control.hasAttribute('disabled')).toBe(true) + expect(control.getAttribute('aria-disabled')).toBe('true') + expect(control.getAttribute('aria-busy')).toBe('true') + fireEvent.click(control) + expect(input.openPage).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it('keeps model pending protection after the Team write settles', async () => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const input = props(false, vi.fn(() => pending.promise)) + const view = render() + const toggle = screen.getByRole('switch') + toggle.focus() + fireEvent.click(toggle) + view.rerender() + await act(async () => { pending.resolve(null) }) + expect(toggle.getAttribute('aria-busy')).toBe('true') + expect(toggle.hasAttribute('disabled')).toBe(false) + fireEvent.click(toggle) + expect(input.selectTeamMode).toHaveBeenCalledTimes(1) + view.rerender() + expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(document.activeElement).toBe(toggle) +}) + it('allows reading settings from the summary while model history loads', () => { const input = props(false, undefined, undefined, 'loading') render() diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 3d37eb7f75..b0e74e370d 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 8caa289a6b9a3987 - zh: 4e68187154ad7a01 + en: 9b301384eb14f6e0 + zh: 7b021daf345506a8 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: 7444798cb92d0f38 - zh: 03edcc1070554437 + en: a57ad8d1ae2c5378 + zh: 391f4a695cdb5232 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 393aae0df60e2abd - zh: f989d6108a047160 + en: 7f5e8e8358c98376 + zh: 5df89a5a0934c885 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: feab134e75f5b2f7 zh: 66bd58568f58ed4f diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 55adbc748d..1d28797205 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -33,7 +33,7 @@ When no model is selected or the saved selection is absent from the catalog, the Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab move to the adjacent control. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort keeps the menu and slider focus in place. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; an effort save also keeps slider focus. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort does not move focus or change the current menu page. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; effort-save completion preserves any page or focus the user navigated to while saving. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. ### Model and effort @@ -45,7 +45,13 @@ Both entries group models by provider, with DeepSeek Account first and DeepSeek The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. -The 260px-wide root menu places the model name above a centered effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag uses the default cursor and its text cannot be selected; hovering still shows the localized “Reasoning effort: {effort}” tooltip without adding a Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. A `Default` stop appears only when the adapter has no configured default effort and submits no explicit effort; it is not a promise of a fixed provider strength. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. +The 260px-wide root menu places the model name above a centered, arrowless effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag displays the complete localized label, such as “Effort: High”, and keeps its hover tooltip. It uses the default cursor, its text cannot be selected, and the label adds no Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. + +The tag shows “Effort: Default” for the localized “Default” stop, which appears only when the adapter has no configured default effort. It submits no explicit effort: model and configuration defaults apply, which does not mean reasoning is off. Only this omitted-effort choice shows a keyboard-focusable information button beside the tag; a provider level with the explicit ID `default` does not. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. + +Standard levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`) use localized names only when the provider's name matches its ID ignoring case. Custom names and unknown levels remain unchanged; for example, `high` named “Thorough mode” keeps that name. This changes display text only, not submitted or persisted IDs. + +The visual thumb and filled track follow pointer movement continuously during a drag; the native range still determines the discrete label and value, with one submission on release. Hovering the thumb with a fine mouse pointer or pressing the slider enlarges only the blue center of the visual thumb; the white disc and hit area keep their size. Mouse hover enlarges only the nearby tick, not neighboring ticks, and is inactive during dragging or saving. Touch interaction leaves no hover highlight. Reduced motion disables position transitions and center and tick enlargement. ### Model label extensions @@ -63,7 +69,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. +The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, required `pending: boolean`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `pending`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. Both slots distinguish an actual composer lock (`locked`) from a model or effort save in flight (`pending`); saving alone does not set `locked`. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index f92ff2ffdd..14de3a0337 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -33,7 +33,7 @@ DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示 与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 移至相邻控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级后保持菜单打开和滑块焦点。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存期间也保留滑块焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级不搬移焦点,也不切换当前菜单页面。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存完成后,保留用户在保存期间主动导航到的页面与焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 ### 模型与推理强度 @@ -45,7 +45,13 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 -260px 宽的一级菜单将模型名放在上方,下方显示居中的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签使用默认鼠标指针,文字不可选中;悬停仍显示本地化的“推理等级:{effort}”提示,不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。仅当适配器未配置默认强度时出现 `Default` 刻度,它不提交显式强度,也不承诺提供方会使用固定档位。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 +260px 宽的一级菜单将模型名放在上方,下方显示居中且不带箭头的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签显示完整本地化文案,例如“推理等级:高”,并保留悬停提示。标签使用默认鼠标指针,文字不可选中,文字本身不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。 + +仅当适配器未配置默认强度时出现本地化的“默认”刻度,标签显示“推理等级:默认”。它不提交显式推理等级,而是使用模型与配置的默认设置,不代表关闭推理。仅此省略等级的选择在标签旁显示可通过键盘聚焦的信息按钮;提供方显式 ID 为 `default` 的档位不显示该说明按钮。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 + +标准档位(`off`、`minimal`、`low`、`medium`、`high`、`xhigh` 和 `max`)仅在提供方名称与 ID 忽略大小写后相同时使用本地化名称。自定义名称与未知档位保持原文,例如名称为“Thorough mode”的 `high` 保留该名称。此规则仅改变显示文字,不改变提交或持久化的 ID。 + +拖动期间,可见滑块圆点与轨道填充连续跟随指针移动;标签和实际值仍由原生滑块的离散档位决定,松手后只提交一次。精细鼠标指针悬停圆点或按下滑块时,只放大可见圆点中间的蓝色部分;白色外圈和命中区域尺寸不变。鼠标悬停仅放大命中的单个刻度,不放大相邻刻度;拖动或保存期间不启用刻度悬停效果。触摸交互不留下悬停高亮。减少动态效果设置会关闭位置过渡以及蓝点和刻度的放大效果。 ### 模型名称扩展 @@ -63,7 +69,7 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 +会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、必填的 `pending: boolean`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`pending`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。两个 slot 均区分输入区的真实锁定(`locked`)与模型或推理等级正在保存(`pending`);仅保存中不会将 `locked` 设为 true。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 ----- diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css index 645a5f5b61..38e05015f9 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -8,13 +8,18 @@ grid-row: 2; display: flex; justify-content: center; - height: 22px; + height: 28px; margin: 10px 14px 0; } .value { + display: inline-flex; + align-items: center; + gap: 4px; + box-sizing: border-box; max-width: 100%; - padding: 1px 10px; + height: 28px; + padding: 1px 8px; border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); border-radius: 999px; corner-shape: round; @@ -25,21 +30,97 @@ font-weight: 500; text-align: center; white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; cursor: default; -webkit-user-select: none; user-select: none; } +.value:has(.infoButton) { + gap: 2px; + padding-inline-end: 1px; +} + +.valueLabel { + display: flex; + gap: 2px; + min-width: 0; + overflow: hidden; + -webkit-user-select: none; + user-select: none; +} + +.valuePrefix { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.valueName { + flex: 0 0 auto; + max-width: calc(100% - 2px); + overflow: hidden; + text-overflow: ellipsis; +} + +.infoButton { + display: inline-flex; + flex: 0 0 24px; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 50%; + corner-shape: round; + background: transparent; + color: inherit; + cursor: pointer; +} + +.infoButton:focus-visible { + outline: 2px solid currentColor; + outline-offset: -2px; +} + +@media (hover: hover) { + .infoButton:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + .rail { grid-row: 3; position: relative; margin: 0 8px 2px; } +.track { + position: absolute; + inset-inline: 0; + top: 50%; + height: var(--effort-track-size); + transform: translateY(-50%); + border-radius: 999px; + corner-shape: round; + overflow: hidden; + pointer-events: none; + background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); +} + +.fill { + display: block; + height: 100%; + width: calc(var(--effort-thumb-size) / 2 + (100% - var(--effort-thumb-size)) * var(--effort-visual-position)); + background: linear-gradient(to right, + color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), + color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); + transition: width 300ms cubic-bezier(.23, 1, .32, 1); +} + .range { appearance: none; + position: relative; display: block; box-sizing: border-box; width: 100%; @@ -54,56 +135,32 @@ .range::-webkit-slider-runnable-track { height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: - linear-gradient(to right, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent) 0, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent) var(--effort-progress), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) var(--effort-progress), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent) 100%), - color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); -} - -.range::-moz-range-track { - height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); + background: transparent; } +.range::-moz-range-track, .range::-moz-range-progress { height: var(--effort-track-size); - border-radius: 999px; - corner-shape: round; - background: linear-gradient(to right, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), - color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); + background: transparent; } - - +/* Native thumb geometry owns hit testing; the inert sibling owns all visual motion. */ .range::-webkit-slider-thumb { appearance: none; + box-sizing: border-box; width: var(--effort-thumb-size); height: var(--effort-thumb-size); margin-top: calc((var(--effort-track-size) - var(--effort-thumb-size)) / 2); - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 50%; - corner-shape: round; - background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); - box-shadow: var(--dsw-elevation-panel); + border: 0; + background: transparent; } .range::-moz-range-thumb { box-sizing: border-box; width: var(--effort-thumb-size); height: var(--effort-thumb-size); - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 50%; - corner-shape: round; - background: radial-gradient(circle, var(--dsw-alias-slider-thumb-mark) 0 4px, var(--dsw-alias-slider-thumb) 4.5px); - box-shadow: var(--dsw-elevation-panel); + border: 0; + background: transparent; } .range:focus-visible { @@ -113,29 +170,102 @@ } .range:disabled { - opacity: 0.5; cursor: default; } -.ticks { +.rail[data-disabled] { + opacity: 0.5; +} + +.ticks, +.thumbRail { position: absolute; inset: 0 calc(var(--effort-thumb-size) / 2); - display: flex; - align-items: center; - justify-content: space-between; pointer-events: none; } .tick, .tickActive { + position: absolute; + top: 50%; width: 4px; height: 4px; + transform: translate(-50%, -50%); border-radius: 50%; corner-shape: round; background: var(--dsw-alias-label-caption); opacity: 0.6; + transition: transform 120ms ease; } -.ticks [data-current] { - visibility: hidden; +@media (hover: hover) and (pointer: fine) { + .ticks [data-hovered] { + transform: translate(-50%, -50%) scale(2); + } +} + +.thumbPosition { + position: absolute; + top: 50%; + left: calc(var(--effort-visual-position) * 100%); + width: var(--effort-thumb-size); + height: var(--effort-thumb-size); + transform: translate(-50%, -50%); + transition: left 300ms cubic-bezier(.23, 1, .32, 1); +} + +.thumb { + position: absolute; + inset: 0; + box-sizing: border-box; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-slider-thumb); + box-shadow: var(--dsw-elevation-panel); +} + +/* The white disc holds its size; only the blue center grows on hover or press. */ +.thumb::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 8px; + height: 8px; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-slider-thumb-mark); + transform: translate(-50%, -50%); + transition: width 140ms cubic-bezier(.23, 1, .32, 1), height 140ms cubic-bezier(.23, 1, .32, 1); +} + +.thumb[data-expanded]::after { + width: 9.6px; + height: 9.6px; +} + +.rail[data-dragging] .thumbPosition, +.rail[data-dragging] .fill { + transition: none; +} + +@media (prefers-reduced-motion: reduce) { + .thumbPosition, + .fill, + .thumb::after, + .thumb[data-expanded]::after, + .tick, + .tickActive { + transition: none; + } + + .thumb[data-expanded]::after { + width: 8px; + height: 8px; + } + + .ticks [data-hovered] { + transform: translate(-50%, -50%); + } } diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx index 301055506f..1c42361954 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.tsx +++ b/packages/client/ui-model-selection/src/client/EffortSlider.tsx @@ -1,5 +1,5 @@ -import { useState, type CSSProperties } from 'react' -import { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { useEffect, useRef, useState, type CSSProperties, type PointerEvent } from 'react' +import { IconInfoOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' import css from './EffortSlider.module.css' /** One adapter-advertised stop; undefined selects the adapter's default behavior. */ @@ -15,38 +15,114 @@ export interface EffortSliderProps { value: string | undefined label: string currentLabel: string - /** Localized tooltip text for the currently displayed effort name. */ - formatTooltip: (effort: string) => string + /** Localized full label for the currently displayed effort name. */ + formatLabel: (effort: string) => string + /** Accessible label for the default-effort explanation button. */ + defaultInfoLabel: string + /** Explanation of unspecified effort, distinct from disabling reasoning. */ + defaultExplanation: string disabled: boolean /** A selection is being saved; keep its displayed value and keyboard focus. */ pending: boolean onSelect: (effort: string | undefined) => void } -type Gesture = { kind: 'pointer' | 'keyboard' | 'cancelled'; source: string; index: number } +type PointerGeometry = { start: number; length: number; size: number; centerY: number; offset: number } +type Gesture = + | { kind: 'pointer'; source: string; index: number; geometry: PointerGeometry | null; position: number | null } + | { kind: 'keyboard' | 'cancelled'; source: string; index: number } + | { kind: 'hover'; catalog: string; thumb: boolean; tick: number | null } const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) /** - * Preview a discrete selection locally and submit once when the gesture finishes. + * Preview native discrete values while an inert visual thumb follows pointer movement. * @param props - Exact-model choices, persisted value, and selection callback. - * @returns A native discrete range with a live value label. + * @returns A native range with a live value label and independent motion decoration. */ -export function EffortSlider({ choices, value, label, currentLabel, formatTooltip, disabled, pending, onSelect }: EffortSliderProps) { +export function EffortSlider({ + choices, value, label, currentLabel, formatLabel, defaultInfoLabel, defaultExplanation, disabled, pending, onSelect, +}: EffortSliderProps) { + const thumbRef = useRef(null) + const rangeRef = useRef(null) + const infoFocused = useRef(false) const selectedIndex = choices.findIndex(choice => choice.effort === value) - const source = JSON.stringify([choices.map(choice => [choice.key, choice.effort]), value]) + const catalog = JSON.stringify(choices.map(choice => [choice.key, choice.effort])) + const source = JSON.stringify([catalog, value]) const [gesture, setGesture] = useState(null) - const preview = gesture?.source === source && gesture.kind !== 'cancelled' ? gesture.index : selectedIndex + const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 + if (gesture?.kind === 'hover' && (gesture.catalog !== catalog || rangeDisabled)) setGesture(null) + if (gesture !== null && gesture.kind !== 'hover' && gesture.kind !== 'cancelled' + && (gesture.source !== source || rangeDisabled || pending)) { + setGesture({ kind: 'cancelled', source, index: selectedIndex }) + } + const active = gesture !== null && gesture.kind !== 'hover' && gesture.source === source && !rangeDisabled && !pending ? gesture : null + const hover = gesture?.kind === 'hover' && gesture.catalog === catalog && !rangeDisabled ? gesture : null + const preview = active !== null && active.kind !== 'cancelled' ? active.index : selectedIndex const index = Math.max(0, preview) const current = choices[preview] - const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 - const commit = (nextIndex: number): void => { - const choice = choices[nextIndex] - setGesture(null) - if (!disabled && !pending && choice !== undefined) onSelect(choice.effort) + const defaultSelected = current !== undefined && current.effort === undefined + const displayName = current?.label ?? currentLabel + const valueLabel = formatLabel(displayName) + // Preserve the effort name when a long localized prefix needs truncation. + const valueStart = Math.max(0, valueLabel.lastIndexOf(displayName)) + useEffect(() => { + // An external selection can remove the focused info button; keep keyboard access on the range. + if (!defaultSelected && infoFocused.current) { + rangeRef.current?.focus() + infoFocused.current = false + } + }, [defaultSelected]) + const progress = choices.length > 1 ? index / (choices.length - 1) : 0 + const dragging = active?.kind === 'pointer' && active.position !== null + const visualProgress = dragging ? active.position : progress + const expanded = active?.kind === 'pointer' || hover?.thumb === true + + // Pointer geometry comes from the unscaled wrapper, so zoom and the spring cannot change the grab offset. + const measure = (input: HTMLInputElement): PointerGeometry | null => { + const range = input.getBoundingClientRect() + const thumb = thumbRef.current?.getBoundingClientRect() + if (thumb === undefined || range.width <= thumb.width) return null + return { + start: range.left + thumb.width / 2, length: range.width - thumb.width, + size: thumb.width, centerY: range.top + range.height / 2, offset: 0, + } } - const finish = (kind: Gesture['kind'], nextIndex: number): void => { - if (gesture?.kind === kind && gesture.source === source) commit(nextIndex) - else setGesture(null) + const hoverAt = (event: PointerEvent, settledIndex?: number): Gesture | null => { + if (rangeDisabled || event.pointerType !== 'mouse' || !window.matchMedia('(hover: hover) and (pointer: fine)').matches) return null + const geometry = measure(event.currentTarget) + const thumb = thumbRef.current?.getBoundingClientRect() + if (geometry === null || thumb === undefined) return null + const center = settledIndex === undefined ? thumb.left + thumb.width / 2 + : geometry.start + settledIndex / (choices.length - 1) * geometry.length + const overThumb = Math.abs(event.clientX - center) <= geometry.size / 2 + && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2 + const nearest = Math.max(0, Math.min(choices.length - 1, + Math.round((event.clientX - geometry.start) / geometry.length * (choices.length - 1)))) + const tickX = geometry.start + nearest / (choices.length - 1) * geometry.length + const overTick = !pending && !overThumb && Math.abs(event.clientX - tickX) <= 8 && Math.abs(event.clientY - geometry.centerY) <= 8 + return { kind: 'hover', catalog, thumb: overThumb, tick: overTick ? nearest : null } + } + const commit = (nextIndex: number, next: Gesture | null = null): void => { + const choice = choices[nextIndex] + setGesture(next) + if (!rangeDisabled && !pending && choice !== undefined) onSelect(choice.effort) + } + const finish = (kind: 'pointer' | 'keyboard', nextIndex: number, next: Gesture | null = null): void => { + if (gesture?.kind === kind && gesture.source === source) commit(nextIndex, next) + else setGesture(next) + } + const movePointer = (event: PointerEvent): void => { + if (gesture?.kind === 'cancelled') return + if (gesture?.kind === 'pointer') { + if (gesture.source !== source || rangeDisabled || pending || gesture.geometry === null) return + const { start, length, offset } = gesture.geometry + const position = Math.max(0, Math.min(1, (event.clientX - start - offset) / length)) + setGesture(previous => previous?.kind === 'pointer' && previous.source === source ? { ...previous, position } : previous) + } else if (gesture === null || gesture.kind === 'hover') { + const next = hoverAt(event) + setGesture(previous => previous?.kind === 'hover' && next?.kind === 'hover' + && previous.catalog === next.catalog && previous.thumb === next.thumb && previous.tick === next.tick ? previous : next) + } } return (
1 ? index / (choices.length - 1) * 100 : 0}%`, + '--effort-progress': `${progress * 100}%`, } as CSSProperties} >
- - {current?.label ?? currentLabel} + + + + {valueLabel.slice(0, valueStart)} + {valueLabel.slice(valueStart)} + + {defaultSelected && ( + + + + )} +
-
+
+ { - if (pending) { event.preventDefault(); return } - setGesture({ kind: 'pointer', source, index }) + if (pending || rangeDisabled) { event.preventDefault(); return } + if (event.button > 0) return + const geometry = measure(event.currentTarget) + const thumb = thumbRef.current?.getBoundingClientRect() + if (geometry !== null && thumb !== undefined) { + const offset = event.clientX - thumb.left - thumb.width / 2 + if (Math.abs(offset) <= geometry.size / 2 && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2) { + geometry.offset = offset + } + } + setGesture({ kind: 'pointer', source, index, geometry, position: null }) }} + onPointerEnter={movePointer} + onPointerMove={movePointer} + onPointerLeave={() => { setGesture(previous => previous?.kind === 'hover' ? null : previous) }} onChange={(event) => { - if (pending || disabled) return + if (pending || rangeDisabled) return const nextIndex = event.currentTarget.valueAsNumber - if (gesture === null) commit(nextIndex) - else if (gesture.source === source && gesture.kind !== 'cancelled') setGesture({ ...gesture, index: nextIndex }) + if (gesture === null || gesture.kind === 'hover') commit(nextIndex) + else if (gesture.source === source && gesture.kind !== 'cancelled') { + setGesture(previous => previous !== null && previous.kind !== 'hover' && previous.source === source && previous.kind !== 'cancelled' + ? { ...previous, index: nextIndex } : previous) + } + }} + onPointerUp={(event) => { + if (gesture?.kind === 'pointer' && gesture.source === source && !rangeDisabled && !pending) event.currentTarget.focus() + finish('pointer', event.currentTarget.valueAsNumber, hoverAt(event, event.currentTarget.valueAsNumber)) }} - onPointerUp={(event) => { finish('pointer', event.currentTarget.valueAsNumber) }} onPointerCancel={() => { setGesture(null) }} - onLostPointerCapture={() => { setGesture(null) }} - onBlur={() => { setGesture(null) }} + onLostPointerCapture={() => { setGesture(previous => previous?.kind === 'hover' ? previous : null) }} + onBlur={(event) => { + // WebKit focuses the enclosing menu when its native range takes over a pointer drag. + const insideAncestor = event.relatedTarget instanceof Node && event.relatedTarget.contains(event.currentTarget) + setGesture(previous => insideAncestor && previous?.kind === 'pointer' && previous.source === source ? previous : null) + }} onKeyDown={(event) => { if (event.nativeEvent.isComposing) return if (pending && ADJUST_KEYS.has(event.key)) { @@ -97,13 +213,13 @@ export function EffortSlider({ choices, value, label, currentLabel, formatToolti event.stopPropagation() return } - if (event.key === 'Escape' && gesture !== null) { + if (event.key === 'Escape' && gesture !== null && gesture.kind !== 'hover') { event.preventDefault() event.stopPropagation() - setGesture({ ...gesture, kind: 'cancelled' }) + setGesture({ kind: 'cancelled', source, index }) } else if (ADJUST_KEYS.has(event.key)) { event.stopPropagation() - if (gesture === null) setGesture({ kind: 'keyboard', source, index }) + if (gesture === null || gesture.kind === 'hover') setGesture({ kind: 'keyboard', source, index }) } }} onKeyUp={(event) => { @@ -114,7 +230,15 @@ export function EffortSlider({ choices, value, label, currentLabel, formatToolti }} /> +
diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 0ae454ffed..c744ba13f5 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -18,6 +18,7 @@ import { import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelLabelOwner, ModelMenuPage, ModelSelectInjected } from './slots.ts' import { EffortSlider, type EffortChoice } from './EffortSlider.tsx' +import { effortDisplayName } from './effort-label.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' @@ -105,7 +106,10 @@ export function ModelSelect( ? state.retainedEffort : effectiveEffort === undefined ? t('effort.providerDefault') - : reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort + : effortDisplayName({ + id: effectiveEffort, + name: reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort, + }, t) const effortChoices = useMemo(() => reasoning === undefined ? [] : [ @@ -115,7 +119,7 @@ export function ModelSelect( ...reasoning.efforts.map((effort: ModelReasoningEffort) => ({ key: `effort:${effort.id}`, effort: effort.id, - label: effort.name, + label: effortDisplayName(effort, t), })), ], [reasoning, t]) const { pending } = state @@ -147,19 +151,14 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | 'effort' | ModelMenuPage | null>(null) + const paneFocus = useRef<'drill' | 'model' | ModelMenuPage | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) - if (intent === 'effort' && busy) return paneFocus.current = null if (!open || intent === null) return - if (intent === 'effort') { - menuRef.current?.querySelector('input[type="range"]:not([disabled])')?.focus() - return - } if (intent === 'drill') { if (typeof pane === 'object') { const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') @@ -329,10 +328,12 @@ export function ModelSelect( const settleSelection = (result: Awaited>, origin: 'model' | 'effort'): void => { if (result === undefined) return if (menuRef.current !== null) { - paneFocus.current = origin - if (result.ok) { - setModelReturnFocus(origin === 'model') - setPane('root') + if (origin === 'model') { + paneFocus.current = 'model' + if (result.ok) { + setModelReturnFocus(true) + setPane('root') + } } setSelectionFocus(false) } @@ -492,14 +493,17 @@ export function ModelSelect( : effectiveEffort} label={t('menu.effort')} currentLabel={effortLabel ?? t('effort.providerDefault')} - formatTooltip={effort => t('effort.tooltip', { effort })} + formatLabel={effort => t('effort.tooltip', { effort })} + defaultInfoLabel={t('effort.defaultInfoLabel')} + defaultExplanation={t('effort.defaultExplanation')} disabled={locked} pending={busy} onSelect={chooseEffort} /> )} {renderSlot('conversation.input.model.options', { - locked: locked || busy, + locked, + pending: busy, openPage: (page) => { drill(page) }, dismiss: () => { close() @@ -616,7 +620,8 @@ export function ModelSelect( {typeof pane === 'object' && (
{renderSlot('conversation.input.model.page', { - locked: locked || busy, + locked, + pending: busy, dismiss: () => { close() triggerRef.current?.focus() diff --git a/packages/client/ui-model-selection/src/client/effort-label.ts b/packages/client/ui-model-selection/src/client/effort-label.ts new file mode 100644 index 0000000000..8745ce10eb --- /dev/null +++ b/packages/client/ui-model-selection/src/client/effort-label.ts @@ -0,0 +1,24 @@ +/** Localized display names for standard reasoning levels, without changing provider IDs or custom names. */ +import type { ModelReasoningEffort } from '@deepseek-ai/dsh-api-remotes/client' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' + +/** + * Translate standard IDs only when the provider's name repeats that ID, ignoring case. + * @param effort - Provider-owned level ID and display name. + * @param t - The model namespace translator. + * @returns The localized standard name, or the provider's unchanged custom or unknown name. + */ +export function effortDisplayName(effort: Pick, t: PropsLocale<'model'>['t']): string { + if (effort.name.toLowerCase() !== effort.id) return effort.name + switch (effort.id) { + case 'off': return t('effort.off') + case 'minimal': return t('effort.minimal') + case 'low': return t('effort.low') + case 'medium': return t('effort.medium') + case 'high': return t('effort.high') + case 'xhigh': return t('effort.xhigh') + case 'max': return t('effort.max') + // Providers may advertise other IDs; their names remain provider-owned. + default: return effort.name + } +} diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index b7b81ff772..5b2e0cd61f 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -11,6 +11,15 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'effort.tooltip': '推理等级:{effort}', + 'effort.off': '关闭', + 'effort.minimal': '最低', + 'effort.low': '低', + 'effort.medium': '中', + 'effort.high': '高', + 'effort.xhigh': '更高', + 'effort.max': '最高', + 'effort.defaultInfoLabel': '默认推理等级说明', + 'effort.defaultExplanation': '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理', 'menu.back': '返回', 'provider.account': 'DeepSeek 账号', 'command.label': '模型', @@ -24,7 +33,7 @@ export const zh = { 'menu.aria': '模型与推理等级', 'menu.model': '模型', 'menu.effort': '推理等级', - 'effort.providerDefault': 'Default', + 'effort.providerDefault': '默认', 'status.loading': '正在刷新模型列表…', 'error.action': '模型操作失败:{message}', 'error.sessionInUse': '当前会话已被占用,可能是其他正在运行的 DSH 导致的(如其他 dsh web、桌面端),请退出其他正在运行的 DSH 后重试。', @@ -42,7 +51,16 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'effort.tooltip': 'Reasoning effort: {effort}', + 'effort.tooltip': 'Effort: {effort}', + 'effort.off': 'Off', + 'effort.minimal': 'Minimal', + 'effort.low': 'Low', + 'effort.medium': 'Medium', + 'effort.high': 'High', + 'effort.xhigh': 'Extra high', + 'effort.max': 'Max', + 'effort.defaultInfoLabel': 'About default reasoning effort', + 'effort.defaultExplanation': 'No reasoning effort is explicitly selected. The model and configuration defaults apply; this does not mean reasoning is off.', 'menu.back': 'Back', 'provider.account': 'DeepSeek Account', 'command.label': 'Model', @@ -71,7 +89,16 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { - 'effort.tooltip': '推論強度:{effort}', + 'effort.tooltip': '強度:{effort}', + 'effort.off': 'オフ', + 'effort.minimal': '最小', + 'effort.low': '低', + 'effort.medium': '中', + 'effort.high': '高', + 'effort.xhigh': 'より高い', + 'effort.max': '最大', + 'effort.defaultInfoLabel': 'デフォルトの推論強度について', + 'effort.defaultExplanation': '推論強度は明示的に指定されていません。モデルと設定のデフォルト値を使用します。推論をオフにするという意味ではありません。', 'menu.back': '戻る', 'provider.account': 'DeepSeek アカウント', 'command.label': 'モデル', @@ -100,7 +127,16 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'effort.tooltip': 'Esfuerzo de razonamiento: {effort}', + 'effort.tooltip': 'Esfuerzo: {effort}', + 'effort.off': 'Desactivado', + 'effort.minimal': 'Mínimo', + 'effort.low': 'Bajo', + 'effort.medium': 'Medio', + 'effort.high': 'Alto', + 'effort.xhigh': 'Muy alto', + 'effort.max': 'Máximo', + 'effort.defaultInfoLabel': 'Acerca del esfuerzo de razonamiento predeterminado', + 'effort.defaultExplanation': 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', 'menu.back': 'Volver', 'provider.account': 'Cuenta DeepSeek', 'command.label': 'modelo', @@ -129,7 +165,16 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'effort.tooltip': 'Effort de raisonnement : {effort}', + 'effort.tooltip': 'Effort : {effort}', + 'effort.off': 'Désactivé', + 'effort.minimal': 'Minimal', + 'effort.low': 'Faible', + 'effort.medium': 'Moyen', + 'effort.high': 'Élevé', + 'effort.xhigh': 'Très élevé', + 'effort.max': 'Maximal', + 'effort.defaultInfoLabel': 'À propos de l’effort de raisonnement par défaut', + 'effort.defaultExplanation': 'Aucun effort de raisonnement n’est explicitement sélectionné. Les valeurs par défaut du modèle et de la configuration s’appliquent ; cela ne signifie pas que le raisonnement est désactivé.', 'menu.back': 'Retour', 'provider.account': 'Compte DeepSeek', 'command.label': 'Modèle', @@ -158,7 +203,16 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'effort.tooltip': 'Denkaufwand: {effort}', + 'effort.tooltip': 'Aufwand: {effort}', + 'effort.off': 'Aus', + 'effort.minimal': 'Minimal', + 'effort.low': 'Niedrig', + 'effort.medium': 'Mittel', + 'effort.high': 'Hoch', + 'effort.xhigh': 'Sehr hoch', + 'effort.max': 'Maximal', + 'effort.defaultInfoLabel': 'Über den standardmäßigen Denkaufwand', + 'effort.defaultExplanation': 'Es ist kein Denkaufwand ausdrücklich ausgewählt. Es gelten die Standardwerte des Modells und der Konfiguration; das bedeutet nicht, dass das Denken deaktiviert ist.', 'menu.back': 'Zurück', 'provider.account': 'DeepSeek-Konto', 'command.label': 'Modell', @@ -187,7 +241,16 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'effort.tooltip': 'Уровень рассуждений: {effort}', + 'effort.tooltip': 'Усилие: {effort}', + 'effort.off': 'Выключено', + 'effort.minimal': 'Минимальный', + 'effort.low': 'Низкий', + 'effort.medium': 'Средний', + 'effort.high': 'Высокий', + 'effort.xhigh': 'Очень высокий', + 'effort.max': 'Максимальный', + 'effort.defaultInfoLabel': 'Об уровне рассуждений по умолчанию', + 'effort.defaultExplanation': 'Уровень рассуждений явно не выбран. Применяются значения по умолчанию модели и конфигурации; это не означает, что рассуждения отключены.', 'menu.back': 'Назад', 'provider.account': 'DeepSeek Аккаунт', 'command.label': 'Модель', @@ -216,7 +279,16 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'effort.tooltip': 'Esforço de raciocínio: {effort}', + 'effort.tooltip': 'Esforço: {effort}', + 'effort.off': 'Desativado', + 'effort.minimal': 'Mínimo', + 'effort.low': 'Baixo', + 'effort.medium': 'Médio', + 'effort.high': 'Alto', + 'effort.xhigh': 'Muito alto', + 'effort.max': 'Máximo', + 'effort.defaultInfoLabel': 'Sobre o esforço de raciocínio padrão', + 'effort.defaultExplanation': 'Nenhum esforço de raciocínio foi selecionado explicitamente. Aplicam-se os valores padrão do modelo e da configuração; isso não significa que o raciocínio esteja desativado.', 'menu.back': 'Voltar', 'provider.account': 'DeepSeek Conta', 'command.label': 'Modelo', diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 7e62e9710c..cbddc39f66 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -27,8 +27,10 @@ export interface ModelMenuPage { /** Selection state and feedback shared by menu option entries and detail pages. */ export interface ModelMenuControls { - /** Whether the composer currently refuses selection changes. */ + /** Whether the composer is unavailable for interaction. */ locked: boolean + /** A model or effort selection is saving; block new actions without dimming or removing focus. */ + pending: boolean /** Close the menu and focus its trigger synchronously before opening another overlay. */ dismiss: () => void /** Report a failed selection through the menu owner's persistent toast. */ diff --git a/packages/client/ui-model-selection/tests/effort-label.client.spec.ts b/packages/client/ui-model-selection/tests/effort-label.client.spec.ts new file mode 100644 index 0000000000..682937f730 --- /dev/null +++ b/packages/client/ui-model-selection/tests/effort-label.client.spec.ts @@ -0,0 +1,30 @@ +import { expect, it } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { effortDisplayName } from '../src/client/effort-label.ts' +import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' + +const standard = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes canonical effort names in %s without changing IDs', (_locale, dictionary) => { + const t = makeTranslate(dictionary) + for (const id of standard) { + for (const name of [id, id.toUpperCase(), id[0]!.toUpperCase() + id.slice(1)]) { + const effort = { id, name } + expect(effortDisplayName(effort, t)).toBe(dictionary[`effort.${id}`]) + expect(effort.id).toBe(id) + expect(effort.name).toBe(name) + } + } +}) + +it.each([ + { id: 'high', name: 'High budget for code review' }, + { id: 'high', name: ' high' }, + { id: 'high', name: 'High ' }, + { id: 'xhigh', name: 'Extra high' }, + { id: 'standard', name: 'Standard' }, + { id: 'retired', name: 'High' }, + { id: 'High', name: 'High' }, +])('preserves provider spelling for $id / $name', (effort) => { + expect(effortDisplayName(effort, makeTranslate(zh))).toBe(effort.name) +}) diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx index 5ff0e2bb20..021b8b1189 100644 --- a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx @@ -14,17 +14,21 @@ const choices = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effo function props(overrides: Partial = {}): EffortSliderProps { return { choices, value: 'high', label: 'Effort', currentLabel: 'high', disabled: false, pending: false, - formatTooltip: effort => `Reasoning effort: ${effort}`, onSelect: vi.fn(), ...overrides, + formatLabel: effort => `Effort: ${effort}`, + defaultInfoLabel: en['effort.defaultInfoLabel'], defaultExplanation: en['effort.defaultExplanation'], + onSelect: vi.fn(), ...overrides, } } function range(): HTMLInputElement { return screen.getByRole('slider') as HTMLInputElement } +function effortLabel(): HTMLElement { + return range().closest('[role="group"]')!.querySelector('[data-effort-label]')! +} -it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag tooltip (%s)', (_locale, dictionary) => { - vi.useFakeTimers() +function tooltipLayout() { vi.stubGlobal('matchMedia', (query: string) => ({ - matches: query === '(hover: hover)' || query === '(any-hover: hover)', media: query, onchange: null, + matches: query.includes('hover: hover'), media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, })) vi.stubGlobal('ResizeObserver', class { @@ -32,21 +36,90 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes the tag t unobserve() {} disconnect() {} }) +} + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('shows the full localized label and default explanation (%s)', (_locale, dictionary) => { + tooltipLayout() const t = makeTranslate(dictionary) + const high = dictionary['effort.high'] + const defaultLabel = dictionary['effort.providerDefault'] const inputProps = props({ - choices: [{ key: 'default', effort: undefined, label: 'Default' }, { key: 'high', effort: 'high', label: 'High' }], - formatTooltip: effort => t('effort.tooltip', { effort }), + choices: [{ key: 'default', effort: undefined, label: defaultLabel }, { key: 'high', effort: 'high', label: high }], + formatLabel: effort => t('effort.tooltip', { effort }), + defaultInfoLabel: dictionary['effort.defaultInfoLabel'], defaultExplanation: dictionary['effort.defaultExplanation'], }) const view = render() - const tag = screen.getByText('High') - expect(tag.tabIndex).toBe(-1) - fireEvent.pointerEnter(tag, { pointerType: 'mouse' }) - act(() => { vi.advanceTimersByTime(500) }) - const tooltip = screen.getByRole('tooltip', { hidden: true }) - expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'High')) + expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', high)) + expect(effortLabel().tabIndex).toBe(-1) + expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(high) + expect(screen.queryByRole('button')).toBeNull() view.rerender() - expect(tooltip.textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', 'Default')) + expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', defaultLabel)) + expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(defaultLabel) + const info = screen.getByRole('button', { name: dictionary['effort.defaultInfoLabel'] }) + info.focus() + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(dictionary['effort.defaultExplanation']) + expect(document.activeElement).toBe(info) expect(inputProps.onSelect).not.toHaveBeenCalled() + fireEvent.keyDown(info, { key: 'Escape' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(document.activeElement).toBe(info) +}) + +it.each([ + ['推理等级:高', zh], ['Effort: High', en], ['強度:高', ja], ['Esfuerzo: Alto', es], + ['Effort : Élevé', fr], ['Aufwand: Hoch', de], ['Усилие: Высокий', ru], ['Esforço: Alto', pt], +] as const)('uses a compact localized caption: %s', (expected, dictionary) => { + const t = makeTranslate(dictionary) + render( t('effort.tooltip', { effort }), + })} />) + expect(effortLabel().textContent).toBe(expected) +}) + +it('protects the final effort name while preserving repeated text in the formatted prefix', () => { + render( `${effort} policy: ${effort}` })} />) + const label = effortLabel() + const name = label.querySelector('[data-effort-name]')! + expect(label.textContent).toBe('high policy: high') + expect(name.textContent).toBe('high') + expect(name.previousElementSibling!.textContent).toBe('high policy: ') + expect(range().getAttribute('aria-valuetext')).toBe('high') +}) + +it('only repeats the full label in a tooltip when the label is clipped', () => { + tooltipLayout() + vi.useFakeTimers() + render() + const label = effortLabel() + fireEvent.pointerEnter(label, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + fireEvent.pointerLeave(label, { pointerType: 'mouse' }) + Object.defineProperty(label, 'scrollWidth', { configurable: true, value: 200 }) + Object.defineProperty(label, 'clientWidth', { configurable: true, value: 80 }) + fireEvent.pointerEnter(label, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('Effort: high') +}) + +it('closes default information on a second activation or Tab without selecting an effort', () => { + tooltipLayout() + const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices], value: undefined }) + render() + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + info.focus() + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true })).toBeTruthy() + fireEvent.click(info) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + fireEvent.click(info) + fireEvent.keyDown(info, { key: 'Tab' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(inputProps.onSelect).not.toHaveBeenCalled() + expect(range().value).toBe('0') }) it('shows exact advertised stops and the selected value', () => { @@ -56,7 +129,8 @@ it('shows exact advertised stops and the selected value', () => { expect(range().getAttribute('aria-valuetext')).toBe('high') expect(range().min).toBe('0') expect(range().step).toBe('1') - expect(screen.getByText('high').tabIndex).toBe(-1) + expect(effortLabel().textContent).toBe('Effort: high') + expect(effortLabel().tabIndex).toBe(-1) expect(screen.queryByRole('button')).toBeNull() }) @@ -183,7 +257,7 @@ it('does not pretend an unknown stored effort matches the first supported stop', render() expect(range().disabled).toBe(true) expect(range().getAttribute('aria-valuetext')).toBe('retired') - expect(screen.getByText('retired')).toBeTruthy() + expect(effortLabel().textContent).toBe('Effort: retired') expect(screen.queryByRole('button')).toBeNull() }) @@ -193,6 +267,160 @@ it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragg expect(range().max).toBe('0') }) +function motionSetup() { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query === '(hover: hover) and (pointer: fine)', media: query, onchange: null, + addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, + })) + const inputProps = props({ value: 'off', currentLabel: 'off' }) + const view = render() + const input = range() + const thumb = view.container.querySelector('[data-effort-thumb]')! + const scale = view.container.querySelector('[data-effort-thumb-scale]')! + vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 220, 40)) + vi.spyOn(thumb, 'getBoundingClientRect').mockImplementation(() => new DOMRect(Number(input.value) / 3 * 200, 10, 20, 20)) + const pointer = (type: string, x: number, pointerType = 'mouse') => fireEvent(input, + Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: 20, button: 0 }), + { pointerType, pointerId: 1, isPrimary: true })) + return { ...view, input, inputProps, thumb, scale, pointer } +} + +it('keeps the visual track and thumb inert while the native range owns interaction', () => { + const view = motionSetup() + expect(screen.getAllByRole('slider')).toHaveLength(1) + expect(view.thumb.closest('[aria-hidden="true"]')).toBeTruthy() + expect(view.container.querySelector('[data-effort-fill]')!.closest('[aria-hidden="true"]')).toBeTruthy() + expect(view.thumb.tabIndex).toBe(-1) + expect(view.scale.tabIndex).toBe(-1) + expect(screen.queryByRole('button')).toBeNull() +}) + +it('hovers one tick in its 16px target without selecting and does not retain touch hover', () => { + const view = motionSetup() + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3 + 7) + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.container.querySelectorAll('[data-effort-tick][data-hovered]')).toHaveLength(1) + expect(view.container.querySelector('[data-effort-tick="1"]')!.hasAttribute('data-hovered')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3 + 9) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + view.pointer('pointermove', 10) + view.pointer('pointermove', 10, 'touch') + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + expect(view.input.value).toBe('0') + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it.each(['pointercancel', 'blur', 'Escape'])('cancels motion decoration and the native preview on %s', (cancel) => { + const view = motionSetup() + view.pointer('pointerdown', 16) + view.pointer('pointermove', 60) + fireEvent.change(view.input, { target: { value: '1' } }) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) + expect(view.container.querySelector('[data-hovered]')).toBeNull() + if (cancel === 'Escape') fireEvent.keyDown(view.input, { key: 'Escape' }) + else if (cancel === 'blur') fireEvent.blur(view.input) + else view.pointer(cancel, 60) + view.pointer('pointerup', 60) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) + expect(view.input.value).toBe('0') + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('keeps a native pointer gesture when focus moves to an ancestor before the first move', () => { + const view = motionSetup() + act(() => { + view.pointer('pointerdown', 16) + fireEvent.blur(view.input, { relatedTarget: view.input.parentElement }) + }) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 76) + fireEvent.change(view.input, { target: { value: '1' } }) + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() + view.pointer('pointerup', 76) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('restores range focus before submitting a valid native pointer release', () => { + const view = motionSetup() + view.input.focus() + view.pointer('pointerdown', 16) + const ancestor = view.input.parentElement! + ancestor.tabIndex = -1 + act(() => { ancestor.focus() }) + fireEvent.change(view.input, { target: { value: '1' } }) + vi.mocked(view.inputProps.onSelect).mockImplementation(() => { expect(document.activeElement).toBe(view.input) }) + view.pointer('pointerup', 76) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) + +it('does not steal outside focus when a cancelled pointer later releases', () => { + const view = motionSetup() + view.input.focus() + view.pointer('pointerdown', 16) + fireEvent.change(view.input, { target: { value: '1' } }) + const outside = document.createElement('button') + view.container.append(outside) + act(() => { outside.focus() }) + view.pointer('pointerup', 76) + expect(document.activeElement).toBe(outside) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it.each(['null', 'outside', 'keyboard-ancestor'])('still cancels a preview on %s focus loss', (kind) => { + const view = motionSetup() + if (kind === 'keyboard-ancestor') fireEvent.keyDown(view.input, { key: 'End' }) + else view.pointer('pointerdown', 16) + fireEvent.change(view.input, { target: { value: '1' } }) + const outside = document.createElement('button') + view.container.append(outside) + fireEvent.blur(view.input, { + relatedTarget: kind === 'keyboard-ancestor' ? view.input.parentElement : kind === 'outside' ? outside : null, + }) + if (kind === 'keyboard-ancestor') fireEvent.keyUp(view.input, { key: 'End' }) + else view.pointer('pointerup', 76) + expect(view.input.value).toBe('0') + expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + +it('retains thumb hover through a pending save without accepting more values', () => { + const view = motionSetup() + view.pointer('pointerdown', 10) + fireEvent.change(view.input, { target: { value: '1' } }) + view.pointer('pointerup', 10 + 200 / 3) + expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.pointer('pointermove', 10 + 200 / 3) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + fireEvent.change(view.input, { target: { value: '3' } }) + expect(view.input.value).toBe('1') + expect(view.inputProps.onSelect).toHaveBeenCalledTimes(1) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(true) +}) + +it('clears hover and motion when locked or when the advertised catalog changes', () => { + const view = motionSetup() + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(true) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.input.disabled).toBe(true) + view.pointer('pointermove', 10) + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + view.rerender() + view.pointer('pointermove', 10) + view.rerender() + expect(view.scale.hasAttribute('data-expanded')).toBe(false) + expect(view.inputProps.onSelect).not.toHaveBeenCalled() +}) + it('keeps the pending target focusable while blocking pointer, keyboard and direct changes', () => { const inputProps = props({ value: 'max', pending: true }) render() diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx index 7c3ae849d4..0dd538e1ca 100644 --- a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx @@ -17,16 +17,17 @@ beforeEach(() => { else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) }) }) -afterEach(cleanup) +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) -function setup(count = 2, hasReasoning = true) { +function setup(count = 2, hasReasoning = true, providerDefault = false) { const select = vi.fn(async () => ({ ok: true as const, value: undefined })) const toggle = vi.fn() const directory = createSnapshotStore({ current: { provider: 'sample', model: 'model-1' }, routable: true, groups: [{ id: 'sample', name: 'Sample', models: Array.from({ length: count }, (_, index) => ({ id: `model-${index + 1}`, name: `Model ${index + 1}`, - ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], defaultEffort: 'high' } } : {}, + ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], + ...providerDefault ? {} : { defaultEffort: 'high' } } } : {}, })) }], failures: [], status: 'ready', pending: null, error: null, }) const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { @@ -34,10 +35,16 @@ function setup(count = 2, hasReasoning = true) { const controls = owner as OwnerOf<'conversation.input.model.options'> return <> - + } - if (name === 'conversation.input.model.page') return + if (name === 'conversation.input.model.page') { + const controls = owner as OwnerOf<'conversation.input.model.page'> + return + } return options?.fallback ?? null } render(<> { + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) + const view = setup(2, true, true) + tab() + expect(document.activeElement).toBe(view.model()) + tab() + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + expect(document.activeElement).toBe(info) + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(en['effort.defaultExplanation']) + fireEvent.keyDown(info, { key: 'Escape' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.getByRole('menu')).toBeTruthy() + expect(document.activeElement).toBe(info) + fireEvent.click(info) + tab() + const slider = screen.getByRole('slider') + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(document.activeElement).toBe(slider) + tab() + expect(document.activeElement).toBe(view.team()) + tab(true) + expect(document.activeElement).toBe(slider) + tab(true) + expect(document.activeElement).toBe(info) + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + +it('removes only the default information Tab stop when the selection changes', () => { + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) + const view = setup(2, true, true) + const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) + info.focus() + act(() => { view.directory.update((snapshot) => { + snapshot.current = { provider: 'sample', model: 'model-1', reasoningEffort: 'high' } + }) }) + const slider = screen.getByRole('slider') + expect(screen.queryByRole('button', { name: en['effort.defaultInfoLabel'] })).toBeNull() + expect(document.activeElement).toBe(slider) + tab(true) + expect(document.activeElement).toBe(view.model()) + act(() => { view.directory.update((snapshot) => { + snapshot.current = { provider: 'sample', model: 'model-1' } + }) }) + tab() + expect(document.activeElement).toBe(screen.getByRole('button', { name: en['effort.defaultInfoLabel'] })) + expect(view.select).not.toHaveBeenCalled() +}) + +it('keeps a pending contributed entry in Tab order without allowing navigation', () => { + const view = setup() + tab(); tab(); tab() + const team = view.team() + expect(document.activeElement).toBe(team) + act(() => { view.directory.update((snapshot) => { + snapshot.status = 'selecting' + snapshot.pending = { provider: 'sample', model: 'model-1', reasoningEffort: 'low' } + }) }) + expect(view.team()).toBe(team) + expect(team.hasAttribute('disabled')).toBe(false) + expect(team.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(team) + fireEvent.click(team) + expect(screen.queryByRole('switch')).toBeNull() + tab(true) + expect(document.activeElement).toBe(screen.getByRole('slider')) + tab() + expect(document.activeElement).toBe(team) + expect(view.select).not.toHaveBeenCalled() + expect(view.toggle).not.toHaveBeenCalled() +}) + it('Shift+Tab from the first root control returns to its trigger instead of activating it', () => { const view = setup() tab() diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index af1861f0a8..fe2cbdcfa9 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -223,14 +223,16 @@ describe('ModelSelect reasoning effort', () => { />) const trigger = screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', }) fireEvent.click(trigger) const efforts = within(screen.getByRole('group', { name: '推理等级' })) expect(efforts.queryByRole('button')).toBeNull() expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') - expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('High') - expect(efforts.getByText('High').tabIndex).toBe(-1) + expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('高') + const label = screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')! + expect(label.textContent).toBe('推理等级:高') + expect(label.tabIndex).toBe(-1) expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() expect(screen.queryByText('Largest budget')).toBeNull() @@ -243,7 +245,7 @@ describe('ModelSelect reasoning effort', () => { model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 Max') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 最高') expect(document.activeElement).toBe(slider) expect(screen.getByRole('menu')).toBeTruthy() }) @@ -272,12 +274,13 @@ describe('ModelSelect reasoning effort', () => { />) fireEvent.click(screen.getByRole('button', { - name: '选择模型,当前 Model,推理等级 Default', + name: '选择模型,当前 Model,推理等级 默认', })) const efforts = within(screen.getByRole('group', { name: '推理等级' })) - expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('button', { name: '默认推理等级说明' })).toBeTruthy() + expect(screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')!.textContent).toBe('推理等级:默认') expect(efforts.getByRole('slider').getAttribute('max')).toBe('1') - expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('Default') + expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('默认') }) it('submits the Default stop by omitting effort instead of sending a display label', async () => { @@ -308,8 +311,8 @@ describe('ModelSelect reasoning effort', () => { fireEvent.pointerDown(slider, { pointerId: 1 }) fireEvent.change(slider, { target: { value: '0' } }) fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('Max') - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 High') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 高') expect(select).not.toHaveBeenCalled() fireEvent.pointerUp(slider, { pointerId: 1 }) expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) @@ -329,7 +332,7 @@ describe('ModelSelect reasoning effort', () => { expect((await screen.findByRole('alert')).textContent).toContain('effort unavailable') expect(screen.getByRole('menu')).toBeTruthy() const slider = screen.getByRole('slider', { name: '推理等级' }) - expect(slider.getAttribute('aria-valuetext')).toBe('High') + expect(slider.getAttribute('aria-valuetext')).toBe('高') expect(slider.hasAttribute('disabled')).toBe(false) expect(document.activeElement).toBe(slider) await act(async () => { fireEvent.change(slider, { target: { value: '0' } }) }) @@ -403,7 +406,7 @@ describe('ModelSelect reasoning effort', () => { directory.set(state()) await waitFor(() => { expect(screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', })).toBeTruthy() }) }) @@ -519,7 +522,7 @@ describe('ModelSelect reasoning effort', () => { expect(slider.hasAttribute('disabled')).toBe(false) expect(slider.getAttribute('aria-disabled')).toBe('true') expect(slider.getAttribute('aria-busy')).toBe('true') - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(document.activeElement).toBe(slider) fireEvent.change(slider, { target: { value: '0' } }) expect(select).toHaveBeenCalledExactlyOnceWith({ @@ -532,10 +535,38 @@ describe('ModelSelect reasoning effort', () => { expect(screen.getByRole('menu')).toBeTruthy() expect(trigger.getAttribute('aria-busy')).toBe('false') expect(slider.getAttribute('aria-disabled')).toBe('false') - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(document.activeElement).toBe(slider) }) + it('keeps the browsed model page and search focus when an effort save finishes', async () => { + const groups = modelGroups(5) + const directory = createSnapshotStore(state({ groups })) + const pending = Promise.withResolvers<{ ok: true; value: undefined }>() + onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) + const select = vi.fn((selection: ModelSelection) => { + directory.set(state({ groups, status: 'selecting', pending: selection })) + return pending.promise + }) + render() + fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) + const slider = screen.getByRole('slider') + slider.focus() + fireEvent.change(slider, { target: { value: '2' } }) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const search = screen.getByRole('searchbox') + expect(document.activeElement).toBe(search) + await act(async () => { + directory.set(state({ groups, current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) + pending.resolve({ ok: true, value: undefined }) + }) + expect(screen.getByRole('searchbox')).toBe(search) + expect(document.activeElement).toBe(search) + expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() + expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) + }) + it('keeps transient focus loss inside the menu but closes on a known outside focus target', () => { render(<>) @@ -695,7 +726,7 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(focused) if (kind === 'inline effort') { expect(fireEvent.mouseDown(screen.getByRole('slider'))).toBe(true) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('High') + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('高') } else { fireEvent.keyDown(focused!, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) @@ -727,7 +758,7 @@ describe('ModelSelect keyboard walk', () => { fireEvent.keyDown(slider, { key: 'End' }) // jsdom does not perform the native range value change for a keyboard event. fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('Max') + expect(slider.getAttribute('aria-valuetext')).toBe('最高') expect(select).not.toHaveBeenCalled() fireEvent.keyUp(slider, { key: 'End' }) expect(select).toHaveBeenCalledExactlyOnceWith({ @@ -782,13 +813,13 @@ describe('ModelSelect keyboard walk', () => { directory={createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } }))} load={vi.fn()} resolveText={resolveText} select={select} t={t} />) fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.queryByRole('slider')).toBeNull() fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('Max') - expect(screen.queryByRole('button', { name: 'Max' })).toBeNull() + expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') + expect(screen.queryByRole('button', { name: '推理等级:最高' })).toBeNull() expect(select).not.toHaveBeenCalled() }) @@ -1226,11 +1257,11 @@ it('restores the account model name after login without changing the saved route const directory = createSnapshotStore(state({ current: selected, groups, retainedEffort: 'High' })) render() - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') act(() => { directory.update((snapshot) => { snapshot.groups = []; snapshot.routable = false }) }) expect(screen.getByRole('button', { name: '请选择模型' }).textContent).toBe('请选择模型') act(() => { directory.update((snapshot) => { snapshot.groups = groups; snapshot.routable = true }) }) - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') expect(directory.getSnapshot().current).toEqual(selected) }) @@ -1239,11 +1270,14 @@ describe('ModelSelect contributed pages', () => { function mountPage(locked = false, withSwitch = true) { const toggle = vi.fn() const select = vi.fn() + const owners = vi.fn((_name: string, _owner: object) => {}) const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { + owners(name, owner) if (name === 'conversation.input.model.options') { const controls = owner as OwnerOf<'conversation.input.model.options'> return } @@ -1253,7 +1287,8 @@ describe('ModelSelect contributed pages', () => { return <>

用于解释该设置的完整说明

{withSwitch && } + disabled={controls.locked} aria-disabled={controls.locked || controls.pending} aria-busy={controls.pending} + onClick={() => { if (!controls.pending) toggle() }}>启用示例设置} @@ -1265,7 +1300,7 @@ describe('ModelSelect contributed pages', () => { load={vi.fn()} resolveText={resolveText} select={select} t={t} renderSlot={renderSlot} />) const trigger = screen.getByRole('button', { name: /^选择模型/ }) if (!locked) fireEvent.click(trigger) - return { directory, view, trigger, renderSlot, toggle, select } + return { directory, view, trigger, renderSlot, owners, toggle, select } } it('opens only the keyed detail controls and returns to the invoking entry with Escape', () => { @@ -1320,12 +1355,30 @@ describe('ModelSelect contributed pages', () => { expect(screen.getByRole('menu')).toBeTruthy() }) - it('passes pending selection locking into the keyed page while keeping Escape navigation available', () => { - const { directory, toggle } = mountPage() - fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) - act(() => { directory.set(state({ status: 'selecting', pending: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) }) + it('passes model pending separately from a genuine lock into both contributed slots', () => { + const { directory, toggle, owners } = mountPage() + const entry = screen.getByRole('menuitem', { name: '设置 关' }) + entry.focus() + owners.mockClear() + const selecting = state({ status: 'selecting', pending: { + provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', + } }) + act(() => { directory.set(selecting) }) + expect(owners).toHaveBeenCalledWith('conversation.input.model.options', expect.objectContaining({ locked: false, pending: true })) + expect(entry.hasAttribute('disabled')).toBe(false) + expect(entry.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(entry) + fireEvent.click(entry) + expect(screen.queryByRole('switch')).toBeNull() + act(() => { directory.set(state()) }) + fireEvent.click(entry) const switchButton = screen.getByRole('switch', { name: '启用示例设置' }) - expect(switchButton.hasAttribute('disabled')).toBe(true) + owners.mockClear() + act(() => { directory.set(selecting) }) + expect(owners).toHaveBeenCalledWith('conversation.input.model.page', expect.objectContaining({ locked: false, pending: true })) + expect(switchButton.hasAttribute('disabled')).toBe(false) + expect(switchButton.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(switchButton) fireEvent.click(switchButton) expect(toggle).not.toHaveBeenCalled() fireEvent.keyDown(switchButton, { key: 'Escape' }) 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 83879bec56..18d5b71615 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1545,7 +1545,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:70', + source: 'packages/client/ui-model-selection/src/client/slots.ts:72', }, { key: 'conversation.input.model.options', @@ -1574,7 +1574,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', ], ownerPropsReferences: [], @@ -1608,7 +1608,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:41', + source: 'packages/client/ui-model-selection/src/client/slots.ts:43', }, { key: 'conversation.input.model.page', @@ -1625,7 +1625,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer currently refuses selection changes. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -1658,7 +1658,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:52', }, { key: 'conversation.input.overlay', From 5c224fff4c98d0fa28052728ab81c4d8cffdda8e Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 17:12:27 +0800 Subject: [PATCH 03/68] feat(ui): make effort tags draggable with lightweight snapping Keep model selection centered above the controls, preserve later navigation, release cancelled gestures, and cover raw effort submissions and pending-state stability. --- apps/web/tests/declared-reasoning.e2e.ts | 341 +++++++++++++++--- .../tests/deepseek-messages-settings.e2e.ts | 4 +- .../declared-reasoning/ui.expected.md | 2 +- apps/web/tests/model-menu-observer.e2e.ts | 6 +- .../model-menu-pending/guide.i18n.yaml | 16 + .../v0.2.2-rc.1/model-menu-pending/guide.md | 20 + .../model-menu-pending/guide.zh.md | 20 + .../ui-model-selection/README.i18n.yaml | 8 +- packages/client/ui-model-selection/README.md | 8 +- .../client/ui-model-selection/README.zh.md | 8 +- .../src/client/EffortSlider.module.css | 70 +++- .../src/client/EffortSlider.tsx | 134 ++++++- .../src/client/ModelSelect.tsx | 11 +- .../tests/effort-slider.client.spec.tsx | 10 +- .../tests/effort-tag-drag.client.spec.tsx | 205 +++++++++++ .../tests/model-menu-tab.client.spec.tsx | 13 +- .../tests/model-select.client.spec.tsx | 104 +++++- 17 files changed, 864 insertions(+), 116 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md create mode 100644 packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index c697d3dd84..4b804893b0 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -29,11 +29,11 @@ async function readEffortMotion(slider: Locator) { const thumb = group.querySelector('[data-effort-thumb]')! const scale = group.querySelector('[data-effort-thumb-scale]')! const fill = group.querySelector('[data-effort-fill]')! - const label = group.querySelector('[data-effort-label]')! + const tag = group.querySelector('[data-effort-tag]')! const rangeRect = input.getBoundingClientRect() const thumbRect = thumb.getBoundingClientRect() const fillRect = fill.getBoundingClientRect() - const labelRect = label.parentElement!.getBoundingClientRect() + const labelRect = tag.getBoundingClientRect() const thumbSize = Number.parseFloat(getComputedStyle(thumb).width) const ratio = (input.valueAsNumber - Number(input.min)) / (Number(input.max) - Number(input.min)) return { @@ -46,10 +46,10 @@ async function readEffortMotion(slider: Locator) { dotWidth: Number.parseFloat(getComputedStyle(scale, '::after').width), dotDuration: getComputedStyle(scale, '::after').transitionDuration, dotEasing: getComputedStyle(scale, '::after').transitionTimingFunction, - labelCenter: labelRect.left + labelRect.width / 2, - thumbDuration: getComputedStyle(thumb).transitionDuration, - thumbEasing: getComputedStyle(thumb).transitionTimingFunction, - fillDuration: getComputedStyle(fill).transitionDuration, + labelCenter: labelRect.left + labelRect.width / 2, labelWidth: labelRect.width, + thumbDuration: getComputedStyle(input.parentElement!).transitionDuration, + thumbEasing: getComputedStyle(input.parentElement!).transitionTimingFunction, + fillDuration: getComputedStyle(input.parentElement!).transitionDuration, tickDuration: getComputedStyle(group.querySelector('[data-effort-tick]')!).transitionDuration, ticks: [...group.querySelectorAll('[data-effort-tick]')].map((tick) => { const rect = tick.getBoundingClientRect() @@ -60,6 +60,12 @@ async function readEffortMotion(slider: Locator) { }) } +/** The tag tracks the handle but stops at the menu edges. */ +function expectedTagCenter(view: { left: number; right: number; labelWidth: number }, target: number): number { + const half = view.labelWidth / 2 + return Math.min(Math.max(target, view.left + half), view.right - half) +} + async function assertSettledEffort(slider: Locator) { await expect.poll(async () => { const view = await readEffortMotion(slider) @@ -69,10 +75,35 @@ async function assertSettledEffort(slider: Locator) { expect(view.nativeHeight).toBe(40) expect(view.thumbSize).toBe(20) expect(Math.abs(view.centerY - view.y)).toBeLessThan(1) - expect(Math.abs(view.labelCenter - (view.left + view.right) / 2)).toBeLessThan(1) + expect(Math.abs(view.labelCenter - expectedTagCenter(view, view.center))).toBeLessThan(1) return view } +async function restoreSelectionAfterTest(page: Page, scaffold: WebScaffold): Promise { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + const agent = scaffold.ctx.agents.list()[0]! + const savedModel = agent.model.current()! + const savedDefault = scaffold.ctx.agentDefaultModel.currentSelection() + const savedLabel = await trigger.getAttribute('aria-label') + const viewport = page.viewportSize()! + onTestFinished(async () => { + try { + await page.mouse.up() + await page.keyboard.up('ArrowRight') + await page.keyboard.up('ArrowLeft') + await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') + if (JSON.stringify(agent.model.current()) !== JSON.stringify(savedModel)) agent.model.select(savedModel) + // Queue restoration behind background default saves even if the visible default has not changed yet. + await scaffold.ctx.agentDefaultModel.saveSelection(savedDefault) + await expect.poll(() => trigger.getAttribute('aria-label')).toBe(savedLabel) + } finally { + try { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } finally { await page.setViewportSize(viewport) } + } + }) +} + describe.skipIf(MODE === 'record').each([ { name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }, @@ -133,6 +164,7 @@ describe.skipIf(MODE === 'record').each([ onTestFinished(() => { page.off('request', countSelection) }) const previous = scaffold.ctx.agentDefaultModel.currentSelection() const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const team = page.locator('[data-model-menu-page="agent-team"]') @@ -141,14 +173,17 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) } await trigger.click() + const caption = page.locator('[data-effort-caption]') await page.keyboard.press('Tab'); await focused(rootModel) expect(await page.getByRole('menuitemradio').count()).toBe(0) + await page.keyboard.press('Tab'); await focused(caption) await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) expect(await page.getByRole('switch').count()).toBe(0) await page.keyboard.press('Shift+Tab'); await focused(slider) await page.keyboard.press('Shift+Tab'); await focused(info) + await page.keyboard.press('Shift+Tab'); await focused(caption) await page.keyboard.press('Shift+Tab'); await focused(rootModel) await page.keyboard.press('Enter') const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) @@ -170,6 +205,7 @@ describe.skipIf(MODE === 'record').each([ await page.keyboard.press('Tab') await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) await page.keyboard.press('Space'); await focused(rootModel) + await page.keyboard.press('Tab'); await focused(caption) await page.keyboard.press('Tab'); await focused(info) await page.keyboard.press('Tab'); await focused(slider) await page.keyboard.press('Tab'); await focused(team) @@ -194,6 +230,7 @@ describe.skipIf(MODE === 'record').each([ it('reads default information by mouse and keyboard without selecting or closing the menu', async () => { const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) let requests = 0 const count = (request: Request): void => { if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ @@ -218,6 +255,7 @@ describe.skipIf(MODE === 'record').each([ await trigger.focus() await page.keyboard.press('Tab') await page.keyboard.press('Tab') + await page.keyboard.press('Tab') expect(await info.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Enter') await tooltip.waitFor() @@ -265,24 +303,61 @@ describe.skipIf(MODE === 'record').each([ it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) await trigger.waitFor({ timeout: 15_000 }) onTestFinished(async () => { if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() }) await trigger.click() + const model = page.getByRole('menuitem', { name: /^模型/ }) + const layout = await model.evaluate((row) => { + const label = row.children[0]! + const value = row.children[1]! + const name = value.querySelector('[data-model-id]')! + const chevron = row.querySelector(':scope > svg')! + const labelStyle = getComputedStyle(label) + const valueStyle = getComputedStyle(value) + const labelRect = label.getBoundingClientRect() + const valueRect = value.getBoundingClientRect() + const chevronRect = chevron.getBoundingClientRect() + const probe = document.createElement('span') + probe.style.position = 'absolute' + probe.style.color = 'var(--dsw-alias-label-tertiary)' + row.append(probe) + try { + return { + label: label.textContent, labelSize: labelStyle.fontSize, labelPosition: labelStyle.position, + labelClip: labelStyle.clipPath, labelWidth: labelRect.width, labelHeight: labelRect.height, + valueAlign: valueStyle.textAlign, valueColor: valueStyle.color, tertiaryColor: getComputedStyle(probe).color, + valueRightError: Math.abs(name.getBoundingClientRect().right - valueRect.right), + gapToChevron: chevronRect.left - valueRect.right, + chevronWidth: chevronRect.width, chevronHeight: chevronRect.height, + } + } finally { probe.remove() } + }) + expect(layout).toMatchObject({ label: '模型', labelSize: '13px', labelPosition: 'absolute', labelClip: 'inset(50%)', + valueAlign: 'center', chevronWidth: 10, chevronHeight: 10 }) + expect(layout.labelWidth).toBeLessThan(2) + expect(layout.labelHeight).toBeLessThan(2) + expect(layout.gapToChevron).toBe(2) const slider = page.getByRole('slider', { name: '推理等级', exact: true }) const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') - expect(await levels.count()).toBe(1) - expect(await levels.getAttribute('aria-label')).toBe('默认推理等级说明') + expect(await levels.count()).toBe(2) + expect(await levels.nth(1).getAttribute('aria-label')).toBe('默认推理等级说明') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') expect(await slider.getAttribute('aria-valuetext')).toBe('默认') - const tag = page.getByRole('group', { name: '推理等级', exact: true }).getByText('推理等级:默认', { exact: true }) + const tag = page.locator('[data-effort-tag]') expect(await tag.evaluate(element => ({ cursor: getComputedStyle(element).cursor, userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), + }))).toEqual({ cursor: 'default', userSelect: 'none' }) + const caption = page.locator('[data-effort-caption]') + expect(await caption.evaluate(element => ({ + cursor: getComputedStyle(element).cursor, tabIndex: element.tabIndex, - }))).toEqual({ cursor: 'default', userSelect: 'none', tabIndex: -1 }) + label: element.getAttribute('aria-label'), + }))).toEqual({ cursor: 'grab', tabIndex: 0, label: '推理等级:默认' }) expect(await page.getByRole('menuitem', { name: /推理等级/ }).count()).toBe(0) const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) @@ -307,7 +382,10 @@ describe.skipIf(MODE === 'record').each([ expect(await slider.getAttribute('aria-valuetext')).toBe('高') await slider.focus() await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) + await expect.poll(() => page.locator('[data-effort-caption]') + .evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') + await expect.poll(() => page.locator('[data-model-menu-root] > button[role="menuitem"]') .evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') await expect.poll(() => page.getByRole('menu').count()).toBe(0) @@ -317,6 +395,7 @@ describe.skipIf(MODE === 'record').each([ it('opens from the pointer with keyboard focus and closes from the trigger in every pane', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-model-trigger-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) const menu = page.getByRole('menu') for (const pane of ['root', 'model', 'slider']) { await page.locator('[data-composer-input][contenteditable="true"]').focus() @@ -350,6 +429,7 @@ describe.skipIf(MODE === 'record').each([ page.on('request', countSelection) onTestFinished(() => { page.off('request', countSelection) }) const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) const menu = page.getByRole('menu') onTestFinished(async () => { if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() @@ -398,6 +478,9 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') await page.mouse.move(0, 0) await page.keyboard.press('Tab') + const caption = page.locator('[data-effort-caption]') + expect(await caption.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) expect(await info.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Tab') @@ -406,6 +489,8 @@ describe.skipIf(MODE === 'record').each([ await page.keyboard.press('Shift+Tab') expect(await info.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Shift+Tab') + expect(await caption.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Shift+Tab') expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') expect(selections).toBe(1) @@ -417,7 +502,7 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') - await page.route('**/api/session/selectModel', async (route) => { + const rejectSelection = async (route: Route): Promise => { const envelope = route.request().postDataJSON() as { rpcId: string } await route.fulfill({ json: { @@ -428,12 +513,17 @@ describe.skipIf(MODE === 'record').each([ }, }, }) - }, { times: 1 }) - await page.getByRole('menuitem', { name: /^模型/ }).click() - await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) - await current.click() - await page.getByRole('alert').waitFor() + } + await page.route('**/api/session/selectModel', rejectSelection, { times: 1 }) + try { + await page.getByRole('menuitem', { name: /^模型/ }).click() + await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) + expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) + await current.click() + await page.getByRole('alert').waitFor() + } finally { + await page.unroute('**/api/session/selectModel', rejectSelection) + } expect(selections).toBe(3) await compareOrRefreshGolden(POINTER_EXPECTED, await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), MODE) @@ -468,6 +558,7 @@ describe.skipIf(MODE === 'record').each([ it('shows six stops including Default and commits only after releasing a drag outside the range', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-six-effort-drag-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) const viewport = page.viewportSize()! await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() @@ -484,8 +575,8 @@ describe.skipIf(MODE === 'record').each([ const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) const group = menu.getByRole('group', { name: '推理等级', exact: true }) const slider = group.getByRole('slider', { name: '推理等级', exact: true }) - expect(await group.getByRole('button').count()).toBe(1) - expect(await group.getByRole('button').getAttribute('aria-label')).toBe('默认推理等级说明') + expect(await group.getByRole('button').count()).toBe(2) + expect(await group.getByRole('button').nth(1).getAttribute('aria-label')).toBe('默认推理等级说明') expect(await slider.getAttribute('aria-valuetext')).toBe('默认') expect(await slider.getAttribute('max')).toBe('5') await expect.poll(() => menu.evaluate((element) => { @@ -539,6 +630,7 @@ describe.skipIf(MODE === 'record').each([ onTestFailed(() => saveFailureShot(page, `web-e2e-effort-motion-${engine.name()}`)) const viewport = page.viewportSize()! const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) try { await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() @@ -574,11 +666,12 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) const release = Promise.withResolvers() let requests = 0 - let forwarding: Promise | undefined + const forwarding: Promise[] = [] const holdSelection = (route: Route): Promise => { requests++ - forwarding = (async () => { await release.promise; await route.continue() })() - return forwarding + const forwarded = (async () => { await release.promise; await route.continue() })() + forwarding.push(forwarded) + return forwarded } await page.route('**/api/session/selectModel', holdSelection) try { @@ -597,7 +690,17 @@ describe.skipIf(MODE === 'record').each([ expect(tracking.ticks.every(point => point.visibility === 'visible')).toBe(true) expect(tracking.thumbDuration).toBe('0s') expect(tracking.fillDuration).toBe('0s') - expect(Math.abs(tracking.labelCenter - rest.labelCenter)).toBeLessThan(1) + expect(Math.abs(tracking.labelCenter - expectedTagCenter(tracking, tracking.center))).toBeLessThan(1) + for (const offset of [-11, -9, 9, 11]) { + await page.mouse.move(tick.center + offset + grabOffset, rest.y) + const snapped = await readEffortMotion(slider) + const expected = Math.abs(offset) < 10 ? tick.center : tick.center + offset + expect(Math.abs(snapped.center - expected)).toBeLessThan(1) + expect(Math.abs(snapped.fillRight - expected)).toBeLessThan(1) + expect(Math.abs(snapped.labelCenter - expectedTagCenter(snapped, expected))).toBeLessThan(1) + expect(snapped.value).toBe(2) + expect(requests).toBe(0) + } await page.mouse.move(tick.center + grabOffset, rest.y, { steps: 4 }) const dragging = await readEffortMotion(slider) expect(dragging.ticks.every(point => !point.hovered)).toBe(true) @@ -622,9 +725,9 @@ describe.skipIf(MODE === 'record').each([ expect(requests).toBe(1) } finally { release.resolve(undefined) - await page.mouse.up() - await forwarding - await page.unroute('**/api/session/selectModel', holdSelection) + try { await page.mouse.up() } finally { + try { await page.unroute('**/api/session/selectModel', holdSelection) } finally { await Promise.all(forwarding) } + } } await page.mouse.move(rest.ticks[2]!.center, rest.y) await page.mouse.down() @@ -658,14 +761,18 @@ describe.skipIf(MODE === 'record').each([ expect((await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) expect(tripwire.pageErrors).toEqual([]) } finally { - await page.mouse.up() - await page.emulateMedia({ reducedMotion: null }) - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - await page.setViewportSize(viewport) + try { await page.mouse.up() } finally { + try { await page.emulateMedia({ reducedMotion: null }) } finally { + try { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } finally { await page.setViewportSize(viewport) } + } + } } }) it('does not leave thumb or tick hover enlarged after a native touch tap', async () => { + await restoreSelectionAfterTest(page, scaffold) const touch = await browser.newPage({ viewport: { width: 390, height: 700 }, locale: ZH_BROWSER_LOCALE, hasTouch: true, isMobile: true, }) @@ -714,11 +821,15 @@ describe.skipIf(MODE === 'record').each([ touch.off('request', count) } } finally { - await touch.close() + try { + const trigger = touch.getByRole('button', { name: /^选择模型/ }) + if (await trigger.count() === 1) await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') + } finally { await touch.close() } } }) it('keeps the compact Spanish caption and default information readable at 390px', async () => { + await restoreSelectionAfterTest(page, scaffold) const probe = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'es-ES' }) const consoleWatch = watchConsole(probe) try { @@ -786,22 +897,26 @@ describe.skipIf(MODE === 'record').each([ expect(await slider.inputValue()).toBe('0') expect(consoleWatch.pageErrors).toEqual([]) } finally { - await probe.close() + try { + const trigger = probe.getByRole('button', { name: /^Seleccionar modelo/ }) + if (await trigger.count() === 1) await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') + } finally { await probe.close() } } }) it.each(['success', 'failure'] as const)('keeps Team undimmed and guarded through a pending effort %s', async (outcome) => { const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) const release = Promise.withResolvers() let selections = 0 let teamWrites = 0 - let forwarding: Promise | undefined + const forwarding: Promise[] = [] const countTeamWrites = (request: Request): void => { if (new URL(request.url()).pathname.endsWith('/agentTeams/setEnabled')) teamWrites++ } const holdSelection = (route: Route): Promise => { selections++ - forwarding = (async () => { + const forwarded = (async () => { await release.promise if (outcome === 'success') { await route.continue(); return } const envelope = route.request().postDataJSON() as { rpcId: string } @@ -809,7 +924,8 @@ describe.skipIf(MODE === 'record').each([ ok: false, error: { code: 'session/writer-held', message: 'held', details: { sessionId: 'team-pending-fixture' } }, } } }) })() - return forwarding + forwarding.push(forwarded) + return forwarded } await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() @@ -827,8 +943,11 @@ describe.skipIf(MODE === 'record').each([ const menuLocator = page.getByRole('menu', { name: '模型与推理等级', exact: true }) const teamLocator = page.locator('[data-model-menu-page="agent-team"]') const menu = await menuLocator.elementHandle() + onTestFinished(async () => { await menu?.dispose() }) const root = await page.locator('[data-model-menu-root]').elementHandle() + onTestFinished(async () => { await root?.dispose() }) const team = await teamLocator.elementHandle() + onTestFinished(async () => { await team?.dispose() }) if (menu === null || root === null || team === null) throw new Error('Missing pending Team controls') const sample = () => page.evaluate(({ menu, root, team }) => { const rect = (element: Element) => { @@ -898,13 +1017,149 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) } finally { release.resolve(undefined) - await forwarding - await page.unroute('**/api/session/selectModel', holdSelection) page.off('request', countTeamWrites) - await menu.dispose() - await root.dispose() - await team.dispose() - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + try { await page.keyboard.up('ArrowLeft') } finally { + try { await page.unroute('**/api/session/selectModel', holdSelection) } finally { await Promise.all(forwarding) } + } + } + }) + + it('clicks the caption without changing effort and drags outside it to submit Default once', async () => { + const viewport = page.viewportSize()! + const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) + let writes = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) writes++ + } + try { + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + await page.setViewportSize({ width: 390, height: 700 }) + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + const caption = page.locator('[data-effort-caption]') + await slider.press('End') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') + expect(await page.locator('[data-effort-tag] svg').count()).toBe(0) + expect(await page.locator('[data-effort-tail-frame], [data-effort-tail]').count()).toBe(0) + page.on('request', count) + await caption.click() + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(await slider.inputValue()).toBe('5') + expect(writes).toBe(0) + const before = await assertSettledEffort(slider) + const bounds = await caption.boundingBox() + if (bounds === null) throw new Error('Effort caption is not visible') + const start = bounds.x + bounds.width / 2 + const end = start - (before.nativeWidth - before.thumbSize) + const y = bounds.y + bounds.height / 2 + await page.mouse.move(start, y) + await page.mouse.down() + try { + const tick = before.ticks[2]! + for (const offset of [-11, -9, 9, 11]) { + await page.mouse.move(start + tick.center - before.center + offset, y) + const snapped = await readEffortMotion(slider) + const expected = Math.abs(offset) < 10 ? tick.center : tick.center + offset + expect(Math.abs(snapped.center - expected)).toBeLessThan(1) + expect(Math.abs(snapped.fillRight - expected)).toBeLessThan(1) + expect(Math.abs(snapped.labelCenter - expectedTagCenter(snapped, expected))).toBeLessThan(1) + expect(snapped.value).toBe(2) + expect(writes).toBe(0) + } + await page.mouse.move(end, y, { steps: 8 }) + await expect.poll(() => slider.inputValue()).toBe('0') + await assertSettledEffort(slider) + expect(await page.evaluate(({ x, y }) => Boolean(document.elementFromPoint(x, y)?.closest('[data-effort-caption]')), + { x: end, y })).toBe(false) + expect(writes).toBe(0) + } finally { + await page.mouse.up() + } + await expect.poll(() => writes).toBe(1) + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBeUndefined() + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + } finally { + page.off('request', count) + try { await page.mouse.up() } finally { + try { + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + } finally { await page.setViewportSize(viewport) } + } + } + }) + + it.each(['Escape', 'capture loss'] as const)('cancels a native caption drag on %s and lets Escape close the root afterward', async (cancel) => { + const trigger = page.getByRole('button', { name: /^选择模型/ }) + await restoreSelectionAfterTest(page, scaffold) + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() + const slider = page.getByRole('slider', { name: '推理等级', exact: true }) + await slider.press('End') + await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') + const before = await assertSettledEffort(slider) + const caption = page.locator('[data-effort-caption]') + const capture = await caption.evaluateHandle((element) => { + const button = element as HTMLButtonElement + let pointerId: number | null = null + let lost = 0 + const started = (event: PointerEvent) => { pointerId = event.pointerId } + const released = () => { lost++ } + button.addEventListener('pointerdown', started) + button.addEventListener('lostpointercapture', released) + return { + read: () => ({ held: pointerId !== null && button.hasPointerCapture(pointerId), lost }), + release: () => { if (pointerId !== null) button.releasePointerCapture(pointerId) }, + dispose: () => { + button.removeEventListener('pointerdown', started) + button.removeEventListener('lostpointercapture', released) + }, + } + }) + let writes = 0 + const count = (request: Request): void => { + if (new URL(request.url()).pathname.endsWith('/session/selectModel')) writes++ + } + page.on('request', count) + try { + const bounds = await caption.boundingBox() + if (bounds === null) throw new Error('Effort caption is not visible') + const x = bounds.x + bounds.width / 2 + const y = bounds.y + bounds.height / 2 + const end = x - (before.nativeWidth - before.thumbSize) * 0.6 + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(end, y, { steps: 4 }) + await expect.poll(() => capture.evaluate(probe => probe.read().held)).toBe(true) + await expect.poll(() => slider.inputValue()).toBe('2') + expect(writes).toBe(0) + if (cancel === 'Escape') await page.keyboard.press('Escape') + else await capture.evaluate((probe) => { probe.release() }) + // Moving flushes the browser's pending lostpointercapture, not a synthetic event. + await page.mouse.move(end - 1, y) + await expect.poll(() => capture.evaluate(probe => probe.read())).toEqual({ held: false, lost: 1 }) + expect(await slider.inputValue()).toBe('5') + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + await page.mouse.up() + expect(writes).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') + await page.keyboard.press('Escape') + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) + expect(writes).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + page.off('request', count) + try { await page.mouse.up() } finally { + try { await capture.evaluate((probe) => { probe.dispose() }) } finally { await capture.dispose() } + } } }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 5a5c6727cc..db0d0b517c 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -124,7 +124,9 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await page.keyboard.press('Escape') const effort = page.getByRole('group', { name: '推理等级', exact: true }) await effort.getByRole('slider', { name: '推理等级', exact: true }).waitFor() - expect(await effort.getByRole('button').count()).toBe(0) + expect(await effort.getByRole('button').count()).toBe(1) + expect(await effort.getByRole('button', { name: '推理等级:高', exact: true }).count()).toBe(1) + expect(await effort.getByRole('button', { name: '默认推理等级说明', exact: true }).count()).toBe(0) const slider = effort.getByRole('slider') expect(await slider.getAttribute('min')).toBe('0') expect(await slider.getAttribute('max')).toBe('3') diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index 4ad2a55d90..9818268879 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,7 +1,7 @@ - menu "模型与推理等级": - menuitem "模型 Acme Think" - group "推理等级": - - text: 推理等级:默认 + - button "推理等级:默认": 推理等级: 默认 - button "默认推理等级说明" - slider "推理等级": "0" - menuitem "智能体团队协作 关" diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index 5dfc2d06d3..0c41d9e657 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -413,9 +413,11 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) - const information = menu.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') + const effort = menu.getByRole('group', { name: '推理等级', exact: true }) + expect(await effort.getByRole('button').count()).toBe(2) + expect(await effort.getByRole('button', { name: '推理等级:默认', exact: true }).count()).toBe(1) + const information = effort.getByRole('button', { name: '默认推理等级说明', exact: true }) expect(await information.count()).toBe(1) - expect(await information.getAttribute('aria-label')).toBe('默认推理等级说明') await expect.poll(() => slider.evaluate((range) => { const scroller = range.closest('[data-model-menu-root]')! scroller.scrollTop = scroller.scrollHeight diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml new file mode 100644 index 0000000000..e1bb2c2871 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md +/: + en: ebebf4bc1ef9481b + zh: b4ed29de386704e4 +/model-menu-save-state-is-separate-from-locking: + en: b7b55a3a795a61c2 + zh: 38b482bdfdaa9f36 +/model-menu-save-state-is-separate-from-locking/change: + en: 93b3eede8138d457 + zh: 77059bce0d8bed83 +/model-menu-save-state-is-separate-from-locking/migration: + en: f7ae11e689abe49f + zh: 66d0085592ff8244 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md new file mode 100644 index 0000000000..6368e7e282 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Model-menu extensions must distinguish composer locking from a model selection being saved." +--- + +# Model-menu save state is separate from locking + +English | [中文](guide.zh.md) + +## Change + +Extensions contributing to `conversation.input.model.options` receive a separate `pending` owner prop. Previously, `locked` also became true while a model or reasoning selection was being saved. `locked` now represents only the composer's unavailable state; `pending` represents the save in flight. An extension that guards actions only with `locked` can therefore accept another action during a save. + +## Migration + +1. Derive contribution props from `PropsRuntime<'conversation.input.model.options'>` and read both `locked` and `pending`. Update hand-built test owners to supply `pending`. +2. Reject state-changing or page-opening actions while `locked || pending`. Use native `disabled` for `locked`; represent temporary saving with `aria-disabled` and `aria-busy` while retaining the control's focus and appearance. +3. Verify that changing reasoning effort does not dim or move the extension's row, and that activating it during a held save issues no action. Verify that a genuine composer lock still disables the control. + +See the [model-menu extension reference](../../../../packages/client/ui-model-selection/README.md) for the current owner props. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md new file mode 100644 index 0000000000..50ce57ace1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "模型菜单扩展需要区分 composer 锁定状态与模型选择的保存状态。" +--- + +# 模型菜单的保存状态与锁定状态分离 + +[English](guide.md) | 中文 + +## 变更 + +向 `conversation.input.model.options` 提供内容的扩展会接收独立的 `pending` owner 属性。此前保存模型或推理等级选择时,`locked` 也会变为 true。现在 `locked` 仅表示 composer 不可用,`pending` 表示正在保存。因此,仅检查 `locked` 的扩展可能在保存期间接受另一个操作。 + +## 迁移 + +1. 从 `PropsRuntime<'conversation.input.model.options'>` 推导扩展 props,并同时读取 `locked` 与 `pending`。手动构造的测试 owner 需要提供 `pending`。 +2. 在 `locked || pending` 时拒绝修改状态或打开子页的操作。对 `locked` 使用原生 `disabled`;对临时保存状态使用 `aria-disabled` 与 `aria-busy`,同时保留控件的焦点与外观。 +3. 验证切换推理等级不会使扩展行变淡或位移,并确认在暂停响应的保存期间激活该行不会产生操作。另行验证 composer 真正锁定时仍禁用控件。 + +当前 owner 属性见[模型菜单扩展参考](../../../../packages/client/ui-model-selection/README.zh.md)。 diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index b0e74e370d..7fe28852de 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 9b301384eb14f6e0 - zh: 7b021daf345506a8 + en: 166aabe003e07a79 + zh: 09fbb4cc7027064d /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: a57ad8d1ae2c5378 - zh: 391f4a695cdb5232 + en: 559791a4c5b1dbc6 + zh: 82a50b670d8e54ab /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 1d28797205..02962fb037 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -31,9 +31,9 @@ DeepSeek account and API-key routes appear as separate provider groups, each exp When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape closes it. Tab and Shift+Tab traverse its controls and leave the menu at either end. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. -Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab move to the adjacent control. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. +Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab traverse the model row, draggable tag, Default information button when present, native slider, and contributed controls. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row; changing effort does not move focus or change the current menu page. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; effort-save completion preserves any page or focus the user navigated to while saving. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row unless the user has navigated to another page or control while saving; effort-save completion does not move focus or change the current menu page. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; effort-save completion preserves any page or focus the user navigated to while saving. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. ### Model and effort @@ -45,13 +45,13 @@ Both entries group models by provider, with DeepSeek Account first and DeepSeek The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. -The 260px-wide root menu places the model name above a centered, arrowless effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag displays the complete localized label, such as “Effort: High”, and keeps its hover tooltip. It uses the default cursor, its text cannot be selected, and the label adds no Tab stop. Pointer drags preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. +The 260px-wide root menu places the centered model name and chevron above an effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag follows the handle horizontally and stays inside the menu at either end. The tag has no arrow or connector. It displays the complete localized label, such as “Effort: High”, with a tooltip when clipped. Clicking or keyboard-activating the tag focuses the native slider without changing its value or opening another menu; dragging the tag adjusts the level. The tag text is not selectable, and its focusable button is separate from the Default information button. Drags on either surface preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. The tag shows “Effort: Default” for the localized “Default” stop, which appears only when the adapter has no configured default effort. It submits no explicit effort: model and configuration defaults apply, which does not mean reasoning is off. Only this omitted-effort choice shows a keyboard-focusable information button beside the tag; a provider level with the explicit ID `default` does not. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. Standard levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`) use localized names only when the provider's name matches its ID ignoring case. Custom names and unknown levels remain unchanged; for example, `high` named “Thorough mode” keeps that name. This changes display text only, not submitted or persisted IDs. -The visual thumb and filled track follow pointer movement continuously during a drag; the native range still determines the discrete label and value, with one submission on release. Hovering the thumb with a fine mouse pointer or pressing the slider enlarges only the blue center of the visual thumb; the white disc and hit area keep their size. Mouse hover enlarges only the nearby tick, not neighboring ticks, and is inactive during dragging or saving. Touch interaction leaves no hover highlight. Reduced motion disables position transitions and center and tick enlargement. +The visual thumb and filled track follow pointer movement during a drag, with visual snapping within 10px of a stop; the tag follows within its layout bounds. Effort choices remain discrete. Hovering the thumb with a fine mouse pointer or pressing the slider enlarges only the blue center of the visual thumb; the white disc and hit area keep their size. Mouse hover enlarges only the nearby tick, not neighboring ticks, and is inactive during dragging or saving. Touch interaction leaves no hover highlight. Reduced motion disables position transitions and center and tick enlargement. ### Model label extensions diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 14de3a0337..afd848c659 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -31,9 +31,9 @@ DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示 未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 关闭列表。Tab 和 Shift+Tab 遍历列表内的控件,到达两端时离开菜单。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 移至相邻控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 依次经过模型行、可拖动标签、默认信息按钮(如有)、原生滑块和扩展控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;调整推理等级不搬移焦点,也不切换当前菜单页面。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存完成后,保留用户在保存期间主动导航到的页面与焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;若用户在保存期间已导航至其他页面或控件,则保留该位置。推理等级保存完成时不搬移焦点,也不切换当前菜单页面。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存完成后,保留用户在保存期间主动导航到的页面与焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 ### 模型与推理强度 @@ -45,13 +45,13 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 -260px 宽的一级菜单将模型名放在上方,下方显示居中且不带箭头的推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签显示完整本地化文案,例如“推理等级:高”,并保留悬停提示。标签使用默认鼠标指针,文字不可选中,文字本身不增加 Tab 焦点。拖动时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。 +260px 宽的一级菜单上方显示居中的模型名与箭头;下方显示推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签横向跟随滑块圆点,在两端保持于菜单内。标签不带箭头或连接线。标签显示完整本地化文案,例如“推理等级:高”,被截断时提供悬停提示。点击或键盘激活标签只聚焦原生滑块,不改变值,也不打开其他菜单;拖动标签可调整档位。标签文字不可选中,其可聚焦按钮与默认信息按钮相互独立。拖动任一表面时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。 仅当适配器未配置默认强度时出现本地化的“默认”刻度,标签显示“推理等级:默认”。它不提交显式推理等级,而是使用模型与配置的默认设置,不代表关闭推理。仅此省略等级的选择在标签旁显示可通过键盘聚焦的信息按钮;提供方显式 ID 为 `default` 的档位不显示该说明按钮。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 标准档位(`off`、`minimal`、`low`、`medium`、`high`、`xhigh` 和 `max`)仅在提供方名称与 ID 忽略大小写后相同时使用本地化名称。自定义名称与未知档位保持原文,例如名称为“Thorough mode”的 `high` 保留该名称。此规则仅改变显示文字,不改变提交或持久化的 ID。 -拖动期间,可见滑块圆点与轨道填充连续跟随指针移动;标签和实际值仍由原生滑块的离散档位决定,松手后只提交一次。精细鼠标指针悬停圆点或按下滑块时,只放大可见圆点中间的蓝色部分;白色外圈和命中区域尺寸不变。鼠标悬停仅放大命中的单个刻度,不放大相邻刻度;拖动或保存期间不启用刻度悬停效果。触摸交互不留下悬停高亮。减少动态效果设置会关闭位置过渡以及蓝点和刻度的放大效果。 +拖动期间,可见滑块圆点与轨道填充跟随指针移动,在刻度 10px 范围内显示吸附效果;标签在布局边界内跟随。推理等级仍按离散档位选择。精细鼠标指针悬停圆点或按下滑块时,只放大可见圆点中间的蓝色部分;白色外圈和命中区域尺寸不变。鼠标悬停仅放大命中的单个刻度,不放大相邻刻度;拖动或保存期间不启用刻度悬停效果。触摸交互不留下悬停高亮。减少动态效果设置会关闭位置过渡以及蓝点和刻度的放大效果。 ### 模型名称扩展 diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css index 38e05015f9..b3b6e82a06 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -1,18 +1,36 @@ +@property --dsh-effort-position { + syntax: ''; + inherits: true; + initial-value: 0; +} + .root { display: contents; --effort-thumb-size: 20px; --effort-track-size: 16px; } +.heading, +.rail { + --dsh-effort-position: var(--effort-visual-position); + transition: --dsh-effort-position 300ms cubic-bezier(.23, 1, .32, 1); +} + .heading { grid-row: 2; - display: flex; - justify-content: center; + container-type: inline-size; + position: relative; height: 28px; - margin: 10px 14px 0; + margin: 8px 8px 0; } .value { + position: absolute; + top: 0; + left: 0; + width: max-content; + /* Percentages use the pill width; cqw uses the rail-aligned container. */ + translate: clamp(0px, calc(var(--effort-thumb-size) / 2 + (100cqw - var(--effort-thumb-size)) * var(--dsh-effort-position) - 50%), calc(100cqw - 100%)) 0; display: inline-flex; align-items: center; gap: 4px; @@ -40,6 +58,38 @@ padding-inline-end: 1px; } +.caption { + display: flex; + flex: 1 1 auto; + align-items: center; + min-width: 0; + height: 24px; + padding: 0; + border: 0; + background: transparent; + color: inherit; + font: inherit; + white-space: inherit; + cursor: grab; + touch-action: pan-y; + -webkit-user-select: none; + user-select: none; +} + +.caption:focus-visible { + outline: 2px solid currentColor; + outline-offset: 1px; + border-radius: var(--dsw-radius-sm); +} + +.caption[aria-disabled='true'] { + cursor: default; +} + +.heading[data-dragging] .caption { + cursor: grabbing; +} + .valueLabel { display: flex; gap: 2px; @@ -92,7 +142,7 @@ .rail { grid-row: 3; position: relative; - margin: 0 8px 2px; + margin: -2px 8px 0; } .track { @@ -111,11 +161,10 @@ .fill { display: block; height: 100%; - width: calc(var(--effort-thumb-size) / 2 + (100% - var(--effort-thumb-size)) * var(--effort-visual-position)); + width: calc(var(--effort-thumb-size) / 2 + (100% - var(--effort-thumb-size)) * var(--dsh-effort-position)); background: linear-gradient(to right, color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); - transition: width 300ms cubic-bezier(.23, 1, .32, 1); } .range { @@ -207,11 +256,10 @@ .thumbPosition { position: absolute; top: 50%; - left: calc(var(--effort-visual-position) * 100%); + left: calc(var(--dsh-effort-position) * 100%); width: var(--effort-thumb-size); height: var(--effort-thumb-size); transform: translate(-50%, -50%); - transition: left 300ms cubic-bezier(.23, 1, .32, 1); } .thumb { @@ -245,12 +293,14 @@ height: 9.6px; } -.rail[data-dragging] .thumbPosition, -.rail[data-dragging] .fill { +.heading[data-dragging], +.rail[data-dragging] { transition: none; } @media (prefers-reduced-motion: reduce) { + .heading, + .rail, .thumbPosition, .fill, .thumb::after, diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx index 1c42361954..95cf1ddc18 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.tsx +++ b/packages/client/ui-model-selection/src/client/EffortSlider.tsx @@ -30,12 +30,25 @@ export interface EffortSliderProps { type PointerGeometry = { start: number; length: number; size: number; centerY: number; offset: number } type Gesture = | { kind: 'pointer'; source: string; index: number; geometry: PointerGeometry | null; position: number | null } + | { + kind: 'caption' + source: string + index: number + pointerId: number + startX: number + startY: number + startPosition: number + length: number + position: number | null + } | { kind: 'keyboard' | 'cancelled'; source: string; index: number } | { kind: 'hover'; catalog: string; thumb: boolean; tick: number | null } const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) +/** Pointer travel under which a dragged thumb settles onto the nearest stop. */ +const SNAP_DISTANCE_PX = 10 /** - * Preview native discrete values while an inert visual thumb follows pointer movement. + * Preview discrete effort choices with a native range and a draggable, range-focusing caption. * @param props - Exact-model choices, persisted value, and selection callback. * @returns A native range with a live value label and independent motion decoration. */ @@ -44,6 +57,7 @@ export function EffortSlider({ }: EffortSliderProps) { const thumbRef = useRef(null) const rangeRef = useRef(null) + const captionRef = useRef(null) const infoFocused = useRef(false) const selectedIndex = choices.findIndex(choice => choice.effort === value) const catalog = JSON.stringify(choices.map(choice => [choice.key, choice.effort])) @@ -72,10 +86,25 @@ export function EffortSlider({ infoFocused.current = false } }, [defaultSelected]) + const capturedPointer = gesture?.kind === 'caption' ? gesture.pointerId : null + useEffect(() => { + const caption = captionRef.current + if (capturedPointer === null || caption === null) return + // Source changes, locks, and unmounts end the caption's capture as well as its preview. + return () => { if (caption.hasPointerCapture(capturedPointer)) caption.releasePointerCapture(capturedPointer) } + }, [capturedPointer]) const progress = choices.length > 1 ? index / (choices.length - 1) : 0 - const dragging = active?.kind === 'pointer' && active.position !== null - const visualProgress = dragging ? active.position : progress - const expanded = active?.kind === 'pointer' || hover?.thumb === true + const dragging = (active?.kind === 'pointer' || active?.kind === 'caption') && active.position !== null + const snapPosition = (position: number, length: number | null): number => { + if (length === null || choices.length < 2) return position + const nearest = Math.round(position * (choices.length - 1)) / (choices.length - 1) + return Math.abs(position - nearest) * length <= SNAP_DISTANCE_PX ? nearest : position + } + const dragLength = active?.kind === 'caption' ? active.length : active?.kind === 'pointer' ? active.geometry?.length ?? null : null + const visualProgress = active !== null && (active.kind === 'pointer' || active.kind === 'caption') && active.position !== null + ? snapPosition(active.position, dragLength) + : progress + const expanded = active?.kind === 'pointer' || (active?.kind === 'caption' && dragging) || hover?.thumb === true // Pointer geometry comes from the unscaled wrapper, so zoom and the spring cannot change the grab offset. const measure = (input: HTMLInputElement): PointerGeometry | null => { @@ -124,6 +153,54 @@ export function EffortSlider({ && previous.catalog === next.catalog && previous.thumb === next.thumb && previous.tick === next.tick ? previous : next) } } + const releaseCaption = (pointerId: number): void => { + const caption = captionRef.current + if (caption?.hasPointerCapture(pointerId)) caption.releasePointerCapture(pointerId) + } + const cancelCaption = (pointerId: number): void => { + releaseCaption(pointerId) + setGesture(previous => previous?.kind === 'caption' && previous.pointerId === pointerId + ? { kind: 'cancelled', source: previous.source, index: previous.index } : previous) + } + const startCaption = (event: PointerEvent): void => { + if (pending || rangeDisabled) { event.preventDefault(); return } + if (!event.isPrimary || event.button > 0) return + event.preventDefault() + const input = rangeRef.current + if (input === null) return + input.focus() + const geometry = measure(input) + const thumb = thumbRef.current?.getBoundingClientRect() + if (geometry === null || thumb === undefined) return + // The caption may be clamped at an edge; its center is never the drag's value origin. + const startPosition = (thumb.left + thumb.width / 2 - geometry.start) / geometry.length + event.currentTarget.setPointerCapture(event.pointerId) + setGesture({ kind: 'caption', source, index, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, + startPosition, length: geometry.length, position: null }) + } + const moveCaption = (event: PointerEvent): void => { + if (gesture?.kind !== 'caption' || gesture.pointerId !== event.pointerId || gesture.source !== source || rangeDisabled || pending) return + const deltaX = event.clientX - gesture.startX + const deltaY = event.clientY - gesture.startY + if (gesture.position === null) { + if (event.pointerType === 'touch' && Math.abs(deltaY) >= 3 && Math.abs(deltaY) > Math.abs(deltaX)) { + cancelCaption(event.pointerId) + return + } + if (Math.abs(deltaX) < 3) return + } + event.preventDefault() + const position = Math.max(0, Math.min(1, gesture.startPosition + deltaX / gesture.length)) + const nextIndex = Math.round(position * (choices.length - 1)) + setGesture(previous => previous?.kind === 'caption' && previous.pointerId === event.pointerId && previous.source === source + ? { ...previous, position, index: nextIndex } : previous) + } + const finishCaption = (event: PointerEvent): void => { + releaseCaption(event.pointerId) + if (gesture?.kind !== 'caption' || gesture.pointerId !== event.pointerId || gesture.source !== source) return + if (gesture.position !== null && gesture.index !== selectedIndex && !rangeDisabled && !pending) commit(gesture.index) + else setGesture(null) + } return (
-
- - - - {valueLabel.slice(0, valueStart)} - {valueLabel.slice(valueStart)} - +
+ + + {defaultSelected && (
-
+
@@ -190,8 +279,8 @@ export function EffortSlider({ if (pending || rangeDisabled) return const nextIndex = event.currentTarget.valueAsNumber if (gesture === null || gesture.kind === 'hover') commit(nextIndex) - else if (gesture.source === source && gesture.kind !== 'cancelled') { - setGesture(previous => previous !== null && previous.kind !== 'hover' && previous.source === source && previous.kind !== 'cancelled' + else if (gesture.source === source && (gesture.kind === 'pointer' || gesture.kind === 'keyboard')) { + setGesture(previous => (previous?.kind === 'pointer' || previous?.kind === 'keyboard') && previous.source === source ? { ...previous, index: nextIndex } : previous) } }} @@ -204,7 +293,11 @@ export function EffortSlider({ onBlur={(event) => { // WebKit focuses the enclosing menu when its native range takes over a pointer drag. const insideAncestor = event.relatedTarget instanceof Node && event.relatedTarget.contains(event.currentTarget) - setGesture(previous => insideAncestor && previous?.kind === 'pointer' && previous.source === source ? previous : null) + if (gesture?.kind === 'caption') releaseCaption(gesture.pointerId) + setGesture(previous => previous?.kind === 'caption' + ? { kind: 'cancelled', source: previous.source, index: previous.index } + : previous?.kind === 'cancelled' || (insideAncestor && previous?.kind === 'pointer' && previous.source === source) + ? previous : null) }} onKeyDown={(event) => { if (event.nativeEvent.isComposing) return @@ -213,13 +306,18 @@ export function EffortSlider({ event.stopPropagation() return } - if (event.key === 'Escape' && gesture !== null && gesture.kind !== 'hover') { + if (event.key === 'Escape' && gesture !== null && gesture.kind !== 'hover' && gesture.kind !== 'cancelled') { event.preventDefault() event.stopPropagation() + if (gesture.kind === 'caption') releaseCaption(gesture.pointerId) setGesture({ kind: 'cancelled', source, index }) } else if (ADJUST_KEYS.has(event.key)) { event.stopPropagation() - if (gesture === null || gesture.kind === 'hover') setGesture({ kind: 'keyboard', source, index }) + if (gesture?.kind === 'caption') releaseCaption(gesture.pointerId) + if (gesture === null || gesture.kind === 'hover' || gesture.kind === 'caption' + || (gesture.kind === 'cancelled' && !event.repeat)) { + setGesture({ kind: 'keyboard', source, index }) + } } }} onKeyUp={(event) => { diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index c744ba13f5..cf930361a7 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -325,10 +325,14 @@ export function ModelSelect( close() } - const settleSelection = (result: Awaited>, origin: 'model' | 'effort'): void => { + const settleSelection = ( + result: Awaited>, origin: 'model' | 'effort', selectionPage: HTMLDivElement | null, + ): void => { if (result === undefined) return if (menuRef.current !== null) { - if (origin === 'model') { + // Restore only the selection's own view and focus, not navigation made while saving. + if (origin === 'model' && selectionPage !== null && selectionPage === groupsRef.current + && document.activeElement === triggerRef.current) { paneFocus.current = 'model' if (result.ok) { setModelReturnFocus(true) @@ -353,7 +357,8 @@ export function ModelSelect( // Model rows may unmount; the inline slider keeps focus while its value is saved. setSelectionFocus(true) if (origin === 'model') triggerRef.current?.focus() - void select(selection).then((result) => { settleSelection(result, origin) }) + const selectionPage = origin === 'model' ? groupsRef.current : null + void select(selection).then((result) => { settleSelection(result, origin, selectionPage) }) } const choose = (selection: ModelSelection): void => { diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx index 021b8b1189..3df7288604 100644 --- a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx @@ -52,7 +52,7 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('shows the full loca expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', high)) expect(effortLabel().tabIndex).toBe(-1) expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(high) - expect(screen.queryByRole('button')).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) view.rerender() expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', defaultLabel)) expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(defaultLabel) @@ -131,7 +131,7 @@ it('shows exact advertised stops and the selected value', () => { expect(range().step).toBe('1') expect(effortLabel().textContent).toBe('Effort: high') expect(effortLabel().tabIndex).toBe(-1) - expect(screen.queryByRole('button')).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) }) it('previews a drag but submits only its final stop on release', () => { @@ -258,7 +258,7 @@ it('does not pretend an unknown stored effort matches the first supported stop', expect(range().disabled).toBe(true) expect(range().getAttribute('aria-valuetext')).toBe('retired') expect(effortLabel().textContent).toBe('Effort: retired') - expect(screen.queryByRole('button')).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) }) it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragging with fewer than two choices', ({ levels }) => { @@ -285,14 +285,14 @@ function motionSetup() { return { ...view, input, inputProps, thumb, scale, pointer } } -it('keeps the visual track and thumb inert while the native range owns interaction', () => { +it('keeps motion decoration inert beside the native range and caption', () => { const view = motionSetup() expect(screen.getAllByRole('slider')).toHaveLength(1) expect(view.thumb.closest('[aria-hidden="true"]')).toBeTruthy() expect(view.container.querySelector('[data-effort-fill]')!.closest('[aria-hidden="true"]')).toBeTruthy() expect(view.thumb.tabIndex).toBe(-1) expect(view.scale.tabIndex).toBe(-1) - expect(screen.queryByRole('button')).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) }) it('hovers one tick in its 16px target without selecting and does not retain touch hover', () => { diff --git a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx new file mode 100644 index 0000000000..345d4bae3f --- /dev/null +++ b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx @@ -0,0 +1,205 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' + +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) + +function setup(value: string | null = 'off', includeDefault = false, parentKey?: ReturnType) { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query.includes('hover: hover'), media: query, onchange: null, + addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, + })) + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) + const levels = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effort, label: effort })) + const props: EffortSliderProps = { + choices: includeDefault ? [{ key: 'default', effort: undefined, label: 'Default' }, ...levels] : levels, + value: value ?? undefined, label: 'Effort', currentLabel: value ?? 'Default', formatLabel: label => `Effort: ${label}`, + defaultInfoLabel: 'About default effort', defaultExplanation: 'Uses the model defaults, not reasoning off.', + disabled: false, pending: false, onSelect: vi.fn(), + } + const slider = + const view = render(parentKey === undefined ? slider :
{slider}
) + const input = screen.getByRole('slider') + const tag = screen.getByRole('button', { name: /^Effort:/ }) + const thumb = view.container.querySelector('[data-effort-thumb]')! + vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 40, 220, 40)) + vi.spyOn(thumb, 'getBoundingClientRect').mockImplementation(() => new DOMRect(Number(input.value) / Number(input.max) * 200, 50, 20, 20)) + vi.spyOn(tag, 'getBoundingClientRect').mockImplementation(() => { + const center = 10 + Number(input.value) / Number(input.max) * 200 + return new DOMRect(Math.max(0, Math.min(120, center - 50)), 0, 100, 28) + }) + const captured = new Set() + const tagCapture = vi.fn((id: number) => { captured.add(id) }) + tag.setPointerCapture = tagCapture + tag.hasPointerCapture = vi.fn((id: number) => captured.has(id)) + const tagRelease = vi.fn((id: number) => { captured.delete(id) }) + tag.releasePointerCapture = tagRelease + const inputCapture = vi.fn() + input.setPointerCapture = inputCapture + const pointer = (target: HTMLElement, type: string, x: number, y = 14, pointerType = 'mouse') => fireEvent(target, + Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }), + { pointerId: 1, pointerType, isPrimary: true })) + return { ...view, props, input, tag, thumb, pointer, tagCapture, tagRelease, inputCapture } +} + +it('focuses the range on a tag click without selecting or opening an effort menu', () => { + const view = setup() + fireEvent.click(view.tag) + expect(document.activeElement).toBe(view.input) + expect(view.props.onSelect).not.toHaveBeenCalled() + expect(screen.queryByRole('menuitemradio')).toBeNull() +}) + +it.each(['mouse', 'touch'])('does not turn a sub-threshold %s movement into a selection', (pointerType) => { + const view = setup() + view.pointer(view.tag, 'pointerdown', 80, 14, pointerType) + view.pointer(view.tag, 'pointermove', 82, 14, pointerType) + view.pointer(view.tag, 'pointerup', 82, 14, pointerType) + fireEvent.click(view.tag) + expect(view.input.value).toBe('0') + expect(view.props.onSelect).not.toHaveBeenCalled() + expect(document.activeElement).toBe(view.input) + expect(view.inputCapture).not.toHaveBeenCalled() +}) + +it.each([ + { start: 'off', down: 80, move: 120, expected: 'low', index: '1' }, + { start: 'max', down: 130, move: 90, expected: 'high', index: '2' }, +])('preserves the thumb-relative offset when the $start tag is clamped to an edge', ({ start, down, move, expected, index }) => { + const view = setup(start) + view.pointer(view.tag, 'pointerdown', down) + view.pointer(view.tag, 'pointermove', move) + expect(view.input.value).toBe(index) + expect(view.props.onSelect).not.toHaveBeenCalled() + expect(view.tagCapture).toHaveBeenCalledWith(1) + view.pointer(view.tag, 'pointerup', move) + fireEvent.click(view.tag) + expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith(expected) + expect(view.inputCapture).not.toHaveBeenCalled() +}) + +it.each(['pointercancel', 'lostpointercapture', 'Escape', 'blur'])('discards a tag drag on %s and ignores its late release', (cancel) => { + const view = setup() + view.pointer(view.tag, 'pointerdown', 80) + view.pointer(view.tag, 'pointermove', 160) + expect(view.props.onSelect).not.toHaveBeenCalled() + if (cancel === 'Escape') fireEvent.keyDown(view.input, { key: 'Escape' }) + else if (cancel === 'blur') fireEvent.blur(view.input) + else view.pointer(view.tag, cancel, 160) + expect(view.tag.hasPointerCapture(1)).toBe(false) + expect(view.tagRelease).toHaveBeenCalledExactlyOnceWith(1) + view.pointer(view.tag, 'pointerup', 160) + expect(view.input.value).toBe('0') + expect(view.props.onSelect).not.toHaveBeenCalled() +}) + +it('lets the second Escape reach the menu after cancelling a caption drag and releasing the pointer', () => { + const parentKey = vi.fn() + const view = setup('off', false, parentKey) + view.pointer(view.tag, 'pointerdown', 80) + view.pointer(view.tag, 'pointermove', 160) + expect(view.input.value).not.toBe('0') + const cancel = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + fireEvent(view.input, cancel) + expect(cancel.defaultPrevented).toBe(true) + expect(parentKey).not.toHaveBeenCalled() + expect(view.input.value).toBe('0') + view.pointer(view.tag, 'pointerup', 160) + expect(view.props.onSelect).not.toHaveBeenCalled() + const close = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + fireEvent(view.input, close) + expect(close.defaultPrevented).toBe(false) + expect(parentKey).toHaveBeenCalledOnce() + expect(view.input.value).toBe('0') + expect(view.props.onSelect).not.toHaveBeenCalled() +}) + +it('discards a tag gesture when a different selection arrives', () => { + const view = setup() + view.pointer(view.tag, 'pointerdown', 80) + view.pointer(view.tag, 'pointermove', 160) + view.rerender() + view.pointer(view.tag, 'pointerup', 160) + expect(view.input.value).toBe('1') + expect(view.props.onSelect).not.toHaveBeenCalled() +}) + +it.each(['pending', 'disabled'] as const)('prevents tag selection while %s', (state) => { + const view = setup() + view.rerender() + view.pointer(view.tag, 'pointerdown', 80) + view.pointer(view.tag, 'pointermove', 160) + view.pointer(view.tag, 'pointerup', 160) + expect(view.props.onSelect).not.toHaveBeenCalled() + expect(view.tagCapture).not.toHaveBeenCalled() +}) + +it.each(['source', 'catalog', 'pending', 'disabled', 'unmount'] as const)('releases caption capture when %s invalidates the drag', (change) => { + const view = setup() + view.pointer(view.tag, 'pointerdown', 80) + view.pointer(view.tag, 'pointermove', 160) + expect(view.tag.hasPointerCapture(1)).toBe(true) + if (change === 'unmount') view.unmount() + else view.rerender() + expect(view.tag.hasPointerCapture(1)).toBe(false) + expect(view.tagRelease).toHaveBeenCalledExactlyOnceWith(1) + view.pointer(view.tag, 'pointerup', 160) + expect(view.props.onSelect).not.toHaveBeenCalled() +}) + +it.each(['range', 'caption'] as const)('snaps %s motion within 10px of a stop but follows beyond it', (surface) => { + const view = setup(null, true) + const target = surface === 'range' ? view.input : view.tag + const start = surface === 'range' ? 10 : 80 + const y = surface === 'range' ? 60 : 14 + view.pointer(target, 'pointerdown', start, y) + // Five stops over a measured 200px travel put the first advertised level at 50px. + for (const offset of [-11, -10, -9, 9, 10, 11]) { + view.pointer(target, 'pointermove', start + 50 + offset, y) + if (surface === 'range') fireEvent.change(view.input, { target: { value: '1' } }) + const position = Number(view.input.closest('[role="group"]')!.style.getPropertyValue('--effort-visual-position')) + expect(position * 200).toBeCloseTo(Math.abs(offset) <= 10 ? 50 : 50 + offset, 5) + expect(view.input.value).toBe('1') + expect(view.props.onSelect).not.toHaveBeenCalled() + } + view.pointer(target, 'pointerup', start + 61, y) + expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith('off') + expect(view.inputCapture).not.toHaveBeenCalled() + expect(view.tag.hasPointerCapture(1)).toBe(false) +}) + +it('keeps default information independent from the draggable caption', () => { + const view = setup(null, true) + const info = screen.getByRole('button', { name: 'About default effort' }) + expect(view.tag.contains(info)).toBe(false) + view.pointer(info, 'pointerdown', 100) + view.pointer(info, 'pointerup', 100) + fireEvent.click(info) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toContain('model defaults') + expect(view.props.onSelect).not.toHaveBeenCalled() + expect(view.tagCapture).not.toHaveBeenCalled() +}) + +it('keeps the draggable caption free of SVG and tail decoration', () => { + const view = setup() + const tag = view.container.querySelector('[data-effort-tag]')! + expect(tag.querySelector('svg')).toBeNull() + expect(view.container.querySelector('[data-effort-tail-frame], [data-effort-tail], [data-effort-tail-edge]')).toBeNull() + fireEvent.click(view.tag) + expect(document.activeElement).toBe(view.input) + expect(view.props.onSelect).not.toHaveBeenCalled() +}) + +it('keeps native range gestures free of explicit pointer capture', () => { + const view = setup() + view.pointer(view.input, 'pointerdown', 10, 60) + fireEvent.change(view.input, { target: { value: '1' } }) + view.pointer(view.input, 'pointerup', 76, 60) + expect(view.inputCapture).not.toHaveBeenCalled() + expect(view.tagCapture).not.toHaveBeenCalled() + expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith('low') +}) diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx index 0dd538e1ca..8a4f332279 100644 --- a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx @@ -53,7 +53,8 @@ function setup(count = 2, hasReasoning = true, providerDefault = false) { fireEvent.click(trigger) const model = () => screen.getByRole('menuitem', { name: /Model.*Model 1/ }) const team = () => screen.getByRole('menuitem', { name: 'Agent teamwork' }) - return { select, toggle, directory, trigger, model, team } + const tag = () => screen.getByRole('button', { name: /^Effort:/ }) + return { select, toggle, directory, trigger, model, team, tag } } function tab(shiftKey = false) { const event = new KeyboardEvent('keydown', { key: 'Tab', shiftKey, bubbles: true, cancelable: true }) @@ -66,12 +67,16 @@ it('Tab moves from the trigger through root controls without opening a page or s tab() expect(document.activeElement).toBe(view.model()) tab() + expect(document.activeElement).toBe(view.tag()) + tab() expect(document.activeElement).toBe(screen.getByRole('slider', { name: 'Effort' })) tab() expect(document.activeElement).toBe(view.team()) tab(true) expect(document.activeElement).toBe(screen.getByRole('slider')) tab(true) + expect(document.activeElement).toBe(view.tag()) + tab(true) expect(document.activeElement).toBe(view.model()) expect(screen.queryByRole('menuitemradio')).toBeNull() expect(screen.queryByRole('switch')).toBeNull() @@ -85,6 +90,8 @@ it('includes default information before the range and keeps Escape at the toolti tab() expect(document.activeElement).toBe(view.model()) tab() + expect(document.activeElement).toBe(view.tag()) + tab() const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) expect(document.activeElement).toBe(info) fireEvent.click(info) @@ -120,7 +127,7 @@ it('removes only the default information Tab stop when the selection changes', ( expect(screen.queryByRole('button', { name: en['effort.defaultInfoLabel'] })).toBeNull() expect(document.activeElement).toBe(slider) tab(true) - expect(document.activeElement).toBe(view.model()) + expect(document.activeElement).toBe(view.tag()) act(() => { view.directory.update((snapshot) => { snapshot.current = { provider: 'sample', model: 'model-1' } }) }) @@ -131,7 +138,7 @@ it('removes only the default information Tab stop when the selection changes', ( it('keeps a pending contributed entry in Tab order without allowing navigation', () => { const view = setup() - tab(); tab(); tab() + tab(); tab(); tab(); tab() const team = view.team() expect(document.activeElement).toBe(team) act(() => { view.directory.update((snapshot) => { diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index fe2cbdcfa9..a0e8414204 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -227,7 +227,7 @@ describe('ModelSelect reasoning effort', () => { }) fireEvent.click(trigger) const efforts = within(screen.getByRole('group', { name: '推理等级' })) - expect(efforts.queryByRole('button')).toBeNull() + expect(efforts.getByRole('button', { name: '推理等级:高' })).toBeTruthy() expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('高') const label = screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')! @@ -501,6 +501,73 @@ describe('ModelSelect reasoning effort', () => { expect(trigger.getAttribute('aria-busy')).toBe('false') }) + it.each([ + { outcome: 'success', navigation: 'reopen-model' }, + { outcome: 'failure', navigation: 'reopen-model' }, + { outcome: 'success', navigation: 'tab-search' }, + { outcome: 'failure', navigation: 'tab-search' }, + { outcome: 'success', navigation: 'none' }, + { outcome: 'failure', navigation: 'none' }, + ] as const)('settles a delayed model $outcome without overriding $navigation navigation', async ({ outcome, navigation }) => { + const groups = modelGroups(5) + const directory = createSnapshotStore(state({ groups })) + const pending = Promise.withResolvers['select']>>>() + onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) + const selection: ModelSelection = { provider: 'deepseek-official', model: 'model-2' } + const select = vi.fn((next: ModelSelection) => { + directory.set(state({ groups, status: 'selecting', pending: next })) + return pending.promise + }) + render() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + fireEvent.click(trigger) + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + const originalSearch = screen.getByRole('searchbox') + fireEvent.click(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(select).toHaveBeenCalledExactlyOnceWith(selection) + expect(document.activeElement).toBe(trigger) + expect(trigger.getAttribute('aria-busy')).toBe('true') + + if (navigation === 'reopen-model') { + fireEvent.keyDown(trigger, { key: 'Escape' }) + expect(screen.queryByRole('searchbox')).toBeNull() + fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + expect(screen.getByRole('searchbox')).not.toBe(originalSearch) + } else if (navigation === 'tab-search') { + fireEvent.keyDown(trigger, { key: 'Tab' }) + expect(screen.getByRole('searchbox')).toBe(originalSearch) + } + const search = screen.getByRole('searchbox') + if (navigation !== 'none') expect(document.activeElement).toBe(search) + + const error = new RemoteError('session/model-unavailable', 'model is unavailable', selection) + await act(async () => { + directory.set(outcome === 'success' + ? state({ groups, current: selection }) + : state({ groups, status: 'error', error: error.message })) + pending.resolve(outcome === 'success' ? { ok: true, value: undefined } : { ok: false, error }) + }) + + expect(trigger.getAttribute('aria-busy')).toBe('false') + if (navigation !== 'none') { + expect(screen.getByRole('searchbox')).toBe(search) + expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() + expect(document.activeElement).toBe(search) + } else if (outcome === 'success') { + expect(screen.queryByRole('searchbox')).toBeNull() + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /模型.*Model 2/ })) + } + if (outcome === 'failure') { + expect(screen.getByRole('alert').textContent).toBe('模型操作失败:session/model-unavailable: model is unavailable') + expect(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }).getAttribute('aria-checked')).toBe('true') + } else { + expect(screen.queryByRole('alert')).toBeNull() + expect(directory.getSnapshot().current).toEqual(selection) + } + expect(select).toHaveBeenCalledTimes(1) + }) + it('announces the pending target while retaining slider focus and blocking duplicate submissions', async () => { const directory = createSnapshotStore(state()) const pending = Promise.withResolvers<{ ok: true; value: undefined }>() @@ -684,13 +751,12 @@ describe('ModelSelect keyboard walk', () => { const modelCell = screen.getByRole('menuitem', { name: /^模型/ }) const slider = screen.getByRole('slider', { name: '推理等级' }) fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(modelCell) fireEvent.keyDown(modelCell, { key: 'ArrowDown' }) expect(document.activeElement).toBe(slider) expect(fireEvent.keyDown(slider, { key: 'ArrowDown' })).toBe(true) expect(document.activeElement).toBe(slider) expect(screen.queryByRole('searchbox')).toBeNull() - fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true }) - expect(document.activeElement).toBe(modelCell) fireEvent.click(modelCell) const model = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(model) @@ -735,18 +801,22 @@ describe('ModelSelect keyboard walk', () => { it('walks between root controls while leaving adjustment arrows to the native range', () => { const select = mountOpen() + const trigger = screen.getByRole('button', { name: /选择模型/ }) + const tag = screen.getByRole('button', { name: /^推理等级/ }) const model = screen.getByRole('menuitem', { name: /^模型/ }) const slider = screen.getByRole('slider', { name: '推理等级' }) - expect(fireEvent.keyDown(model, { key: 'ArrowDown' })).toBe(false) + fireEvent.keyDown(trigger, { key: 'Tab' }) expect(document.activeElement).toBe(model) - fireEvent.keyDown(model, { key: 'ArrowDown' }) + fireEvent.keyDown(model, { key: 'Tab' }) + expect(document.activeElement).toBe(tag) + fireEvent.keyDown(tag, { key: 'Tab' }) expect(document.activeElement).toBe(slider) expect(fireEvent.keyDown(slider, { key: 'ArrowRight' })).toBe(true) expect(document.activeElement).toBe(slider) - expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) + fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true }) + expect(document.activeElement).toBe(tag) + fireEvent.keyDown(tag, { key: 'Tab', shiftKey: true }) expect(document.activeElement).toBe(model) - fireEvent.keyDown(model, { key: 'ArrowUp' }) - expect(document.activeElement).toBe(slider) expect(screen.getByRole('menu')).toBeTruthy() expect(select).not.toHaveBeenCalled() }) @@ -789,19 +859,15 @@ describe('ModelSelect keyboard walk', () => { const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) - // The root pane's first cell carries the current selection. - const cells = screen.getAllByRole('menuitem') - expect(document.activeElement).toBe(cells[0]) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.getByRole('menu')).toBeTruthy() }) it('a backward step from outside the list enters at the last row, and a closed menu leaves Tab native', () => { mountOpen() - const modelRow = screen.getByRole('menuitem', { name: /^模型/ }) - const slider = screen.getByRole('slider', { name: '推理等级' }) - expect(fireEvent.keyDown(modelRow, { key: 'ArrowUp' })).toBe(false) - expect(document.activeElement).toBe(slider) const trigger = screen.getByRole('button', { name: /选择模型/ }) + expect(fireEvent.keyDown(trigger, { key: 'ArrowUp' })).toBe(false) + expect(document.activeElement).toBe(screen.getByRole('slider')) fireEvent.keyDown(trigger, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(true) @@ -819,7 +885,9 @@ describe('ModelSelect keyboard walk', () => { fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') - expect(screen.queryByRole('button', { name: '推理等级:最高' })).toBeNull() + const caption = screen.getByRole('button', { name: '推理等级:最高' }) + fireEvent.click(caption) + expect(document.activeElement).toBe(screen.getByRole('slider')) expect(select).not.toHaveBeenCalled() }) @@ -1331,14 +1399,14 @@ describe('ModelSelect contributed pages', () => { it('moves Tab from the inline range to a contributed entry and Shift+Tab back without changing effort', () => { const { select } = mountPage() const slider = screen.getByRole('slider', { name: '推理等级' }) - const model = screen.getByRole('menuitem', { name: /^模型/ }) + const tag = screen.getByRole('button', { name: /^推理等级/ }) const entry = screen.getByRole('menuitem', { name: '设置 关' }) slider.focus() expect(fireEvent.keyDown(slider, { key: 'Tab' })).toBe(false) expect(document.activeElement).toBe(entry) slider.focus() expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(model) + expect(document.activeElement).toBe(tag) expect(select).not.toHaveBeenCalled() }) From 53183d374cfbdebc25a2a11f12ca607347bc61e2 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 17:53:01 +0800 Subject: [PATCH 04/68] fix(ui): keep effort tag edge clicks out of the slider --- apps/web/tests/declared-reasoning.e2e.ts | 19 +++++++++++ .../src/client/EffortSlider.module.css | 32 ++++++++++--------- .../tests/effort-tag-drag.client.spec.tsx | 3 +- 3 files changed, 38 insertions(+), 16 deletions(-) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 4b804893b0..ebba03e46f 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -245,6 +245,25 @@ describe.skipIf(MODE === 'record').each([ const defaultHeight = await menu.evaluate(element => element.getBoundingClientRect().height) await menu.locator('[data-effort-label]').click() expect(await slider.inputValue()).toBe('0') + const tagHit = await menu.locator('[data-effort-tag]').evaluate((tag) => { + const caption = tag.querySelector('[data-effort-caption]')! + const bounds = tag.getBoundingClientRect() + const x = bounds.left + bounds.width / 2 + const y = bounds.bottom - 1 + return { + x, y, hitsCaption: document.elementFromPoint(x, y) === caption, + tagScrollWidth: tag.scrollWidth, tagClientWidth: tag.clientWidth, + captionScrollWidth: caption.scrollWidth, captionClientWidth: caption.clientWidth, + } + }) + expect(tagHit.hitsCaption).toBe(true) + await trigger.focus() + await page.mouse.click(tagHit.x, tagHit.y) + expect(await slider.inputValue()).toBe('0') + expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + expect(requests).toBe(0) + expect(tagHit.tagScrollWidth).toBe(tagHit.tagClientWidth) + expect(tagHit.captionScrollWidth).toBe(tagHit.captionClientWidth) await info.click() const tooltip = page.getByRole('tooltip') await tooltip.waitFor() diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css index b3b6e82a06..872b22df55 100644 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ b/packages/client/ui-model-selection/src/client/EffortSlider.module.css @@ -20,12 +20,15 @@ grid-row: 2; container-type: inline-size; position: relative; + z-index: 1; + pointer-events: none; height: 28px; margin: 8px 8px 0; } .value { position: absolute; + pointer-events: auto; top: 0; left: 0; width: max-content; @@ -33,15 +36,9 @@ translate: clamp(0px, calc(var(--effort-thumb-size) / 2 + (100cqw - var(--effort-thumb-size)) * var(--dsh-effort-position) - 50%), calc(100cqw - 100%)) 0; display: inline-flex; align-items: center; - gap: 4px; box-sizing: border-box; max-width: 100%; height: 28px; - padding: 1px 8px; - border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); - border-radius: 999px; - corner-shape: round; - background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); color: var(--dsw-alias-state-business-primary); font-size: 13px; line-height: 18px; @@ -53,20 +50,23 @@ user-select: none; } -.value:has(.infoButton) { - gap: 2px; - padding-inline-end: 1px; +.value:has(.infoButton) .caption { + padding-inline-end: 27px; } .caption { display: flex; flex: 1 1 auto; align-items: center; + box-sizing: border-box; min-width: 0; - height: 24px; - padding: 0; - border: 0; - background: transparent; + width: 100%; + height: 28px; + padding: 1px 8px; + border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); + border-radius: 999px; + corner-shape: round; + background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); color: inherit; font: inherit; white-space: inherit; @@ -79,7 +79,6 @@ .caption:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; - border-radius: var(--dsw-radius-sm); } .caption[aria-disabled='true'] { @@ -113,8 +112,11 @@ } .infoButton { + position: absolute; + top: 2px; + right: 2px; + z-index: 1; display: inline-flex; - flex: 0 0 24px; align-items: center; justify-content: center; width: 24px; diff --git a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx index 345d4bae3f..b39a361555 100644 --- a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx @@ -1,11 +1,12 @@ // @vitest-environment jsdom import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' +import type { ComponentProps } from 'react' import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) -function setup(value: string | null = 'off', includeDefault = false, parentKey?: ReturnType) { +function setup(value: string | null = 'off', includeDefault = false, parentKey?: ComponentProps<'div'>['onKeyDown']) { vi.stubGlobal('matchMedia', (query: string) => ({ matches: query.includes('hover: hover'), media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, From 7e14cfcd6a64b39e9a76f8461d9665ad637d2bc3 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 17:59:22 +0800 Subject: [PATCH 05/68] test(ui): wait for resized effort controls to become hittable --- apps/web/tests/declared-reasoning.e2e.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index ebba03e46f..0f12004a44 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -872,7 +872,7 @@ describe.skipIf(MODE === 'record').each([ const label = menu.locator('[data-effort-label]') const info = menu.getByRole('button', { name: 'Acerca del esfuerzo de razonamiento predeterminado', exact: true }) await info.waitFor() - const layout = await info.evaluate((button) => { + const readLayout = () => info.evaluate((button) => { const tag = button.parentElement! const text = tag.querySelector('[data-effort-label]')! const name = text.querySelector('[data-effort-name]')! @@ -889,8 +889,9 @@ describe.skipIf(MODE === 'record').each([ contained: bounds.left >= tagBounds.left && bounds.right <= tagBounds.right, reachable: hit?.closest('button') === button } }) - expect(layout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', + await expect.poll(readLayout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', nameText: 'Predeterminado', nameFits: true, nameVisible: true, contained: true, reachable: true }) + const layout = await readLayout() expect(layout.textWidth).toBeGreaterThan(0) expect(layout.textGap).toBeCloseTo(2, 1) expect(layout.endInset).toBeCloseTo(2, 1) From 7cc5ed7ad5b2c42d3a4df459e14723daa3c6dff7 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 18:24:51 +0800 Subject: [PATCH 06/68] test(ui): align recorded image previews with localized effort labels --- snapshots/web/file-upload-round/ui.expected.md | 2 +- snapshots/web/minimal-read-image/ui.expected.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index a3e682317c..94d259cd4b 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -24,7 +24,7 @@ - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Workspace Write"': Workspace Write -- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort high": DeepSeek-V4-Flash-Vision-Exp high +- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort High": DeepSeek-V4-Flash-Vision-Exp High - button "Send message" [disabled] - button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s - button "17.3K tok · Cache hit 51%": 17.3K tokCache hit 51% diff --git a/snapshots/web/minimal-read-image/ui.expected.md b/snapshots/web/minimal-read-image/ui.expected.md index ab1052525e..38c5c387bd 100644 --- a/snapshots/web/minimal-read-image/ui.expected.md +++ b/snapshots/web/minimal-read-image/ui.expected.md @@ -29,7 +29,7 @@ - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Workspace Write"': Workspace Write -- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort high": DeepSeek-V4-Flash-Vision-Exp high +- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort High": DeepSeek-V4-Flash-Vision-Exp High - button "Send message" [disabled] - button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s - button "28 tok · Cache hit 0%": 28 tokCache hit 0% From 7e5f45c4154ffc70449e12b0a32413337fa37679 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 20:33:45 +0800 Subject: [PATCH 07/68] refactor(ui): narrow model menu changes to team settings --- apps/web/tests/agent-team-panel.e2e.ts | 51 - apps/web/tests/declared-reasoning.e2e.ts | 1075 ++--------------- .../tests/deepseek-messages-settings.e2e.ts | 19 +- apps/web/tests/default-model.e2e.ts | 40 +- .../pointer-menu.expected.md | 2 +- .../declared-reasoning/ui.expected.md | 10 +- .../picker.expected.md | 2 +- .../expected/default-model/search.expected.md | 2 +- apps/web/tests/model-menu-observer.e2e.ts | 59 +- apps/web/tests/plugin-manager.e2e.ts | 1 - .../model-menu-pending/guide.i18n.yaml | 16 - .../v0.2.2-rc.1/model-menu-pending/guide.md | 20 - .../model-menu-pending/guide.zh.md | 20 - .../client/ui-agent-team/README.i18n.yaml | 4 +- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.tsx | 13 +- .../tests/team-mode.client.spec.tsx | 91 +- .../ui-model-selection/README.i18n.yaml | 20 +- packages/client/ui-model-selection/README.md | 28 +- .../client/ui-model-selection/README.zh.md | 28 +- .../src/client/EffortSlider.module.css | 323 ----- .../src/client/EffortSlider.tsx | 344 ------ .../src/client/ModelSelect.module.css | 75 +- .../src/client/ModelSelect.tsx | 280 +++-- .../src/client/effort-label.ts | 24 - .../ui-model-selection/src/client/locales.ts | 90 +- .../ui-model-selection/src/client/slots.ts | 4 +- .../tests/effort-label.client.spec.ts | 30 - .../tests/effort-slider.client.spec.tsx | 442 ------- .../tests/effort-tag-drag.client.spec.tsx | 206 ---- .../tests/model-menu-page.client.spec.tsx | 78 ++ .../tests/model-menu-tab.client.spec.tsx | 274 ----- .../tests/model-select.client.spec.tsx | 641 +++------- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/Switch.tsx | 11 +- .../tests/switch.client.spec.tsx | 33 - .../ui-theme/src/styles/design-platform.css | 4 - .../src/client/slot-catalog.ts | 10 +- .../web/file-upload-round/ui.expected.md | 2 +- .../web/minimal-read-image/ui.expected.md | 2 +- 43 files changed, 580 insertions(+), 3810 deletions(-) delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md delete mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.module.css delete mode 100644 packages/client/ui-model-selection/src/client/EffortSlider.tsx delete mode 100644 packages/client/ui-model-selection/src/client/effort-label.ts delete mode 100644 packages/client/ui-model-selection/tests/effort-label.client.spec.ts delete mode 100644 packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx delete mode 100644 packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx create mode 100644 packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx delete mode 100644 packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index e8477cfba4..3cf5e843f0 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -134,8 +134,6 @@ describe('web e2e: agent teamwork panel', () => { const menu = page.getByRole('menu') const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) await summary.waitFor() - // The route-only fixture supplies no reasoning capability, so no range is invented. - expect(await menu.getByRole('slider', { name: 'Effort', exact: true }).count()).toBe(0) expect(await menu.getByRole('switch').count()).toBe(0) expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) const rootSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) @@ -204,55 +202,6 @@ describe('web e2e: agent teamwork panel', () => { } }) - it('keeps keyboard focus on the Team switch through pending writes and rejects repeated activation', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-team-keyboard-pending')) - const service = scaffold.ctx.agentTeams - const setEnabled = service.setEnabled.bind(service) - const agent = scaffold.ctx.agents.list()[0]! - const initial = service.isEnabled(agent) - onTestFinished(async () => { - await closeModelMenu(page) - await setEnabled(agent, initial) - }) - await openTeamSettings(page) - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - for (const enabled of [true, false]) { - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - let inFlight: Promise | undefined - const write = vi.spyOn(service, 'setEnabled').mockImplementation((...args) => { - inFlight = (async () => { - entered.resolve(undefined) - await release.promise - await setEnabled(...args) - })() - return inFlight - }) - try { - await toggle.focus() - await page.keyboard.press('Space') - await entered.promise - await expect.poll(() => toggle.getAttribute('aria-busy')).toBe('true') - expect(await toggle.evaluate(element => (element as HTMLButtonElement).disabled)).toBe(false) - expect(await toggle.getAttribute('aria-disabled')).toBe('true') - expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Enter') - await page.keyboard.press('Space') - expect(write).toHaveBeenCalledTimes(1) - expect(await toggle.getAttribute('aria-checked')).toBe(String(!enabled)) - release.resolve(undefined) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) - await expect.poll(() => toggle.getAttribute('aria-busy')).toBeNull() - expect(await toggle.getAttribute('aria-disabled')).toBeNull() - expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) - } finally { - release.resolve(undefined) - try { await inFlight } finally { write.mockRestore() } - } - } - expect(tripwire.pageErrors).toEqual([]) - }) - it('defaults off and saves a Session selection in the model menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode')) expect(await page.locator('[data-subagent-action]').count()).toBe(0) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 0f12004a44..27619f0bf1 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -1,12 +1,12 @@ // Web e2e scenario: a hand-declared model's `reasoningEfforts` reaches the -// composer's inline effort slider — the levels a settings profile declares are exactly +// composer's effort pane — the levels a settings profile declares are exactly // what the picker offers, and picking one records it with the Agent default. // Zero model calls: declaring, describing, and switching are settings/llm // traffic only, so there is no fixture and a stray stream would fail loud. import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import type { Browser, Locator, Page, Request, Route } from 'playwright' +import type { Browser, Page, Request } from 'playwright' import { chromium, webkit } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' import { @@ -22,88 +22,6 @@ const UI_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/ui.expe const POINTER_EXPECTED = fileURLToPath(new URL('./expected/declared-reasoning/pointer-menu.expected.md', import.meta.url)) const MODE = webSnapshotMode() -async function readEffortMotion(slider: Locator) { - return slider.evaluate((element) => { - const input = element as HTMLInputElement - const group = input.closest('[role="group"]')! - const thumb = group.querySelector('[data-effort-thumb]')! - const scale = group.querySelector('[data-effort-thumb-scale]')! - const fill = group.querySelector('[data-effort-fill]')! - const tag = group.querySelector('[data-effort-tag]')! - const rangeRect = input.getBoundingClientRect() - const thumbRect = thumb.getBoundingClientRect() - const fillRect = fill.getBoundingClientRect() - const labelRect = tag.getBoundingClientRect() - const thumbSize = Number.parseFloat(getComputedStyle(thumb).width) - const ratio = (input.valueAsNumber - Number(input.min)) / (Number(input.max) - Number(input.min)) - return { - value: input.valueAsNumber, dragging: input.parentElement!.hasAttribute('data-dragging'), - nativeWidth: rangeRect.width, nativeHeight: rangeRect.height, - left: rangeRect.left, right: rangeRect.right, y: rangeRect.top + rangeRect.height / 2, - center: thumbRect.left + thumbRect.width / 2, centerY: thumbRect.top + thumbRect.height / 2, - expectedCenter: rangeRect.left + thumbSize / 2 + (rangeRect.width - thumbSize) * ratio, - thumbSize, visualWidth: scale.getBoundingClientRect().width, fillRight: fillRect.right, - dotWidth: Number.parseFloat(getComputedStyle(scale, '::after').width), - dotDuration: getComputedStyle(scale, '::after').transitionDuration, - dotEasing: getComputedStyle(scale, '::after').transitionTimingFunction, - labelCenter: labelRect.left + labelRect.width / 2, labelWidth: labelRect.width, - thumbDuration: getComputedStyle(input.parentElement!).transitionDuration, - thumbEasing: getComputedStyle(input.parentElement!).transitionTimingFunction, - fillDuration: getComputedStyle(input.parentElement!).transitionDuration, - tickDuration: getComputedStyle(group.querySelector('[data-effort-tick]')!).transitionDuration, - ticks: [...group.querySelectorAll('[data-effort-tick]')].map((tick) => { - const rect = tick.getBoundingClientRect() - return { center: rect.left + rect.width / 2, width: rect.width, - hovered: tick.hasAttribute('data-hovered'), visibility: getComputedStyle(tick).visibility } - }), - } - }) -} - -/** The tag tracks the handle but stops at the menu edges. */ -function expectedTagCenter(view: { left: number; right: number; labelWidth: number }, target: number): number { - const half = view.labelWidth / 2 - return Math.min(Math.max(target, view.left + half), view.right - half) -} - -async function assertSettledEffort(slider: Locator) { - await expect.poll(async () => { - const view = await readEffortMotion(slider) - return Math.max(Math.abs(view.center - view.expectedCenter), Math.abs(view.fillRight - view.center)) - }).toBeLessThan(1) - const view = await readEffortMotion(slider) - expect(view.nativeHeight).toBe(40) - expect(view.thumbSize).toBe(20) - expect(Math.abs(view.centerY - view.y)).toBeLessThan(1) - expect(Math.abs(view.labelCenter - expectedTagCenter(view, view.center))).toBeLessThan(1) - return view -} - -async function restoreSelectionAfterTest(page: Page, scaffold: WebScaffold): Promise { - const trigger = page.getByRole('button', { name: /^选择模型/ }) - const agent = scaffold.ctx.agents.list()[0]! - const savedModel = agent.model.current()! - const savedDefault = scaffold.ctx.agentDefaultModel.currentSelection() - const savedLabel = await trigger.getAttribute('aria-label') - const viewport = page.viewportSize()! - onTestFinished(async () => { - try { - await page.mouse.up() - await page.keyboard.up('ArrowRight') - await page.keyboard.up('ArrowLeft') - await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') - if (JSON.stringify(agent.model.current()) !== JSON.stringify(savedModel)) agent.model.select(savedModel) - // Queue restoration behind background default saves even if the visible default has not changed yet. - await scaffold.ctx.agentDefaultModel.saveSelection(savedDefault) - await expect.poll(() => trigger.getAttribute('aria-label')).toBe(savedLabel) - } finally { - try { - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - } finally { await page.setViewportSize(viewport) } - } - }) -} - describe.skipIf(MODE === 'record').each([ { name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }, @@ -131,9 +49,7 @@ describe.skipIf(MODE === 'record').each([ { id: 'acme-lite', name: 'Acme Lite' }, ].map(model => ({ ...model, - reasoningEfforts: model.id === 'acme-lite' - ? { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' } - : { off: null, high: 'high', max: 'ultra' }, + reasoningEfforts: { off: null, high: 'high', max: 'ultra' }, })), }, }, @@ -154,269 +70,76 @@ describe.skipIf(MODE === 'record').each([ } }) - it('uses Tab only for focus while Enter and Space open model and Team pages', async () => { - onTestFailed(() => saveFailureShot(page, `web-e2e-model-tab-${engine.name()}`)) - let selections = 0 - const countSelection = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ - } - page.on('request', countSelection) - onTestFinished(() => { page.off('request', countSelection) }) - const previous = scaffold.ctx.agentDefaultModel.currentSelection() - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - const rootModel = page.locator('[data-model-menu-root] > button[role="menuitem"]') - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - const team = page.locator('[data-model-menu-page="agent-team"]') - const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) - const focused = async (locator: Locator): Promise => { - await expect.poll(() => locator.evaluate(element => element === document.activeElement)).toBe(true) - } - await trigger.click() - const caption = page.locator('[data-effort-caption]') - await page.keyboard.press('Tab'); await focused(rootModel) - expect(await page.getByRole('menuitemradio').count()).toBe(0) - await page.keyboard.press('Tab'); await focused(caption) - await page.keyboard.press('Tab'); await focused(info) - await page.keyboard.press('Tab'); await focused(slider) - await page.keyboard.press('Tab'); await focused(team) - expect(await page.getByRole('switch').count()).toBe(0) - await page.keyboard.press('Shift+Tab'); await focused(slider) - await page.keyboard.press('Shift+Tab'); await focused(info) - await page.keyboard.press('Shift+Tab'); await focused(caption) - await page.keyboard.press('Shift+Tab'); await focused(rootModel) - await page.keyboard.press('Enter') - const search = page.getByRole('searchbox', { name: '搜索模型…', exact: true }) - await search.waitFor(); await focused(search) - await page.mouse.move(0, 0) - await page.keyboard.press('Escape'); await focused(rootModel) - expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') - await page.keyboard.press('Space'); await focused(search) - await page.keyboard.press('Tab') - await focused(page.locator('[role="menuitemradio"][tabindex="0"]')) - expect(selections).toBe(0) - expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) - await page.keyboard.press('Shift+Tab'); await focused(search) - await page.keyboard.press('Shift+Tab'); await focused(trigger) - expect(await search.count()).toBe(0) - await page.keyboard.press('Enter') - await page.keyboard.press('Tab'); await focused(rootModel) - await page.keyboard.press('Space'); await search.waitFor() - await page.keyboard.press('Tab') - await focused(page.locator('[role="menuitemradio"][aria-checked="true"]')) - await page.keyboard.press('Space'); await focused(rootModel) - await page.keyboard.press('Tab'); await focused(caption) - await page.keyboard.press('Tab'); await focused(info) - await page.keyboard.press('Tab'); await focused(slider) - await page.keyboard.press('Tab'); await focused(team) - await page.keyboard.press('Space') - const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) - await toggle.waitFor(); await focused(toggle) - const checked = await toggle.getAttribute('aria-checked') - await page.keyboard.press('Shift+Tab'); await focused(trigger) - expect(await toggle.count()).toBe(0) - await page.keyboard.press('Enter') - await team.click(); await focused(toggle) - expect(await toggle.getAttribute('aria-checked')).toBe(checked) - expect(await page.getByRole('button', { name: '返回', exact: true }).count()).toBe(0) - await page.keyboard.press('Escape'); await focused(team) - await page.keyboard.press('Tab') - await page.locator('[data-model-menu-root]').waitFor({ state: 'detached' }) - expect(await trigger.evaluate(element => element === document.activeElement)).toBe(false) - expect(selections).toBe(0) - expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) - expect(tripwire.pageErrors).toEqual([]) - }, 60_000) - - it('reads default information by mouse and keyboard without selecting or closing the menu', async () => { - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - let requests = 0 - const count = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ - } - page.on('request', count) - try { - await trigger.click() - const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) - const info = menu.getByRole('button', { name: '默认推理等级说明', exact: true }) - const explanation = '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理' - const defaultHeight = await menu.evaluate(element => element.getBoundingClientRect().height) - await menu.locator('[data-effort-label]').click() - expect(await slider.inputValue()).toBe('0') - const tagHit = await menu.locator('[data-effort-tag]').evaluate((tag) => { - const caption = tag.querySelector('[data-effort-caption]')! - const bounds = tag.getBoundingClientRect() - const x = bounds.left + bounds.width / 2 - const y = bounds.bottom - 1 - return { - x, y, hitsCaption: document.elementFromPoint(x, y) === caption, - tagScrollWidth: tag.scrollWidth, tagClientWidth: tag.clientWidth, - captionScrollWidth: caption.scrollWidth, captionClientWidth: caption.clientWidth, - } - }) - expect(tagHit.hitsCaption).toBe(true) - await trigger.focus() - await page.mouse.click(tagHit.x, tagHit.y) - expect(await slider.inputValue()).toBe('0') - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(requests).toBe(0) - expect(tagHit.tagScrollWidth).toBe(tagHit.tagClientWidth) - expect(tagHit.captionScrollWidth).toBe(tagHit.captionClientWidth) - await info.click() - const tooltip = page.getByRole('tooltip') - await tooltip.waitFor() - expect(await tooltip.textContent()).toBe(explanation) - expect(await menu.isVisible()).toBe(true) - await info.click() - await tooltip.waitFor({ state: 'hidden' }) - await trigger.focus() - await page.keyboard.press('Tab') - await page.keyboard.press('Tab') - await page.keyboard.press('Tab') - expect(await info.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Enter') - await tooltip.waitFor() - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await menu.isVisible()).toBe(true) - expect(await info.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Space') - await tooltip.waitFor() - await page.keyboard.press('Tab') - await tooltip.waitFor({ state: 'hidden' }) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(requests).toBe(0) - await slider.press('ArrowRight') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('off') - expect(await slider.getAttribute('aria-valuetext')).toBe('关闭') - expect(await menu.locator('[data-effort-label]').textContent()).toBe('推理等级:关闭') - expect(await info.count()).toBe(0) - expect(await menu.evaluate(element => element.getBoundingClientRect().height)).toBe(defaultHeight) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ - provider: 'acme-gateway', model: 'acme-think', - }) - expect(await info.count()).toBe(1) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - await page.keyboard.press('Enter') - await tooltip.waitFor() - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await menu.isVisible()).toBe(true) - await page.keyboard.press('Escape') - await menu.waitFor({ state: 'hidden' }) - expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) - expect(requests).toBe(2) - expect(tripwire.pageErrors).toEqual([]) - } finally { - page.off('request', count) - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - } - }) - - it('offers exactly the declared levels in the root slider and records one keyboard selection', async () => { + it('offers exactly the declared levels and records the picked one', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-declared-reasoning-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) await trigger.waitFor({ timeout: 15_000 }) - onTestFinished(async () => { - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - }) await trigger.click() - const model = page.getByRole('menuitem', { name: /^模型/ }) - const layout = await model.evaluate((row) => { - const label = row.children[0]! - const value = row.children[1]! - const name = value.querySelector('[data-model-id]')! - const chevron = row.querySelector(':scope > svg')! - const labelStyle = getComputedStyle(label) - const valueStyle = getComputedStyle(value) - const labelRect = label.getBoundingClientRect() - const valueRect = value.getBoundingClientRect() - const chevronRect = chevron.getBoundingClientRect() - const probe = document.createElement('span') - probe.style.position = 'absolute' - probe.style.color = 'var(--dsw-alias-label-tertiary)' - row.append(probe) - try { - return { - label: label.textContent, labelSize: labelStyle.fontSize, labelPosition: labelStyle.position, - labelClip: labelStyle.clipPath, labelWidth: labelRect.width, labelHeight: labelRect.height, - valueAlign: valueStyle.textAlign, valueColor: valueStyle.color, tertiaryColor: getComputedStyle(probe).color, - valueRightError: Math.abs(name.getBoundingClientRect().right - valueRect.right), - gapToChevron: chevronRect.left - valueRect.right, - chevronWidth: chevronRect.width, chevronHeight: chevronRect.height, - } - } finally { probe.remove() } - }) - expect(layout).toMatchObject({ label: '模型', labelSize: '13px', labelPosition: 'absolute', labelClip: 'inset(50%)', - valueAlign: 'center', chevronWidth: 10, chevronHeight: 10 }) - expect(layout.labelWidth).toBeLessThan(2) - expect(layout.labelHeight).toBeLessThan(2) - expect(layout.gapToChevron).toBe(2) - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - const levels = page.getByRole('group', { name: '推理等级', exact: true }).getByRole('button') - expect(await levels.count()).toBe(2) - expect(await levels.nth(1).getAttribute('aria-label')).toBe('默认推理等级说明') - expect(await slider.getAttribute('min')).toBe('0') - expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('默认') - const tag = page.locator('[data-effort-tag]') - expect(await tag.evaluate(element => ({ - cursor: getComputedStyle(element).cursor, - userSelect: getComputedStyle(element).getPropertyValue(CSS.supports('user-select', 'none') ? 'user-select' : '-webkit-user-select'), - }))).toEqual({ cursor: 'default', userSelect: 'none' }) - const caption = page.locator('[data-effort-caption]') - expect(await caption.evaluate(element => ({ - cursor: getComputedStyle(element).cursor, - tabIndex: element.tabIndex, - label: element.getAttribute('aria-label'), - }))).toEqual({ cursor: 'grab', tabIndex: 0, label: '推理等级:默认' }) - expect(await page.getByRole('menuitem', { name: /推理等级/ }).count()).toBe(0) + await page.getByRole('menuitem', { name: /推理等级/ }).click() + + // Declared levels, nothing else: the provider-default entry (the route + // configures no `reasoning`), then Off/High/Max — minimal, low, medium, + // and xhigh were not declared and must not be offered. + const levels = page.getByRole('menuitemradio') + await expect.poll(async () => levels.allTextContents(), { timeout: 10_000 }) + .toEqual(['Default', 'Off', 'High', 'Max']) const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) - const previous = scaffold.ctx.agentDefaultModel.currentSelection() - await slider.focus() - try { - await page.keyboard.down('ArrowRight') - await expect.poll(() => slider.inputValue()).toBe('1') - await page.keyboard.down('ArrowRight') - await expect.poll(() => slider.inputValue()).toBe('2') - expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(previous) - } finally { - await page.keyboard.up('ArrowRight') - } - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) + + // Keyboard: the clicked cell unmounts with its pane, so the drilled pane's + // checked row takes the focus it left behind. ↑↓ walk the rows from there + // and Tab settles the focused one exactly as Enter would. + await expect.poll( + () => levels.nth(0).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + await page.keyboard.press('ArrowDown') + await expect.poll( + () => levels.nth(1).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + await page.keyboard.press('ArrowDown') + await expect.poll( + () => levels.nth(2).evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) + + // Settling with Tab is the same gesture that saves the default selection, so + // the effort lands in the Agent default Settings section beside provider/model. + await page.keyboard.press('Tab') + await expect.poll(() => levels.count(), { timeout: 10_000 }).toBe(0) await expect.poll( async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 10_000 }, ).toContain('reasoningEffort: high') - await expect.poll(() => trigger.getAttribute('aria-label')).toBe('选择模型,当前 Acme Think,推理等级 高') - expect(await slider.getAttribute('aria-valuetext')).toBe('高') - await slider.focus() + await expect.poll(() => trigger.getAttribute('aria-label'), { timeout: 10_000 }) + .toBe('选择模型,当前 Acme Think,推理等级 High') + + // Reopening the drilled pane parks the keyboard on the level in use, and + // Shift+Tab walks back out like Escape: to the drilled cell, then closed. + await trigger.click() + await page.getByRole('menuitem', { name: /推理等级/ }).click() + const high = page.getByRole('menuitemradio', { name: 'High' }) + await expect.poll( + () => high.evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.locator('[data-effort-caption]') - .evaluate(element => element === document.activeElement)).toBe(true) + await expect.poll( + () => page.getByRole('menuitem', { name: /推理等级/ }) + .evaluate(element => element === document.activeElement), + { timeout: 10_000 }, + ).toBe(true) await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.locator('[data-model-menu-root] > button[role="menuitem"]') - .evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - await expect.poll(() => page.getByRole('menu').count()).toBe(0) + await expect.poll(() => page.getByRole('menu').count(), { timeout: 10_000 }).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) it('opens from the pointer with keyboard focus and closes from the trigger in every pane', async () => { onTestFailed(() => saveFailureShot(page, `web-e2e-model-trigger-${engine.name()}`)) const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) const menu = page.getByRole('menu') - for (const pane of ['root', 'model', 'slider']) { + for (const pane of ['root', 'model', 'effort']) { await page.locator('[data-composer-input][contenteditable="true"]').focus() await trigger.click() await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) @@ -425,11 +148,10 @@ describe.skipIf(MODE === 'record').each([ await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) .evaluate(element => element === document.activeElement)).toBe(true) } else { - if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() + await page.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }).click() const focused = pane === 'model' ? page.getByRole('searchbox', { name: '搜索模型…' }) - : page.getByRole('slider', { name: '推理等级', exact: true }) - if (pane === 'slider') await focused.focus() + : page.locator('[role="menuitemradio"][aria-checked="true"]') await expect.poll(() => focused.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) } await trigger.click() @@ -448,11 +170,7 @@ describe.skipIf(MODE === 'record').each([ page.on('request', countSelection) onTestFinished(() => { page.off('request', countSelection) }) const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) const menu = page.getByRole('menu') - onTestFinished(async () => { - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - }) await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() const current = page.getByRole('menuitemradio', { name: 'Acme Think', exact: true }) @@ -485,43 +203,20 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() await target.getByText('Acme Swift', { exact: true }).click() - await page.locator('[data-model-menu-root]').waitFor() + await menu.waitFor({ state: 'detached' }) expect(selections).toBe(1) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model, { timeout: 10_000 }) .toBe('acme-swift') - const rootModel = page.getByRole('menuitem', { name: /^模型/ }) - await expect.poll(() => rootModel.evaluate(element => element === document.activeElement)).toBe(true) - expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') - await rootModel.hover() - await expect.poll(() => rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') - await page.mouse.move(0, 0) - await page.keyboard.press('Tab') - const caption = page.locator('[data-effort-caption]') - expect(await caption.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Tab') - const info = page.getByRole('button', { name: '默认推理等级说明', exact: true }) - expect(await info.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Tab') - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - expect(await info.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - expect(await caption.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - expect(await rootModel.evaluate(element => element === document.activeElement)).toBe(true) - expect(await rootModel.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') - expect(selections).toBe(1) - const rangeBounds = await slider.boundingBox() - if (rangeBounds === null) throw new Error('Reasoning slider is not visible') - await page.mouse.click(rangeBounds.x + rangeBounds.width - 8, rangeBounds.y + rangeBounds.height / 2) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') + await trigger.click() + await page.getByRole('menuitem', { name: /推理等级/ }).click() + await page.getByRole('menuitemradio', { name: 'Max', exact: true }).click() + await menu.waitFor({ state: 'detached' }) expect(selections).toBe(2) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort, { timeout: 10_000 }) .toBe('max') - const rejectSelection = async (route: Route): Promise => { + await page.route('**/api/session/selectModel', async (route) => { const envelope = route.request().postDataJSON() as { rpcId: string } await route.fulfill({ json: { @@ -532,28 +227,21 @@ describe.skipIf(MODE === 'record').each([ }, }, }) - } - await page.route('**/api/session/selectModel', rejectSelection, { times: 1 }) - try { - await page.getByRole('menuitem', { name: /^模型/ }).click() - await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) - await current.click() - await page.getByRole('alert').waitFor() - } finally { - await page.unroute('**/api/session/selectModel', rejectSelection) - } + }, { times: 1 }) + await trigger.click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) + expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) + await current.click() + await page.getByRole('alert').waitFor() expect(selections).toBe(3) await compareOrRefreshGolden(POINTER_EXPECTED, - await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), MODE) - const focusedRow = page.locator('[role="menuitemradio"][tabindex="0"]') - await expect.poll(() => focusedRow.evaluate(element => element === document.activeElement)).toBe(true) - expect(await target.getAttribute('aria-checked')).toBe('true') - expect(scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-swift') - await page.keyboard.press('Shift+Tab') + await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), MODE) + await expect.poll(() => trigger.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Tab') await expect.poll(() => search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - await search.fill('Acme Think') - await search.press('ArrowDown') + expect(await search.getAttribute('aria-activedescendant')).toBe(await target.getAttribute('id')) + await search.press('ArrowUp') expect(await search.getAttribute('aria-activedescendant')).toBe(await current.getAttribute('id')) expect(await search.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) await page.keyboard.press('Escape') @@ -562,11 +250,7 @@ describe.skipIf(MODE === 'record').each([ await trigger.click() await page.getByRole('menuitem', { name: /^模型/ }).click() - await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true) - const composer = page.locator('[data-composer-input][contenteditable="true"]') - // Native focus supplies relatedTarget; Playwright's contentEditable focus first blurs to null. - await composer.evaluate((element) => { element.focus() }) - await expect.poll(() => composer.evaluate(element => element === document.activeElement)).toBe(true) + await page.locator('[data-composer-input][contenteditable="true"]').focus() await menu.waitFor({ state: 'detached' }) await trigger.click() await page.mouse.click(0, 0) @@ -574,615 +258,6 @@ describe.skipIf(MODE === 'record').each([ expect(tripwire.pageErrors).toEqual([]) }) - it('shows six stops including Default and commits only after releasing a drag outside the range', async () => { - onTestFailed(() => saveFailureShot(page, `web-e2e-six-effort-drag-${engine.name()}`)) - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - const viewport = page.viewportSize()! - await trigger.click() - await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().model).toBe('acme-lite') - let selections = 0 - const countSelection = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) selections++ - } - page.on('request', countSelection) - onTestFinished(() => { page.off('request', countSelection) }) - try { - await page.setViewportSize({ width: 390, height: 700 }) - const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - const group = menu.getByRole('group', { name: '推理等级', exact: true }) - const slider = group.getByRole('slider', { name: '推理等级', exact: true }) - expect(await group.getByRole('button').count()).toBe(2) - expect(await group.getByRole('button').nth(1).getAttribute('aria-label')).toBe('默认推理等级说明') - expect(await slider.getAttribute('aria-valuetext')).toBe('默认') - expect(await slider.getAttribute('max')).toBe('5') - await expect.poll(() => menu.evaluate((element) => { - const rect = element.getBoundingClientRect() - return rect.left >= 12 && rect.right <= innerWidth - 12 && rect.top >= 12 && rect.bottom <= innerHeight - 12 - && element.scrollWidth <= element.clientWidth - })).toBe(true) - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await slider.hover() - const bounds = await slider.boundingBox() - if (bounds === null) throw new Error('Reasoning slider is not visible') - const y = bounds.y + bounds.height / 2 - await page.mouse.move(bounds.x + 8, y) - await page.mouse.down() - try { - await page.mouse.move(bounds.x + bounds.width * .4, y, { steps: 4 }) - await page.mouse.move(bounds.x + bounds.width * .6, y, { steps: 4 }) - await page.mouse.move(bounds.x + bounds.width - 8, y, { steps: 4 }) - await page.mouse.move(bounds.x + bounds.width + 24, y, { steps: 4 }) - expect(await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.matches('input[type="range"]'), - { x: bounds.x + bounds.width + 24, y })).not.toBe(true) - expect(selections).toBe(0) - expect(await menu.isVisible()).toBe(true) - await expect.poll(() => slider.evaluate(input => ({ - value: (input as HTMLInputElement).value, - label: input.getAttribute('aria-valuetext'), - busy: input.getAttribute('aria-busy'), - disabled: (input as HTMLInputElement).disabled, - }))).toEqual({ value: '5', label: '最高', busy: 'false', disabled: false }) - } catch (error) { - await page.screenshot({ path: fileURLToPath(new URL( - `../../../.artifacts/model-picker-master-sync/drag-${engine.name()}-regression.png`, import.meta.url, - )) }) - throw error - } finally { - await page.mouse.up() - } - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - expect(await menu.isVisible()).toBe(true) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(selections).toBe(1) - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') - expect(tripwire.pageErrors).toEqual([]) - } finally { - await page.keyboard.press('Escape') - await page.setViewportSize(viewport) - } - }) - - it('keeps visual motion aligned with native dragging, hover targets and pending saves at 390px', async () => { - onTestFailed(() => saveFailureShot(page, `web-e2e-effort-motion-${engine.name()}`)) - const viewport = page.viewportSize()! - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - try { - await trigger.click() - await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - await page.setViewportSize({ width: 390, height: 700 }) - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await slider.hover() - await page.mouse.move(0, 0) - await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) - const rest = await assertSettledEffort(slider) - await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) - expect(rest.dotWidth).toBeCloseTo(8, 1) - expect(rest.thumbDuration).toBe('0.3s') - expect(rest.fillDuration).toBe('0.3s') - expect(rest.thumbEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1)') - expect(rest.dotDuration.split(',').map(value => value.trim())).toEqual(['0.14s', '0.14s']) - expect(rest.dotEasing).toBe('cubic-bezier(0.23, 1, 0.32, 1), cubic-bezier(0.23, 1, 0.32, 1)') - expect(rest.tickDuration).toBe('0.12s') - await page.mouse.move(rest.center, rest.y) - await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) - const expanded = await readEffortMotion(slider) - expect(expanded.visualWidth).toBeCloseTo(20, 1) - expect(Math.abs(expanded.center - rest.center)).toBeLessThan(1) - const tick = rest.ticks[2]! - await page.mouse.move(tick.center + 7, rest.y) - await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(8, 1) - const hovered = await readEffortMotion(slider) - expect(hovered.ticks.filter(point => point.hovered)).toHaveLength(1) - expect(Math.abs(hovered.ticks[2]!.center - tick.center)).toBeLessThan(1) - await page.mouse.move(tick.center + 9, rest.y) - await expect.poll(async () => (await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) - const release = Promise.withResolvers() - let requests = 0 - const forwarding: Promise[] = [] - const holdSelection = (route: Route): Promise => { - requests++ - const forwarded = (async () => { await release.promise; await route.continue() })() - forwarding.push(forwarded) - return forwarded - } - await page.route('**/api/session/selectModel', holdSelection) - try { - const grabOffset = 6 - await page.mouse.move(rest.center + grabOffset, rest.y) - await page.mouse.down() - await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(9.6, 1) - expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) - const step = (rest.nativeWidth - rest.thumbSize) / 5 - const between = rest.center + step * 0.3 - await page.mouse.move(between + grabOffset, rest.y, { steps: 3 }) - const tracking = await readEffortMotion(slider) - expect(tracking.value).toBe(0) - expect(Math.abs(tracking.center - between)).toBeLessThan(1) - expect(Math.abs(tracking.fillRight - tracking.center)).toBeLessThan(1) - expect(tracking.ticks.every(point => point.visibility === 'visible')).toBe(true) - expect(tracking.thumbDuration).toBe('0s') - expect(tracking.fillDuration).toBe('0s') - expect(Math.abs(tracking.labelCenter - expectedTagCenter(tracking, tracking.center))).toBeLessThan(1) - for (const offset of [-11, -9, 9, 11]) { - await page.mouse.move(tick.center + offset + grabOffset, rest.y) - const snapped = await readEffortMotion(slider) - const expected = Math.abs(offset) < 10 ? tick.center : tick.center + offset - expect(Math.abs(snapped.center - expected)).toBeLessThan(1) - expect(Math.abs(snapped.fillRight - expected)).toBeLessThan(1) - expect(Math.abs(snapped.labelCenter - expectedTagCenter(snapped, expected))).toBeLessThan(1) - expect(snapped.value).toBe(2) - expect(requests).toBe(0) - } - await page.mouse.move(tick.center + grabOffset, rest.y, { steps: 4 }) - const dragging = await readEffortMotion(slider) - expect(dragging.ticks.every(point => !point.hovered)).toBe(true) - expect(dragging.ticks.every(point => Math.abs(point.width - 4) < 0.1)).toBe(true) - await page.mouse.move(rest.right + 24, rest.y, { steps: 8 }) - expect(requests).toBe(0) - await page.mouse.up() - await expect.poll(() => requests).toBe(1) - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('true') - const pending = await assertSettledEffort(slider) - expect(pending.value).toBe(5) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(await slider.evaluate(element => (element as HTMLInputElement).disabled)).toBe(false) - await slider.press('ArrowLeft') - expect((await readEffortMotion(slider)).value).toBe(5) - expect(requests).toBe(1) - release.resolve(undefined) - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - const saved = await assertSettledEffort(slider) - expect(Math.abs(saved.center - pending.center)).toBeLessThan(1) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(requests).toBe(1) - } finally { - release.resolve(undefined) - try { await page.mouse.up() } finally { - try { await page.unroute('**/api/session/selectModel', holdSelection) } finally { await Promise.all(forwarding) } - } - } - await page.mouse.move(rest.ticks[2]!.center, rest.y) - await page.mouse.down() - try { - await expect.poll(() => slider.inputValue()).toBe('2') - const clicked = await readEffortMotion(slider) - expect(clicked.dragging).toBe(false) - expect(clicked.thumbDuration).toBe('0.3s') - expect(clicked.fillDuration).toBe('0.3s') - } finally { - await page.mouse.up() - } - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - expect((await assertSettledEffort(slider)).value).toBe(2) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - expect((await assertSettledEffort(slider)).value).toBe(0) - await page.emulateMedia({ reducedMotion: 'reduce' }) - await slider.press('End') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - const reduced = await assertSettledEffort(slider) - expect(reduced.value).toBe(5) - expect(reduced.thumbDuration).toBe('0s') - expect(reduced.fillDuration).toBe('0s') - expect(reduced.dotDuration).toBe('0s') - expect(reduced.tickDuration).toBe('0s') - await page.mouse.move(reduced.center, reduced.y) - expect((await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) - expect((await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) - await page.mouse.move(reduced.ticks[2]!.center, reduced.y) - expect((await readEffortMotion(slider)).ticks[2]!.width).toBeCloseTo(4, 1) - expect(tripwire.pageErrors).toEqual([]) - } finally { - try { await page.mouse.up() } finally { - try { await page.emulateMedia({ reducedMotion: null }) } finally { - try { - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - } finally { await page.setViewportSize(viewport) } - } - } - } - }) - - it('does not leave thumb or tick hover enlarged after a native touch tap', async () => { - await restoreSelectionAfterTest(page, scaffold) - const touch = await browser.newPage({ - viewport: { width: 390, height: 700 }, locale: ZH_BROWSER_LOCALE, hasTouch: true, isMobile: true, - }) - const consoleWatch = watchConsole(touch) - try { - await touch.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await connectFreshWorkspaceZh(touch, scaffold.workspaceCwd) - await touch.getByRole('button', { name: /^选择模型/ }).click() - await touch.getByRole('menuitem', { name: /^模型/ }).click() - await touch.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - const slider = touch.getByRole('slider', { name: '推理等级', exact: true }) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - const before = await assertSettledEffort(slider) - expect(before.value).toBe(0) - expect(await touch.evaluate(() => matchMedia('(hover: hover) and (pointer: fine)').matches)).toBe(false) - let requests = 0 - const count = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) requests++ - } - touch.on('request', count) - try { - const info = touch.getByRole('button', { name: '默认推理等级说明', exact: true }) - const bounds = await info.boundingBox() - if (bounds === null) throw new Error('Default information is not visible') - await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) - const tooltip = touch.getByRole('tooltip') - await tooltip.waitFor() - expect(await tooltip.textContent()).toBe('未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理') - expect(await slider.inputValue()).toBe('0') - expect(requests).toBe(0) - await touch.touchscreen.tap(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) - await tooltip.waitFor({ state: 'hidden' }) - expect(await info.isVisible()).toBe(true) - await touch.touchscreen.tap(before.right - 10, before.y) - await expect.poll(() => slider.inputValue()).toBe('5') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await assertSettledEffort(slider) - await expect.poll(async () => (await readEffortMotion(slider)).visualWidth).toBeCloseTo(20, 1) - await expect.poll(async () => (await readEffortMotion(slider)).dotWidth).toBeCloseTo(8, 1) - expect(await touch.locator('[data-effort-thumb-scale][data-expanded]').count()).toBe(0) - expect((await readEffortMotion(slider)).ticks.every(tick => !tick.hovered && Math.abs(tick.width - 4) < 0.1)).toBe(true) - expect(requests).toBe(1) - expect(consoleWatch.pageErrors).toEqual([]) - } finally { - touch.off('request', count) - } - } finally { - try { - const trigger = touch.getByRole('button', { name: /^选择模型/ }) - if (await trigger.count() === 1) await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') - } finally { await touch.close() } - } - }) - - it('keeps the compact Spanish caption and default information readable at 390px', async () => { - await restoreSelectionAfterTest(page, scaffold) - const probe = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'es-ES' }) - const consoleWatch = watchConsole(probe) - try { - await probe.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await probe.getByRole('button', { name: 'Agregar espacio de trabajo', exact: true }).click() - const directory = probe.getByRole('dialog', { name: 'Seleccionar carpeta de trabajo', exact: true }) - await directory.getByRole('button', { name: 'Editar ruta', exact: true }).click() - const path = directory.getByRole('textbox', { name: 'Editar ruta', exact: true }) - await path.fill(join(scaffold.workspaceCwd, 'workspace')) - await path.press('Enter') - await directory.getByRole('button', { name: 'Abrir', exact: true }).click() - await probe.locator('[data-composer-input][contenteditable="true"]').waitFor() - await probe.getByRole('button', { name: /^Seleccionar modelo/ }).click() - await probe.getByRole('menuitem', { name: /^modelo/ }).click() - await probe.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - const menu = probe.getByRole('menu', { name: 'Esfuerzo de modelo y razonamiento.', exact: true }) - const slider = menu.getByRole('slider', { name: 'Esfuerzo', exact: true }) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await probe.setViewportSize({ width: 390, height: 700 }) - const label = menu.locator('[data-effort-label]') - const info = menu.getByRole('button', { name: 'Acerca del esfuerzo de razonamiento predeterminado', exact: true }) - await info.waitFor() - const readLayout = () => info.evaluate((button) => { - const tag = button.parentElement! - const text = tag.querySelector('[data-effort-label]')! - const name = text.querySelector('[data-effort-name]')! - const prefix = name.previousElementSibling! - const bounds = button.getBoundingClientRect() - const tagBounds = tag.getBoundingClientRect() - const nameBounds = name.getBoundingClientRect() - const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2) - return { width: bounds.width, height: bounds.height, textWidth: text.clientWidth, - textGap: bounds.left - text.getBoundingClientRect().right, endInset: tagBounds.right - bounds.right, - clipped: prefix.scrollWidth > prefix.clientWidth, ellipsis: getComputedStyle(prefix).textOverflow, - nameText: name.textContent, nameFits: name.scrollWidth <= name.clientWidth, - nameVisible: nameBounds.width > 0 && nameBounds.left >= tagBounds.left && nameBounds.right <= bounds.left, - contained: bounds.left >= tagBounds.left && bounds.right <= tagBounds.right, - reachable: hit?.closest('button') === button } - }) - await expect.poll(readLayout).toMatchObject({ width: 24, height: 24, clipped: false, ellipsis: 'ellipsis', - nameText: 'Predeterminado', nameFits: true, nameVisible: true, contained: true, reachable: true }) - const layout = await readLayout() - expect(layout.textWidth).toBeGreaterThan(0) - expect(layout.textGap).toBeCloseTo(2, 1) - expect(layout.endInset).toBeCloseTo(2, 1) - expect(await label.textContent()).toBe('Esfuerzo: Predeterminado') - await label.hover() - const tooltip = probe.getByRole('tooltip') - expect(await tooltip.count()).toBe(0) - await info.click() - await expect.poll(() => tooltip.allTextContents()).toEqual([ - 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', - ]) - expect(await menu.isVisible()).toBe(true) - expect(await slider.inputValue()).toBe('0') - await probe.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await menu.isVisible()).toBe(true) - await info.focus() - await probe.keyboard.press('Enter') - await tooltip.waitFor() - await probe.keyboard.press('Tab') - await tooltip.waitFor({ state: 'hidden' }) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(await slider.inputValue()).toBe('0') - expect(consoleWatch.pageErrors).toEqual([]) - } finally { - try { - const trigger = probe.getByRole('button', { name: /^Seleccionar modelo/ }) - if (await trigger.count() === 1) await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') - } finally { await probe.close() } - } - }) - - it.each(['success', 'failure'] as const)('keeps Team undimmed and guarded through a pending effort %s', async (outcome) => { - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - const release = Promise.withResolvers() - let selections = 0 - let teamWrites = 0 - const forwarding: Promise[] = [] - const countTeamWrites = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/agentTeams/setEnabled')) teamWrites++ - } - const holdSelection = (route: Route): Promise => { - selections++ - const forwarded = (async () => { - await release.promise - if (outcome === 'success') { await route.continue(); return } - const envelope = route.request().postDataJSON() as { rpcId: string } - await route.fulfill({ json: { type: 'server-response', rpcId: envelope.rpcId, result: { - ok: false, error: { code: 'session/writer-held', message: 'held', details: { sessionId: 'team-pending-fixture' } }, - } } }) - })() - forwarding.push(forwarded) - return forwarded - } - await trigger.click() - await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - await slider.press('Home') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await page.keyboard.down('ArrowRight') - await page.keyboard.down('ArrowRight') - await page.keyboard.down('ArrowRight') - await page.keyboard.up('ArrowRight') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('high') - await page.mouse.move(0, 0) - const menuLocator = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - const teamLocator = page.locator('[data-model-menu-page="agent-team"]') - const menu = await menuLocator.elementHandle() - onTestFinished(async () => { await menu?.dispose() }) - const root = await page.locator('[data-model-menu-root]').elementHandle() - onTestFinished(async () => { await root?.dispose() }) - const team = await teamLocator.elementHandle() - onTestFinished(async () => { await team?.dispose() }) - if (menu === null || root === null || team === null) throw new Error('Missing pending Team controls') - const sample = () => page.evaluate(({ menu, root, team }) => { - const rect = (element: Element) => { - const value = element.getBoundingClientRect() - return { x: value.x, y: value.y, width: value.width, height: value.height } - } - return { - same: { - menu: menu === document.querySelector('[role="menu"][aria-label="模型与推理等级"]'), - root: root === document.querySelector('[data-model-menu-root]'), - team: team === document.querySelector('[data-model-menu-page="agent-team"]'), - }, - connected: menu.isConnected && root.isConnected && team.isConnected, - rect: { menu: rect(menu), root: rect(root), team: rect(team) }, - disabled: (team as HTMLButtonElement).disabled, opacity: getComputedStyle(team).opacity, - ariaDisabled: team.getAttribute('aria-disabled'), ariaBusy: team.getAttribute('aria-busy'), - focus: document.activeElement === team ? 'team' : document.activeElement === root.querySelector('input[type="range"]') ? 'range' : 'other', - } - }, { menu, root, team }) - page.on('request', countTeamWrites) - try { - const before = await sample() - expect(before).toMatchObject({ same: { menu: true, root: true, team: true }, connected: true, - disabled: false, opacity: '1', ariaDisabled: null, ariaBusy: null, focus: 'range' }) - await page.route('**/api/session/selectModel', holdSelection) - await page.keyboard.down('ArrowLeft') - await page.keyboard.down('ArrowLeft') - await page.keyboard.up('ArrowLeft') - await expect.poll(() => selections).toBe(1) - await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBe('true') - const during = await sample() - expect(during).toEqual({ ...before, ariaDisabled: 'true', ariaBusy: 'true' }) - const bounds = during.rect.team - await page.mouse.click(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2) - expect(await menuLocator.getByRole('switch').count()).toBe(0) - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Tab') - expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Enter') - await page.keyboard.press('Space') - expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) - expect(await menuLocator.getByRole('switch').count()).toBe(0) - expect(teamWrites).toBe(0) - expect(selections).toBe(1) - release.resolve(undefined) - await expect.poll(() => teamLocator.getAttribute('aria-busy')).toBeNull() - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - const after = await sample() - expect(after).toEqual({ ...before, focus: 'team' }) - expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) - await page.keyboard.press('Shift+Tab') - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe(outcome === 'success' ? 'low' : 'high') - if (outcome === 'failure') await page.getByRole('alert').waitFor() - expect(selections).toBe(1) - expect(teamWrites).toBe(0) - const lockedOpacity = await team.evaluate((element) => { - const button = element as HTMLButtonElement - try { button.disabled = true; return getComputedStyle(button).opacity } finally { button.disabled = false } - }) - expect(lockedOpacity).toBe('0.5') - await page.keyboard.press('Tab') - expect(await teamLocator.evaluate(element => element === document.activeElement)).toBe(true) - await teamLocator.click() - await page.getByRole('switch', { name: '启用智能体团队协作', exact: true }).waitFor() - expect(teamWrites).toBe(0) - expect(tripwire.pageErrors).toEqual([]) - } finally { - release.resolve(undefined) - page.off('request', countTeamWrites) - try { await page.keyboard.up('ArrowLeft') } finally { - try { await page.unroute('**/api/session/selectModel', holdSelection) } finally { await Promise.all(forwarding) } - } - } - }) - - it('clicks the caption without changing effort and drags outside it to submit Default once', async () => { - const viewport = page.viewportSize()! - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - let writes = 0 - const count = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) writes++ - } - try { - await trigger.click() - await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - await page.setViewportSize({ width: 390, height: 700 }) - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - const caption = page.locator('[data-effort-caption]') - await slider.press('End') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') - expect(await page.locator('[data-effort-tag] svg').count()).toBe(0) - expect(await page.locator('[data-effort-tail-frame], [data-effort-tail]').count()).toBe(0) - page.on('request', count) - await caption.click() - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(await slider.inputValue()).toBe('5') - expect(writes).toBe(0) - const before = await assertSettledEffort(slider) - const bounds = await caption.boundingBox() - if (bounds === null) throw new Error('Effort caption is not visible') - const start = bounds.x + bounds.width / 2 - const end = start - (before.nativeWidth - before.thumbSize) - const y = bounds.y + bounds.height / 2 - await page.mouse.move(start, y) - await page.mouse.down() - try { - const tick = before.ticks[2]! - for (const offset of [-11, -9, 9, 11]) { - await page.mouse.move(start + tick.center - before.center + offset, y) - const snapped = await readEffortMotion(slider) - const expected = Math.abs(offset) < 10 ? tick.center : tick.center + offset - expect(Math.abs(snapped.center - expected)).toBeLessThan(1) - expect(Math.abs(snapped.fillRight - expected)).toBeLessThan(1) - expect(Math.abs(snapped.labelCenter - expectedTagCenter(snapped, expected))).toBeLessThan(1) - expect(snapped.value).toBe(2) - expect(writes).toBe(0) - } - await page.mouse.move(end, y, { steps: 8 }) - await expect.poll(() => slider.inputValue()).toBe('0') - await assertSettledEffort(slider) - expect(await page.evaluate(({ x, y }) => Boolean(document.elementFromPoint(x, y)?.closest('[data-effort-caption]')), - { x: end, y })).toBe(false) - expect(writes).toBe(0) - } finally { - await page.mouse.up() - } - await expect.poll(() => writes).toBe(1) - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBeUndefined() - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - expect(tripwire.pageErrors).toEqual([]) - } finally { - page.off('request', count) - try { await page.mouse.up() } finally { - try { - if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() - } finally { await page.setViewportSize(viewport) } - } - } - }) - - it.each(['Escape', 'capture loss'] as const)('cancels a native caption drag on %s and lets Escape close the root afterward', async (cancel) => { - const trigger = page.getByRole('button', { name: /^选择模型/ }) - await restoreSelectionAfterTest(page, scaffold) - await trigger.click() - await page.getByRole('menuitem', { name: /^模型/ }).click() - await page.getByRole('menuitemradio', { name: 'Acme Lite', exact: true }).click() - const slider = page.getByRole('slider', { name: '推理等级', exact: true }) - await slider.press('End') - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') - const before = await assertSettledEffort(slider) - const caption = page.locator('[data-effort-caption]') - const capture = await caption.evaluateHandle((element) => { - const button = element as HTMLButtonElement - let pointerId: number | null = null - let lost = 0 - const started = (event: PointerEvent) => { pointerId = event.pointerId } - const released = () => { lost++ } - button.addEventListener('pointerdown', started) - button.addEventListener('lostpointercapture', released) - return { - read: () => ({ held: pointerId !== null && button.hasPointerCapture(pointerId), lost }), - release: () => { if (pointerId !== null) button.releasePointerCapture(pointerId) }, - dispose: () => { - button.removeEventListener('pointerdown', started) - button.removeEventListener('lostpointercapture', released) - }, - } - }) - let writes = 0 - const count = (request: Request): void => { - if (new URL(request.url()).pathname.endsWith('/session/selectModel')) writes++ - } - page.on('request', count) - try { - const bounds = await caption.boundingBox() - if (bounds === null) throw new Error('Effort caption is not visible') - const x = bounds.x + bounds.width / 2 - const y = bounds.y + bounds.height / 2 - const end = x - (before.nativeWidth - before.thumbSize) * 0.6 - await page.mouse.move(x, y) - await page.mouse.down() - await page.mouse.move(end, y, { steps: 4 }) - await expect.poll(() => capture.evaluate(probe => probe.read().held)).toBe(true) - await expect.poll(() => slider.inputValue()).toBe('2') - expect(writes).toBe(0) - if (cancel === 'Escape') await page.keyboard.press('Escape') - else await capture.evaluate((probe) => { probe.release() }) - // Moving flushes the browser's pending lostpointercapture, not a synthetic event. - await page.mouse.move(end - 1, y) - await expect.poll(() => capture.evaluate(probe => probe.read())).toEqual({ held: false, lost: 1 }) - expect(await slider.inputValue()).toBe('5') - expect(await trigger.getAttribute('aria-expanded')).toBe('true') - expect(await slider.evaluate(element => element === document.activeElement)).toBe(true) - await page.mouse.up() - expect(writes).toBe(0) - expect(scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBe('max') - await page.keyboard.press('Escape') - await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') - expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) - expect(writes).toBe(0) - expect(tripwire.pageErrors).toEqual([]) - } finally { - page.off('request', count) - try { await page.mouse.up() } finally { - try { await capture.evaluate((probe) => { probe.dispose() }) } finally { await capture.dispose() } - } - } - }) - it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md', 'pointer-menu.expected.md']) }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index db0d0b517c..6033c8f06f 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -120,20 +120,13 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await page.getByRole('menuitem', { name: /模型/ }).click() await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'picker.expected.md'), - await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), webSnapshotMode()) await page.keyboard.press('Escape') - const effort = page.getByRole('group', { name: '推理等级', exact: true }) - await effort.getByRole('slider', { name: '推理等级', exact: true }).waitFor() - expect(await effort.getByRole('button').count()).toBe(1) - expect(await effort.getByRole('button', { name: '推理等级:高', exact: true }).count()).toBe(1) - expect(await effort.getByRole('button', { name: '默认推理等级说明', exact: true }).count()).toBe(0) - const slider = effort.getByRole('slider') - expect(await slider.getAttribute('min')).toBe('0') - expect(await slider.getAttribute('max')).toBe('3') - expect(await slider.getAttribute('aria-valuetext')).toBe('高') - const tag = effort.getByText('推理等级:高', { exact: true }) - expect(await tag.evaluate(element => getComputedStyle(element).fontWeight)).toBe('500') - expect(await tag.evaluate(element => element.tabIndex)).toBe(-1) + await page.getByRole('menuitem', { name: /推理等级/ }).click() + const effortWeights = await page.getByRole('menuitemradio').evaluateAll(rows => rows.map(row => + getComputedStyle(row.querySelector('span span')!).fontWeight, + )) + expect(new Set(effortWeights)).toEqual(new Set(['400'])) expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index 78c45f1bb0..afd89b3c77 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -116,23 +116,20 @@ describe('web e2e: the composer model switch is the default for later sessions', JSON.stringify(await readLabels(menu), null, 2), webSnapshotMode(), ) - await page.keyboard.press('Escape') - await expect.poll(() => cell.evaluate(element => element === document.activeElement)).toBe(true) - expect(await page.getByRole('menuitemradio').count()).toBe(0) } finally { await page.keyboard.press('Escape') await page.keyboard.press('Escape') } }) - it.each(['root', 'model'])('keeps the %s menu aligned as a label grows and shrinks without a window resize', async (pane) => { + it.each(['root', 'model'])('reanchors the %s menu when a label grows and shrinks without a window resize', async (pane) => { const viewport = page.viewportSize()! const trigger = page.getByRole('button', { name: /^选择模型/ }) try { await page.setViewportSize({ width: 390, height: 844 }) await trigger.click() if (pane === 'model') await page.getByRole('menuitem', { name: /^模型/ }).click() - const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: pane === 'model' ? '模型' : '模型与推理等级', exact: true }) + const surface = page.getByRole(pane === 'model' ? 'group' : 'menu', { name: '模型与推理等级', exact: true }) const label = surface.locator('[data-provider-id="origin-gateway"][data-model-id="origin-large"]') await label.waitFor() const original = await surface.boundingBox() @@ -144,9 +141,7 @@ describe('web e2e: the composer model switch is the default for later sessions', badge.textContent = ' — Provider identification badge with a long channel name' node.appendChild(badge) }) - expect(original!.width).toBe(260) - await expect.poll(async () => (await surface.boundingBox())!.width).toBeCloseTo(original!.width) - expect(await surface.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) await expect.poll(async () => { const box = (await surface.boundingBox())! return box.x >= 12 && box.x + box.width <= 378 @@ -277,10 +272,6 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(() => model.evaluate(element => document.activeElement === element)).toBe(true) await observeFocus('Enter model pane') await devicePage.keyboard.press('ArrowDown') - const next = devicePage.getByRole('menuitemradio', { name: 'Acme Large', exact: true }) - await expect.poll(() => next.evaluate(element => document.activeElement === element)).toBe(true) - expect(await devicePage.locator('[role="menuitemradio"][tabindex="0"]').count()).toBe(1) - await devicePage.keyboard.press('Shift+Tab') const search = devicePage.getByRole('searchbox', { name: '搜索模型…' }) expect(await search.evaluate(input => getComputedStyle(input).fontSize)).toBe('16px') await expect.poll(() => search.evaluate(element => document.activeElement === element)).toBe(true) @@ -329,7 +320,7 @@ describe('web e2e: the composer model switch is the default for later sessions', try { await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const menu = page.getByRole('group', { name: '模型', exact: true }) + const menu = page.getByRole('group', { name: '模型与推理等级', exact: true }) const menuSearch = page.getByRole('searchbox', { name: '搜索模型…' }) const order = await readGroups(menu, 'menuitemradio') const sticky = await checkSticky(menu, menu.getByRole('menu', { name: '模型', exact: true })) @@ -377,11 +368,8 @@ describe('web e2e: the composer model switch is the default for later sessions', for (let index = 0; index < 4; index++) await page.keyboard.press('ArrowDown') expect(await page.evaluate(() => document.activeElement?.id)).toBe(currentId) await page.keyboard.press('Enter') - await expect.poll(() => page.getByRole('menuitem', { name: /^模型/ }) - .evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) - expect(await trigger.getAttribute('aria-expanded')).toBe('true') - await page.keyboard.press('Escape') - await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') + await expect.poll(() => trigger.evaluate(node => node === node.ownerDocument.activeElement)).toBe(true) + expect(await trigger.evaluate(node => getComputedStyle(node).boxShadow)).toBe('none') await page.getByRole('button', { name: '添加文件或调用指令', exact: true }).click() await page.getByRole('option', { name: /^模型/ }).click() const commandSearch = page.getByRole('textbox', { name: '筛选选项', exact: true }) @@ -410,12 +398,11 @@ describe('web e2e: the composer model switch is the default for later sessions', platform: document.documentElement.getAttribute('data-platform'), theme: document.body.getAttribute('data-ds-dark-theme'), })) - const surface = page.getByRole('group', { name: '模型', exact: true }) + const surface = page.getByRole('group', { name: '模型与推理等级', exact: true }) const trigger = page.getByRole('button', { name: /^选择模型/ }) const search = page.getByRole('searchbox', { name: '搜索模型…' }) try { - // Keep multiple provider groups scrollable beneath the search field. - await page.setViewportSize({ width: 1680, height: 280 }) + await page.setViewportSize({ width: 1680, height: 220 }) await trigger.click() await page.getByRole('menuitem', { name: /模型/ }).click() const scroller = page.getByRole('menu', { name: '模型', exact: true }) @@ -455,7 +442,6 @@ describe('web e2e: the composer model switch is the default for later sessions', await expect.poll(readPinned).toEqual([true, false, false]) await search.fill('Origin Large') await expect.poll(() => headings.count()).toBe(1) - await expect.poll(() => scroller.evaluate(element => element.scrollHeight <= element.clientHeight)).toBe(true) await expect.poll(readPinned).toEqual([false]) await page.getByRole('button', { name: '清除搜索', exact: true }).click() await expect.poll(readPinned).toEqual([false, false, false]) @@ -548,7 +534,7 @@ describe('web e2e: the composer model switch is the default for later sessions', getComputedStyle(row.querySelector('span span')!).fontWeight, )) expect(new Set(modelWeights)).toEqual(new Set(['400'])) - const headingPalettes = await page.getByRole('group', { name: '模型', exact: true }).evaluate((menu) => { + const headingPalettes = await page.getByRole('group', { name: '模型与推理等级', exact: true }).evaluate((menu) => { const html = menu.ownerDocument.documentElement const body = menu.ownerDocument.body const previousPlatform = html.getAttribute('data-platform') @@ -596,7 +582,7 @@ describe('web e2e: the composer model switch is the default for later sessions', expect(await page.getByRole('group', { name: 'Origin Gateway', exact: true }).count()).toBe(0) await compareOrRefreshGolden( fileURLToPath(new URL('./expected/default-model/search.expected.md', import.meta.url)), - await captureStableAria(page, '[role="group"][aria-label="模型"]', scaffold.workspaceCwd), + await captureStableAria(page, '[role="group"][aria-label="模型与推理等级"]', scaffold.workspaceCwd), webSnapshotMode(), ) const entered = Promise.withResolvers() @@ -614,11 +600,9 @@ describe('web e2e: the composer model switch is the default for later sessions', await page.keyboard.press('Enter') await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false') await expect.poll(() => trigger.textContent()).toContain('Acme Large') - await expect.poll(() => modelCell.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) - expect(await trigger.getAttribute('aria-expanded')).toBe('true') + await expect.poll(() => trigger.evaluate(element => element === element.ownerDocument.activeElement)).toBe(true) + expect(await trigger.evaluate(element => getComputedStyle(element).boxShadow)).toBe('none') expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: START_ROUTE, model: START_MODEL }) - await page.keyboard.press('Escape') - await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') const aria = await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/default-model/background-save.expected.md', import.meta.url)), aria, webSnapshotMode()) } finally { diff --git a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md index 007884ec01..2a5271a974 100644 --- a/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md +++ b/apps/web/tests/expected/declared-reasoning/pointer-menu.expected.md @@ -1,4 +1,4 @@ -- group "模型": +- group "模型与推理等级": - searchbox "搜索模型…" - menu "模型": - group "DeepSeek": diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md index 9818268879..2b18a73716 100644 --- a/apps/web/tests/expected/declared-reasoning/ui.expected.md +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -1,7 +1,5 @@ - menu "模型与推理等级": - - menuitem "模型 Acme Think" - - group "推理等级": - - button "推理等级:默认": 推理等级: 默认 - - button "默认推理等级说明" - - slider "推理等级": "0" - - menuitem "智能体团队协作 关" + - menuitemradio "Default" [checked] + - menuitemradio "Off" + - menuitemradio "High" + - menuitemradio "Max" diff --git a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md index 5b8cc4753a..f256339fcd 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/picker.expected.md @@ -1,4 +1,4 @@ -- group "模型": +- group "模型与推理等级": - menu "模型": - group "DeepSeek": - text: DeepSeek diff --git a/apps/web/tests/expected/default-model/search.expected.md b/apps/web/tests/expected/default-model/search.expected.md index 2379835f56..9b2d48e3c8 100644 --- a/apps/web/tests/expected/default-model/search.expected.md +++ b/apps/web/tests/expected/default-model/search.expected.md @@ -1,4 +1,4 @@ -- group "模型": +- group "模型与推理等级": - searchbox "搜索模型…": ACMLG - button "清除搜索" - menu "模型": diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index 0c41d9e657..7bd5720bc5 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -150,7 +150,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ for (const entry of ['button', 'command'] as const) { const composer = page.locator('[data-composer-input]').first() const surface = entry === 'button' - ? page.getByRole('group', { name: '模型', exact: true }) + ? page.getByRole('group', { name: '模型与推理等级', exact: true }) : page.locator('[aria-label="/model 选项"]') const viewport = entry === 'button' ? surface.getByRole('menu', { name: '模型', exact: true }) @@ -296,7 +296,7 @@ describe.skipIf(webSnapshotMode() === 'record').each([ await page.setViewportSize({ width: 402, height: 874 }) await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /^模型/ }).click() - const panel = page.getByRole('group', { name: '模型', exact: true }) + const panel = page.getByRole('group', { name: '模型与推理等级', exact: true }) for (const height of [874, 500]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) @@ -398,71 +398,66 @@ describe.skipIf(webSnapshotMode() === 'record').each([ } }) - it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without root overflow', async () => { + it.runIf(engine === chromium)('keeps reasoning efforts selectable after zooming with and without list overflow', async () => { const cdp = await page.context().newCDPSession(page) try { - for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 220, scrolls: true }]) { + for (const { height, scrolls } of [{ height: 500, scrolls: false }, { height: 350, scrolls: true }]) { await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) await page.setViewportSize({ width: 402, height }) await page.getByRole('button', { name: /^选择模型/ }).click() + await page.getByRole('menuitem', { name: /^推理等级/ }).click() const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) - const slider = menu.getByRole('slider', { name: '推理等级', exact: true }) - await slider.press('Home') + await menu.getByRole('menuitemradio').first().click() await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().reasoningEffort).toBeUndefined() - await expect.poll(() => slider.getAttribute('aria-busy')).toBe('false') + await page.getByRole('button', { name: /^选择模型/ }).click() + await page.getByRole('menuitem', { name: /^推理等级/ }).click() + const last = menu.getByRole('menuitemradio').last() + await expect.poll(() => last.getAttribute('aria-checked')).toBe('false') await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(2.5) - expect(Number(await slider.getAttribute('max'))).toBeGreaterThanOrEqual(7) - const effort = menu.getByRole('group', { name: '推理等级', exact: true }) - expect(await effort.getByRole('button').count()).toBe(2) - expect(await effort.getByRole('button', { name: '推理等级:默认', exact: true }).count()).toBe(1) - const information = effort.getByRole('button', { name: '默认推理等级说明', exact: true }) - expect(await information.count()).toBe(1) - await expect.poll(() => slider.evaluate((range) => { - const scroller = range.closest('[data-model-menu-root]')! + expect(await menu.getByRole('menuitemradio').count()).toBeGreaterThanOrEqual(7) + await expect.poll(() => last.evaluate((row) => { + const scroller = row.parentElement! scroller.scrollTop = scroller.scrollHeight return { overflow: getComputedStyle(scroller).overflowY, overflows: scroller.scrollHeight > scroller.clientHeight, moved: scroller.scrollTop > 0 } })).toEqual({ overflow: 'auto', overflows: scrolls, moved: scrolls }) - await expect.poll(() => slider.evaluate((range) => { - const rect = range.getBoundingClientRect() - const viewport = range.closest('[data-model-menu-root]')!.getBoundingClientRect() + await expect.poll(() => last.evaluate((row) => { + const rect = row.getBoundingClientRect() + const viewport = row.parentElement!.getBoundingClientRect() return rect.top >= viewport.top - 1 && rect.bottom <= viewport.bottom + 1 })).toBe(true) - const target = await slider.evaluate((range) => { - const rect = range.getBoundingClientRect() + const target = await last.evaluate((row) => { + const rect = row.getBoundingClientRect() const viewport = window.visualViewport! return { - left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.right - 8 - viewport.width / 2)), + left: Math.max(0, Math.min(window.innerWidth - viewport.width, rect.left + rect.width / 2 - viewport.width / 2)), top: Math.max(0, Math.min(window.innerHeight - viewport.height, rect.top + rect.height / 2 - viewport.height / 2)), offsetLeft: viewport.offsetLeft, offsetTop: viewport.offsetTop, } }) - // Pan from the page margin so wheel input cannot scroll the menu instead. + // Pan from the page margin so wheel input cannot scroll the list instead. await cdp.send('Input.synthesizeScrollGesture', { x: 1, y: 1, xDistance: target.offsetLeft - target.left, yDistance: target.offsetTop - target.top, gestureSourceType: 'mouse', speed: 800, }) - await expect.poll(() => slider.evaluate((range) => { - const rect = range.getBoundingClientRect() + await expect.poll(() => last.evaluate((row) => { + const rect = row.getBoundingClientRect() const viewport = window.visualViewport! - const x = rect.right - 8 - viewport.offsetLeft + const x = rect.left + rect.width / 2 - viewport.offsetLeft const y = rect.top + rect.height / 2 - viewport.offsetTop return x >= 0 && x < viewport.width && y >= 0 && y < viewport.height })).toBe(true) - // Native touch must select the last stop without locator auto-scrolling. - const point = await slider.evaluate((range) => { - const rect = range.getBoundingClientRect() + // Dispatch touch without locator auto-scrolling the last row into view. + const point = await last.evaluate((row) => { + const rect = row.getBoundingClientRect() const viewport = window.visualViewport! - return { x: rect.right - 8 - viewport.offsetLeft, + return { x: rect.left + rect.width / 2 - viewport.offsetLeft, y: rect.top + rect.height / 2 - viewport.offsetTop } }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }) await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) - expect(await menu.isVisible()).toBe(true) - await expect.poll(() => slider.getAttribute('aria-valuetext')).toBe('最高') - await page.keyboard.press('Escape') await menu.waitFor({ state: 'detached' }) } } finally { diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 3c606b7624..66bd3cfb1d 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -1191,7 +1191,6 @@ describe('web e2e: plugin manager', () => { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) await teamPage.getByRole('button', { name: /^选择模型/u }).click() - await teamPage.getByRole('menuitem', { name: '智能体团队协作 关', exact: true }).click() const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) await mode.waitFor() expect(await mode.getAttribute('aria-checked')).toBe('false') diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml deleted file mode 100644 index e1bb2c2871..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.i18n.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md -/: - en: ebebf4bc1ef9481b - zh: b4ed29de386704e4 -/model-menu-save-state-is-separate-from-locking: - en: b7b55a3a795a61c2 - zh: 38b482bdfdaa9f36 -/model-menu-save-state-is-separate-from-locking/change: - en: 93b3eede8138d457 - zh: 77059bce0d8bed83 -/model-menu-save-state-is-separate-from-locking/migration: - en: f7ae11e689abe49f - zh: 66d0085592ff8244 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md deleted file mode 100644 index 6368e7e282..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -kind: upgrade-guide -description: "Model-menu extensions must distinguish composer locking from a model selection being saved." ---- - -# Model-menu save state is separate from locking - -English | [中文](guide.zh.md) - -## Change - -Extensions contributing to `conversation.input.model.options` receive a separate `pending` owner prop. Previously, `locked` also became true while a model or reasoning selection was being saved. `locked` now represents only the composer's unavailable state; `pending` represents the save in flight. An extension that guards actions only with `locked` can therefore accept another action during a save. - -## Migration - -1. Derive contribution props from `PropsRuntime<'conversation.input.model.options'>` and read both `locked` and `pending`. Update hand-built test owners to supply `pending`. -2. Reject state-changing or page-opening actions while `locked || pending`. Use native `disabled` for `locked`; represent temporary saving with `aria-disabled` and `aria-busy` while retaining the control's focus and appearance. -3. Verify that changing reasoning effort does not dim or move the extension's row, and that activating it during a held save issues no action. Verify that a genuine composer lock still disables the control. - -See the [model-menu extension reference](../../../../packages/client/ui-model-selection/README.md) for the current owner props. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md deleted file mode 100644 index 50ce57ace1..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/model-menu-pending/guide.zh.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -kind: upgrade-guide -description: "模型菜单扩展需要区分 composer 锁定状态与模型选择的保存状态。" ---- - -# 模型菜单的保存状态与锁定状态分离 - -[English](guide.md) | 中文 - -## 变更 - -向 `conversation.input.model.options` 提供内容的扩展会接收独立的 `pending` owner 属性。此前保存模型或推理等级选择时,`locked` 也会变为 true。现在 `locked` 仅表示 composer 不可用,`pending` 表示正在保存。因此,仅检查 `locked` 的扩展可能在保存期间接受另一个操作。 - -## 迁移 - -1. 从 `PropsRuntime<'conversation.input.model.options'>` 推导扩展 props,并同时读取 `locked` 与 `pending`。手动构造的测试 owner 需要提供 `pending`。 -2. 在 `locked || pending` 时拒绝修改状态或打开子页的操作。对 `locked` 使用原生 `disabled`;对临时保存状态使用 `aria-disabled` 与 `aria-busy`,同时保留控件的焦点与外观。 -3. 验证切换推理等级不会使扩展行变淡或位移,并确认在暂停响应的保存期间激活该行不会产生操作。另行验证 composer 真正锁定时仍禁用控件。 - -当前 owner 属性见[模型菜单扩展参考](../../../../packages/client/ui-model-selection/README.zh.md)。 diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index e7ab86a3a4..87dafe0190 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: 5485135ed71fbbf5 - zh: 37112168c8785012 + en: 4b66566b2e676572 + zh: 2cb4e9d8cff3bcca /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index f94c571c56..115987b4b6 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,9 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The settings switch combines model-menu pending state with its own save state through the [Switch pending state](../ui-primitives/README.md#component-catalog). Either pending save blocks another Team change while keeping keyboard focus; it does not bypass the disable confirmation. - -During a model or reasoning-effort save, the root Team row keeps its opacity and focus and refuses activation. It reports `aria-disabled` and `aria-busy` without setting native `disabled`. An actual composer lock still sets native `disabled` and retains the disabled appearance. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows only the saved On/Off state and opens the page without changing the selection; the settings page places the switch above the full explanation. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The settings page shows the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. Its entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index e906b386f7..8173e4af02 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,9 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。设置页将模型菜单的 pending 状态与自身保存状态合并为 [Switch 的 pending 状态](../ui-primitives/README.zh.md#component-catalog)。任一保存进行中都会阻止再次切换 Team,同时保留键盘焦点;这不会绕过关闭确认。 - -模型或推理等级保存期间,一级 Team 行保持原有不透明度和焦点,并拒绝激活。它设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`。输入区真正锁定时,仍设置原生 `disabled` 并保留禁用外观。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index a1b4b52dd6..a4a9bb09b2 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -36,7 +36,7 @@ export function TeamModeToggle(props: TeamModeToggleProps) { return } -function RootTeamModeSummary({ useProjection, locked, pending, openPage, t }: TeamModeToggleProps) { +function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { const mode = useProjection('agentTeam') if (mode === undefined) return null return ( @@ -46,9 +46,7 @@ function RootTeamModeSummary({ useProjection, locked, pending, openPage, t }: Te className={css.summary} data-model-menu-page="agent-team" disabled={locked} - aria-disabled={locked || pending || undefined} - aria-busy={pending || undefined} - onClick={() => { if (!locked && !pending) openPage({ key: 'agent-team', title: t('command.title') }) }} + onClick={() => { if (!locked) openPage({ key: 'agent-team', title: t('command.title') }) }} > {t('command.title')} {t(mode.enabled ? 'mode.on' : 'mode.off')} @@ -71,14 +69,14 @@ export function TeamModePage(props: TeamModePageProps) { /** Read and change the selection only for root Sessions. */ function RootTeamModePage({ - useProjection, locked, pending: modelPending, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, + useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, }: TeamModePageProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (locked || modelPending || pending || modelSelection === undefined) return + if (locked || pending || modelSelection === undefined) return if (!enabled && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() @@ -95,8 +93,7 @@ function RootTeamModePage({
{t('mode.label')} - +

{t('mode.description')}

diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 82029d9af2..91cd8fcbff 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -19,7 +19,7 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, pending: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), + locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), } as TestProps @@ -56,82 +56,6 @@ it('keeps summary state projection-owned and blocks navigation while locked', () expect(lockedInput.openPage).not.toHaveBeenCalled() }) -it.each([false, true])('keeps the summary node focused and natively enabled during a model save (enabled: %s)', (enabled) => { - const input = props(enabled) - const view = render() - const summary = screen.getByRole('menuitem') - summary.focus() - view.rerender() - expect(screen.getByRole('menuitem')).toBe(summary) - expect(summary.isConnected).toBe(true) - expect(summary.hasAttribute('disabled')).toBe(false) - expect(summary.getAttribute('aria-disabled')).toBe('true') - expect(summary.getAttribute('aria-busy')).toBe('true') - expect(document.activeElement).toBe(summary) - fireEvent.click(summary) - expect(input.openPage).not.toHaveBeenCalled() - expect(input.selectTeamMode).not.toHaveBeenCalled() - view.rerender() - expect(screen.getByRole('menuitem')).toBe(summary) - expect(summary.getAttribute('aria-disabled')).toBeNull() - expect(summary.getAttribute('aria-busy')).toBeNull() - expect(document.activeElement).toBe(summary) - fireEvent.click(summary) - expect(input.openPage).toHaveBeenCalledOnce() -}) - -it.each([false, true])('blocks Team writes and confirmation without dropping switch focus during a model save (enabled: %s)', (enabled) => { - const input = props(enabled, undefined, undefined, true) - const view = render() - const toggle = screen.getByRole('switch') - toggle.focus() - view.rerender() - expect(screen.getByRole('switch')).toBe(toggle) - expect(toggle.hasAttribute('disabled')).toBe(false) - expect(toggle.getAttribute('aria-disabled')).toBe('true') - expect(toggle.getAttribute('aria-busy')).toBe('true') - fireEvent.click(toggle) - expect(input.selectTeamMode).not.toHaveBeenCalled() - expect(input.requestDisableConfirmation).not.toHaveBeenCalled() - expect(input.dismiss).not.toHaveBeenCalled() - expect(document.activeElement).toBe(toggle) - view.rerender() - expect(toggle.getAttribute('aria-disabled')).toBeNull() - expect(toggle.getAttribute('aria-busy')).toBeNull() - expect(document.activeElement).toBe(toggle) -}) - -it.each([TeamModeToggle, TeamModePage])('keeps a genuine lock natively disabled while a model write is pending', (Component) => { - const input = props(false) - render() - const control = screen.queryByRole('menuitem') ?? screen.getByRole('switch') - expect(control.hasAttribute('disabled')).toBe(true) - expect(control.getAttribute('aria-disabled')).toBe('true') - expect(control.getAttribute('aria-busy')).toBe('true') - fireEvent.click(control) - expect(input.openPage).not.toHaveBeenCalled() - expect(input.selectTeamMode).not.toHaveBeenCalled() -}) - -it('keeps model pending protection after the Team write settles', async () => { - const pending = Promise.withResolvers() - onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) - const input = props(false, vi.fn(() => pending.promise)) - const view = render() - const toggle = screen.getByRole('switch') - toggle.focus() - fireEvent.click(toggle) - view.rerender() - await act(async () => { pending.resolve(null) }) - expect(toggle.getAttribute('aria-busy')).toBe('true') - expect(toggle.hasAttribute('disabled')).toBe(false) - fireEvent.click(toggle) - expect(input.selectTeamMode).toHaveBeenCalledTimes(1) - view.rerender() - expect(toggle.getAttribute('aria-busy')).toBeNull() - expect(document.activeElement).toBe(toggle) -}) - it('allows reading settings from the summary while model history loads', () => { const input = props(false, undefined, undefined, 'loading') render() @@ -140,7 +64,7 @@ it('allows reading settings from the summary while model history loads', () => { expect(input.selectTeamMode).not.toHaveBeenCalled() }) -it.each([false, true])('retains focus and blocks repeated writes while waiting for persisted mode (enabled: %s)', async (enabled) => { +it.each([false, true])('blocks repeated writes while waiting for persisted mode (enabled: %s)', async (enabled) => { const pending = Promise.withResolvers() onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) const select = vi.fn(() => pending.promise) @@ -150,20 +74,15 @@ it.each([false, true])('retains focus and blocks repeated writes while waiting f fireEvent.click(toggle) expect(select).toHaveBeenCalledExactlyOnceWith(!enabled) expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) - expect(toggle.hasAttribute('disabled')).toBe(false) - expect(toggle.getAttribute('aria-disabled')).toBe('true') - expect(toggle.getAttribute('aria-busy')).toBe('true') - expect(document.activeElement).toBe(toggle) + expect(toggle.hasAttribute('disabled')).toBe(true) fireEvent.click(toggle) fireEvent.click(toggle) expect(select).toHaveBeenCalledTimes(1) await act(async () => { pending.resolve(null) }) expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) - expect(toggle.getAttribute('aria-disabled')).toBeNull() - expect(toggle.getAttribute('aria-busy')).toBeNull() + expect(toggle.hasAttribute('disabled')).toBe(false) view.rerender() expect(toggle.getAttribute('aria-checked')).toBe(String(!enabled)) - expect(document.activeElement).toBe(toggle) }) it.each(['returned', 'error', 'string'])('reports rejected mode writes through the menu host (%s)', async (failure) => { @@ -176,8 +95,6 @@ it.each(['returned', 'error', 'string'])('reports rejected mode writes through t const toggle = screen.getByRole('switch') toggle.focus() await act(async () => { fireEvent.click(toggle) }) - expect(document.activeElement).toBe(toggle) - expect(toggle.getAttribute('aria-busy')).toBeNull() expect(input.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 7fe28852de..f708304789 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 166aabe003e07a79 - zh: 09fbb4cc7027064d + en: 0e2230da6a2214a1 + zh: 0452e7556c9175f2 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: 559791a4c5b1dbc6 - zh: 82a50b670d8e54ab + en: cead8d55a9508a8f + zh: d1ef63a880cbec55 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 8da3af8ae98adbb3 zh: b411b32d6b2b9e04 @@ -27,11 +27,11 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 7f5e8e8358c98376 - zh: 5df89a5a0934c885 + en: 39d2e58b779bb4c2 + zh: df6c74db7a18d338 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: - en: feab134e75f5b2f7 - zh: 66bd58568f58ed4f + en: c1d14a925c92950f + zh: f80f8169bc283c60 /deepseek-ai-dsh-client-ui-model-selection/further-exploration: en: 14acd4692e923480 zh: ff89aed852aa0da8 @@ -42,8 +42,8 @@ en: 68e54c00412a40d1 zh: 0ac96f57fd194d96 /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work: - en: 01a55381300a60c5 - zh: 3561ca742b9272ca + en: 7003aff3aa57e40c + zh: 450d88a5e9332f05 /deepseek-ai-dsh-client-ui-model-selection/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 02962fb037..2957526cb9 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -29,30 +29,22 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses DeepSeek account and API-key routes appear as separate provider groups, each exposing the same configured model catalog. -When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape closes it. Tab and Shift+Tab traverse its controls and leave the menu at either end. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. +When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. -Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. In the root menu, `↑`/`↓` move between the model row, reasoning slider, and contributed options. A focused slider keeps arrow, Home, and End keys for its own value; Tab and Shift+Tab traverse the model row, draggable tag, Default information button when present, native slider, and contributed controls. In model search, arrows move the highlight and Enter selects it. Tab and Shift+Tab traverse search, its clear button, and the highlighted model without selecting; focused buttons activate with Enter or Space. Detail pages have no visible title or Back button. Escape returns to the root and restores the invoking row's focus; pressing Escape again closes the menu and focuses its trigger. Returning from the model list with Escape or after a successful model selection restores focus to the root model row without its grey background. Subsequent pointer movement or Tab navigation restores normal hover and focus styling. Phones and tablets leave model search unfocused until the user taps it or uses keyboard navigation. Removing a model or provider, including sign-out, preserves the saved route and effort without displaying their IDs; restoring its catalog entry restores its name and caption. +Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown on desktop devices; otherwise it focuses the current model or effort row, or the first enabled row when none is selected. Going back focuses the cell that opened the pane. Phones and tablets leave search unfocused until the user taps it or uses keyboard navigation. The composer shows the catalog name while the selected model is available. Removing a model or provider, including account sign-out, preserves the stored provider, model, and reasoning effort without displaying their IDs. Restoring the catalog entry restores its name and effort caption. -Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes it. Selecting a model returns to the root menu and its model row unless the user has navigated to another page or control while saving; effort-save completion does not move focus or change the current menu page. While a model selection is pending, the trigger and chosen model-list row show spinners. Pending selections retain their target value and block duplicate submissions without a loading cursor; effort-save completion preserves any page or focus the user navigated to while saving. A rejected selection leaves the menu and previous selection available for retry. Settings detail pages retain native Tab traversal. +Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes the menu and returns focus there. Root rows and the search-clear button show the same fill for keyboard focus and hover, without a native outline. Selecting a model or effort returns focus to the trigger without a focus ring; leaving the trigger or reopening the menu restores its normal focus indication. While a selection from either entry is pending, focus stays on the trigger, the trigger shows a spinner in place of its chevron, and each row whose value the selection carries shows one in place of its check; a rejected selection leaves the menu open. Tab returns to model search with the current model highlighted when search is shown, otherwise to the current row. ### Model and effort -The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups. In the composer menu, Enter selects the result and Tab moves focus without selecting it; the `/model` popup retains its command-menu keyboard behavior. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. +The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups; Enter or Tab selects it. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. -Model names use weight 400 (regular); the current effort tag uses weight 500. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. +Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. -Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the reasoning slider absent; there is no arbitrary effort input. +Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. The composer replaces the model and effort text with the Models icon when the expanded controls cannot share one line, and restores the text when space permits. The full selection remains available in the trigger's accessible name, tooltip, and menu. -The 260px-wide root menu places the centered model name and chevron above an effort tag and a native slider with discrete stops for the exact model's ordered reasoning choices. The tag follows the handle horizontally and stays inside the menu at either end. The tag has no arrow or connector. It displays the complete localized label, such as “Effort: High”, with a tooltip when clipped. Clicking or keyboard-activating the tag focuses the native slider without changing its value or opening another menu; dragging the tag adjusts the level. The tag text is not selectable, and its focusable button is separate from the Default information button. Drags on either surface preview locally and submit once on release; keyboard adjustments submit on key release. Escape during adjustment cancels the preview, and changing models discards any unfinished gesture. - -The tag shows “Effort: Default” for the localized “Default” stop, which appears only when the adapter has no configured default effort. It submits no explicit effort: model and configuration defaults apply, which does not mean reasoning is off. Only this omitted-effort choice shows a keyboard-focusable information button beside the tag; a provider level with the explicit ID `default` does not. A single supported stop is readable but not draggable. No arbitrary token budget is entered here. - -Standard levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`) use localized names only when the provider's name matches its ID ignoring case. Custom names and unknown levels remain unchanged; for example, `high` named “Thorough mode” keeps that name. This changes display text only, not submitted or persisted IDs. - -The visual thumb and filled track follow pointer movement during a drag, with visual snapping within 10px of a stop; the tag follows within its layout bounds. Effort choices remain discrete. Hovering the thumb with a fine mouse pointer or pressing the slider enlarges only the blue center of the visual thumb; the white disc and hit area keep their size. Mouse hover enlarges only the nearby tick, not neighboring ticks, and is inactive during dragging or saving. Touch interaction leaves no hover highlight. Reduced motion disables position transitions and center and tick enlargement. - ### Model label extensions `conversation.input.model.label` is a session-scoped, inline `single` slot for the composer trigger (`placement: 'trigger'`), the root menu's current value (`'menu'`), and each model option (`'option'`). Its owner props provide `provider: { id, name }`, the exact catalog `model`, `placement`, and `selected`. Provider names are localized display names; match channels by `provider.id`, and identify a model by the provider/model ID pair. Connection URLs and credentials are not passed to the slot. @@ -69,18 +61,18 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends root options below model and reasoning controls. Its owner props expose `locked`, required `pending: boolean`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. A root option marks its button with `data-model-menu-page` equal to its registration key and opens that key in `conversation.input.model.page`, a session-scoped keyed slot. The menu owner supplies scrolling, Escape navigation, focus return, and an accessible page name from `title`, without a visible title or Back button; the page receives `locked`, `pending`, `reportFailure`, and `dismiss`, while its owning plugin retains all settings and confirmation logic. Both slots distinguish an actual composer lock (`locked`) from a model or effort save in flight (`pending`); saving alone does not set `locked`. `dismiss()` closes the entire menu and focuses its trigger before another overlay opens. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Its owner supplies `locked`, `reportFailure(message)`, `dismiss()`, and `openPage({ key, title })`. Register detail content in the session-scoped keyed `conversation.input.model.page` slot and mark the invoking button with `data-model-menu-page` equal to that key. The menu uses `title` as the accessible page name, focuses its first enabled switch on entry, and restores the invoking row on Escape; Tab closes a detail page without activating its switch. Detail pages receive `locked`, `reportFailure`, and `dismiss`; the owning plugin retains settings and confirmation logic. `locked` includes a model or effort save in flight. `dismiss()` closes the menu and focuses its trigger before another overlay opens. ----- ## Understand the implementation +Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. Model and reasoning-effort lists scroll vertically within the panel height limit. +
Implementation internals — click to expand -Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal and CSS Anchor Positioning, which requires browser support for `anchor-name`, `position-anchor`, and `anchor()`. The trigger and menu share a unique anchor name. CSS prefers the position above the trigger with right edges aligned and an 8px gap, and keeps the menu within the layout viewport's 12px insets and desktop frame clearance. The trigger gap is preserved when desktop page zoom reflows the sticky composer. No JavaScript reads the trigger rectangle or tracks viewport changes for this placement. Pinch zoom scales the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. The root controls, model list, and settings pages have their own scroll area inside the panel height limit. - The composer `ModelSelect` and `/model` option builder share [provider ordering](src/client/provider-order.ts), while both searches use `rankByName` within each provider. The command supplies optional groups and `searchMode: 'fuzzy-label'` through the [popupSelect API](../ui-commands/README.md#use-this-package); both entries use `MenuGroup` and rebuild its sticky observer when the rendered groups change. The command popup fills the composer overlay, while the button retains its compact menu. Two entries over ONE per-session directory owned by `ModelDirectoryResolver` (`ctx.modelDirectories`): the `/model` popupSelect contribution (registered through `ctx.commandUi`) and the composer's named `conversation.input.model` seat both load the session's available directory through `session.models` and submit through `session.selectModel` via the same `ModelDirectory` instance, so a switch made in either entry is what the other shows next. Directory loads and selections share a generation counter so an older response never overwrites a newer one. The directory publishes the latest submitted selection as `pending` until it settles or a connection reset invalidates it; a connection reset drops every resident projection and repulls the Host-restored selection before display. Directories are per-session, resolved lazily, and disposed with the session scope; addressed subagent sessions expose neither entry. Every resident directory refetches directly on forwarded `llm/adapters-updated`, `llm/models-updated`, `settings/document-updated`, and credential update events. @@ -118,7 +110,7 @@ These limits define the current model surface. They are current package constrai - **No create-time or addressed-subagent selection** — both entries require an existing ordinary session's Agent; there is no draft-phase model choice to fold into session creation, and subagent continuation deliberately exposes no independent model-selection contract. - **Directory names are presentation-only** — selection and persistence use provider/model/effort ids; a provider whose catalog or exact-model metadata lookup fails lists as an unselectable failure row until reload. -- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the reasoning slider absent. +- **No arbitrary effort input** — the composer offers only the exact model's adapter-advertised levels; an adapter without reasoning metadata leaves the Effort row absent. - **Badges label the composer seat only** — `/model` popup rows, the trigger's accessible name, and its tooltip keep the plain catalog name. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index afd848c659..e83125c996 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -29,30 +29,22 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示相同的已配置模型目录。 -未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 关闭列表。Tab 和 Shift+Tab 遍历列表内的控件,到达两端时离开菜单。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” +未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。根菜单内,`↑`/`↓` 在模型行、推理滑块和扩展选项间移动。滑块聚焦后,方向键、Home 和 End 用于调整自身档位;Tab 和 Shift+Tab 依次经过模型行、可拖动标签、默认信息按钮(如有)、原生滑块和扩展控件。模型搜索框内,方向键移动高亮,Enter 选定。Tab 和 Shift+Tab 在搜索框、清除按钮与高亮模型之间移动,不提交选择;按钮聚焦后用 Enter 或 Space 激活。二级页不显示标题或返回按钮。Escape 返回一级并恢复入口行焦点,再按一次则关闭菜单并聚焦触发器。从模型列表按 Escape 返回或成功选定模型后,焦点回到一级模型行,但不显示灰色底色。随后再次移动鼠标或使用 Tab 导航时,恢复正常的悬停与焦点样式。手机和平板在用户主动点按搜索框或使用键盘导航前,不聚焦搜索框。模型或提供方被删除时(包括账号退登),保留已保存的路由与推理强度,但不展示其 ID;目录条目恢复后重新显示名称与强度。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时,桌面设备在显示模型搜索框时聚焦搜索框;其他情况聚焦当前模型或推理强度行,没有选中项时聚焦首个可用行。返回时聚焦打开该面板的格子。手机和平板在用户主动点按搜索框或使用键盘导航前,不会聚焦搜索框。所选模型可用时,composer 显示目录中的模型名称。模型或提供方被删除时(包括账号退登),保留已保存的提供方、模型和推理强度,但不展示其 ID。目录条目恢复后重新显示名称和推理强度。 -鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击该按钮会关闭菜单。选定模型后回到一级菜单并聚焦模型行;若用户在保存期间已导航至其他页面或控件,则保留该位置。推理等级保存完成时不搬移焦点,也不切换当前菜单页面。等待模型选择结果时,触发器和模型列表待选行显示加载图标。选择保存期间保留目标值,阻止重复提交,但不显示加载鼠标;推理等级保存完成后,保留用户在保存期间主动导航到的页面与焦点。选择失败后保留菜单及原选择,允许重试。设置二级页保留原生 Tab 焦点遍历。 +鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击触发按钮会关闭菜单并把焦点还给它。根菜单行和搜索清除按钮的键盘焦点与悬停使用相同底色,不显示原生焦点轮廓。选定模型或推理等级后,焦点返回触发按钮但不显示焦点环;焦点离开按钮或重新打开菜单后恢复正常焦点提示。等待任一入口发起的选择结果时,焦点停在触发按钮,触发按钮以加载图标代替下拉箭头,该选择包含的值所在行以加载图标代替勾选标记;选择被拒绝后菜单保持打开。显示模型搜索框时,Tab 返回搜索框并高亮当前模型,否则返回当前选中行。 ### 模型与推理强度 -按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框。composer 菜单用 Enter 选定高亮项,Tab 只移动焦点而不选定;`/model` 弹窗保留命令菜单的键盘行为。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 +按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框;Enter 或 Tab 选定高亮项。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 -composer 菜单中的模型名称使用 400(regular)字重;当前推理等级标签使用 500 字重。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 +composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 -两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示推理滑块;不存在任意推理强度输入。 +两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 展开的控件无法排在同一行时,composer 将模型与推理强度文字替换为模型图标;空间足够后恢复文字。触发器的无障碍名称、提示和菜单仍提供完整选择。 -260px 宽的一级菜单上方显示居中的模型名与箭头;下方显示推理等级标签与原生滑块,滑块以离散刻度表示当前模型公布的有序推理选项。标签横向跟随滑块圆点,在两端保持于菜单内。标签不带箭头或连接线。标签显示完整本地化文案,例如“推理等级:高”,被截断时提供悬停提示。点击或键盘激活标签只聚焦原生滑块,不改变值,也不打开其他菜单;拖动标签可调整档位。标签文字不可选中,其可聚焦按钮与默认信息按钮相互独立。拖动任一表面时只在本地预览,松手后提交一次;键盘调整在松键时提交。调整过程中按 Escape 取消预览,切换模型会丢弃尚未结束的手势。 - -仅当适配器未配置默认强度时出现本地化的“默认”刻度,标签显示“推理等级:默认”。它不提交显式推理等级,而是使用模型与配置的默认设置,不代表关闭推理。仅此省略等级的选择在标签旁显示可通过键盘聚焦的信息按钮;提供方显式 ID 为 `default` 的档位不显示该说明按钮。只有一个支持档位时仍可阅读,但不能拖动。此处不输入任意 token 预算。 - -标准档位(`off`、`minimal`、`low`、`medium`、`high`、`xhigh` 和 `max`)仅在提供方名称与 ID 忽略大小写后相同时使用本地化名称。自定义名称与未知档位保持原文,例如名称为“Thorough mode”的 `high` 保留该名称。此规则仅改变显示文字,不改变提交或持久化的 ID。 - -拖动期间,可见滑块圆点与轨道填充跟随指针移动,在刻度 10px 范围内显示吸附效果;标签在布局边界内跟随。推理等级仍按离散档位选择。精细鼠标指针悬停圆点或按下滑块时,只放大可见圆点中间的蓝色部分;白色外圈和命中区域尺寸不变。鼠标悬停仅放大命中的单个刻度,不放大相邻刻度;拖动或保存期间不启用刻度悬停效果。触摸交互不留下悬停高亮。减少动态效果设置会关闭位置过渡以及蓝点和刻度的放大效果。 - ### 模型名称扩展 `conversation.input.model.label` 是会话作用域的内联 `single` slot,覆盖 composer 触发按钮(`placement: 'trigger'`)、根菜单中的当前值(`'menu'`)和各模型选项(`'option'`)。owner props 提供 `provider: { id, name }`、准确的目录 `model`、`placement` 和 `selected`。提供方名称是本地化显示名称;按 `provider.id` 匹配渠道,按提供方与模型 ID 的组合识别模型。slot 不接收连接 URL 或凭据。 @@ -69,18 +61,18 @@ composer 菜单中的模型名称使用 400(regular)字重;当前推理等 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理控件下方追加一级选项。Owner props 提供 `locked`、必填的 `pending: boolean`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。一级选项在按钮上设置与注册 key 相同的 `data-model-menu-page`,并打开会话作用域 keyed slot `conversation.input.model.page` 中的对应 key。菜单 owner 负责滚动、Escape 导航、焦点返回,以及由 `title` 提供的页面无障碍名称,不显示标题或返回按钮;二级页接收 `locked`、`pending`、`reportFailure` 与 `dismiss`,所属插件保留全部设置与确认业务逻辑。两个 slot 均区分输入区的真实锁定(`locked`)与模型或推理等级正在保存(`pending`);仅保存中不会将 `locked` 设为 true。`dismiss()` 关闭整个菜单并聚焦触发按钮,随后可打开其他浮层。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。Owner 提供 `locked`、`reportFailure(message)`、`dismiss()` 和 `openPage({ key, title })`。二级内容注册到会话级 keyed slot `conversation.input.model.page`;入口按钮的 `data-model-menu-page` 与注册键一致。菜单以 `title` 作为页面无障碍名称,进入时聚焦首个可用开关,Escape 返回入口行;Tab 关闭二级页而不激活开关。二级页收到 `locked`、`reportFailure` 和 `dismiss`,设置与确认逻辑仍由贡献插件负责。`locked` 包含模型或推理等级保存中状态。`dismiss()` 关闭菜单并同步聚焦触发按钮,供贡献方随后打开其他浮层。 ----- ## 理解实现 +菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。模型与推理等级列表在面板高度限制内纵向滚动。 +
实现细节——点击展开 -菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位及 CSS Anchor Positioning,要求浏览器支持 `anchor-name`、`position-anchor` 和 `anchor()`。触发按钮和菜单共享唯一的锚点名称。CSS 优先将菜单放在按钮上方,右边缘对齐、间距为 8px,并将菜单限制在布局视口的 12px 内边距及桌面窗口边框间距内。桌面页面缩放导致 sticky 输入区重新布局时,面板仍保持与触发器的间距。定位不通过 JavaScript 读取按钮矩形或追踪视口变化。双指缩放时菜单随页面一起缩放,可以超出视觉视口,包括键盘打开时。模型名称超出面板宽度时以省略号截断,角标保持可见。一级控件、模型列表和设置二级页均在面板高度限制内使用各自的滚动区域。 - composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](src/client/provider-order.ts),两个搜索框均在每个提供方内使用 `rankByName`。命令通过 [popupSelect API](../ui-commands/README.zh.md#use-this-package) 提供可选分组与 `searchMode: 'fuzzy-label'`;两个入口均使用 `MenuGroup`,并在渲染分组变化时重建其吸顶观察器。命令弹窗撑满 composer 浮层,按钮则保留紧凑菜单。 两个入口共用一份由 `ModelDirectoryResolver`(`ctx.modelDirectories`)持有的会话级目录:`/model` popupSelect 贡献项(经 `ctx.commandUi` 注册)与 composer 的具名 `conversation.input.model` 位都经 `session.models` 加载会话的可用目录、经 `session.selectModel` 通过同一个 `ModelDirectory` 实例提交,因此任一入口所做的切换正是另一个入口接下来显示的。目录加载与选择共享一个代次计数器,旧响应不会覆盖新结果。目录把最近一次提交的选择发布为 `pending`,直到它完成或被连接重置作废;连接重置丢弃所有常驻投影,并在显示前重新拉取 Host 恢复的选择。目录按会话惰性解析,随会话作用域一并 dispose(资源释放);已寻址 subagent 会话不公开任一入口。每份常驻目录都会直接在转发的 `llm/adapters-updated`、`llm/models-updated`、`settings/document-updated` 与凭据更新事件上重拉。 @@ -118,7 +110,7 @@ composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](s - **无创建期或已寻址 subagent 选择**——两个入口都要求既有普通会话的 agent(智能体);没有可纳入会话创建的草稿阶段模型选择,subagent 继续执行也有意不公开独立的模型选择约定。 - **目录名仅供呈现**——选择与持久化使用提供方/模型/推理强度 id;目录查询或确切模型元数据查询失败的提供方以不可选失败行列出,重新加载前保持原样。 -- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示推理滑块。 +- **不能任意输入推理强度**——composer 仅提供确切模型由适配器公布的推理强度;适配器没有推理元数据时不显示 Effort 行。 - **角标只出现在 composer 模型位**——`/model` 弹窗各行、触发按钮的无障碍名称及其提示仍只显示目录名称。 diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.module.css b/packages/client/ui-model-selection/src/client/EffortSlider.module.css deleted file mode 100644 index 872b22df55..0000000000 --- a/packages/client/ui-model-selection/src/client/EffortSlider.module.css +++ /dev/null @@ -1,323 +0,0 @@ -@property --dsh-effort-position { - syntax: ''; - inherits: true; - initial-value: 0; -} - -.root { - display: contents; - --effort-thumb-size: 20px; - --effort-track-size: 16px; -} - -.heading, -.rail { - --dsh-effort-position: var(--effort-visual-position); - transition: --dsh-effort-position 300ms cubic-bezier(.23, 1, .32, 1); -} - -.heading { - grid-row: 2; - container-type: inline-size; - position: relative; - z-index: 1; - pointer-events: none; - height: 28px; - margin: 8px 8px 0; -} - -.value { - position: absolute; - pointer-events: auto; - top: 0; - left: 0; - width: max-content; - /* Percentages use the pill width; cqw uses the rail-aligned container. */ - translate: clamp(0px, calc(var(--effort-thumb-size) / 2 + (100cqw - var(--effort-thumb-size)) * var(--dsh-effort-position) - 50%), calc(100cqw - 100%)) 0; - display: inline-flex; - align-items: center; - box-sizing: border-box; - max-width: 100%; - height: 28px; - color: var(--dsw-alias-state-business-primary); - font-size: 13px; - line-height: 18px; - font-weight: 500; - text-align: center; - white-space: nowrap; - cursor: default; - -webkit-user-select: none; - user-select: none; -} - -.value:has(.infoButton) .caption { - padding-inline-end: 27px; -} - -.caption { - display: flex; - flex: 1 1 auto; - align-items: center; - box-sizing: border-box; - min-width: 0; - width: 100%; - height: 28px; - padding: 1px 8px; - border: 1px solid color-mix(in srgb, var(--dsw-alias-state-business-primary) 45%, transparent); - border-radius: 999px; - corner-shape: round; - background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, var(--dsw-alias-bg-module-platform)); - color: inherit; - font: inherit; - white-space: inherit; - cursor: grab; - touch-action: pan-y; - -webkit-user-select: none; - user-select: none; -} - -.caption:focus-visible { - outline: 2px solid currentColor; - outline-offset: 1px; -} - -.caption[aria-disabled='true'] { - cursor: default; -} - -.heading[data-dragging] .caption { - cursor: grabbing; -} - -.valueLabel { - display: flex; - gap: 2px; - min-width: 0; - overflow: hidden; - -webkit-user-select: none; - user-select: none; -} - -.valuePrefix { - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; -} - -.valueName { - flex: 0 0 auto; - max-width: calc(100% - 2px); - overflow: hidden; - text-overflow: ellipsis; -} - -.infoButton { - position: absolute; - top: 2px; - right: 2px; - z-index: 1; - display: inline-flex; - align-items: center; - justify-content: center; - width: 24px; - height: 24px; - padding: 0; - border: 0; - border-radius: 50%; - corner-shape: round; - background: transparent; - color: inherit; - cursor: pointer; -} - -.infoButton:focus-visible { - outline: 2px solid currentColor; - outline-offset: -2px; -} - -@media (hover: hover) { - .infoButton:hover { - background: var(--dsw-alias-interactive-bg-hover); - } -} - -.rail { - grid-row: 3; - position: relative; - margin: -2px 8px 0; -} - -.track { - position: absolute; - inset-inline: 0; - top: 50%; - height: var(--effort-track-size); - transform: translateY(-50%); - border-radius: 999px; - corner-shape: round; - overflow: hidden; - pointer-events: none; - background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent); -} - -.fill { - display: block; - height: 100%; - width: calc(var(--effort-thumb-size) / 2 + (100% - var(--effort-thumb-size)) * var(--dsh-effort-position)); - background: linear-gradient(to right, - color-mix(in srgb, var(--dsw-alias-state-business-primary) 8%, transparent), - color-mix(in srgb, var(--dsw-alias-state-business-primary) 54%, transparent)); -} - -.range { - appearance: none; - position: relative; - display: block; - box-sizing: border-box; - width: 100%; - height: 40px; - margin: 0; - padding: 0; - border: 0; - background: transparent; - cursor: pointer; - touch-action: pan-y; -} - -.range::-webkit-slider-runnable-track { - height: var(--effort-track-size); - background: transparent; -} - -.range::-moz-range-track, -.range::-moz-range-progress { - height: var(--effort-track-size); - background: transparent; -} - -/* Native thumb geometry owns hit testing; the inert sibling owns all visual motion. */ -.range::-webkit-slider-thumb { - appearance: none; - box-sizing: border-box; - width: var(--effort-thumb-size); - height: var(--effort-thumb-size); - margin-top: calc((var(--effort-track-size) - var(--effort-thumb-size)) / 2); - border: 0; - background: transparent; -} - -.range::-moz-range-thumb { - box-sizing: border-box; - width: var(--effort-thumb-size); - height: var(--effort-thumb-size); - border: 0; - background: transparent; -} - -.range:focus-visible { - outline: 2px solid var(--dsw-alias-state-business-primary); - outline-offset: 1px; - border-radius: var(--dsw-radius-sm); -} - -.range:disabled { - cursor: default; -} - -.rail[data-disabled] { - opacity: 0.5; -} - -.ticks, -.thumbRail { - position: absolute; - inset: 0 calc(var(--effort-thumb-size) / 2); - pointer-events: none; -} - -.tick, -.tickActive { - position: absolute; - top: 50%; - width: 4px; - height: 4px; - transform: translate(-50%, -50%); - border-radius: 50%; - corner-shape: round; - background: var(--dsw-alias-label-caption); - opacity: 0.6; - transition: transform 120ms ease; -} - -@media (hover: hover) and (pointer: fine) { - .ticks [data-hovered] { - transform: translate(-50%, -50%) scale(2); - } -} - -.thumbPosition { - position: absolute; - top: 50%; - left: calc(var(--dsh-effort-position) * 100%); - width: var(--effort-thumb-size); - height: var(--effort-thumb-size); - transform: translate(-50%, -50%); -} - -.thumb { - position: absolute; - inset: 0; - box-sizing: border-box; - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: 50%; - corner-shape: round; - background: var(--dsw-alias-slider-thumb); - box-shadow: var(--dsw-elevation-panel); -} - -/* The white disc holds its size; only the blue center grows on hover or press. */ -.thumb::after { - content: ''; - position: absolute; - top: 50%; - left: 50%; - width: 8px; - height: 8px; - border-radius: 50%; - corner-shape: round; - background: var(--dsw-alias-slider-thumb-mark); - transform: translate(-50%, -50%); - transition: width 140ms cubic-bezier(.23, 1, .32, 1), height 140ms cubic-bezier(.23, 1, .32, 1); -} - -.thumb[data-expanded]::after { - width: 9.6px; - height: 9.6px; -} - -.heading[data-dragging], -.rail[data-dragging] { - transition: none; -} - -@media (prefers-reduced-motion: reduce) { - .heading, - .rail, - .thumbPosition, - .fill, - .thumb::after, - .thumb[data-expanded]::after, - .tick, - .tickActive { - transition: none; - } - - .thumb[data-expanded]::after { - width: 8px; - height: 8px; - } - - .ticks [data-hovered] { - transform: translate(-50%, -50%); - } -} diff --git a/packages/client/ui-model-selection/src/client/EffortSlider.tsx b/packages/client/ui-model-selection/src/client/EffortSlider.tsx deleted file mode 100644 index 95cf1ddc18..0000000000 --- a/packages/client/ui-model-selection/src/client/EffortSlider.tsx +++ /dev/null @@ -1,344 +0,0 @@ -import { useEffect, useRef, useState, type CSSProperties, type PointerEvent } from 'react' -import { IconInfoOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' -import css from './EffortSlider.module.css' - -/** One adapter-advertised stop; undefined selects the adapter's default behavior. */ -export interface EffortChoice { - key: string - effort: string | undefined - label: string -} - -/** Data and localized chrome supplied by the model selector. */ -export interface EffortSliderProps { - choices: readonly EffortChoice[] - value: string | undefined - label: string - currentLabel: string - /** Localized full label for the currently displayed effort name. */ - formatLabel: (effort: string) => string - /** Accessible label for the default-effort explanation button. */ - defaultInfoLabel: string - /** Explanation of unspecified effort, distinct from disabling reasoning. */ - defaultExplanation: string - disabled: boolean - /** A selection is being saved; keep its displayed value and keyboard focus. */ - pending: boolean - onSelect: (effort: string | undefined) => void -} - -type PointerGeometry = { start: number; length: number; size: number; centerY: number; offset: number } -type Gesture = - | { kind: 'pointer'; source: string; index: number; geometry: PointerGeometry | null; position: number | null } - | { - kind: 'caption' - source: string - index: number - pointerId: number - startX: number - startY: number - startPosition: number - length: number - position: number | null - } - | { kind: 'keyboard' | 'cancelled'; source: string; index: number } - | { kind: 'hover'; catalog: string; thumb: boolean; tick: number | null } -const ADJUST_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']) -/** Pointer travel under which a dragged thumb settles onto the nearest stop. */ -const SNAP_DISTANCE_PX = 10 - -/** - * Preview discrete effort choices with a native range and a draggable, range-focusing caption. - * @param props - Exact-model choices, persisted value, and selection callback. - * @returns A native range with a live value label and independent motion decoration. - */ -export function EffortSlider({ - choices, value, label, currentLabel, formatLabel, defaultInfoLabel, defaultExplanation, disabled, pending, onSelect, -}: EffortSliderProps) { - const thumbRef = useRef(null) - const rangeRef = useRef(null) - const captionRef = useRef(null) - const infoFocused = useRef(false) - const selectedIndex = choices.findIndex(choice => choice.effort === value) - const catalog = JSON.stringify(choices.map(choice => [choice.key, choice.effort])) - const source = JSON.stringify([catalog, value]) - const [gesture, setGesture] = useState(null) - const rangeDisabled = disabled || selectedIndex < 0 || choices.length < 2 - if (gesture?.kind === 'hover' && (gesture.catalog !== catalog || rangeDisabled)) setGesture(null) - if (gesture !== null && gesture.kind !== 'hover' && gesture.kind !== 'cancelled' - && (gesture.source !== source || rangeDisabled || pending)) { - setGesture({ kind: 'cancelled', source, index: selectedIndex }) - } - const active = gesture !== null && gesture.kind !== 'hover' && gesture.source === source && !rangeDisabled && !pending ? gesture : null - const hover = gesture?.kind === 'hover' && gesture.catalog === catalog && !rangeDisabled ? gesture : null - const preview = active !== null && active.kind !== 'cancelled' ? active.index : selectedIndex - const index = Math.max(0, preview) - const current = choices[preview] - const defaultSelected = current !== undefined && current.effort === undefined - const displayName = current?.label ?? currentLabel - const valueLabel = formatLabel(displayName) - // Preserve the effort name when a long localized prefix needs truncation. - const valueStart = Math.max(0, valueLabel.lastIndexOf(displayName)) - useEffect(() => { - // An external selection can remove the focused info button; keep keyboard access on the range. - if (!defaultSelected && infoFocused.current) { - rangeRef.current?.focus() - infoFocused.current = false - } - }, [defaultSelected]) - const capturedPointer = gesture?.kind === 'caption' ? gesture.pointerId : null - useEffect(() => { - const caption = captionRef.current - if (capturedPointer === null || caption === null) return - // Source changes, locks, and unmounts end the caption's capture as well as its preview. - return () => { if (caption.hasPointerCapture(capturedPointer)) caption.releasePointerCapture(capturedPointer) } - }, [capturedPointer]) - const progress = choices.length > 1 ? index / (choices.length - 1) : 0 - const dragging = (active?.kind === 'pointer' || active?.kind === 'caption') && active.position !== null - const snapPosition = (position: number, length: number | null): number => { - if (length === null || choices.length < 2) return position - const nearest = Math.round(position * (choices.length - 1)) / (choices.length - 1) - return Math.abs(position - nearest) * length <= SNAP_DISTANCE_PX ? nearest : position - } - const dragLength = active?.kind === 'caption' ? active.length : active?.kind === 'pointer' ? active.geometry?.length ?? null : null - const visualProgress = active !== null && (active.kind === 'pointer' || active.kind === 'caption') && active.position !== null - ? snapPosition(active.position, dragLength) - : progress - const expanded = active?.kind === 'pointer' || (active?.kind === 'caption' && dragging) || hover?.thumb === true - - // Pointer geometry comes from the unscaled wrapper, so zoom and the spring cannot change the grab offset. - const measure = (input: HTMLInputElement): PointerGeometry | null => { - const range = input.getBoundingClientRect() - const thumb = thumbRef.current?.getBoundingClientRect() - if (thumb === undefined || range.width <= thumb.width) return null - return { - start: range.left + thumb.width / 2, length: range.width - thumb.width, - size: thumb.width, centerY: range.top + range.height / 2, offset: 0, - } - } - const hoverAt = (event: PointerEvent, settledIndex?: number): Gesture | null => { - if (rangeDisabled || event.pointerType !== 'mouse' || !window.matchMedia('(hover: hover) and (pointer: fine)').matches) return null - const geometry = measure(event.currentTarget) - const thumb = thumbRef.current?.getBoundingClientRect() - if (geometry === null || thumb === undefined) return null - const center = settledIndex === undefined ? thumb.left + thumb.width / 2 - : geometry.start + settledIndex / (choices.length - 1) * geometry.length - const overThumb = Math.abs(event.clientX - center) <= geometry.size / 2 - && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2 - const nearest = Math.max(0, Math.min(choices.length - 1, - Math.round((event.clientX - geometry.start) / geometry.length * (choices.length - 1)))) - const tickX = geometry.start + nearest / (choices.length - 1) * geometry.length - const overTick = !pending && !overThumb && Math.abs(event.clientX - tickX) <= 8 && Math.abs(event.clientY - geometry.centerY) <= 8 - return { kind: 'hover', catalog, thumb: overThumb, tick: overTick ? nearest : null } - } - const commit = (nextIndex: number, next: Gesture | null = null): void => { - const choice = choices[nextIndex] - setGesture(next) - if (!rangeDisabled && !pending && choice !== undefined) onSelect(choice.effort) - } - const finish = (kind: 'pointer' | 'keyboard', nextIndex: number, next: Gesture | null = null): void => { - if (gesture?.kind === kind && gesture.source === source) commit(nextIndex, next) - else setGesture(next) - } - const movePointer = (event: PointerEvent): void => { - if (gesture?.kind === 'cancelled') return - if (gesture?.kind === 'pointer') { - if (gesture.source !== source || rangeDisabled || pending || gesture.geometry === null) return - const { start, length, offset } = gesture.geometry - const position = Math.max(0, Math.min(1, (event.clientX - start - offset) / length)) - setGesture(previous => previous?.kind === 'pointer' && previous.source === source ? { ...previous, position } : previous) - } else if (gesture === null || gesture.kind === 'hover') { - const next = hoverAt(event) - setGesture(previous => previous?.kind === 'hover' && next?.kind === 'hover' - && previous.catalog === next.catalog && previous.thumb === next.thumb && previous.tick === next.tick ? previous : next) - } - } - const releaseCaption = (pointerId: number): void => { - const caption = captionRef.current - if (caption?.hasPointerCapture(pointerId)) caption.releasePointerCapture(pointerId) - } - const cancelCaption = (pointerId: number): void => { - releaseCaption(pointerId) - setGesture(previous => previous?.kind === 'caption' && previous.pointerId === pointerId - ? { kind: 'cancelled', source: previous.source, index: previous.index } : previous) - } - const startCaption = (event: PointerEvent): void => { - if (pending || rangeDisabled) { event.preventDefault(); return } - if (!event.isPrimary || event.button > 0) return - event.preventDefault() - const input = rangeRef.current - if (input === null) return - input.focus() - const geometry = measure(input) - const thumb = thumbRef.current?.getBoundingClientRect() - if (geometry === null || thumb === undefined) return - // The caption may be clamped at an edge; its center is never the drag's value origin. - const startPosition = (thumb.left + thumb.width / 2 - geometry.start) / geometry.length - event.currentTarget.setPointerCapture(event.pointerId) - setGesture({ kind: 'caption', source, index, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, - startPosition, length: geometry.length, position: null }) - } - const moveCaption = (event: PointerEvent): void => { - if (gesture?.kind !== 'caption' || gesture.pointerId !== event.pointerId || gesture.source !== source || rangeDisabled || pending) return - const deltaX = event.clientX - gesture.startX - const deltaY = event.clientY - gesture.startY - if (gesture.position === null) { - if (event.pointerType === 'touch' && Math.abs(deltaY) >= 3 && Math.abs(deltaY) > Math.abs(deltaX)) { - cancelCaption(event.pointerId) - return - } - if (Math.abs(deltaX) < 3) return - } - event.preventDefault() - const position = Math.max(0, Math.min(1, gesture.startPosition + deltaX / gesture.length)) - const nextIndex = Math.round(position * (choices.length - 1)) - setGesture(previous => previous?.kind === 'caption' && previous.pointerId === event.pointerId && previous.source === source - ? { ...previous, position, index: nextIndex } : previous) - } - const finishCaption = (event: PointerEvent): void => { - releaseCaption(event.pointerId) - if (gesture?.kind !== 'caption' || gesture.pointerId !== event.pointerId || gesture.source !== source) return - if (gesture.position !== null && gesture.index !== selectedIndex && !rangeDisabled && !pending) commit(gesture.index) - else setGesture(null) - } - return ( -
-
- - - - {defaultSelected && ( - - - - )} - - -
-
- - { - if (pending || rangeDisabled) { event.preventDefault(); return } - if (event.button > 0) return - const geometry = measure(event.currentTarget) - const thumb = thumbRef.current?.getBoundingClientRect() - if (geometry !== null && thumb !== undefined) { - const offset = event.clientX - thumb.left - thumb.width / 2 - if (Math.abs(offset) <= geometry.size / 2 && Math.abs(event.clientY - geometry.centerY) <= geometry.size / 2) { - geometry.offset = offset - } - } - setGesture({ kind: 'pointer', source, index, geometry, position: null }) - }} - onPointerEnter={movePointer} - onPointerMove={movePointer} - onPointerLeave={() => { setGesture(previous => previous?.kind === 'hover' ? null : previous) }} - onChange={(event) => { - if (pending || rangeDisabled) return - const nextIndex = event.currentTarget.valueAsNumber - if (gesture === null || gesture.kind === 'hover') commit(nextIndex) - else if (gesture.source === source && (gesture.kind === 'pointer' || gesture.kind === 'keyboard')) { - setGesture(previous => (previous?.kind === 'pointer' || previous?.kind === 'keyboard') && previous.source === source - ? { ...previous, index: nextIndex } : previous) - } - }} - onPointerUp={(event) => { - if (gesture?.kind === 'pointer' && gesture.source === source && !rangeDisabled && !pending) event.currentTarget.focus() - finish('pointer', event.currentTarget.valueAsNumber, hoverAt(event, event.currentTarget.valueAsNumber)) - }} - onPointerCancel={() => { setGesture(null) }} - onLostPointerCapture={() => { setGesture(previous => previous?.kind === 'hover' ? previous : null) }} - onBlur={(event) => { - // WebKit focuses the enclosing menu when its native range takes over a pointer drag. - const insideAncestor = event.relatedTarget instanceof Node && event.relatedTarget.contains(event.currentTarget) - if (gesture?.kind === 'caption') releaseCaption(gesture.pointerId) - setGesture(previous => previous?.kind === 'caption' - ? { kind: 'cancelled', source: previous.source, index: previous.index } - : previous?.kind === 'cancelled' || (insideAncestor && previous?.kind === 'pointer' && previous.source === source) - ? previous : null) - }} - onKeyDown={(event) => { - if (event.nativeEvent.isComposing) return - if (pending && ADJUST_KEYS.has(event.key)) { - event.preventDefault() - event.stopPropagation() - return - } - if (event.key === 'Escape' && gesture !== null && gesture.kind !== 'hover' && gesture.kind !== 'cancelled') { - event.preventDefault() - event.stopPropagation() - if (gesture.kind === 'caption') releaseCaption(gesture.pointerId) - setGesture({ kind: 'cancelled', source, index }) - } else if (ADJUST_KEYS.has(event.key)) { - event.stopPropagation() - if (gesture?.kind === 'caption') releaseCaption(gesture.pointerId) - if (gesture === null || gesture.kind === 'hover' || gesture.kind === 'caption' - || (gesture.kind === 'cancelled' && !event.repeat)) { - setGesture({ kind: 'keyboard', source, index }) - } - } - }} - onKeyUp={(event) => { - if (ADJUST_KEYS.has(event.key)) { - event.stopPropagation() - finish('keyboard', event.currentTarget.valueAsNumber) - } - }} - /> - - -
-
- ) -} diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index 802871af67..9ef7fc2e80 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -106,14 +106,13 @@ z-index: 1100; display: flex; flex-direction: column; - /* Every pane shares one width so drilling in cannot resize the card. */ - width: min(260px, calc(100vw - 24px)); + /* Rows size the card up to its visible bounds; longer names ellipsize. */ + width: fit-content; height: fit-content; - min-width: 0; - max-width: min(260px, calc(100vw - 24px)); + min-width: min(240px, calc(100vw - 24px)); + max-width: min(420px, calc(100vw - 24px)); max-height: min(360px, calc(100dvh - 96px)); overflow: hidden; - outline: none; padding: 4px; /* Surface tokens match the Menu primitive card (ui-primitives * Menu.module.css) so every dropdown reads as the same material. */ @@ -130,65 +129,6 @@ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } - - -.rootPage { - display: flex; - flex-direction: column; - min-height: 0; - overflow-y: auto; -} - -.rootPage > * { - flex-shrink: 0; -} - -.reasoningPage { - display: grid; - grid-template-columns: minmax(0, 1fr); -} - -.reasoningPage .modelHeadline { - grid-row: 1; - justify-self: center; - justify-content: center; - width: fit-content; - min-width: 0; - max-width: 100%; - height: 34px; - margin: 4px 0 0; - padding: 0 6px; - gap: 2px; - border-radius: var(--dsw-radius-sm); -} - -.reasoningPage .modelHeadline .cellChevron { - width: 10px; - height: 10px; -} - -.modelHeadline .cellLabel { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip-path: inset(50%); -} - -.modelHeadline .cellValue { - flex: 0 1 auto; - text-align: center; - font-size: 14px; - color: var(--dsw-alias-label-secondary); -} - -.pageBody { - width: 100%; - min-width: 0; - min-height: 0; - overflow-y: auto; -} - .status, .empty { padding: 8px; @@ -422,16 +362,11 @@ } @media (hover: hover) { - .cell:hover:not(.modelHeadline), - .reasoningPage .modelHeadline:hover:not(:disabled) { + .cell:hover { background: var(--dsw-alias-interactive-bg-hover); } } -.rootPage .cell[data-return-focus]:is(:hover, :focus-visible) { - background: transparent; -} - .cellLabel { flex: 0 0 auto; white-space: nowrap; diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index cf930361a7..bd7c24383c 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -1,6 +1,31 @@ /** - * Session model menu with inline reasoning stops and keyed settings pages. - * Model choices and submissions share the same directory as the /model command. + * ModelSelect: the composer's named model seat (`conversation.input.model`). + * Two-level selection per figma 496:26454's MenuDropdown: the root menu is + * the Model / Effort row pair (label + current value + a right chevron), + * each drilling into its own list — the provider-grouped model list over + * the shared directory, and the effort levels. The trigger (313:14108's + * ToggleButton) shows both: model name + effort in the caption tone. + * Model catalogs above four entries show search, which retains focus while + * ↑/↓ cycle the highlighted result; Enter and Tab accept it. Smaller model + * catalogs, root panes, and effort panes move focus between rows. Escape and Shift+Tab leave a drilled pane first and otherwise close + * back to the trigger. A drilled pane focuses the current effort or model + * search field. Provider headings paint their background only while pinned + * by scrolling. Clearing a query restores the full list and search focus. + * Selecting restores trigger focus without a ring until the trigger loses focus + * or the menu reopens. Mobile devices restore button focus when opening or + * drilling; model search takes focus only after explicit user input. + * Model names match a case-insensitive ordered subsequence + * within each provider group, ranked by + * prefix, alignment score, then catalog order. Returning to the root pane + * hands focus back to the cell that opened it. Data and submission ride the + * same per-session ModelDirectory as the /model popup; exact-model reasoning + * metadata and the selected effort come from the Host rather than a + * client-owned vocabulary. A rejected selection announces through the shared + * transient Toast anchored to the composer card; the in-menu strip with + * Retry remains the catalog-load surface. While the directory's pending + * selection is unsettled, the trigger shows a spinner in place of its + * chevron, and each row whose value that selection carries shows one in place + * of its check mark. */ import { MenuGroup, MenuSurface, observeStickyMenuGroups } from '@deepseek-ai/dsh-client-ui-primitives' import { @@ -11,19 +36,23 @@ import { createPortal } from 'react-dom' import clsx from 'clsx' import type { ModelReasoningEffort, ModelSelection } from '@deepseek-ai/dsh-api-remotes/client' import { - IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, - IconCloseFillRegular, + IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelLabelOwner, ModelMenuPage, ModelSelectInjected } from './slots.ts' -import { EffortSlider, type EffortChoice } from './EffortSlider.tsx' -import { effortDisplayName } from './effort-label.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** The root controls, all models, or a keyed plugin-owned settings page. */ -type Pane = 'root' | 'model' | ModelMenuPage +/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ +type Pane = 'root' | 'model' | 'effort' | ModelMenuPage + +/** One dynamic effort row; undefined means preserve the provider default. */ +interface EffortChoice { + key: string + effort: string | undefined + label: string +} /** * Render the composer model seat. @@ -45,7 +74,6 @@ export function ModelSelect( const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) - const [modelReturnFocus, setModelReturnFocus] = useState(false) // The in-menu error strip serves catalog loads (its Retry re-runs the // load); a rejected SELECTION announces through the transient toast // instead, so the strip renders only while the latest failure-capable @@ -106,10 +134,7 @@ export function ModelSelect( ? state.retainedEffort : effectiveEffort === undefined ? t('effort.providerDefault') - : effortDisplayName({ - id: effectiveEffort, - name: reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort, - }, t) + : reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort const effortChoices = useMemo(() => reasoning === undefined ? [] : [ @@ -119,7 +144,7 @@ export function ModelSelect( ...reasoning.efforts.map((effort: ModelReasoningEffort) => ({ key: `effort:${effort.id}`, effort: effort.id, - label: effortDisplayName(effort, t), + label: effort.name, })), ], [reasoning, t]) const { pending } = state @@ -151,7 +176,7 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | ModelMenuPage | null>(null) + const paneFocus = useRef<'drill' | Exclude | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch @@ -178,11 +203,12 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = intent === 'model' ? itemRefs.current[0] - : Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) + const cell = typeof intent === 'object' + ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) .find(button => button.dataset.modelMenuPage === intent.key) + : itemRefs.current[intent === 'effort' ? 1 : 0] ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() - }, [open, pane, showSearch, selectionFocus, busy]) + }, [open, pane, showSearch]) useEffect(() => { const viewport = groupsRef.current @@ -200,7 +226,6 @@ export function ModelSelect( const show = (): void => { setSelectionFocus(false) - setModelReturnFocus(false) triggerRef.current?.focus() setQuery('') setHighlightedIndex(null) @@ -221,6 +246,11 @@ export function ModelSelect( if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } + const closeAfterSelection = (): void => { + setSelectionFocus(true) + close(true) + } + const drill = (next: Pane): void => { setQuery('') setHighlightedIndex(null) @@ -230,14 +260,13 @@ export function ModelSelect( /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ const back = (from: Exclude): void => { - setModelReturnFocus(from === 'model') paneFocus.current = from setPane('root') } const moveFocus = (offset: number): void => { - const items = Array.from(menuRef.current?.querySelectorAll( - 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled]), input[type="range"]:not([disabled])', + const items = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', ) ?? []) if (items.length === 0) return const active = items.findIndex(item => item === document.activeElement) @@ -254,60 +283,68 @@ export function ModelSelect( if (event.nativeEvent.isComposing) return if (event.key === 'Escape' && open) { event.preventDefault() - event.stopPropagation() // Escape backs out of a drilled pane first, then closes. - if (typeof pane === 'object' || (pane === 'model' && currentChoice !== undefined)) back(pane) + if (typeof pane === 'object' || (pane !== 'root' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (event.key === 'Tab') { - const menu = menuRef.current - const trigger = triggerRef.current - if (menu === null || trigger === null) return - const stops = Array.from(menu.querySelectorAll('button, input, select, textarea, a[href], [tabindex]')) - .filter(item => item.tabIndex >= 0 && !item.matches(':disabled') && item.closest('[hidden], [inert]') === null) - const focused = document.activeElement - if (focused === trigger || focused === menu) { - if (event.shiftKey) { - close() - if (focused === menu) { event.preventDefault(); trigger.focus() } - } else { - event.preventDefault() - ;(stops[0] ?? trigger).focus() - } - return - } - const index = stops.findIndex(item => item === focused) - if (index < 0) return - const next = stops[index + (event.shiftKey ? -1 : 1)] - if (next !== undefined) { - event.preventDefault() - next.focus() - } else { - // Forward Tab continues from the trigger into the composer, not from the body portal. - if (event.shiftKey) event.preventDefault() - close() - trigger.focus() - } + if (typeof pane === 'object' && event.key === 'Tab') { + event.preventDefault() + close(true) return } - if (pane === 'model' && showSearch && event.target === searchRef.current - && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 setHighlightedIndex((activeModelIndex + direction + visibleModels.length) % visibleModels.length) - searchRef.current.focus() + searchRef.current?.focus() } return } - if (pane === 'model' && showSearch && event.target === searchRef.current && event.key === 'Enter') { + if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement + && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { + if (event.key === 'Tab' && visibleModels.length === 0) return event.preventDefault() const highlighted = visibleModels[activeModelIndex] if (!busy && highlighted !== undefined) choose(highlighted) return } + // Tab settles like Enter and Shift+Tab leaves like Escape, so the menu's + // keys mean what they mean in the composer. Both are consumed: the card + // keeps the browser's focus traversal out while it is open. + if (event.key === 'Tab') { + if (event.shiftKey) { + event.preventDefault() + if (typeof pane === 'object' || (pane !== 'root' && currentChoice !== undefined)) back(pane) + else close(true) + return + } + // Settling activates the row the keyboard is on; with focus still on the + // trigger, Tab enters the menu at the value in use instead. Any other + // control inside the card (a retry button) keeps the browser's traversal, + // so the keystroke stays unconsumed there. + const focused = document.activeElement + const rows = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', + ) ?? []) + if (focused instanceof HTMLButtonElement && rows.includes(focused)) { + event.preventDefault() + focused.click() + return + } + if (focused !== triggerRef.current) return + event.preventDefault() + if (pane === 'model' && showSearch) { + setHighlightedIndex(null) + searchRef.current?.focus() + return + } + const checked = menuRef.current?.querySelector('[role="menuitemradio"][aria-checked="true"]:not([disabled])') + ;(checked ?? rows.find(item => !item.disabled))?.focus() + return + } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault() moveFocus(event.key === 'ArrowDown' ? 1 : -1) @@ -315,9 +352,8 @@ export function ModelSelect( } const onBlur = (event: FocusEvent): void => { - // Non-focusable menu text and native range dragging can temporarily clear DOM focus. - // Outside pointer presses are handled separately; close only for a known outside focus target. - if (event.relatedTarget === null) return + // Clicking explanation text can clear focus without leaving its page. + if (typeof pane === 'object' && event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -325,23 +361,12 @@ export function ModelSelect( close() } - const settleSelection = ( - result: Awaited>, origin: 'model' | 'effort', selectionPage: HTMLDivElement | null, - ): void => { + const settleSelection = (result: Awaited>): void => { if (result === undefined) return - if (menuRef.current !== null) { - // Restore only the selection's own view and focus, not navigation made while saving. - if (origin === 'model' && selectionPage !== null && selectionPage === groupsRef.current - && document.activeElement === triggerRef.current) { - paneFocus.current = 'model' - if (result.ok) { - setModelReturnFocus(true) - setPane('root') - } - } - setSelectionFocus(false) + if (result.ok) { + if (rootRef.current !== null) closeAfterSelection() + return } - if (result.ok) return const { error } = result toastSeq.current += 1 setToast({ @@ -352,32 +377,34 @@ export function ModelSelect( }) } - const submit = (selection: ModelSelection, origin: 'model' | 'effort'): void => { + const submit = (selection: ModelSelection): void => { lastActionRef.current = 'select' - // Model rows may unmount; the inline slider keeps focus while its value is saved. + // Disabled option rows cannot retain focus while a selection is pending. setSelectionFocus(true) - if (origin === 'model') triggerRef.current?.focus() - const selectionPage = origin === 'model' ? groupsRef.current : null - void select(selection).then((result) => { settleSelection(result, origin, selectionPage) }) + triggerRef.current?.focus() + void select(selection).then(settleSelection) } const choose = (selection: ModelSelection): void => { if (state.current?.provider === selection.provider && state.current.model === selection.model) { - back('model') + closeAfterSelection() return } - submit(selection, 'model') + submit(selection) } const chooseEffort = (effort: string | undefined): void => { - if (state.current === null || locked || busy) return - if (effectiveEffort === effort || (effort === undefined && state.current.reasoningEffort === undefined)) return + if (state.current === null) return + if (effectiveEffort === effort) { + closeAfterSelection() + return + } const selection: ModelSelection = { provider: state.current.provider, model: state.current.model, ...effort === undefined ? {} : { reasoningEffort: effort }, } - submit(selection, 'effort') + submit(selection) } const waiting = currentChoice === undefined && state.status === 'loading' @@ -467,48 +494,32 @@ export function ModelSelect( {open && createPortal( {pane === 'root' && ( -
- - {currentChoice !== undefined && reasoning !== undefined && ( - t('effort.tooltip', { effort })} - defaultInfoLabel={t('effort.defaultInfoLabel')} - defaultExplanation={t('effort.defaultExplanation')} - disabled={locked} - pending={busy} - onSelect={chooseEffort} - /> + {reasoning !== undefined && ( + )} {renderSlot('conversation.input.model.options', { - locked, - pending: busy, + locked: locked || busy, openPage: (page) => { drill(page) }, dismiss: () => { close() @@ -516,7 +527,7 @@ export function ModelSelect( }, reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, })} -
+ )} {pane === 'model' && ( @@ -586,7 +597,7 @@ export function ModelSelect( role="menuitemradio" aria-checked={selected} id={`${id}-model-${index}`} - tabIndex={showSearch && index !== activeModelIndex ? -1 : 0} + tabIndex={showSearch ? -1 : 0} onFocus={() => { setHighlightedIndex(index) }} data-highlighted={index === activeModelIndex ? '' : undefined} className={clsx( @@ -622,11 +633,46 @@ export function ModelSelect( )} + {pane === 'effort' && ( + <> + {state.error !== null && lastActionRef.current === 'load' && ( +
+ {t('error.action', { message: state.error })} + +
+ )} +
+ {effortChoices.length === 0 + ?
{t('empty.efforts')}
+ : effortChoices.map(level => ( + + ))} +
+ + )} {typeof pane === 'object' && ( -
+
{renderSlot('conversation.input.model.page', { - locked, - pending: busy, + locked: locked || busy, dismiss: () => { close() triggerRef.current?.focus() diff --git a/packages/client/ui-model-selection/src/client/effort-label.ts b/packages/client/ui-model-selection/src/client/effort-label.ts deleted file mode 100644 index 8745ce10eb..0000000000 --- a/packages/client/ui-model-selection/src/client/effort-label.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** Localized display names for standard reasoning levels, without changing provider IDs or custom names. */ -import type { ModelReasoningEffort } from '@deepseek-ai/dsh-api-remotes/client' -import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' - -/** - * Translate standard IDs only when the provider's name repeats that ID, ignoring case. - * @param effort - Provider-owned level ID and display name. - * @param t - The model namespace translator. - * @returns The localized standard name, or the provider's unchanged custom or unknown name. - */ -export function effortDisplayName(effort: Pick, t: PropsLocale<'model'>['t']): string { - if (effort.name.toLowerCase() !== effort.id) return effort.name - switch (effort.id) { - case 'off': return t('effort.off') - case 'minimal': return t('effort.minimal') - case 'low': return t('effort.low') - case 'medium': return t('effort.medium') - case 'high': return t('effort.high') - case 'xhigh': return t('effort.xhigh') - case 'max': return t('effort.max') - // Providers may advertise other IDs; their names remain provider-owned. - default: return effort.name - } -} diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index 5b2e0cd61f..cb2749f9a9 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -10,17 +10,6 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'effort.tooltip': '推理等级:{effort}', - 'effort.off': '关闭', - 'effort.minimal': '最低', - 'effort.low': '低', - 'effort.medium': '中', - 'effort.high': '高', - 'effort.xhigh': '更高', - 'effort.max': '最高', - 'effort.defaultInfoLabel': '默认推理等级说明', - 'effort.defaultExplanation': '未显式指定推理等级,将使用模型与配置的默认设置;这不代表关闭推理', - 'menu.back': '返回', 'provider.account': 'DeepSeek 账号', 'command.label': '模型', 'command.description': '选择本会话使用的模型', @@ -33,7 +22,7 @@ export const zh = { 'menu.aria': '模型与推理等级', 'menu.model': '模型', 'menu.effort': '推理等级', - 'effort.providerDefault': '默认', + 'effort.providerDefault': 'Default', 'status.loading': '正在刷新模型列表…', 'error.action': '模型操作失败:{message}', 'error.sessionInUse': '当前会话已被占用,可能是其他正在运行的 DSH 导致的(如其他 dsh web、桌面端),请退出其他正在运行的 DSH 后重试。', @@ -51,17 +40,6 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'effort.tooltip': 'Effort: {effort}', - 'effort.off': 'Off', - 'effort.minimal': 'Minimal', - 'effort.low': 'Low', - 'effort.medium': 'Medium', - 'effort.high': 'High', - 'effort.xhigh': 'Extra high', - 'effort.max': 'Max', - 'effort.defaultInfoLabel': 'About default reasoning effort', - 'effort.defaultExplanation': 'No reasoning effort is explicitly selected. The model and configuration defaults apply; this does not mean reasoning is off.', - 'menu.back': 'Back', 'provider.account': 'DeepSeek Account', 'command.label': 'Model', 'command.description': 'Select the model for this conversation', @@ -89,17 +67,6 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { - 'effort.tooltip': '強度:{effort}', - 'effort.off': 'オフ', - 'effort.minimal': '最小', - 'effort.low': '低', - 'effort.medium': '中', - 'effort.high': '高', - 'effort.xhigh': 'より高い', - 'effort.max': '最大', - 'effort.defaultInfoLabel': 'デフォルトの推論強度について', - 'effort.defaultExplanation': '推論強度は明示的に指定されていません。モデルと設定のデフォルト値を使用します。推論をオフにするという意味ではありません。', - 'menu.back': '戻る', 'provider.account': 'DeepSeek アカウント', 'command.label': 'モデル', 'command.description': 'この会話で使用するモデルを選択', @@ -127,17 +94,6 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'effort.tooltip': 'Esfuerzo: {effort}', - 'effort.off': 'Desactivado', - 'effort.minimal': 'Mínimo', - 'effort.low': 'Bajo', - 'effort.medium': 'Medio', - 'effort.high': 'Alto', - 'effort.xhigh': 'Muy alto', - 'effort.max': 'Máximo', - 'effort.defaultInfoLabel': 'Acerca del esfuerzo de razonamiento predeterminado', - 'effort.defaultExplanation': 'No se ha seleccionado explícitamente un esfuerzo de razonamiento. Se aplican los valores predeterminados del modelo y de la configuración; esto no significa que el razonamiento esté desactivado.', - 'menu.back': 'Volver', 'provider.account': 'Cuenta DeepSeek', 'command.label': 'modelo', 'command.description': 'Selecciona el modelo para esta conversación', @@ -165,17 +121,6 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'effort.tooltip': 'Effort : {effort}', - 'effort.off': 'Désactivé', - 'effort.minimal': 'Minimal', - 'effort.low': 'Faible', - 'effort.medium': 'Moyen', - 'effort.high': 'Élevé', - 'effort.xhigh': 'Très élevé', - 'effort.max': 'Maximal', - 'effort.defaultInfoLabel': 'À propos de l’effort de raisonnement par défaut', - 'effort.defaultExplanation': 'Aucun effort de raisonnement n’est explicitement sélectionné. Les valeurs par défaut du modèle et de la configuration s’appliquent ; cela ne signifie pas que le raisonnement est désactivé.', - 'menu.back': 'Retour', 'provider.account': 'Compte DeepSeek', 'command.label': 'Modèle', 'command.description': 'Sélectionnez le modèle pour cette conversation', @@ -203,17 +148,6 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'effort.tooltip': 'Aufwand: {effort}', - 'effort.off': 'Aus', - 'effort.minimal': 'Minimal', - 'effort.low': 'Niedrig', - 'effort.medium': 'Mittel', - 'effort.high': 'Hoch', - 'effort.xhigh': 'Sehr hoch', - 'effort.max': 'Maximal', - 'effort.defaultInfoLabel': 'Über den standardmäßigen Denkaufwand', - 'effort.defaultExplanation': 'Es ist kein Denkaufwand ausdrücklich ausgewählt. Es gelten die Standardwerte des Modells und der Konfiguration; das bedeutet nicht, dass das Denken deaktiviert ist.', - 'menu.back': 'Zurück', 'provider.account': 'DeepSeek-Konto', 'command.label': 'Modell', 'command.description': 'Wählen Sie das Modell für dieses Gespräch aus', @@ -241,17 +175,6 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'effort.tooltip': 'Усилие: {effort}', - 'effort.off': 'Выключено', - 'effort.minimal': 'Минимальный', - 'effort.low': 'Низкий', - 'effort.medium': 'Средний', - 'effort.high': 'Высокий', - 'effort.xhigh': 'Очень высокий', - 'effort.max': 'Максимальный', - 'effort.defaultInfoLabel': 'Об уровне рассуждений по умолчанию', - 'effort.defaultExplanation': 'Уровень рассуждений явно не выбран. Применяются значения по умолчанию модели и конфигурации; это не означает, что рассуждения отключены.', - 'menu.back': 'Назад', 'provider.account': 'DeepSeek Аккаунт', 'command.label': 'Модель', 'command.description': 'Выберите модель для этого разговора', @@ -279,17 +202,6 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'effort.tooltip': 'Esforço: {effort}', - 'effort.off': 'Desativado', - 'effort.minimal': 'Mínimo', - 'effort.low': 'Baixo', - 'effort.medium': 'Médio', - 'effort.high': 'Alto', - 'effort.xhigh': 'Muito alto', - 'effort.max': 'Máximo', - 'effort.defaultInfoLabel': 'Sobre o esforço de raciocínio padrão', - 'effort.defaultExplanation': 'Nenhum esforço de raciocínio foi selecionado explicitamente. Aplicam-se os valores padrão do modelo e da configuração; isso não significa que o raciocínio esteja desativado.', - 'menu.back': 'Voltar', 'provider.account': 'DeepSeek Conta', 'command.label': 'Modelo', 'command.description': 'Selecione o modelo para esta conversa', diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index cbddc39f66..5b0b589b19 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -27,10 +27,8 @@ export interface ModelMenuPage { /** Selection state and feedback shared by menu option entries and detail pages. */ export interface ModelMenuControls { - /** Whether the composer is unavailable for interaction. */ + /** Whether the composer refuses changes, including while a model selection is saving. */ locked: boolean - /** A model or effort selection is saving; block new actions without dimming or removing focus. */ - pending: boolean /** Close the menu and focus its trigger synchronously before opening another overlay. */ dismiss: () => void /** Report a failed selection through the menu owner's persistent toast. */ diff --git a/packages/client/ui-model-selection/tests/effort-label.client.spec.ts b/packages/client/ui-model-selection/tests/effort-label.client.spec.ts deleted file mode 100644 index 682937f730..0000000000 --- a/packages/client/ui-model-selection/tests/effort-label.client.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { expect, it } from 'vitest' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { effortDisplayName } from '../src/client/effort-label.ts' -import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' - -const standard = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const - -it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('localizes canonical effort names in %s without changing IDs', (_locale, dictionary) => { - const t = makeTranslate(dictionary) - for (const id of standard) { - for (const name of [id, id.toUpperCase(), id[0]!.toUpperCase() + id.slice(1)]) { - const effort = { id, name } - expect(effortDisplayName(effort, t)).toBe(dictionary[`effort.${id}`]) - expect(effort.id).toBe(id) - expect(effort.name).toBe(name) - } - } -}) - -it.each([ - { id: 'high', name: 'High budget for code review' }, - { id: 'high', name: ' high' }, - { id: 'high', name: 'High ' }, - { id: 'xhigh', name: 'Extra high' }, - { id: 'standard', name: 'Standard' }, - { id: 'retired', name: 'High' }, - { id: 'High', name: 'High' }, -])('preserves provider spelling for $id / $name', (effort) => { - expect(effortDisplayName(effort, makeTranslate(zh))).toBe(effort.name) -}) diff --git a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx deleted file mode 100644 index 3df7288604..0000000000 --- a/packages/client/ui-model-selection/tests/effort-slider.client.spec.tsx +++ /dev/null @@ -1,442 +0,0 @@ -// @vitest-environment jsdom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' - -afterEach(() => { - cleanup() - vi.useRealTimers() - vi.unstubAllGlobals() -}) -const choices = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effort, label: effort })) -function props(overrides: Partial = {}): EffortSliderProps { - return { - choices, value: 'high', label: 'Effort', currentLabel: 'high', disabled: false, pending: false, - formatLabel: effort => `Effort: ${effort}`, - defaultInfoLabel: en['effort.defaultInfoLabel'], defaultExplanation: en['effort.defaultExplanation'], - onSelect: vi.fn(), ...overrides, - } -} -function range(): HTMLInputElement { - return screen.getByRole('slider') as HTMLInputElement -} -function effortLabel(): HTMLElement { - return range().closest('[role="group"]')!.querySelector('[data-effort-label]')! -} - -function tooltipLayout() { - vi.stubGlobal('matchMedia', (query: string) => ({ - matches: query.includes('hover: hover'), media: query, onchange: null, - addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, - })) - vi.stubGlobal('ResizeObserver', class { - observe() {} - unobserve() {} - disconnect() {} - }) -} - -it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('shows the full localized label and default explanation (%s)', (_locale, dictionary) => { - tooltipLayout() - const t = makeTranslate(dictionary) - const high = dictionary['effort.high'] - const defaultLabel = dictionary['effort.providerDefault'] - const inputProps = props({ - choices: [{ key: 'default', effort: undefined, label: defaultLabel }, { key: 'high', effort: 'high', label: high }], - formatLabel: effort => t('effort.tooltip', { effort }), - defaultInfoLabel: dictionary['effort.defaultInfoLabel'], defaultExplanation: dictionary['effort.defaultExplanation'], - }) - const view = render() - expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', high)) - expect(effortLabel().tabIndex).toBe(-1) - expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(high) - expect(screen.getAllByRole('button')).toHaveLength(1) - view.rerender() - expect(effortLabel().textContent).toBe(dictionary['effort.tooltip'].replace('{effort}', defaultLabel)) - expect(effortLabel().querySelector('[data-effort-name]')!.textContent).toBe(defaultLabel) - const info = screen.getByRole('button', { name: dictionary['effort.defaultInfoLabel'] }) - info.focus() - fireEvent.click(info) - expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(dictionary['effort.defaultExplanation']) - expect(document.activeElement).toBe(info) - expect(inputProps.onSelect).not.toHaveBeenCalled() - fireEvent.keyDown(info, { key: 'Escape' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - expect(document.activeElement).toBe(info) -}) - -it.each([ - ['推理等级:高', zh], ['Effort: High', en], ['強度:高', ja], ['Esfuerzo: Alto', es], - ['Effort : Élevé', fr], ['Aufwand: Hoch', de], ['Усилие: Высокий', ru], ['Esforço: Alto', pt], -] as const)('uses a compact localized caption: %s', (expected, dictionary) => { - const t = makeTranslate(dictionary) - render( t('effort.tooltip', { effort }), - })} />) - expect(effortLabel().textContent).toBe(expected) -}) - -it('protects the final effort name while preserving repeated text in the formatted prefix', () => { - render( `${effort} policy: ${effort}` })} />) - const label = effortLabel() - const name = label.querySelector('[data-effort-name]')! - expect(label.textContent).toBe('high policy: high') - expect(name.textContent).toBe('high') - expect(name.previousElementSibling!.textContent).toBe('high policy: ') - expect(range().getAttribute('aria-valuetext')).toBe('high') -}) - -it('only repeats the full label in a tooltip when the label is clipped', () => { - tooltipLayout() - vi.useFakeTimers() - render() - const label = effortLabel() - fireEvent.pointerEnter(label, { pointerType: 'mouse' }) - act(() => { vi.advanceTimersByTime(500) }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - fireEvent.pointerLeave(label, { pointerType: 'mouse' }) - Object.defineProperty(label, 'scrollWidth', { configurable: true, value: 200 }) - Object.defineProperty(label, 'clientWidth', { configurable: true, value: 80 }) - fireEvent.pointerEnter(label, { pointerType: 'mouse' }) - act(() => { vi.advanceTimersByTime(500) }) - expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('Effort: high') -}) - -it('closes default information on a second activation or Tab without selecting an effort', () => { - tooltipLayout() - const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices], value: undefined }) - render() - const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) - info.focus() - fireEvent.click(info) - expect(screen.getByRole('tooltip', { hidden: true })).toBeTruthy() - fireEvent.click(info) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - fireEvent.click(info) - fireEvent.keyDown(info, { key: 'Tab' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - expect(inputProps.onSelect).not.toHaveBeenCalled() - expect(range().value).toBe('0') -}) - -it('shows exact advertised stops and the selected value', () => { - render() - expect(range().max).toBe('3') - expect(range().value).toBe('2') - expect(range().getAttribute('aria-valuetext')).toBe('high') - expect(range().min).toBe('0') - expect(range().step).toBe('1') - expect(effortLabel().textContent).toBe('Effort: high') - expect(effortLabel().tabIndex).toBe(-1) - expect(screen.getAllByRole('button')).toHaveLength(1) -}) - -it('previews a drag but submits only its final stop on release', () => { - const inputProps = props() - render() - const input = range() - fireEvent.pointerDown(input, { pointerId: 1 }) - fireEvent.change(input, { target: { value: '1' } }) - fireEvent.change(input, { target: { value: '3' } }) - expect(input.getAttribute('aria-valuetext')).toBe('max') - expect(inputProps.onSelect).not.toHaveBeenCalled() - fireEvent.pointerUp(input, { pointerId: 1 }) - expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('max') -}) - -it.each(['pointerCancel', 'lostPointerCapture', 'blur'] as const)('cancels a drag on %s', (event) => { - const inputProps = props() - render() - const input = range() - fireEvent.pointerDown(input) - fireEvent.change(input, { target: { value: '3' } }) - fireEvent[event](input) - fireEvent.pointerUp(input) - expect(inputProps.onSelect).not.toHaveBeenCalled() - expect(input.value).toBe('2') -}) - -it('Escape discards the drag and ignores further movement until release', () => { - const inputProps = props() - const parentKey = vi.fn() - render(
) - const input = range() - fireEvent.pointerDown(input) - fireEvent.change(input, { target: { value: '3' } }) - fireEvent.keyDown(input, { key: 'Escape' }) - fireEvent.change(input, { target: { value: '0' } }) - fireEvent.pointerUp(input) - expect(inputProps.onSelect).not.toHaveBeenCalled() - expect(parentKey).not.toHaveBeenCalled() - expect(input.value).toBe('2') -}) - -it('commits keyboard changes on key release without forwarding adjustment keys', () => { - const inputProps = props() - const parentKey = vi.fn() - render(
) - const input = range() - fireEvent.keyDown(input, { key: 'ArrowLeft' }) - fireEvent.change(input, { target: { value: '1' } }) - fireEvent.keyDown(input, { key: 'ArrowLeft', repeat: true }) - fireEvent.change(input, { target: { value: '0' } }) - expect(inputProps.onSelect).not.toHaveBeenCalled() - fireEvent.keyUp(input, { key: 'ArrowLeft' }) - expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('off') - expect(parentKey).not.toHaveBeenCalled() -}) - -it('lets Tab and an idle Escape reach the owning menu', () => { - const parentKey = vi.fn() - render(
) - fireEvent.keyDown(range(), { key: 'Tab' }) - fireEvent.keyDown(range(), { key: 'Escape' }) - fireEvent.keyUp(range(), { key: 'Tab' }) - expect(parentKey).toHaveBeenCalledTimes(2) -}) - -it('handles a direct assistive-technology change without a preceding pointer or keyboard gesture', () => { - const inputProps = props() - render() - fireEvent.change(range(), { target: { value: '1' } }) - expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') -}) - -it('keeps Default distinct from Off and submits an absent effort', () => { - const inputProps = props({ choices: [{ key: 'default', effort: undefined, label: 'Default' }, ...choices] }) - render() - expect(range().max).toBe('4') - fireEvent.change(range(), { target: { value: '0' } }) - expect(inputProps.onSelect).toHaveBeenCalledExactlyOnceWith(undefined) -}) - -it('does not submit a gesture started before the persisted selection changes', () => { - const inputProps = props() - const view = render() - const input = range() - fireEvent.pointerDown(input) - fireEvent.change(input, { target: { value: '3' } }) - view.rerender() - fireEvent.pointerUp(input) - expect(inputProps.onSelect).not.toHaveBeenCalled() - expect(input.value).toBe('1') -}) - -it('blocks selection while locked', () => { - const inputProps = props({ disabled: true }) - render() - expect(range().disabled).toBe(true) - fireEvent.change(range(), { target: { value: '3' } }) - expect(inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('does not commit when another selection locks the control during a gesture', () => { - const inputProps = props() - const view = render() - const input = range() - fireEvent.pointerDown(input) - fireEvent.change(input, { target: { value: '3' } }) - view.rerender() - fireEvent.pointerUp(input) - expect(inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('leaves IME composition keys untouched', () => { - const inputProps = props() - const key = vi.fn() - render(
) - fireEvent.keyDown(range(), { key: 'ArrowRight', isComposing: true }) - expect(key).toHaveBeenCalledOnce() - expect(inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('does not pretend an unknown stored effort matches the first supported stop', () => { - render() - expect(range().disabled).toBe(true) - expect(range().getAttribute('aria-valuetext')).toBe('retired') - expect(effortLabel().textContent).toBe('Effort: retired') - expect(screen.getAllByRole('button')).toHaveLength(1) -}) - -it.each([{ levels: [] }, { levels: choices.slice(0, 1) }])('does not offer dragging with fewer than two choices', ({ levels }) => { - render() - expect(range().disabled).toBe(true) - expect(range().max).toBe('0') -}) - -function motionSetup() { - vi.stubGlobal('matchMedia', (query: string) => ({ - matches: query === '(hover: hover) and (pointer: fine)', media: query, onchange: null, - addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, - })) - const inputProps = props({ value: 'off', currentLabel: 'off' }) - const view = render() - const input = range() - const thumb = view.container.querySelector('[data-effort-thumb]')! - const scale = view.container.querySelector('[data-effort-thumb-scale]')! - vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 220, 40)) - vi.spyOn(thumb, 'getBoundingClientRect').mockImplementation(() => new DOMRect(Number(input.value) / 3 * 200, 10, 20, 20)) - const pointer = (type: string, x: number, pointerType = 'mouse') => fireEvent(input, - Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: 20, button: 0 }), - { pointerType, pointerId: 1, isPrimary: true })) - return { ...view, input, inputProps, thumb, scale, pointer } -} - -it('keeps motion decoration inert beside the native range and caption', () => { - const view = motionSetup() - expect(screen.getAllByRole('slider')).toHaveLength(1) - expect(view.thumb.closest('[aria-hidden="true"]')).toBeTruthy() - expect(view.container.querySelector('[data-effort-fill]')!.closest('[aria-hidden="true"]')).toBeTruthy() - expect(view.thumb.tabIndex).toBe(-1) - expect(view.scale.tabIndex).toBe(-1) - expect(screen.getAllByRole('button')).toHaveLength(1) -}) - -it('hovers one tick in its 16px target without selecting and does not retain touch hover', () => { - const view = motionSetup() - view.pointer('pointermove', 10) - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - view.pointer('pointermove', 10 + 200 / 3 + 7) - expect(view.scale.hasAttribute('data-expanded')).toBe(false) - expect(view.container.querySelectorAll('[data-effort-tick][data-hovered]')).toHaveLength(1) - expect(view.container.querySelector('[data-effort-tick="1"]')!.hasAttribute('data-hovered')).toBe(true) - view.pointer('pointermove', 10 + 200 / 3 + 9) - expect(view.container.querySelector('[data-hovered]')).toBeNull() - view.pointer('pointermove', 10) - view.pointer('pointermove', 10, 'touch') - expect(view.scale.hasAttribute('data-expanded')).toBe(false) - expect(view.container.querySelector('[data-hovered]')).toBeNull() - expect(view.input.value).toBe('0') - expect(view.inputProps.onSelect).not.toHaveBeenCalled() -}) - -it.each(['pointercancel', 'blur', 'Escape'])('cancels motion decoration and the native preview on %s', (cancel) => { - const view = motionSetup() - view.pointer('pointerdown', 16) - view.pointer('pointermove', 60) - fireEvent.change(view.input, { target: { value: '1' } }) - expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) - expect(view.container.querySelector('[data-hovered]')).toBeNull() - if (cancel === 'Escape') fireEvent.keyDown(view.input, { key: 'Escape' }) - else if (cancel === 'blur') fireEvent.blur(view.input) - else view.pointer(cancel, 60) - view.pointer('pointerup', 60) - expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) - expect(view.input.value).toBe('0') - expect(view.inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('keeps a native pointer gesture when focus moves to an ancestor before the first move', () => { - const view = motionSetup() - act(() => { - view.pointer('pointerdown', 16) - fireEvent.blur(view.input, { relatedTarget: view.input.parentElement }) - }) - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - view.pointer('pointermove', 76) - fireEvent.change(view.input, { target: { value: '1' } }) - expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(true) - expect(view.inputProps.onSelect).not.toHaveBeenCalled() - view.pointer('pointerup', 76) - expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') -}) - -it('restores range focus before submitting a valid native pointer release', () => { - const view = motionSetup() - view.input.focus() - view.pointer('pointerdown', 16) - const ancestor = view.input.parentElement! - ancestor.tabIndex = -1 - act(() => { ancestor.focus() }) - fireEvent.change(view.input, { target: { value: '1' } }) - vi.mocked(view.inputProps.onSelect).mockImplementation(() => { expect(document.activeElement).toBe(view.input) }) - view.pointer('pointerup', 76) - expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') -}) - -it('does not steal outside focus when a cancelled pointer later releases', () => { - const view = motionSetup() - view.input.focus() - view.pointer('pointerdown', 16) - fireEvent.change(view.input, { target: { value: '1' } }) - const outside = document.createElement('button') - view.container.append(outside) - act(() => { outside.focus() }) - view.pointer('pointerup', 76) - expect(document.activeElement).toBe(outside) - expect(view.inputProps.onSelect).not.toHaveBeenCalled() -}) - -it.each(['null', 'outside', 'keyboard-ancestor'])('still cancels a preview on %s focus loss', (kind) => { - const view = motionSetup() - if (kind === 'keyboard-ancestor') fireEvent.keyDown(view.input, { key: 'End' }) - else view.pointer('pointerdown', 16) - fireEvent.change(view.input, { target: { value: '1' } }) - const outside = document.createElement('button') - view.container.append(outside) - fireEvent.blur(view.input, { - relatedTarget: kind === 'keyboard-ancestor' ? view.input.parentElement : kind === 'outside' ? outside : null, - }) - if (kind === 'keyboard-ancestor') fireEvent.keyUp(view.input, { key: 'End' }) - else view.pointer('pointerup', 76) - expect(view.input.value).toBe('0') - expect(view.input.parentElement!.hasAttribute('data-dragging')).toBe(false) - expect(view.inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('retains thumb hover through a pending save without accepting more values', () => { - const view = motionSetup() - view.pointer('pointerdown', 10) - fireEvent.change(view.input, { target: { value: '1' } }) - view.pointer('pointerup', 10 + 200 / 3) - expect(view.inputProps.onSelect).toHaveBeenCalledExactlyOnceWith('low') - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - view.rerender() - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - view.pointer('pointermove', 10 + 200 / 3) - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - fireEvent.change(view.input, { target: { value: '3' } }) - expect(view.input.value).toBe('1') - expect(view.inputProps.onSelect).toHaveBeenCalledTimes(1) - view.rerender() - expect(view.scale.hasAttribute('data-expanded')).toBe(true) -}) - -it('clears hover and motion when locked or when the advertised catalog changes', () => { - const view = motionSetup() - view.pointer('pointermove', 10) - expect(view.scale.hasAttribute('data-expanded')).toBe(true) - view.rerender() - expect(view.scale.hasAttribute('data-expanded')).toBe(false) - expect(view.input.disabled).toBe(true) - view.pointer('pointermove', 10) - expect(view.scale.hasAttribute('data-expanded')).toBe(false) - view.rerender() - view.pointer('pointermove', 10) - view.rerender() - expect(view.scale.hasAttribute('data-expanded')).toBe(false) - expect(view.inputProps.onSelect).not.toHaveBeenCalled() -}) - -it('keeps the pending target focusable while blocking pointer, keyboard and direct changes', () => { - const inputProps = props({ value: 'max', pending: true }) - render() - const input = range() - input.focus() - expect(input.disabled).toBe(false) - expect(input.getAttribute('aria-disabled')).toBe('true') - expect(input.getAttribute('aria-busy')).toBe('true') - expect(input.value).toBe('3') - expect(input.getAttribute('aria-valuetext')).toBe('max') - expect(fireEvent.pointerDown(input)).toBe(false) - expect(fireEvent.keyDown(input, { key: 'ArrowLeft' })).toBe(false) - fireEvent.change(input, { target: { value: '0' } }) - fireEvent.keyUp(input, { key: 'ArrowLeft' }) - fireEvent.pointerUp(input) - expect(inputProps.onSelect).not.toHaveBeenCalled() - expect(input.value).toBe('3') - expect(document.activeElement).toBe(input) -}) diff --git a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx b/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx deleted file mode 100644 index b39a361555..0000000000 --- a/packages/client/ui-model-selection/tests/effort-tag-drag.client.spec.tsx +++ /dev/null @@ -1,206 +0,0 @@ -// @vitest-environment jsdom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { ComponentProps } from 'react' -import { EffortSlider, type EffortSliderProps } from '../src/client/EffortSlider.tsx' - -afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) - -function setup(value: string | null = 'off', includeDefault = false, parentKey?: ComponentProps<'div'>['onKeyDown']) { - vi.stubGlobal('matchMedia', (query: string) => ({ - matches: query.includes('hover: hover'), media: query, onchange: null, - addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: () => true, - })) - vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) - const levels = ['off', 'low', 'high', 'max'].map(effort => ({ key: effort, effort, label: effort })) - const props: EffortSliderProps = { - choices: includeDefault ? [{ key: 'default', effort: undefined, label: 'Default' }, ...levels] : levels, - value: value ?? undefined, label: 'Effort', currentLabel: value ?? 'Default', formatLabel: label => `Effort: ${label}`, - defaultInfoLabel: 'About default effort', defaultExplanation: 'Uses the model defaults, not reasoning off.', - disabled: false, pending: false, onSelect: vi.fn(), - } - const slider = - const view = render(parentKey === undefined ? slider :
{slider}
) - const input = screen.getByRole('slider') - const tag = screen.getByRole('button', { name: /^Effort:/ }) - const thumb = view.container.querySelector('[data-effort-thumb]')! - vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 40, 220, 40)) - vi.spyOn(thumb, 'getBoundingClientRect').mockImplementation(() => new DOMRect(Number(input.value) / Number(input.max) * 200, 50, 20, 20)) - vi.spyOn(tag, 'getBoundingClientRect').mockImplementation(() => { - const center = 10 + Number(input.value) / Number(input.max) * 200 - return new DOMRect(Math.max(0, Math.min(120, center - 50)), 0, 100, 28) - }) - const captured = new Set() - const tagCapture = vi.fn((id: number) => { captured.add(id) }) - tag.setPointerCapture = tagCapture - tag.hasPointerCapture = vi.fn((id: number) => captured.has(id)) - const tagRelease = vi.fn((id: number) => { captured.delete(id) }) - tag.releasePointerCapture = tagRelease - const inputCapture = vi.fn() - input.setPointerCapture = inputCapture - const pointer = (target: HTMLElement, type: string, x: number, y = 14, pointerType = 'mouse') => fireEvent(target, - Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }), - { pointerId: 1, pointerType, isPrimary: true })) - return { ...view, props, input, tag, thumb, pointer, tagCapture, tagRelease, inputCapture } -} - -it('focuses the range on a tag click without selecting or opening an effort menu', () => { - const view = setup() - fireEvent.click(view.tag) - expect(document.activeElement).toBe(view.input) - expect(view.props.onSelect).not.toHaveBeenCalled() - expect(screen.queryByRole('menuitemradio')).toBeNull() -}) - -it.each(['mouse', 'touch'])('does not turn a sub-threshold %s movement into a selection', (pointerType) => { - const view = setup() - view.pointer(view.tag, 'pointerdown', 80, 14, pointerType) - view.pointer(view.tag, 'pointermove', 82, 14, pointerType) - view.pointer(view.tag, 'pointerup', 82, 14, pointerType) - fireEvent.click(view.tag) - expect(view.input.value).toBe('0') - expect(view.props.onSelect).not.toHaveBeenCalled() - expect(document.activeElement).toBe(view.input) - expect(view.inputCapture).not.toHaveBeenCalled() -}) - -it.each([ - { start: 'off', down: 80, move: 120, expected: 'low', index: '1' }, - { start: 'max', down: 130, move: 90, expected: 'high', index: '2' }, -])('preserves the thumb-relative offset when the $start tag is clamped to an edge', ({ start, down, move, expected, index }) => { - const view = setup(start) - view.pointer(view.tag, 'pointerdown', down) - view.pointer(view.tag, 'pointermove', move) - expect(view.input.value).toBe(index) - expect(view.props.onSelect).not.toHaveBeenCalled() - expect(view.tagCapture).toHaveBeenCalledWith(1) - view.pointer(view.tag, 'pointerup', move) - fireEvent.click(view.tag) - expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith(expected) - expect(view.inputCapture).not.toHaveBeenCalled() -}) - -it.each(['pointercancel', 'lostpointercapture', 'Escape', 'blur'])('discards a tag drag on %s and ignores its late release', (cancel) => { - const view = setup() - view.pointer(view.tag, 'pointerdown', 80) - view.pointer(view.tag, 'pointermove', 160) - expect(view.props.onSelect).not.toHaveBeenCalled() - if (cancel === 'Escape') fireEvent.keyDown(view.input, { key: 'Escape' }) - else if (cancel === 'blur') fireEvent.blur(view.input) - else view.pointer(view.tag, cancel, 160) - expect(view.tag.hasPointerCapture(1)).toBe(false) - expect(view.tagRelease).toHaveBeenCalledExactlyOnceWith(1) - view.pointer(view.tag, 'pointerup', 160) - expect(view.input.value).toBe('0') - expect(view.props.onSelect).not.toHaveBeenCalled() -}) - -it('lets the second Escape reach the menu after cancelling a caption drag and releasing the pointer', () => { - const parentKey = vi.fn() - const view = setup('off', false, parentKey) - view.pointer(view.tag, 'pointerdown', 80) - view.pointer(view.tag, 'pointermove', 160) - expect(view.input.value).not.toBe('0') - const cancel = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) - fireEvent(view.input, cancel) - expect(cancel.defaultPrevented).toBe(true) - expect(parentKey).not.toHaveBeenCalled() - expect(view.input.value).toBe('0') - view.pointer(view.tag, 'pointerup', 160) - expect(view.props.onSelect).not.toHaveBeenCalled() - const close = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) - fireEvent(view.input, close) - expect(close.defaultPrevented).toBe(false) - expect(parentKey).toHaveBeenCalledOnce() - expect(view.input.value).toBe('0') - expect(view.props.onSelect).not.toHaveBeenCalled() -}) - -it('discards a tag gesture when a different selection arrives', () => { - const view = setup() - view.pointer(view.tag, 'pointerdown', 80) - view.pointer(view.tag, 'pointermove', 160) - view.rerender() - view.pointer(view.tag, 'pointerup', 160) - expect(view.input.value).toBe('1') - expect(view.props.onSelect).not.toHaveBeenCalled() -}) - -it.each(['pending', 'disabled'] as const)('prevents tag selection while %s', (state) => { - const view = setup() - view.rerender() - view.pointer(view.tag, 'pointerdown', 80) - view.pointer(view.tag, 'pointermove', 160) - view.pointer(view.tag, 'pointerup', 160) - expect(view.props.onSelect).not.toHaveBeenCalled() - expect(view.tagCapture).not.toHaveBeenCalled() -}) - -it.each(['source', 'catalog', 'pending', 'disabled', 'unmount'] as const)('releases caption capture when %s invalidates the drag', (change) => { - const view = setup() - view.pointer(view.tag, 'pointerdown', 80) - view.pointer(view.tag, 'pointermove', 160) - expect(view.tag.hasPointerCapture(1)).toBe(true) - if (change === 'unmount') view.unmount() - else view.rerender() - expect(view.tag.hasPointerCapture(1)).toBe(false) - expect(view.tagRelease).toHaveBeenCalledExactlyOnceWith(1) - view.pointer(view.tag, 'pointerup', 160) - expect(view.props.onSelect).not.toHaveBeenCalled() -}) - -it.each(['range', 'caption'] as const)('snaps %s motion within 10px of a stop but follows beyond it', (surface) => { - const view = setup(null, true) - const target = surface === 'range' ? view.input : view.tag - const start = surface === 'range' ? 10 : 80 - const y = surface === 'range' ? 60 : 14 - view.pointer(target, 'pointerdown', start, y) - // Five stops over a measured 200px travel put the first advertised level at 50px. - for (const offset of [-11, -10, -9, 9, 10, 11]) { - view.pointer(target, 'pointermove', start + 50 + offset, y) - if (surface === 'range') fireEvent.change(view.input, { target: { value: '1' } }) - const position = Number(view.input.closest('[role="group"]')!.style.getPropertyValue('--effort-visual-position')) - expect(position * 200).toBeCloseTo(Math.abs(offset) <= 10 ? 50 : 50 + offset, 5) - expect(view.input.value).toBe('1') - expect(view.props.onSelect).not.toHaveBeenCalled() - } - view.pointer(target, 'pointerup', start + 61, y) - expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith('off') - expect(view.inputCapture).not.toHaveBeenCalled() - expect(view.tag.hasPointerCapture(1)).toBe(false) -}) - -it('keeps default information independent from the draggable caption', () => { - const view = setup(null, true) - const info = screen.getByRole('button', { name: 'About default effort' }) - expect(view.tag.contains(info)).toBe(false) - view.pointer(info, 'pointerdown', 100) - view.pointer(info, 'pointerup', 100) - fireEvent.click(info) - expect(screen.getByRole('tooltip', { hidden: true }).textContent).toContain('model defaults') - expect(view.props.onSelect).not.toHaveBeenCalled() - expect(view.tagCapture).not.toHaveBeenCalled() -}) - -it('keeps the draggable caption free of SVG and tail decoration', () => { - const view = setup() - const tag = view.container.querySelector('[data-effort-tag]')! - expect(tag.querySelector('svg')).toBeNull() - expect(view.container.querySelector('[data-effort-tail-frame], [data-effort-tail], [data-effort-tail-edge]')).toBeNull() - fireEvent.click(view.tag) - expect(document.activeElement).toBe(view.input) - expect(view.props.onSelect).not.toHaveBeenCalled() -}) - -it('keeps native range gestures free of explicit pointer capture', () => { - const view = setup() - view.pointer(view.input, 'pointerdown', 10, 60) - fireEvent.change(view.input, { target: { value: '1' } }) - view.pointer(view.input, 'pointerup', 76, 60) - expect(view.inputCapture).not.toHaveBeenCalled() - expect(view.tagCapture).not.toHaveBeenCalled() - expect(view.props.onSelect).toHaveBeenCalledExactlyOnceWith('low') -}) diff --git a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx new file mode 100644 index 0000000000..859bb53344 --- /dev/null +++ b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx @@ -0,0 +1,78 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { ComponentProps } from 'react' +import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { ModelDirectoryState } from '../src/client/directory.ts' +import { ModelSelect } from '../src/client/ModelSelect.tsx' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +function setup(locked = false) { + const directory = createSnapshotStore({ + current: { provider: 'fixture', model: 'fixture' }, routable: true, + groups: [{ id: 'fixture', name: 'Fixture', models: [{ id: 'fixture', name: 'Fixture' }] }], + failures: [], status: 'ready', pending: null, error: null, + }) + const change = vi.fn() + const select = vi.fn() + const renderSlot: ComponentProps['renderSlot'] = (name, owner, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as object as OwnerOf<'conversation.input.model.options'> + return + } + if (name === 'conversation.input.model.page') { + const controls = owner as object as OwnerOf<'conversation.input.model.page'> + expect(options?.entryKey).toBe('fixture') + return <>

Fixture explanation

+ } + return options?.fallback ?? null + } + render( typeof text === 'string' ? text : text.en} t={makeTranslate(en)} renderSlot={renderSlot} />) + const trigger = screen.getByRole('button', { name: /^Select model/ }) + fireEvent.click(trigger) + return { trigger, change, select, directory } +} + +it('dispatches a keyed page and returns focus to its invoking summary on Escape', () => { + const { trigger, change, select } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + const toggle = screen.getByRole('switch') + expect(document.activeElement).toBe(toggle) + expect(screen.getByRole('menu', { name: 'Fixture settings' })).toBeTruthy() + fireEvent.blur(toggle, { relatedTarget: null }) + expect(screen.getByText('Fixture explanation')).toBeTruthy() + fireEvent.keyDown(toggle, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) + expect(screen.queryByRole('switch')).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(change).not.toHaveBeenCalled() + expect(select).not.toHaveBeenCalled() +}) + +it.each([false, true])('closes a detail page on Tab without changing its setting (shift: %s)', async (shiftKey) => { + const { trigger, change } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + fireEvent.keyDown(screen.getByRole('switch'), { key: 'Tab', shiftKey }) + await act(async () => {}) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(document.activeElement).toBe(trigger) + expect(change).not.toHaveBeenCalled() +}) + +it('keeps the baseline model-save lock on both summary and detail controls', () => { + const { directory } = setup() + act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) + expect(screen.getByRole('menuitem', { name: 'Fixture settings' }).hasAttribute('disabled')).toBe(true) + act(() => { directory.update((state) => { state.pending = null }) }) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +}) diff --git a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx deleted file mode 100644 index 8a4f332279..0000000000 --- a/packages/client/ui-model-selection/tests/model-menu-tab.client.spec.tsx +++ /dev/null @@ -1,274 +0,0 @@ -// @vitest-environment jsdom -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { ComponentProps } from 'react' -import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' -import { ModelSelect } from '../src/client/ModelSelect.tsx' -import type { ModelDirectoryState } from '../src/client/directory.ts' -import { en } from '../src/client/locales.ts' - -beforeEach(() => { - const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') - Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }) - onTestFinished(() => { - if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, 'scrollIntoView') - else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) - }) -}) -afterEach(() => { cleanup(); vi.unstubAllGlobals() }) - -function setup(count = 2, hasReasoning = true, providerDefault = false) { - const select = vi.fn(async () => ({ ok: true as const, value: undefined })) - const toggle = vi.fn() - const directory = createSnapshotStore({ - current: { provider: 'sample', model: 'model-1' }, routable: true, - groups: [{ id: 'sample', name: 'Sample', models: Array.from({ length: count }, (_, index) => ({ - id: `model-${index + 1}`, name: `Model ${index + 1}`, - ...hasReasoning ? { reasoning: { efforts: [{ id: 'low', name: 'Low' }, { id: 'high', name: 'High' }], - ...providerDefault ? {} : { defaultEffort: 'high' } } } : {}, - })) }], failures: [], status: 'ready', pending: null, error: null, - }) - const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { - if (name === 'conversation.input.model.options') { - const controls = owner as OwnerOf<'conversation.input.model.options'> - return <> - - - - } - if (name === 'conversation.input.model.page') { - const controls = owner as OwnerOf<'conversation.input.model.page'> - return - } - return options?.fallback ?? null - } - render(<> typeof text === 'string' ? text : text.en} select={select} renderSlot={renderSlot} t={makeTranslate(en)} />) - const trigger = screen.getByRole('button', { name: /^Select model, current/ }) - fireEvent.click(trigger) - const model = () => screen.getByRole('menuitem', { name: /Model.*Model 1/ }) - const team = () => screen.getByRole('menuitem', { name: 'Agent teamwork' }) - const tag = () => screen.getByRole('button', { name: /^Effort:/ }) - return { select, toggle, directory, trigger, model, team, tag } -} -function tab(shiftKey = false) { - const event = new KeyboardEvent('keydown', { key: 'Tab', shiftKey, bubbles: true, cancelable: true }) - fireEvent(document.activeElement!, event) - return event -} - -it('Tab moves from the trigger through root controls without opening a page or selecting a value', () => { - const view = setup() - tab() - expect(document.activeElement).toBe(view.model()) - tab() - expect(document.activeElement).toBe(view.tag()) - tab() - expect(document.activeElement).toBe(screen.getByRole('slider', { name: 'Effort' })) - tab() - expect(document.activeElement).toBe(view.team()) - tab(true) - expect(document.activeElement).toBe(screen.getByRole('slider')) - tab(true) - expect(document.activeElement).toBe(view.tag()) - tab(true) - expect(document.activeElement).toBe(view.model()) - expect(screen.queryByRole('menuitemradio')).toBeNull() - expect(screen.queryByRole('switch')).toBeNull() - expect(view.select).not.toHaveBeenCalled() - expect(view.toggle).not.toHaveBeenCalled() -}) - -it('includes default information before the range and keeps Escape at the tooltip layer first', () => { - vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) - const view = setup(2, true, true) - tab() - expect(document.activeElement).toBe(view.model()) - tab() - expect(document.activeElement).toBe(view.tag()) - tab() - const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) - expect(document.activeElement).toBe(info) - fireEvent.click(info) - expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(en['effort.defaultExplanation']) - fireEvent.keyDown(info, { key: 'Escape' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - expect(screen.getByRole('menu')).toBeTruthy() - expect(document.activeElement).toBe(info) - fireEvent.click(info) - tab() - const slider = screen.getByRole('slider') - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - expect(document.activeElement).toBe(slider) - tab() - expect(document.activeElement).toBe(view.team()) - tab(true) - expect(document.activeElement).toBe(slider) - tab(true) - expect(document.activeElement).toBe(info) - expect(view.select).not.toHaveBeenCalled() - expect(view.toggle).not.toHaveBeenCalled() -}) - -it('removes only the default information Tab stop when the selection changes', () => { - vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }) - const view = setup(2, true, true) - const info = screen.getByRole('button', { name: en['effort.defaultInfoLabel'] }) - info.focus() - act(() => { view.directory.update((snapshot) => { - snapshot.current = { provider: 'sample', model: 'model-1', reasoningEffort: 'high' } - }) }) - const slider = screen.getByRole('slider') - expect(screen.queryByRole('button', { name: en['effort.defaultInfoLabel'] })).toBeNull() - expect(document.activeElement).toBe(slider) - tab(true) - expect(document.activeElement).toBe(view.tag()) - act(() => { view.directory.update((snapshot) => { - snapshot.current = { provider: 'sample', model: 'model-1' } - }) }) - tab() - expect(document.activeElement).toBe(screen.getByRole('button', { name: en['effort.defaultInfoLabel'] })) - expect(view.select).not.toHaveBeenCalled() -}) - -it('keeps a pending contributed entry in Tab order without allowing navigation', () => { - const view = setup() - tab(); tab(); tab(); tab() - const team = view.team() - expect(document.activeElement).toBe(team) - act(() => { view.directory.update((snapshot) => { - snapshot.status = 'selecting' - snapshot.pending = { provider: 'sample', model: 'model-1', reasoningEffort: 'low' } - }) }) - expect(view.team()).toBe(team) - expect(team.hasAttribute('disabled')).toBe(false) - expect(team.getAttribute('aria-disabled')).toBe('true') - expect(document.activeElement).toBe(team) - fireEvent.click(team) - expect(screen.queryByRole('switch')).toBeNull() - tab(true) - expect(document.activeElement).toBe(screen.getByRole('slider')) - tab() - expect(document.activeElement).toBe(team) - expect(view.select).not.toHaveBeenCalled() - expect(view.toggle).not.toHaveBeenCalled() -}) - -it('Shift+Tab from the first root control returns to its trigger instead of activating it', () => { - const view = setup() - tab() - expect(tab(true).defaultPrevented).toBe(true) - expect(document.activeElement).toBe(view.trigger) - expect(screen.queryByRole('menu')).toBeNull() - expect(view.select).not.toHaveBeenCalled() -}) - -it('Tab at the final root control closes the portal and leaves native forward traversal enabled', () => { - const view = setup() - view.team().focus() - expect(tab().defaultPrevented).toBe(false) - expect(document.activeElement).toBe(view.trigger) - expect(screen.queryByRole('menu')).toBeNull() - expect(view.toggle).not.toHaveBeenCalled() -}) - -it('skips a reasoning control when the model does not advertise one', () => { - const view = setup(2, false) - tab(); tab() - expect(document.activeElement).toBe(view.team()) - expect(screen.queryByRole('slider')).toBeNull() - expect(view.select).not.toHaveBeenCalled() -}) - -it('Tab and Shift+Tab traverse small model lists without choosing any model', () => { - const view = setup() - fireEvent.click(view.model()) - const rows = screen.getAllByRole('menuitemradio') - expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() - expect(document.activeElement).toBe(rows[0]) - tab() - expect(document.activeElement).toBe(rows[1]) - tab(true) - expect(document.activeElement).toBe(rows[0]) - expect(view.select).not.toHaveBeenCalled() -}) - -it('Tab leaves search without committing; Shift+Tab returns through search to the trigger', () => { - const view = setup(6) - fireEvent.click(view.model()) - const search = screen.getByRole('searchbox') - fireEvent.keyDown(search, { key: 'ArrowDown' }) - tab() - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) - expect(view.select).not.toHaveBeenCalled() - expect(screen.getAllByRole('menuitemradio').filter(row => row.tabIndex === 0)).toHaveLength(1) - tab(true) - expect(document.activeElement).toBe(search) - tab(true) - expect(document.activeElement).toBe(view.trigger) - expect(screen.queryByRole('searchbox')).toBeNull() -}) - -it('includes the search clear button in Tab order and keeps Space native in search', () => { - const view = setup(6) - fireEvent.click(view.model()) - const search = screen.getByRole('searchbox') - fireEvent.change(search, { target: { value: 'Model 2' } }) - const space = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }) - fireEvent(search, space) - expect(space.defaultPrevented).toBe(false) - tab() - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Clear search' })) - tab() - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) - expect(view.select).not.toHaveBeenCalled() -}) - -it('Enter still selects a highlighted search result', async () => { - const view = setup(6) - fireEvent.click(view.model()) - const search = screen.getByRole('searchbox') - fireEvent.change(search, { target: { value: 'Model 2' } }) - await act(async () => { fireEvent.keyDown(search, { key: 'Enter' }) }) - await waitFor(() => { - expect(view.select).toHaveBeenCalledExactlyOnceWith({ provider: 'sample', model: 'model-2' }) - }) -}) - -it.each([2, 6])('returns from %i model choices with Escape, then closes the root with Escape', async (count) => { - const view = setup(count) - fireEvent.click(view.model()) - expect(screen.queryByText('Model', { exact: true })).toBeNull() - expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() - fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) - expect(screen.getByRole('slider')).toBeTruthy() - expect(document.activeElement).toBe(view.model()) - fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) - await waitFor(() => { expect(document.activeElement).toBe(view.trigger) }) - expect(screen.queryByRole('menu')).toBeNull() - expect(view.select).not.toHaveBeenCalled() -}) - -it('Tab leaves the Team page without toggling, while Escape returns to its root entry', () => { - const view = setup() - fireEvent.click(view.team()) - const toggle = screen.getByRole('switch') - expect(screen.getByRole('menu', { name: 'Team settings' })).toBeTruthy() - expect(screen.queryByText('Team settings')).toBeNull() - expect(document.activeElement).toBe(toggle) - expect(screen.queryByRole('button', { name: 'Back' })).toBeNull() - tab(true) - expect(document.activeElement).toBe(view.trigger) - expect(screen.queryByRole('switch')).toBeNull() - expect(view.toggle).not.toHaveBeenCalled() - fireEvent.click(view.trigger) - fireEvent.click(view.team()) - fireEvent.keyDown(screen.getByRole('switch'), { key: 'Escape' }) - expect(screen.queryByRole('switch')).toBeNull() - expect(view.team()).toBe(document.activeElement) -}) diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index a0e8414204..7990890cec 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import * as uiPrimitives from '@deepseek-ai/dsh-client-ui-primitives' -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { RemoteError, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { SessionId } from '@deepseek-ai/dsh-session/types' @@ -100,7 +100,6 @@ describe('ModelSelect label slot', () => { await runtime.root.declare({ 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, - 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, }, ({ renderSlot, SessionProvider }) => @@ -130,14 +129,15 @@ describe('ModelSelect label slot', () => { expect(external.querySelector('div')).toBeNull() fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'trusted: Same model' }), { key: 'ArrowDown' }) expect(document.activeElement).toBe(external) - fireEvent.click(external) + fireEvent.keyDown(external, { key: 'Tab' }) await waitFor(() => { expect(screen.getByTestId('trigger-external')).toBeTruthy() }) expect(select).toHaveBeenCalledWith({ provider: 'external', model: 'same-model' }) - await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) await act(async () => { await plugin.dispose() }) expect(runtime.slots.entries('conversation.input.model.label')).toHaveLength(0) expect(trigger.textContent).toBe('Same model') expect(trigger.querySelector('[data-provider-id="external"][data-model-id="same-model"]')).toBeTruthy() + fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.getAllByRole('menuitemradio').map(row => row.textContent)).toEqual(['Same model', 'Same model']) }) @@ -223,31 +223,23 @@ describe('ModelSelect reasoning effort', () => { />) const trigger = screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', }) fireEvent.click(trigger) - const efforts = within(screen.getByRole('group', { name: '推理等级' })) - expect(efforts.getByRole('button', { name: '推理等级:高' })).toBeTruthy() - expect(efforts.getByRole('slider').getAttribute('max')).toBe('2') - expect(efforts.getByRole('slider', { name: '推理等级' }).getAttribute('aria-valuetext')).toBe('高') - const label = screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')! - expect(label.textContent).toBe('推理等级:高') - expect(label.tabIndex).toBe(-1) - expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) + .toEqual(['Off', 'High', 'Max']) expect(screen.queryByText('Largest budget')).toBeNull() - const slider = efforts.getByRole('slider') - slider.focus() - fireEvent.change(slider, { target: { value: '2' } }) + fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) await waitFor(() => { expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 最高') - expect(document.activeElement).toBe(slider) - expect(screen.getByRole('menu')).toBeTruthy() + expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 Max') + expect(document.activeElement).toBe(trigger) }) }) @@ -274,69 +266,11 @@ describe('ModelSelect reasoning effort', () => { />) fireEvent.click(screen.getByRole('button', { - name: '选择模型,当前 Model,推理等级 默认', + name: '选择模型,当前 Model,推理等级 Default', })) - const efforts = within(screen.getByRole('group', { name: '推理等级' })) - expect(efforts.getByRole('button', { name: '默认推理等级说明' })).toBeTruthy() - expect(screen.getByRole('group', { name: '推理等级' }).querySelector('[data-effort-label]')!.textContent).toBe('推理等级:默认') - expect(efforts.getByRole('slider').getAttribute('max')).toBe('1') - expect(efforts.getByRole('slider').getAttribute('aria-valuetext')).toBe('默认') - }) - - it('submits the Default stop by omitting effort instead of sending a display label', async () => { - const current = { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } - const groups = state().groups.map(group => ({ ...group, models: group.models.map(model => ({ - ...model, reasoning: { efforts: reasoning.efforts }, - })) })) - const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) - render() - fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - screen.getByRole('slider').focus() - fireEvent.change(screen.getByRole('slider'), { target: { value: '0' } }) - expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) - await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('slider')) }) - expect(screen.getByRole('menu')).toBeTruthy() - }) - - it('submits the final dragged stop once and keeps the committed trigger caption until acceptance', async () => { - const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) - render() - const trigger = screen.getByRole('button', { name: /选择模型/ }) - fireEvent.click(trigger) - const slider = screen.getByRole('slider', { name: '推理等级' }) - slider.focus() - fireEvent.pointerDown(slider, { pointerId: 1 }) - fireEvent.change(slider, { target: { value: '0' } }) - fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('最高') - expect(trigger.getAttribute('aria-label')).toBe('选择模型,当前 DeepSeek-V4-Flash,推理等级 高') - expect(select).not.toHaveBeenCalled() - fireEvent.pointerUp(slider, { pointerId: 1 }) - expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) - await waitFor(() => { expect(document.activeElement).toBe(slider) }) - expect(screen.getByRole('menu')).toBeTruthy() - }) - - it('keeps the committed effort and allows retry after a rejected inline selection', async () => { - const select = vi.fn().mockResolvedValue({ ok: false, error: new RemoteError('session/model-unavailable', 'effort unavailable', { - provider: 'deepseek-official', model: 'deepseek-v4-flash', - }) }) - render() - fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - screen.getByRole('slider').focus() - fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) - expect((await screen.findByRole('alert')).textContent).toContain('effort unavailable') - expect(screen.getByRole('menu')).toBeTruthy() - const slider = screen.getByRole('slider', { name: '推理等级' }) - expect(slider.getAttribute('aria-valuetext')).toBe('高') - expect(slider.hasAttribute('disabled')).toBe(false) - expect(document.activeElement).toBe(slider) - await act(async () => { fireEvent.change(slider, { target: { value: '0' } }) }) - expect(select).toHaveBeenLastCalledWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'off' }) + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + expect(screen.getAllByRole('menuitemradio').map(item => item.textContent)) + .toEqual(['Default', 'Standard']) }) it('opens model choices without exposing a saved route absent from the catalog', () => { @@ -364,7 +298,7 @@ describe('ModelSelect reasoning effort', () => { expect(select).not.toHaveBeenCalled() expect(directory.getSnapshot().current).toEqual({ provider: 'deepseek-official', model: 'removed-model' }) fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }), { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) it.each(['model', 'provider'])('hides the saved id and effort when the selected %s disappears', (removed) => { @@ -382,7 +316,7 @@ describe('ModelSelect reasoning effort', () => { fireEvent.click(trigger) expect(screen.getByRole('status').textContent).toBe(zh['empty.models']) fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true }) - expect(screen.queryByRole('group', { name: '模型' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) it.each([null, state().current])('shows loading until the catalog and Session projection are both ready (%j)', async (current) => { @@ -406,7 +340,7 @@ describe('ModelSelect reasoning effort', () => { directory.set(state()) await waitFor(() => { expect(screen.getByRole('button', { - name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 高', + name: '选择模型,当前 DeepSeek-V4-Flash,推理等级 High', })).toBeTruthy() }) }) @@ -444,17 +378,15 @@ describe('ModelSelect reasoning effort', () => { fireEvent.mouseMove(rejected) fireEvent.click(rejected) const toast = await screen.findByRole('alert') - const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) - expect(document.activeElement).toBe(selected) + expect(document.activeElement).toBe(trigger) expect(toast.textContent).toBe(sessionInUse ? zh['error.sessionInUse'] : '模型操作失败:session/model-unavailable: session already contains images') // The selection failure does not render the in-menu load strip (no Retry). expect(screen.queryByRole('button', { name: '重试' })).toBeNull() - fireEvent.keyDown(selected, { key: 'Tab' }) + fireEvent.keyDown(trigger, { key: 'Tab' }) expect(screen.queryByRole('searchbox')).toBeNull() - expect(document.activeElement).toBe(rejected) - expect(select).toHaveBeenCalledTimes(1) + expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) }) it('spins on the trigger and the chosen model row until the selection settles, across pane changes', async () => { @@ -501,161 +433,21 @@ describe('ModelSelect reasoning effort', () => { expect(trigger.getAttribute('aria-busy')).toBe('false') }) - it.each([ - { outcome: 'success', navigation: 'reopen-model' }, - { outcome: 'failure', navigation: 'reopen-model' }, - { outcome: 'success', navigation: 'tab-search' }, - { outcome: 'failure', navigation: 'tab-search' }, - { outcome: 'success', navigation: 'none' }, - { outcome: 'failure', navigation: 'none' }, - ] as const)('settles a delayed model $outcome without overriding $navigation navigation', async ({ outcome, navigation }) => { - const groups = modelGroups(5) - const directory = createSnapshotStore(state({ groups })) - const pending = Promise.withResolvers['select']>>>() - onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) - const selection: ModelSelection = { provider: 'deepseek-official', model: 'model-2' } - const select = vi.fn((next: ModelSelection) => { - directory.set(state({ groups, status: 'selecting', pending: next })) - return pending.promise - }) - render() - const trigger = screen.getByRole('button', { name: /选择模型/ }) - fireEvent.click(trigger) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - const originalSearch = screen.getByRole('searchbox') - fireEvent.click(screen.getByRole('menuitemradio', { name: 'Model 2' })) - expect(select).toHaveBeenCalledExactlyOnceWith(selection) - expect(document.activeElement).toBe(trigger) - expect(trigger.getAttribute('aria-busy')).toBe('true') - - if (navigation === 'reopen-model') { - fireEvent.keyDown(trigger, { key: 'Escape' }) - expect(screen.queryByRole('searchbox')).toBeNull() - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - expect(screen.getByRole('searchbox')).not.toBe(originalSearch) - } else if (navigation === 'tab-search') { - fireEvent.keyDown(trigger, { key: 'Tab' }) - expect(screen.getByRole('searchbox')).toBe(originalSearch) - } - const search = screen.getByRole('searchbox') - if (navigation !== 'none') expect(document.activeElement).toBe(search) - - const error = new RemoteError('session/model-unavailable', 'model is unavailable', selection) - await act(async () => { - directory.set(outcome === 'success' - ? state({ groups, current: selection }) - : state({ groups, status: 'error', error: error.message })) - pending.resolve(outcome === 'success' ? { ok: true, value: undefined } : { ok: false, error }) - }) - - expect(trigger.getAttribute('aria-busy')).toBe('false') - if (navigation !== 'none') { - expect(screen.getByRole('searchbox')).toBe(search) - expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() - expect(document.activeElement).toBe(search) - } else if (outcome === 'success') { - expect(screen.queryByRole('searchbox')).toBeNull() - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /模型.*Model 2/ })) - } - if (outcome === 'failure') { - expect(screen.getByRole('alert').textContent).toBe('模型操作失败:session/model-unavailable: model is unavailable') - expect(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }).getAttribute('aria-checked')).toBe('true') - } else { - expect(screen.queryByRole('alert')).toBeNull() - expect(directory.getSnapshot().current).toEqual(selection) - } - expect(select).toHaveBeenCalledTimes(1) - }) - - it('announces the pending target while retaining slider focus and blocking duplicate submissions', async () => { + it('spins on the chosen effort row only', () => { const directory = createSnapshotStore(state()) - const pending = Promise.withResolvers<{ ok: true; value: undefined }>() - onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) const select = vi.fn((selection: ModelSelection) => { directory.set(state({ status: 'selecting', pending: selection })) - return pending.promise + return new Promise(() => {}) }) render() - const trigger = screen.getByRole('button', { name: /选择模型|当前/ }) - fireEvent.click(trigger) - const slider = screen.getByRole('slider', { name: '推理等级' }) - screen.getByRole('slider').focus() - fireEvent.change(screen.getByRole('slider'), { target: { value: '2' } }) - expect(trigger.getAttribute('aria-busy')).toBe('true') - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - expect(slider.hasAttribute('disabled')).toBe(false) - expect(slider.getAttribute('aria-disabled')).toBe('true') - expect(slider.getAttribute('aria-busy')).toBe('true') - expect(slider.getAttribute('aria-valuetext')).toBe('最高') - expect(document.activeElement).toBe(slider) - fireEvent.change(slider, { target: { value: '0' } }) - expect(select).toHaveBeenCalledExactlyOnceWith({ - provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', - }) - await act(async () => { - directory.set(state({ current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) - pending.resolve({ ok: true, value: undefined }) - }) - expect(screen.getByRole('menu')).toBeTruthy() - expect(trigger.getAttribute('aria-busy')).toBe('false') - expect(slider.getAttribute('aria-disabled')).toBe('false') - expect(slider.getAttribute('aria-valuetext')).toBe('最高') - expect(document.activeElement).toBe(slider) - }) - - it('keeps the browsed model page and search focus when an effort save finishes', async () => { - const groups = modelGroups(5) - const directory = createSnapshotStore(state({ groups })) - const pending = Promise.withResolvers<{ ok: true; value: undefined }>() - onTestFinished(async () => { await act(async () => { pending.resolve({ ok: true, value: undefined }) }) }) - const select = vi.fn((selection: ModelSelection) => { - directory.set(state({ groups, status: 'selecting', pending: selection })) - return pending.promise - }) - render() - fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - const slider = screen.getByRole('slider') - slider.focus() - fireEvent.change(slider, { target: { value: '2' } }) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - const search = screen.getByRole('searchbox') - expect(document.activeElement).toBe(search) - await act(async () => { - directory.set(state({ groups, current: { provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' } })) - pending.resolve({ ok: true, value: undefined }) - }) - expect(screen.getByRole('searchbox')).toBe(search) - expect(document.activeElement).toBe(search) - expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() - expect(select).toHaveBeenCalledExactlyOnceWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max' }) - }) - - it('keeps transient focus loss inside the menu but closes on a known outside focus target', () => { - render(<>) - const trigger = screen.getByRole('button', { name: /选择模型/ }) - fireEvent.click(trigger) - fireEvent.blur(trigger, { relatedTarget: null }) - expect(screen.getByRole('menu')).toBeTruthy() - fireEvent.blur(trigger, { relatedTarget: screen.getByRole('button', { name: 'Outside' }) }) - expect(screen.queryByRole('menu')).toBeNull() - }) - - it('closes the portaled model list when focus moves from search to an outside editor', () => { - render(<>
) - fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - expect(document.activeElement).toBe(screen.getByRole('searchbox')) - const editor = screen.getByLabelText('Outside editor') - act(() => { editor.focus() }) - expect(document.activeElement).toBe(editor) - expect(screen.queryByRole('menu')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: /选择模型|当前/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + fireEvent.click(screen.getByRole('menuitemradio', { name: /Max/ })) + expect(screen.getAllByRole('menuitemradio') + .filter(row => row.querySelector('[data-state="ongoing"]') !== null) + .map(row => row.textContent)).toEqual(['Max']) }) it('anchors the body portal with CSS and closes only on truly-outside mousedown', () => { @@ -749,22 +541,31 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(trigger) const modelCell = screen.getByRole('menuitem', { name: /^模型/ }) - const slider = screen.getByRole('slider', { name: '推理等级' }) + const effortCell = screen.getByRole('menuitem', { name: /推理等级/ }) fireEvent.keyDown(trigger, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(modelCell) fireEvent.keyDown(modelCell, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(slider) - expect(fireEvent.keyDown(slider, { key: 'ArrowDown' })).toBe(true) - expect(document.activeElement).toBe(slider) - expect(screen.queryByRole('searchbox')).toBeNull() - fireEvent.click(modelCell) + expect(document.activeElement).toBe(effortCell) + fireEvent.keyDown(effortCell, { key: 'Tab' }) + const high = screen.getByRole('menuitemradio', { name: 'High' }) + const max = screen.getByRole('menuitemradio', { name: /Max/ }) + expect(document.activeElement).toBe(high) + fireEvent.keyDown(high, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(max) + fireEvent.keyDown(max, { key: 'Escape' }) + + const restoredEffortCell = screen.getByRole('menuitem', { name: /推理等级/ }) + expect(document.activeElement).toBe(restoredEffortCell) + fireEvent.keyDown(restoredEffortCell, { key: 'ArrowUp' }) + const restoredModelCell = screen.getByRole('menuitem', { name: /^模型/ }) + expect(document.activeElement).toBe(restoredModelCell) + fireEvent.keyDown(restoredModelCell, { key: 'Tab' }) const model = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(model) if (modelCount > 4) { const search = screen.getByRole('searchbox') expect(document.activeElement).not.toBe(search) fireEvent.keyDown(model, { key: 'ArrowDown' }) - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 2' })) + expect(document.activeElement).toBe(search) } else { expect(screen.queryByRole('searchbox')).toBeNull() } @@ -777,73 +578,63 @@ describe('ModelSelect keyboard walk', () => { }, ) - it.each(['model', 'inline effort'])('does not select on button mousedown and mouseup alone in %s controls', (kind) => { + it.each(['model', 'effort'])('prevents button mousedown defaults in the %s pane without selecting it', (pane) => { const select = mountOpen() - const cell = screen.getByRole('menuitem', { name: /^模型/ }) + const cell = screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ }) expect(fireEvent.mouseDown(cell.firstElementChild!)).toBe(false) - if (kind === 'model') fireEvent.click(cell) - const target = kind === 'model' - ? screen.getAllByRole('menuitemradio')[0]! - : screen.getByRole('slider') + fireEvent.click(cell) + const rows = screen.getAllByRole('menuitemradio') const focused = document.activeElement - expect(fireEvent.mouseDown(target)).toBe(kind === 'inline effort') + expect(fireEvent.mouseDown(rows[0]!.firstElementChild!)).toBe(false) fireEvent.mouseUp(screen.getByRole('menu')) expect(select).not.toHaveBeenCalled() - expect(document.activeElement).toBe(focused) - if (kind === 'inline effort') { - expect(fireEvent.mouseDown(screen.getByRole('slider'))).toBe(true) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('高') - } else { - fireEvent.keyDown(focused!, { key: 'Escape' }) - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) - } + fireEvent.keyDown(focused!, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: pane === 'model' ? /^模型/ : /推理等级/ })) }) - it('walks between root controls while leaving adjustment arrows to the native range', () => { - const select = mountOpen() - const trigger = screen.getByRole('button', { name: /选择模型/ }) - const tag = screen.getByRole('button', { name: /^推理等级/ }) - const model = screen.getByRole('menuitem', { name: /^模型/ }) - const slider = screen.getByRole('slider', { name: '推理等级' }) - fireEvent.keyDown(trigger, { key: 'Tab' }) - expect(document.activeElement).toBe(model) - fireEvent.keyDown(model, { key: 'Tab' }) - expect(document.activeElement).toBe(tag) - fireEvent.keyDown(tag, { key: 'Tab' }) - expect(document.activeElement).toBe(slider) - expect(fireEvent.keyDown(slider, { key: 'ArrowRight' })).toBe(true) - expect(document.activeElement).toBe(slider) - fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true }) - expect(document.activeElement).toBe(tag) - fireEvent.keyDown(tag, { key: 'Tab', shiftKey: true }) - expect(document.activeElement).toBe(model) + it('↑↓ walk the rows of the shown pane, wrapping, and stay open', () => { + mountOpen() + // The trigger holds focus while the menu opens: the first forward step + // enters at the first cell instead of skipping it. false = preventDefault ran. + const cells = screen.getAllByRole('menuitem') + expect(fireEvent.keyDown(cells[0]!, { key: 'ArrowDown' })).toBe(false) + expect(document.activeElement).toBe(cells[0]) + + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + const rows = screen.getAllByRole('menuitemradio') + expect(rows.map(row => row.textContent)).toEqual(['Off', 'High', 'Max']) + // The pane opens on its checked row, so walking starts from High. + fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(rows[2]) + fireEvent.keyDown(rows[2]!, { key: 'ArrowDown' }) // wraps to the top + expect(document.activeElement).toBe(rows[0]) + fireEvent.keyDown(rows[0]!, { key: 'ArrowUp' }) // wraps to the bottom + expect(document.activeElement).toBe(rows[2]) expect(screen.getByRole('menu')).toBeTruthy() - expect(select).not.toHaveBeenCalled() }) - it('commits a range keyboard gesture once with the model route and retains slider focus', async () => { + it('Tab settles the focused row like Enter and closes the menu', async () => { const select = mountOpen() - const slider = screen.getByRole('slider', { name: '推理等级' }) - slider.focus() - fireEvent.keyDown(slider, { key: 'End' }) - // jsdom does not perform the native range value change for a keyboard event. - fireEvent.change(slider, { target: { value: '2' } }) - expect(slider.getAttribute('aria-valuetext')).toBe('最高') - expect(select).not.toHaveBeenCalled() - fireEvent.keyUp(slider, { key: 'End' }) - expect(select).toHaveBeenCalledExactlyOnceWith({ + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + const rows = screen.getAllByRole('menuitemradio') + fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) // High → Max + expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) + expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', }) - await waitFor(() => { expect(document.activeElement).toBe(slider) }) - expect(screen.getByRole('menu')).toBeTruthy() + await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) }) - it('Shift+Tab from the first model closes the menu and returns to the trigger', () => { + it('Shift+Tab leaves a drilled pane and then closes, like Escape', () => { mountOpen() - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - const selected = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) - expect(fireEvent.keyDown(selected, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + const rows = screen.getAllByRole('menuitemradio') + expect(fireEvent.keyDown(rows[0]!, { key: 'Tab', shiftKey: true })).toBe(false) + // Back on the drilled cell, then closed on the second press. + const cells = screen.getAllByRole('menuitem') + expect(document.activeElement).toBe(cells[1]) + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.keyDown(cells[1]!, { key: 'Tab', shiftKey: true }) expect(screen.queryByRole('menu')).toBeNull() }) @@ -859,36 +650,34 @@ describe('ModelSelect keyboard walk', () => { const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) + // The root pane's first cell carries the current selection. + const cells = screen.getAllByRole('menuitem') + expect(document.activeElement).toBe(cells[0]) expect(screen.getByRole('menu')).toBeTruthy() }) it('a backward step from outside the list enters at the last row, and a closed menu leaves Tab native', () => { mountOpen() + const [modelRow, effortRow] = screen.getAllByRole('menuitem') + expect(fireEvent.keyDown(modelRow!, { key: 'ArrowUp' })).toBe(false) + expect(document.activeElement).toBe(effortRow) const trigger = screen.getByRole('button', { name: /选择模型/ }) - expect(fireEvent.keyDown(trigger, { key: 'ArrowUp' })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('slider')) fireEvent.keyDown(trigger, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(true) }) - it('returns from all models to the committed effort without submitting another selection', () => { - const select = vi.fn() - render() - fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) - expect(screen.queryByRole('slider')).toBeNull() - fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) - expect(screen.getByRole('slider').getAttribute('aria-valuetext')).toBe('最高') - const caption = screen.getByRole('button', { name: '推理等级:最高' }) - fireEvent.click(caption) - expect(document.activeElement).toBe(screen.getByRole('slider')) - expect(select).not.toHaveBeenCalled() + it('hands a drilled pane the focus its unmounted cell left behind, on the value in use', () => { + mountOpen() + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + const rows = screen.getAllByRole('menuitemradio') + // The fixture's model defaults to the High effort: the checked row is where + // the keyboard lands, not the top of the list. + expect(rows[1]!.getAttribute('aria-checked')).toBe('true') + expect(document.activeElement).toBe(rows[1]) + // The walk continues from there. + fireEvent.keyDown(rows[1]!, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(rows[2]) }) it('keeps the card navigable when a pane has no rows, and leaves a retry its Tab', () => { @@ -913,12 +702,12 @@ describe('ModelSelect keyboard walk', () => { expect(fireEvent.mouseDown(retry)).toBe(false) fireEvent.click(retry) expect(load).toHaveBeenCalledTimes(2) - expect(screen.getByRole('group', { name: '模型' })).toBeTruthy() + expect(screen.getByRole('group', { name: '模型与推理等级' })).toBeTruthy() retry.focus() // A control that is not a row keeps the browser's traversal. expect(fireEvent.keyDown(retry, { key: 'Tab' })).toBe(true) fireEvent.keyDown(retry, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) it('focuses the checked model in a small catalog', () => { @@ -930,15 +719,19 @@ describe('ModelSelect keyboard walk', () => { expect(document.activeElement).toBe(rows[0]) }) - it('Escape from an unchanged inline slider closes the root menu and restores trigger focus', async () => { - const select = mountOpen() - const trigger = screen.getByRole('button', { name: /选择模型/ }) - const slider = screen.getByRole('slider', { name: '推理等级' }) - slider.focus() - expect(fireEvent.keyDown(slider, { key: 'Escape' })).toBe(false) + it('Escape returns to the root pane with the keyboard on the cell that drilled in', () => { + mountOpen() + fireEvent.click(screen.getByRole('menuitem', { name: /推理等级/ })) + const rows = screen.getAllByRole('menuitemradio') + fireEvent.keyDown(rows[0]!, { key: 'Escape' }) + // The root pane is back with its two cells. + const cells = screen.getAllByRole('menuitem') + // Back on the drilled cell, so the next keystroke still reaches the menu. + expect(document.activeElement).toBe(cells[1]) + expect(screen.getByRole('menu')).toBeTruthy() + // A second Escape closes back to the trigger. + fireEvent.keyDown(cells[1]!, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() - await waitFor(() => { expect(document.activeElement).toBe(trigger) }) - expect(select).not.toHaveBeenCalled() }) it('Escape from the model list lands back on the model cell', () => { @@ -983,7 +776,7 @@ describe('ModelSelect catalog size', () => { expect(search).toBeInstanceOf(HTMLInputElement) expect(document.activeElement).toBe(search) expect(search.getAttribute('aria-activedescendant')).toBe(rows[1]!.id) - expect(rows.filter(row => row.tabIndex === 0)).toEqual([rows[1]]) + expect(rows.every(row => row.tabIndex === -1)).toBe(true) } else { expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(count === 0 ? trigger : rows[count > 1 ? 1 : 0]) @@ -1034,7 +827,7 @@ describe('ModelSelect catalog size', () => { .toBe(screen.getAllByRole('menuitemradio')[checked ? 2 : 0]!.id) }) - it('moves actual row focus with arrows and Tab without choosing, then activates a small-catalog row', async () => { + it('moves actual row focus with arrows, leaves Enter native, and selects with Tab in a small catalog', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render( { expect(document.activeElement).toBe(rows[2]) expect(select).not.toHaveBeenCalled() expect(fireEvent.keyDown(rows[2]!, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(rows[3]) - expect(select).not.toHaveBeenCalled() - fireEvent.click(rows[3]!) - expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-4' }) - await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) - expect(screen.queryByRole('menuitemradio')).toBeNull() - expect(screen.getByRole('menu')).toBeTruthy() + expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() + expect(trigger.hasAttribute('data-selection-focus')).toBe(true) }) - it('moves Tab focus without selecting after hovering a small-catalog row', () => { + it('keeps Tab selection available after hovering a small-catalog row', async () => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) render() @@ -1080,8 +870,8 @@ describe('ModelSelect catalog size', () => { expect(document.activeElement).toBe(row) expect(row.hasAttribute('data-highlighted')).toBe(true) expect(fireEvent.keyDown(row, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'Model 4' })) - expect(select).not.toHaveBeenCalled() + expect(select).toHaveBeenCalledWith({ provider: 'deepseek-official', model: 'model-3' }) + await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) }) it.each(['Escape', 'Tab'])('leaves a small model pane with %s and returns to its root cell', (key) => { @@ -1092,14 +882,10 @@ describe('ModelSelect catalog size', () => { fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const row = screen.getAllByRole('menuitemradio')[0]! expect(fireEvent.keyDown(row, { key, shiftKey: key === 'Tab' })).toBe(false) + const cell = screen.getByRole('menuitem', { name: /^模型/ }) + expect(document.activeElement).toBe(cell) expect(select).not.toHaveBeenCalled() - if (key === 'Escape') { - const cell = screen.getByRole('menuitem', { name: /^模型/ }) - expect(document.activeElement).toBe(cell) - fireEvent.keyDown(cell, { key }) - } else { - expect(document.activeElement).toBe(screen.getByRole('button', { name: /选择模型/ })) - } + fireEvent.keyDown(cell, { key, shiftKey: key === 'Tab' }) expect(screen.queryByRole('menu')).toBeNull() }) }) @@ -1115,7 +901,7 @@ describe('ModelSelect search', () => { expect(document.activeElement).toBe(search) fireEvent.change(search, { target: { value: 'zzzz' } }) fireEvent.keyDown(search, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() fireEvent.click(trigger) expect(screen.getByRole('searchbox').getAttribute('value')).toBe('') expect(document.activeElement).toBe(screen.getByRole('searchbox')) @@ -1136,7 +922,7 @@ describe('ModelSelect search', () => { expect(screen.getByRole('status').closest('[role="menu"]')).toBeNull() }) - it('returns to the root model after Enter accepts the current model, without suppressing later focus', async () => { + it.each(['Enter', 'Tab'])('returns focus silently after %s accepts the current model, without suppressing later focus', async (key) => { const select = vi.fn() render(<> @@ -1146,9 +932,9 @@ describe('ModelSelect search', () => { const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) fireEvent.click(screen.getByRole('menuitem', { name: /模型/ })) - fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Enter' }) - await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) - expect(trigger.hasAttribute('data-selection-focus')).toBe(false) + fireEvent.keyDown(screen.getByRole('searchbox'), { key }) + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + expect(trigger.hasAttribute('data-selection-focus')).toBe(true) expect(select).not.toHaveBeenCalled() act(() => { screen.getByRole('button', { name: 'Outside' }).focus() }) expect(trigger.hasAttribute('data-selection-focus')).toBe(false) @@ -1156,7 +942,7 @@ describe('ModelSelect search', () => { expect(trigger.hasAttribute('data-selection-focus')).toBe(false) }) - it('keeps typing focus while arrows wrap across groups and Enter accepts the highlight', async () => { + it.each(['Enter', 'Tab'])('keeps typing focus while arrows wrap across groups and %s accepts the highlight', async (key) => { const select = vi.fn().mockResolvedValue({ ok: true, value: undefined }) const directory = createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'beta' }, @@ -1199,19 +985,19 @@ describe('ModelSelect search', () => { expect(search.hasAttribute('aria-activedescendant')).toBe(false) fireEvent.keyDown(search, { key: 'Enter' }) expect(select).not.toHaveBeenCalled() - expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('button', { name: '清除搜索' })) + expect(fireEvent.keyDown(search, { key: 'Tab' })).toBe(true) fireEvent.click(screen.getByRole('button', { name: '清除搜索' })) const restored = screen.getAllByRole('menuitemradio') expect(search.getAttribute('aria-activedescendant')).toBe(restored[0]!.id) fireEvent.mouseMove(restored[4]!) expect(search.getAttribute('aria-activedescendant')).toBe(restored[4]!.id) expect(document.activeElement).toBe(search) - fireEvent.keyDown(search, { key: 'Enter' }) + fireEvent.keyDown(search, { key }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gamma' }) - await waitFor(() => { expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: /^模型/ })) }) - expect(screen.queryByRole('menuitemradio')).toBeNull() - expect(screen.getByRole('menu')).toBeTruthy() + await waitFor(() => { expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) + const trigger = screen.getByRole('button', { name: /选择模型/ }) + await waitFor(() => { expect(document.activeElement).toBe(trigger) }) + expect(trigger.hasAttribute('data-selection-focus')).toBe(true) }) it('filters model names fuzzily, hides empty groups, clears on reopening, and selects a result', async () => { @@ -1259,8 +1045,8 @@ describe('ModelSelect search', () => { fireEvent.keyDown(reopened, { key: 'ArrowDown' }) expect(document.activeElement).toBe(reopened) expect(reopened.getAttribute('aria-activedescendant')).toBe(row.id) - fireEvent.keyDown(reopened, { key: 'Enter' }) - await waitFor(() => { expect(screen.queryByRole('menuitemradio')).toBeNull() }) + fireEvent.keyDown(reopened, { key: 'Tab' }) + await waitFor(() => { expect(screen.queryByRole('menu')).toBeNull() }) expect(select).toHaveBeenCalledWith({ provider: 'other', model: 'gemini' }) }) }) @@ -1280,7 +1066,7 @@ it('hides the inherited effort until a listed model is selected', async () => { const row = screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }) expect(document.activeElement).toBe(row) fireEvent.keyDown(row, { key: 'Escape' }) - expect(screen.queryByRole('group', { name: '模型' })).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() fireEvent.click(trigger) expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })) @@ -1325,148 +1111,15 @@ it('restores the account model name after login without changing the saved route const directory = createSnapshotStore(state({ current: selected, groups, retainedEffort: 'High' })) render() - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') act(() => { directory.update((snapshot) => { snapshot.groups = []; snapshot.routable = false }) }) expect(screen.getByRole('button', { name: '请选择模型' }).textContent).toBe('请选择模型') act(() => { directory.update((snapshot) => { snapshot.groups = groups; snapshot.routable = true }) }) - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek Flash高') + expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') expect(directory.getSnapshot().current).toEqual(selected) }) -describe('ModelSelect contributed pages', () => { - function mountPage(locked = false, withSwitch = true) { - const toggle = vi.fn() - const select = vi.fn() - const owners = vi.fn((_name: string, _owner: object) => {}) - const renderSlot: ComponentProps['renderSlot'] = (name, owner: object, options) => { - owners(name, owner) - if (name === 'conversation.input.model.options') { - const controls = owner as OwnerOf<'conversation.input.model.options'> - return - } - if (name === 'conversation.input.model.page') { - if (options?.entryKey !== 'fixture-settings') throw new Error('Unexpected detail page key') - const controls = owner as OwnerOf<'conversation.input.model.page'> - return <> -

用于解释该设置的完整说明

- {withSwitch && } - - - - } - return options?.fallback ?? null - } - const directory = createSnapshotStore(state()) - const view = render() - const trigger = screen.getByRole('button', { name: /^选择模型/ }) - if (!locked) fireEvent.click(trigger) - return { directory, view, trigger, renderSlot, owners, toggle, select } - } - - it('opens only the keyed detail controls and returns to the invoking entry with Escape', () => { - const { toggle, select } = mountPage() - expect(screen.queryByRole('switch')).toBeNull() - expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() - const entry = screen.getByRole('menuitem', { name: '设置 关' }) - fireEvent.click(entry) - const toggleButton = screen.getByRole('switch', { name: '启用示例设置' }) - expect(document.activeElement).toBe(toggleButton) - expect(screen.queryByText('示例设置')).toBeNull() - expect(screen.getByRole('menu', { name: '示例设置' })).toBeTruthy() - expect(screen.queryByRole('button', { name: '返回' })).toBeNull() - expect(screen.getByText('用于解释该设置的完整说明')).toBeTruthy() - expect(screen.queryByRole('slider')).toBeNull() - expect(screen.queryByRole('menuitem', { name: /^模型/ })).toBeNull() - fireEvent.click(toggleButton) - expect(toggle).toHaveBeenCalledOnce() - expect(select).not.toHaveBeenCalled() - expect(screen.getByRole('menu')).toBeTruthy() - fireEvent.keyDown(toggleButton, { key: 'Escape' }) - expect(screen.queryByRole('switch')).toBeNull() - expect(screen.queryByText('用于解释该设置的完整说明')).toBeNull() - expect(screen.getByRole('slider', { name: '推理等级' })).toBeTruthy() - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: '设置 关' })) - }) - - it('moves Tab from the inline range to a contributed entry and Shift+Tab back without changing effort', () => { - const { select } = mountPage() - const slider = screen.getByRole('slider', { name: '推理等级' }) - const tag = screen.getByRole('button', { name: /^推理等级/ }) - const entry = screen.getByRole('menuitem', { name: '设置 关' }) - slider.focus() - expect(fireEvent.keyDown(slider, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(entry) - slider.focus() - expect(fireEvent.keyDown(slider, { key: 'Tab', shiftKey: true })).toBe(false) - expect(document.activeElement).toBe(tag) - expect(select).not.toHaveBeenCalled() - }) - - it('focuses the keyed page when it has no switch and Tabs through its controls', () => { - mountPage(false, false) - fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) - const page = screen.getByRole('menu', { name: '示例设置' }) - expect(document.activeElement).toBe(page) - expect(fireEvent.keyDown(page, { key: 'Tab' })).toBe(false) - const report = screen.getByRole('button', { name: '报告失败' }) - expect(document.activeElement).toBe(report) - expect(fireEvent.keyDown(report, { key: 'Tab' })).toBe(false) - expect(document.activeElement).toBe(screen.getByRole('button', { name: '关闭设置' })) - expect(screen.getByRole('menu')).toBeTruthy() - }) - - it('passes model pending separately from a genuine lock into both contributed slots', () => { - const { directory, toggle, owners } = mountPage() - const entry = screen.getByRole('menuitem', { name: '设置 关' }) - entry.focus() - owners.mockClear() - const selecting = state({ status: 'selecting', pending: { - provider: 'deepseek-official', model: 'deepseek-v4-flash', reasoningEffort: 'max', - } }) - act(() => { directory.set(selecting) }) - expect(owners).toHaveBeenCalledWith('conversation.input.model.options', expect.objectContaining({ locked: false, pending: true })) - expect(entry.hasAttribute('disabled')).toBe(false) - expect(entry.getAttribute('aria-disabled')).toBe('true') - expect(document.activeElement).toBe(entry) - fireEvent.click(entry) - expect(screen.queryByRole('switch')).toBeNull() - act(() => { directory.set(state()) }) - fireEvent.click(entry) - const switchButton = screen.getByRole('switch', { name: '启用示例设置' }) - owners.mockClear() - act(() => { directory.set(selecting) }) - expect(owners).toHaveBeenCalledWith('conversation.input.model.page', expect.objectContaining({ locked: false, pending: true })) - expect(switchButton.hasAttribute('disabled')).toBe(false) - expect(switchButton.getAttribute('aria-disabled')).toBe('true') - expect(document.activeElement).toBe(switchButton) - fireEvent.click(switchButton) - expect(toggle).not.toHaveBeenCalled() - fireEvent.keyDown(switchButton, { key: 'Escape' }) - expect(screen.getByRole('slider').hasAttribute('disabled')).toBe(false) - expect(screen.getByRole('slider').getAttribute('aria-disabled')).toBe('true') - }) - - it('retains detail controls after reported failure and lets the contribution dismiss with trigger focus', () => { - const { trigger } = mountPage() - fireEvent.click(screen.getByRole('menuitem', { name: '设置 关' })) - fireEvent.click(screen.getByRole('button', { name: '报告失败' })) - expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') - expect(screen.getByRole('switch', { name: '启用示例设置' })).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: '关闭设置' })) - expect(screen.queryByRole('menu')).toBeNull() - expect(document.activeElement).toBe(trigger) - expect(screen.getByRole('alert').textContent).toBe('示例设置保存失败') - }) -}) - it('dismisses contributed options with focus on the trigger before opening another overlay', () => { const renderSlot = vi.fn((_name: string, _owner: object) => null) render(-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 4c106f3908..95f4afe55f 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。可选的 `pending` 拒绝新变更并设置 `aria-disabled` 与 `aria-busy`,但不设置原生 `disabled`,因此保存期间保留焦点,除非 `disabled` 同时为 true。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 3a48484f76..980a08f6be 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -9,18 +9,17 @@ import css from './Switch.module.css' * @param props.checked - the current state; the control is fully controlled. * @param props.onChange - called with the state the click asks for. * @param props.label - localized accessible name, owned by the render site. - * @param props.disabled - whether the control is unavailable and excluded from keyboard focus. - * @param props.pending - a write is in flight; refuse further changes while preserving focus. + * @param props.disabled - whether the control refuses input; owners also set it + * while a write is in flight, not only when a deployment locks the toggle. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, pending = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, title, className }: { checked: boolean onChange: (next: boolean) => void label: string disabled?: boolean - pending?: boolean title?: string | undefined // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). @@ -34,10 +33,8 @@ export function Switch({ checked, onChange, label, disabled = false, pending = f aria-label={label} title={title} disabled={disabled} - aria-disabled={disabled || pending || undefined} - aria-busy={pending || undefined} className={clsx(css.switch, className)} - onClick={() => { if (!pending) onChange(!checked) }} + onClick={() => { onChange(!checked) }} > diff --git a/packages/client/ui-primitives/tests/switch.client.spec.tsx b/packages/client/ui-primitives/tests/switch.client.spec.tsx index 6aef86cc3e..a80eae48d3 100644 --- a/packages/client/ui-primitives/tests/switch.client.spec.tsx +++ b/packages/client/ui-primitives/tests/switch.client.spec.tsx @@ -33,39 +33,6 @@ describe('Switch', () => { expect(onChange).not.toHaveBeenCalled() }) - it.each([false, true])('keeps focus while pending and refuses repeated activation (checked: %s)', (checked) => { - const onChange = vi.fn() - const { rerender } = render() - const control = screen.getByRole('switch') as HTMLButtonElement - control.focus() - rerender() - expect(control.disabled).toBe(false) - expect(control.getAttribute('aria-disabled')).toBe('true') - expect(control.getAttribute('aria-busy')).toBe('true') - expect(control.getAttribute('aria-checked')).toBe(String(checked)) - expect(document.activeElement).toBe(control) - fireEvent.click(control) - fireEvent.click(control) - expect(onChange).not.toHaveBeenCalled() - rerender() - expect(control.getAttribute('aria-disabled')).toBeNull() - expect(control.getAttribute('aria-busy')).toBeNull() - expect(document.activeElement).toBe(control) - fireEvent.click(control) - expect(onChange).toHaveBeenCalledExactlyOnceWith(!checked) - }) - - it('keeps a locked switch natively disabled while pending', () => { - const onChange = vi.fn() - render() - const control = screen.getByRole('switch') as HTMLButtonElement - expect(control.disabled).toBe(true) - expect(control.getAttribute('aria-disabled')).toBe('true') - expect(control.getAttribute('aria-busy')).toBe('true') - fireEvent.click(control) - expect(onChange).not.toHaveBeenCalled() - }) - it('carries a lock reason as the hover title when the owner names one', () => { render( {}} />) expect(screen.getByRole('switch').getAttribute('title')).toBe('Managed by policy') diff --git a/packages/client/ui-theme/src/styles/design-platform.css b/packages/client/ui-theme/src/styles/design-platform.css index 89863d247b..bf4ef0fc1d 100644 --- a/packages/client/ui-theme/src/styles/design-platform.css +++ b/packages/client/ui-theme/src/styles/design-platform.css @@ -295,8 +295,6 @@ body { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-100); - --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); - --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-00); --dsw-alias-toast-action: var(--dsw-static-deepseek-400); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-800); @@ -449,8 +447,6 @@ body[data-ds-dark-theme] { --dsw-alias-state-warn-primary: var(--dsw-static-amber-500); --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400); --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-900); - --dsw-alias-slider-thumb: var(--dsw-static-neutral-bluish-00); - --dsw-alias-slider-thumb-mark: var(--dsw-static-deepseek-500); --dsw-alias-switch-thumb: var(--dsw-static-neutral-bluish-400); --dsw-alias-toast-action: var(--dsw-static-deepseek-400); --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-750); 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 5491096df3..99667674df 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1619,7 +1619,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:72', + source: 'packages/client/ui-model-selection/src/client/slots.ts:70', }, { key: 'conversation.input.model.options', @@ -1648,7 +1648,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', ], ownerPropsReferences: [], @@ -1682,7 +1682,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:43', + source: 'packages/client/ui-model-selection/src/client/slots.ts:41', }, { key: 'conversation.input.model.page', @@ -1699,7 +1699,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer is unavailable for interaction. */\n locked: boolean\n /** A model or effort selection is saving; block new actions without dimming or removing focus. */\n pending: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -1732,7 +1732,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:52', + source: 'packages/client/ui-model-selection/src/client/slots.ts:50', }, { key: 'conversation.input.overlay', diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index 94d259cd4b..a3e682317c 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -24,7 +24,7 @@ - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Workspace Write"': Workspace Write -- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort High": DeepSeek-V4-Flash-Vision-Exp High +- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort high": DeepSeek-V4-Flash-Vision-Exp high - button "Send message" [disabled] - button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s - button "17.3K tok · Cache hit 51%": 17.3K tokCache hit 51% diff --git a/snapshots/web/minimal-read-image/ui.expected.md b/snapshots/web/minimal-read-image/ui.expected.md index 38c5c387bd..ab1052525e 100644 --- a/snapshots/web/minimal-read-image/ui.expected.md +++ b/snapshots/web/minimal-read-image/ui.expected.md @@ -29,7 +29,7 @@ - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Workspace Write"': Workspace Write -- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort High": DeepSeek-V4-Flash-Vision-Exp High +- button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort high": DeepSeek-V4-Flash-Vision-Exp high - button "Send message" [disabled] - button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s - button "28 tok · Cache hit 0%": 28 tokCache hit 0% From 38870162a16fb7bd60209901acc95aad439ef4ce Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 21:28:14 +0800 Subject: [PATCH 08/68] fix(ui): align team settings width and Chinese switch copy --- apps/web/tests/agent-team-panel.e2e.ts | 40 +++++++-- apps/web/tests/plugin-manager.e2e.ts | 3 +- .../collaboration.zh.expected.md | 14 +-- .../client/ui-agent-team/README.i18n.yaml | 2 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../ui-agent-team/src/client/locales.ts | 14 +-- .../team-disable-confirmation.client.spec.tsx | 4 +- .../tests/team-mode-callbacks.client.spec.tsx | 85 +++++++++++++++++++ .../tests/team-mode.client.spec.tsx | 17 +++- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../src/client/ModelSelect.module.css | 4 + .../src/client/ModelSelect.tsx | 2 +- 14 files changed, 162 insertions(+), 35 deletions(-) create mode 100644 packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 3cf5e843f0..dfbc248bba 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -30,7 +30,7 @@ const RECEIPT_LOCALES = [ }, { language: 'Chinese', code: 'zh', browserLocale: 'zh-CN', connect: connectFreshWorkspaceZh, - modelButton: /^选择模型/u, toggle: '启用智能体团队协作', title: '智能体团队协作', + modelButton: /^选择模型/u, toggle: '开启智能体团队协作', title: '智能体团队协作', enabled: '已开启', disabled: '已停用', suggestions: '触发候选建议', commandLabel: '智能体团队协作', failure: '执行失败:Use /team on or /team off.', @@ -168,7 +168,7 @@ describe('web e2e: agent teamwork panel', () => { } }) - it('keeps explanatory text noninteractive and the settings page inside wide and narrow viewports', async () => { + it('aligns settings with the root menu and keeps explanatory text noninteractive in wide and narrow viewports', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-settings-page')) const viewport = page.viewportSize()! try { @@ -181,16 +181,37 @@ describe('web e2e: agent teamwork panel', () => { expect(await toggle.getAttribute('aria-checked')).toBe('false') for (const size of [viewport, { width: 390, height: 700 }]) { await page.setViewportSize(size) + await page.keyboard.press('Escape') + const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) + await summary.waitFor() + const rootBounds = await menu.evaluate((element) => { + const { width, left, right } = element.getBoundingClientRect() + return { width, left, right } + }) + expect(rootBounds.width).toBe(240) + await summary.click() + await toggle.waitFor() + await expect.poll(() => menu.evaluate((element) => { + const { width, left, right } = element.getBoundingClientRect() + return { width, left, right } + })).toEqual(rootBounds) await expect.poll(() => menu.evaluate((element) => { const bounds = element.getBoundingClientRect() return bounds.left >= 12 && bounds.right <= innerWidth - 12 && bounds.top >= 12 && bounds.bottom <= innerHeight - 12 && element.scrollWidth <= element.clientWidth })).toBe(true) + expect(await description.evaluate((element) => { + const bounds = element.getBoundingClientRect() + const style = getComputedStyle(element) + return bounds.height > Number.parseFloat(style.lineHeight) + && element.scrollHeight <= element.clientHeight && style.textOverflow !== 'ellipsis' + })).toBe(true) } await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await expect.poll(() => toggle.isEnabled()).toBe(true) + await toggle.press('Escape') await menu.getByRole('menuitem', { name: 'Agent teamwork On', exact: true }).click() await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') @@ -1028,22 +1049,27 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) const agent = scaffold.ctx.agents.list()[0] if (agent === undefined) throw new Error('Chinese Team fixture has no Agent') + const trigger = page.getByRole('button', { name: /^选择模型/u }) + await trigger.click() + await page.getByRole('menuitem', { name: '智能体团队协作 关闭', exact: true }).waitFor() + await closeModelMenu(page) await scaffold.ctx.agentTeams.setEnabled(agent, true) const selection = agent.model.current() if (selection === undefined) throw new Error('Chinese Team fixture has no model') agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) - await openTeamSettings(page, true) - const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await trigger.click() + await page.getByRole('menuitem', { name: '智能体团队协作 开启', exact: true }).click() + const toggle = page.getByRole('switch', { name: '开启智能体团队协作', exact: true }) await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await toggle.click() - const dialog = page.getByRole('dialog', { name: '确认停用智能体团队协作?', exact: true }) + const dialog = page.getByRole('dialog', { name: '确认关闭智能体团队协作?', exact: true }) await dialog.waitFor() - await dialog.getByText('对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', { exact: true }).waitFor() + await dialog.getByText('对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。', { exact: true }).waitFor() await assertWarningDialogLayout(dialog) const confirmation = await captureStableAria(page, '[aria-modal="true"]', scaffold.workspaceCwd) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'collaboration.zh.expected.md'), diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 66bd3cfb1d..d7059f0317 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -1191,7 +1191,8 @@ describe('web e2e: plugin manager', () => { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) await teamPage.getByRole('button', { name: /^选择模型/u }).click() - const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await teamPage.getByRole('menuitem', { name: '智能体团队协作 关闭', exact: true }).click() + const mode = teamPage.getByRole('switch', { name: '开启智能体团队协作', exact: true }) await mode.waitFor() expect(await mode.getAttribute('aria-checked')).toBe('false') await mode.click() diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index 0522d13274..c48d2d2ab0 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,16 +1,16 @@ ## Menu - menu "智能体团队协作": - - text: 启用智能体团队协作 - - switch "启用智能体团队协作" [checked] + - text: 开启智能体团队协作 + - switch "开启智能体团队协作" [checked] - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 ## Confirmation -- dialog "确认停用智能体团队协作?": - - heading "确认停用智能体团队协作?" [level=2] +- dialog "确认关闭智能体团队协作?": + - heading "确认关闭智能体团队协作?" [level=2] - button "关闭" - - paragraph: 对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。 - - paragraph: 停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。 + - paragraph: 对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。 + - paragraph: 关闭后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。 - button "取消" - - button "确认停用" + - button "确认关闭" diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 87dafe0190..1f07c26005 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -16,7 +16,7 @@ zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: en: 4b66566b2e676572 - zh: 2cb4e9d8cff3bcca + zh: 57e6096591983a3c /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index 8173e4af02..8af5e7e585 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,9 +25,9 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**启用智能体团队协作**。一级行只显示已保存的开/关状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行只显示已保存的开启/关闭状态,点击仅进入页面,不改变选择;二级页面将开关放在完整说明文字上方。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。设置页以普通正文显示共享任务协调、复杂任务效果与 token 开销的说明,不使用信息 tooltip。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 -会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 +会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成功的回执。失败回执仍显示 Users 图标、本地化的“智能体团队协作”标题,以及本地化的失败前缀和已记录原因的首个非空行,不翻译原因原文。展开回执可查看完整原始错误。参数无法识别或缺失时仍显示回执。 diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index 8f4ed615a6..f7bba69ff8 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -14,16 +14,16 @@ export const zh = { 'command.failed': '执行失败', 'command.failedReason': '执行失败:{reason}', trigger: '任务板', - 'mode.label': '启用智能体团队协作', - 'mode.on': '开', - 'mode.off': '关', + 'mode.label': '开启智能体团队协作', + 'mode.on': '开启', + 'mode.off': '关闭', 'mode.description': '通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', 'mode.failed': '无法确认智能体团队协作设置已保存,请重试:{message}', - 'disable.title': '确认停用智能体团队协作?', - 'disable.description': '对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', - 'disable.warning': '停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。', + 'disable.title': '确认关闭智能体团队协作?', + 'disable.description': '对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。', + 'disable.warning': '关闭后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。', 'disable.cancel': '取消', - 'disable.confirm': '确认停用', + 'disable.confirm': '确认关闭', 'disable.close': '关闭', loading: '正在加载任务板…', unavailable: '任务板暂不可用', diff --git a/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx index 58b3fa9004..5628894227 100644 --- a/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx @@ -48,8 +48,8 @@ it('renders nothing when no disable request exists', () => { it('shows the localized title, two paragraphs, and actions without a checkbox', () => { const input = props() render() - const dialog = within(screen.getByRole('dialog', { name: '确认停用智能体团队协作?' })) - expect(dialog.getByRole('heading', { name: '确认停用智能体团队协作?' })).toBeTruthy() + const dialog = within(screen.getByRole('dialog', { name: '确认关闭智能体团队协作?' })) + expect(dialog.getByRole('heading', { name: '确认关闭智能体团队协作?' })).toBeTruthy() expect(dialog.getByText(zh['disable.description'], { selector: 'p' })).toBeTruthy() expect(dialog.getByText(zh['disable.warning'], { selector: 'p' })).toBeTruthy() expect(dialog.getAllByRole('paragraph')).toHaveLength(2) diff --git a/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx new file mode 100644 index 0000000000..435f38d3fb --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx @@ -0,0 +1,85 @@ +// @vitest-environment jsdom + +import { isValidElement, type ComponentProps, type FunctionComponent } from 'react' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { Switch } from '@deepseek-ai/dsh-client-ui-primitives' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { TeamModePage, TeamModeToggle, type TeamModePageProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { zh } from '../src/client/locales.ts' + +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + // Deliver callbacks even when the native control would suppress activation. + Switch: (props: ComponentProps) => ( + ) } @@ -76,8 +76,7 @@ function RootTeamModePage({ const [pending, setPending] = useState(false) if (mode === undefined) return null const select = (enabled: boolean): void => { - if (locked || pending || modelSelection === undefined) return - if (!enabled && modelSelection.lastUsed !== null) { + if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { dismiss() requestDisableConfirmation() return diff --git a/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx deleted file mode 100644 index 435f38d3fb..0000000000 --- a/packages/client/ui-agent-team/tests/team-mode-callbacks.client.spec.tsx +++ /dev/null @@ -1,85 +0,0 @@ -// @vitest-environment jsdom - -import { isValidElement, type ComponentProps, type FunctionComponent } from 'react' -import { afterEach, expect, it, onTestFinished, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { Switch } from '@deepseek-ai/dsh-client-ui-primitives' -import { SessionId } from '@deepseek-ai/dsh-session' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModePage, TeamModeToggle, type TeamModePageProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' -import { zh } from '../src/client/locales.ts' - -vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Deliver callbacks even when the native control would suppress activation. - Switch: (props: ComponentProps) => ( - )} - {renderSlot('conversation.input.model.options', { - locked: locked || busy, - openPage: (page) => { drill(page) }, - dismiss: () => { - close() - triggerRef.current?.focus() - }, - reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, - })} + {renderSlot('conversation.input.model.options', { ...controls, openPage: drill })} )} @@ -671,14 +672,7 @@ export function ModelSelect( )} {typeof pane === 'object' && (
- {renderSlot('conversation.input.model.page', { - locked: locked || busy, - dismiss: () => { - close() - triggerRef.current?.focus() - }, - reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, - }, { entryKey: pane.key })} + {renderSlot('conversation.input.model.page', controls, { entryKey: pane.key })}
)} , diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 5b0b589b19..491cb030f8 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -35,16 +35,22 @@ export interface ModelMenuControls { reportFailure: (message: string) => void } +/** Root-menu controls for opening plugin-owned settings pages. */ +export type ModelMenuOptions = ModelMenuControls & { + /** + * Open page.key in conversation.input.model.page with page.title as its localized accessible name. + * The root button's data-model-menu-page must match page.key for focus return. + */ + openPage: (page: ModelMenuPage) => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session options appended after model and reasoning controls in the root menu. */ 'conversation.input.model.options': { kind: 'list' scope: 'session' - owner: ModelMenuControls & { - /** Open a keyed detail page inside this menu; its root button supplies data-model-menu-page for focus return. */ - openPage: (page: ModelMenuPage) => void - } + owner: ModelMenuOptions } /** Plugin-owned content displayed as a model-menu detail page. */ 'conversation.input.model.page': { diff --git a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx index 859bb53344..126d89c119 100644 --- a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx @@ -11,7 +11,7 @@ import { en } from '../src/client/locales.ts' afterEach(cleanup) -function setup(locked = false) { +function setup() { const directory = createSnapshotStore({ current: { provider: 'fixture', model: 'fixture' }, routable: true, groups: [{ id: 'fixture', name: 'Fixture', models: [{ id: 'fixture', name: 'Fixture' }] }], @@ -33,7 +33,7 @@ function setup(locked = false) { } return options?.fallback ?? null } - render( typeof text === 'string' ? text : text.en} t={makeTranslate(en)} renderSlot={renderSlot} />) const trigger = screen.getByRole('button', { name: /^Select model/ }) fireEvent.click(trigger) 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 99667674df..7bcafd9def 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1619,7 +1619,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:70', + source: 'packages/client/ui-model-selection/src/client/slots.ts:76', }, { key: 'conversation.input.model.options', @@ -1649,9 +1649,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], ownerProps: [ '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', - '/** A keyed contribution displayed as a second page of the model menu. */\nexport interface ModelMenuPage {\n /** Registration key in conversation.input.model.page; also marks its root button\'s data-model-menu-page. */\n key: string\n /** Localized accessible name of the detail page. */\n title: string\n}', + '/** Root-menu controls for opening plugin-owned settings pages. */\nexport type ModelMenuOptions = ModelMenuControls & {\n /**\n * Open page.key in conversation.input.model.page with page.title as its localized accessible name.\n * The root button\'s data-model-menu-page must match page.key for focus return.\n */\n openPage: (page: ModelMenuPage) => void\n}', + ], + ownerPropsReferences: [ + 'ModelMenuPage', ], - ownerPropsReferences: [], standardProps: [ 'useRemoteAccess: (action: RemoteEndpoint) => boolean', 'useResource: UseResource', @@ -1682,7 +1684,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:41', + source: 'packages/client/ui-model-selection/src/client/slots.ts:50', }, { key: 'conversation.input.model.page', @@ -1732,7 +1734,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:56', }, { key: 'conversation.input.overlay', diff --git a/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts b/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts index 9965ae63c6..8ff04a1c25 100644 --- a/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts +++ b/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts @@ -7,7 +7,7 @@ import { clientInspectProviders } from '../src/client/providers.ts' const Component = () => null describe('Client inspect providers', () => { - it('exposes Tool owner fields and phases through the live slot lookup', async () => { + it('exposes Tool and model-menu owner fields through the live slot lookup', async () => { const ctx = new Context() const fiber = ctx.plugin(SlotRegistry) try { @@ -15,7 +15,10 @@ describe('Client inspect providers', () => { const slots = ctx.slots as { registerFactory(options: object, component: unknown): () => void } slots.registerFactory({ name: 'provider.tool-owner', scope: 'root', - children: { 'tool.call.toolview': { kind: 'keyed', scope: 'session' } }, + children: { + 'tool.call.toolview': { kind: 'keyed', scope: 'session' }, + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + }, }, Component) const provider = clientInspectProviders(ctx).find(item => item.manifest.id === 'Slots')! const result = await provider.query('listSubTree', { root: 'tool.call.toolview' }, {} as never) @@ -26,6 +29,10 @@ describe('Client inspect providers', () => { } for (const phase of ['preparing', 'start', 'result']) expect(owner).toContain(`phase: '${phase}'`) expect(owner).not.toContain('truncated') + const options = await provider.query('listSubTree', { root: 'conversation.input.model.options' }, {} as never) + const menuOwner = (options as typeof selected).selected.catalog.ownerProps.join('\n') + expect(menuOwner).toContain('ModelMenuOptions') + expect(menuOwner).toContain('openPage: (page: ModelMenuPage) => void') } finally { await fiber.dispose() } From d9971117959aa7061f3caa0bd933958256c8d161 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 6 Nov 2026 23:20:48 +0800 Subject: [PATCH 10/68] test(ui): preserve fixed team root width in label resize coverage --- apps/web/tests/default-model.e2e.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index afd89b3c77..699340f774 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -141,7 +141,13 @@ describe('web e2e: the composer model switch is the default for later sessions', badge.textContent = ' — Provider identification badge with a long channel name' node.appendChild(badge) }) - await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + if (pane === 'root') { + expect(original!.width).toBe(240) + await expect.poll(async () => (await surface.boundingBox())!.width).toBe(240) + await expect.poll(async () => (await surface.boundingBox())!.x).toBeCloseTo(original!.x) + } else { + await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + } await expect.poll(async () => { const box = (await surface.boundingBox())! return box.x >= 12 && box.x + box.width <= 378 From 0c673d916f81fec386ba7bb2d58a0d4b0dcee84f Mon Sep 17 00:00:00 2001 From: zhc Date: Mon, 9 Nov 2026 12:57:10 +0800 Subject: [PATCH 11/68] fix(ui): let model menu detail pages own focus and group semantics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pane 改为带 kind 标签的可辨识联合,ModelMenuPage 更名为 ModelMenuPageRef - 二级页由页面自行设置初始焦点:Switch 新增 autoFocus/describedBy,Team 开关进页即聚焦并关联说明文字;owner 不再查找 [role="switch"] - 二级页容器改用 role="group",菜单 surface 增加 data-model-menu 供测试定位 - 外部按下同时监听 pointerdown,覆盖 WebKit 触摸点击空白区域不派发 mousedown 的情况 - 删除 .page 中多余的 gap: 0 --- apps/web/tests/agent-team-panel.e2e.ts | 12 +-- .../collaboration.zh.expected.md | 2 +- .../agent-team-panel/info.expected.md | 2 +- .../client/ui-agent-team/README.i18n.yaml | 4 +- packages/client/ui-agent-team/README.md | 2 +- packages/client/ui-agent-team/README.zh.md | 2 +- .../src/client/TeamModeToggle.module.css | 1 - .../src/client/TeamModeToggle.tsx | 7 +- .../tests/team-mode.client.spec.tsx | 3 +- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../src/client/ModelSelect.tsx | 97 +++++++++++-------- .../ui-model-selection/src/client/slots.ts | 12 ++- .../tests/model-menu-page.client.spec.tsx | 25 ++++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/Switch.tsx | 8 +- .../tests/switch.client.spec.tsx | 6 ++ .../src/client/slot-catalog.ts | 10 +- .../tests/providers.client.spec.ts | 2 +- 22 files changed, 133 insertions(+), 78 deletions(-) diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 860bd3bf97..957930cfaa 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -131,7 +131,7 @@ describe('web e2e: agent teamwork panel', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) const trigger = page.getByRole('button', { name: /^Select model/u }) await trigger.click() - const menu = page.getByRole('menu') + const menu = page.locator('[data-model-menu]') const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) await summary.waitFor() const stateColor = await summary.getByText('Off', { exact: true }).evaluate(element => getComputedStyle(element).color) @@ -146,7 +146,7 @@ describe('web e2e: agent teamwork panel', () => { expect(await summary.locator('svg').evaluate(inspectArrow)).toEqual(await peerArrow.evaluate(inspectArrow)) expect(await menu.getByRole('switch').count()).toBe(0) expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) - const rootSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const rootSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) const original = await menu.elementHandle() if (original === null) throw new Error('Model menu is missing') try { @@ -166,7 +166,7 @@ describe('web e2e: agent teamwork panel', () => { descriptionGap: element.parentElement!.nextElementSibling!.getBoundingClientRect().top - element.parentElement!.getBoundingClientRect().bottom, }))).toEqual({ rowBackground: 'rgba(0, 0, 0, 0)', focusVisible: true, outline: 'solid', descriptionGap: 0 }) - const settingsSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const settingsSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), `## Root\n\n${rootSnapshot}\n\n## Team settings\n\n${settingsSnapshot}`, MODE) await page.keyboard.press('Escape') @@ -192,7 +192,7 @@ describe('web e2e: agent teamwork panel', () => { const viewport = page.viewportSize()! try { await openTeamSettings(page) - const menu = page.getByRole('menu') + const menu = page.locator('[data-model-menu]') const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) const description = menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }) await description.click() @@ -867,7 +867,7 @@ describe('web e2e: agent teamwork panel', () => { await openConfirmation() const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) await assertWarningDialogLayout(dialog) - expect(await page.getByRole('menu', { name: 'Agent teamwork', exact: true }).count()).toBe(0) + expect(await page.getByRole('group', { name: 'Agent teamwork', exact: true }).count()).toBe(0) expect(await page.getByRole('button', { name: /^Select model/u }).getAttribute('aria-expanded')).toBe('false') expect(await dialog.getByRole('checkbox').count()).toBe(0) expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) @@ -1091,7 +1091,7 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) - const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const menu = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) await toggle.click() const dialog = page.getByRole('dialog', { name: '确认关闭智能体团队协作?', exact: true }) await dialog.waitFor() diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index c48d2d2ab0..ceb1d1097a 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,6 +1,6 @@ ## Menu -- menu "智能体团队协作": +- group "智能体团队协作": - text: 开启智能体团队协作 - switch "开启智能体团队协作" [checked] - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md index d1171d7e32..23af3abb18 100644 --- a/apps/web/tests/snapshots/agent-team-panel/info.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -6,7 +6,7 @@ ## Team settings -- menu "Agent teamwork": +- group "Agent teamwork": - text: Enable agent teamwork - switch "Enable agent teamwork" - paragraph: Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs. diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 0b307a4d15..d4db291eb9 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: c5fe6c80b2979db7 - zh: 6f4640b369c9d22a + en: 39906df046b7fa3b + zh: 9a79438ab5c0811f /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index b5a3b9ff52..d6dbd2a057 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings page shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings page shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the page focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index 650a9f2b63..e3ce5014d4 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置页将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,不使用信息 tooltip。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置页将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置页时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index b312ccfce5..f05212b2d6 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -54,7 +54,6 @@ .page { display: flex; flex-direction: column; - gap: 0; min-width: 0; } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index 90cfc4ebcd..aff18015a7 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -1,6 +1,6 @@ /** Session-owned Agent Teams summary and settings inside the model menu. */ -import { useState } from 'react' +import { useId, useState } from 'react' import { IconChevronRightOutlineRegular, Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' @@ -74,6 +74,7 @@ function RootTeamModePage({ const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) + const descriptionId = useId() if (mode === undefined) return null const select = (enabled: boolean): void => { if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { @@ -92,9 +93,9 @@ function RootTeamModePage({
{t('mode.label')} - +
-

{t('mode.description')}

+

{t('mode.description')}

) } diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index d1c1b40aa3..11d0a253b2 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -110,7 +110,8 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dic expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() expect(screen.queryByRole('button')).toBeNull() - const toggle = screen.getByRole('switch', { name: dictionary['mode.label'] }) + const toggle = screen.getByRole('switch', { name: dictionary['mode.label'], description: dictionary['mode.description'] }) + expect(document.activeElement === toggle).toBe(!locked) expect(toggle.compareDocumentPosition(description) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() expect(toggle.hasAttribute('disabled')).toBe(locked) expect(toggle.getAttribute('aria-checked')).toBe('false') diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 334d05939c..a3a5c13bdf 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 6f790bbbca533c64 - zh: c46d46a94a34dc2c + en: 353daeed6290d445 + zh: b5f0febc130c8a8b /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: c1d14a925c92950f zh: f80f8169bc283c60 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index f5077d3c21..27a6529389 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -61,7 +61,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPage({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.page` slot; the invoking button's `data-model-menu-page` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail pages share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu uses `title` as the accessible page name and focuses its first enabled switch on entry. Escape returns focus to the invoking row; Tab closes a detail page without activating its switch. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPage({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.page` slot; the invoking button's `data-model-menu-page` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail pages share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail page as a group named by `title`; the page places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail page without activating its switch. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index fd870fe115..7337e1136c 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -61,7 +61,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPage({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.page` 的内容;入口按钮的 `data-model-menu-page` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级页共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单以 `title` 作为页面无障碍名称,进入时聚焦首个可用开关。Escape 将焦点还给入口行;Tab 关闭二级页而不激活开关。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPage({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.page` 的内容;入口按钮的 `data-model-menu-page` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级页共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级页呈现为以 `title` 命名的分组;页面自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级页而不激活开关。 ----- diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 0b4734d324..f062b4d8ba 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -40,12 +40,23 @@ import { IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelMenuControls, ModelMenuPage, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuControls, ModelMenuPageRef, ModelSelectInjected } from './slots.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ -type Pane = 'root' | 'model' | 'effort' | ModelMenuPage +/** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail page. */ +type Pane = + | { kind: 'root' } + | { kind: 'model' } + | { kind: 'effort' } + | { kind: 'page'; page: ModelMenuPageRef } + +/** Any pane reached by drilling from the root menu. */ +type DrilledPane = Exclude + +const ROOT_PANE: Pane = { kind: 'root' } +const MODEL_PANE: DrilledPane = { kind: 'model' } +const EFFORT_PANE: DrilledPane = { kind: 'effort' } /** One dynamic effort row; undefined means preserve the provider default. */ interface EffortChoice { @@ -70,7 +81,7 @@ export function ModelSelect( () => directory.getSnapshot(), ) const [open, setOpen] = useState(false) - const [pane, setPane] = useState('root') + const [pane, setPane] = useState(ROOT_PANE) const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) @@ -163,8 +174,13 @@ export function ModelSelect( if (menuRef.current?.contains(event.target as Node) === true) return setOpen(false) } + // WebKit touch taps on non-clickable areas dispatch pointerdown without mousedown. + document.addEventListener('pointerdown', closeOutside) document.addEventListener('mousedown', closeOutside) - return () => { document.removeEventListener('mousedown', closeOutside) } + return () => { + document.removeEventListener('pointerdown', closeOutside) + document.removeEventListener('mousedown', closeOutside) + } }, [open]) useLayoutEffect(() => { @@ -176,21 +192,22 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | Exclude | null>(null) + const paneFocus = useRef<'drill' | DrilledPane | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch - const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) + const intent = paneFocus.current ?? (changedSearchMode && pane.kind === 'model' ? 'drill' : null) paneFocus.current = null if (!open || intent === null) return if (intent === 'drill') { - if (typeof pane === 'object') { - const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') - ;(first ?? menuRef.current ?? triggerRef.current)?.focus() + if (pane.kind === 'page') { + // A detail page places its own initial focus (autoFocus commits before + // this effect); otherwise the surface keeps the menu's keys reachable. + if (menuRef.current?.contains(document.activeElement) !== true) (menuRef.current ?? triggerRef.current)?.focus() return } - if (pane === 'model' && showSearch && !isMobileDevice()) { + if (pane.kind === 'model' && showSearch && !isMobileDevice()) { searchRef.current?.focus() return } @@ -203,10 +220,10 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = typeof intent === 'object' + const cell = intent.kind === 'page' ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) - .find(button => button.dataset.modelMenuPage === intent.key) - : itemRefs.current[intent === 'effort' ? 1 : 0] + .find(button => button.dataset.modelMenuPage === intent.page.key) + : itemRefs.current[intent.kind === 'effort' ? 1 : 0] ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() }, [open, pane, showSearch]) @@ -217,7 +234,7 @@ export function ModelSelect( }, [available, open, pane, filteredGroups]) useLayoutEffect(() => { - if (open && pane === 'model' && activeModelIndex >= 0) { + if (open && pane.kind === 'model' && activeModelIndex >= 0) { itemRefs.current[activeModelIndex]?.scrollIntoView({ block: 'nearest' }) } }, [open, pane, activeModelIndex, visibleModels]) @@ -230,7 +247,7 @@ export function ModelSelect( setQuery('') setHighlightedIndex(null) if (currentChoice === undefined) paneFocus.current = 'drill' - setPane(currentChoice === undefined ? 'model' : 'root') + setPane(currentChoice === undefined ? MODEL_PANE : ROOT_PANE) setOpen(true) reload() } @@ -242,7 +259,7 @@ export function ModelSelect( const close = (restoreFocus = false): void => { setOpen(false) - setPane('root') + setPane(ROOT_PANE) if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } @@ -251,7 +268,7 @@ export function ModelSelect( close(true) } - const drill = (next: Pane): void => { + const drill = (next: DrilledPane): void => { setQuery('') setHighlightedIndex(null) paneFocus.current = 'drill' @@ -259,9 +276,9 @@ export function ModelSelect( } /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ - const back = (from: Exclude): void => { + const back = (from: DrilledPane): void => { paneFocus.current = from - setPane('root') + setPane(ROOT_PANE) } const controls: ModelMenuControls = { @@ -293,17 +310,17 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (typeof pane === 'object' || (pane !== 'root' && currentChoice !== undefined)) back(pane) + if (pane.kind === 'page' || (pane.kind !== 'root' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (typeof pane === 'object' && event.key === 'Tab') { + if (pane.kind === 'page' && event.key === 'Tab') { event.preventDefault() close(true) return } - if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (pane.kind === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 @@ -312,7 +329,7 @@ export function ModelSelect( } return } - if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement + if (pane.kind === 'model' && showSearch && event.target instanceof HTMLInputElement && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { if (event.key === 'Tab' && visibleModels.length === 0) return event.preventDefault() @@ -326,7 +343,7 @@ export function ModelSelect( if (event.key === 'Tab') { if (event.shiftKey) { event.preventDefault() - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (pane.kind !== 'root' && currentChoice !== undefined) back(pane) else close(true) return } @@ -345,7 +362,7 @@ export function ModelSelect( } if (focused !== triggerRef.current) return event.preventDefault() - if (pane === 'model' && showSearch) { + if (pane.kind === 'model' && showSearch) { setHighlightedIndex(null) searchRef.current?.focus() return @@ -362,7 +379,7 @@ export function ModelSelect( const onBlur = (event: FocusEvent): void => { // Clicking explanation text can clear focus without leaving its page. - if (typeof pane === 'object' && event.relatedTarget === null) return + if (pane.kind === 'page' && event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -503,17 +520,19 @@ export function ModelSelect( {open && createPortal( - {pane === 'root' && ( + {pane.kind === 'root' && ( <> - {reasoning !== undefined && ( - )} - {renderSlot('conversation.input.model.options', { ...controls, openPage: drill })} + {renderSlot('conversation.input.model.options', { ...controls, openPage: (page) => { drill({ kind: 'page', page }) } })} )} - {pane === 'model' && ( + {pane.kind === 'model' && ( <> {showSearch &&
)} - {pane === 'effort' && ( + {pane.kind === 'effort' && ( <> {state.error !== null && lastActionRef.current === 'load' && (
@@ -670,9 +689,9 @@ export function ModelSelect(
)} - {typeof pane === 'object' && ( + {pane.kind === 'page' && (
- {renderSlot('conversation.input.model.page', controls, { entryKey: pane.key })} + {renderSlot('conversation.input.model.page', controls, { entryKey: pane.page.key })}
)} , diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 491cb030f8..3f1670f236 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,8 +17,8 @@ export interface ModelLabelOwner { selected: boolean } -/** A keyed contribution displayed as a second page of the model menu. */ -export interface ModelMenuPage { +/** Data identifying a keyed contribution displayed as a second page of the model menu. */ +export interface ModelMenuPageRef { /** Registration key in conversation.input.model.page; also marks its root button's data-model-menu-page. */ key: string /** Localized accessible name of the detail page. */ @@ -41,7 +41,7 @@ export type ModelMenuOptions = ModelMenuControls & { * Open page.key in conversation.input.model.page with page.title as its localized accessible name. * The root button's data-model-menu-page must match page.key for focus return. */ - openPage: (page: ModelMenuPage) => void + openPage: (page: ModelMenuPageRef) => void } declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -52,7 +52,11 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { scope: 'session' owner: ModelMenuOptions } - /** Plugin-owned content displayed as a model-menu detail page. */ + /** + * Plugin-owned content displayed as a model-menu detail page. + * The page places its own initial focus, for example with `autoFocus`; without one, + * focus stays on the menu surface, where Escape and Shift+Tab still return to the root menu. + */ 'conversation.input.model.page': { kind: 'keyed' scope: 'session' diff --git a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx index 126d89c119..c37e850291 100644 --- a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx @@ -11,7 +11,7 @@ import { en } from '../src/client/locales.ts' afterEach(cleanup) -function setup() { +function setup(autoFocus = true) { const directory = createSnapshotStore({ current: { provider: 'fixture', model: 'fixture' }, routable: true, groups: [{ id: 'fixture', name: 'Fixture', models: [{ id: 'fixture', name: 'Fixture' }] }], @@ -29,7 +29,7 @@ function setup() { const controls = owner as object as OwnerOf<'conversation.input.model.page'> expect(options?.entryKey).toBe('fixture') return <>

Fixture explanation

+ autoFocus={autoFocus} onClick={change}>Fixture setting

Fixture explanation

} return options?.fallback ?? null } @@ -45,7 +45,7 @@ it('dispatches a keyed page and returns focus to its invoking summary on Escape' fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) const toggle = screen.getByRole('switch') expect(document.activeElement).toBe(toggle) - expect(screen.getByRole('menu', { name: 'Fixture settings' })).toBeTruthy() + expect(screen.getByRole('group', { name: 'Fixture settings' })).toBeTruthy() fireEvent.blur(toggle, { relatedTarget: null }) expect(screen.getByText('Fixture explanation')).toBeTruthy() fireEvent.keyDown(toggle, { key: 'Escape' }) @@ -57,6 +57,25 @@ it('dispatches a keyed page and returns focus to its invoking summary on Escape' expect(select).not.toHaveBeenCalled() }) +it('keeps focus on the page surface when the page places none, so Escape still returns', () => { + setup(false) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + const surface = screen.getByRole('group', { name: 'Fixture settings' }) + expect(document.activeElement).toBe(surface) + fireEvent.keyDown(surface, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) +}) + +it('closes a detail page on an outside touch press that dispatches no mousedown', () => { + const { trigger } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + fireEvent.blur(screen.getByRole('switch'), { relatedTarget: null }) + fireEvent.pointerDown(screen.getByText('Fixture explanation')) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + fireEvent.pointerDown(document.body) + expect(trigger.getAttribute('aria-expanded')).toBe('false') +}) + it.each([false, true])('closes a detail page on Tab without changing its setting (shift: %s)', async (shiftKey) => { const { trigger, change } = setup() fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 662fc787a4..ab419ad832 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: ead6be55c7c9d7cf zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 54c5085d03bf4c53 - zh: 6b5114206ca545f3 + en: 11686b52743a702d + zh: d865bb79d8f56ee1 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: 8265fa792c6fd9ec zh: 600d2af4d5a3d183 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 5c817b94b2..87d319ed09 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -43,7 +43,7 @@ Check this table before writing a control in a feature package. A plugin cannot | Export | What it is | |---|---| | `Button` | Clickable action; `variant` selects `primary`, `ghost`, `outline`, or `toolbar`. Outlined actions use an inset hairline. Its ref targets the native button for focus and overlay anchoring. | -| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. | +| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. Optional `autoFocus` and `describedBy` forward to the native button. | | `SegmentedControl` | Tablist of two or more equal-width segments with one sliding indicator, for switching a card or panel between a few modes; the owner holds the selection and `label` names the list. `id` seeds each tab's id (`-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f3e1c1719a..a7258c74dc 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。可选的 `autoFocus` 与 `describedBy` 直接传给原生按钮。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 980a08f6be..8816e1975a 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -13,9 +13,11 @@ import css from './Switch.module.css' * while a write is in flight, not only when a deployment locks the toggle. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. + * @param props.autoFocus - whether the control takes focus when it mounts enabled. + * @param props.describedBy - id of the element that describes the control. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, title, className, autoFocus, describedBy }: { checked: boolean onChange: (next: boolean) => void label: string @@ -24,6 +26,8 @@ export function Switch({ checked, onChange, label, disabled = false, title, clas // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). className?: string | undefined + autoFocus?: boolean + describedBy?: string | undefined }) { return (
diff --git a/packages/experimental/subagent-oar/README.zh.md b/packages/experimental/subagent-oar/README.zh.md index 89e6f8405d..09d2a0db76 100644 --- a/packages/experimental/subagent-oar/README.zh.md +++ b/packages/experimental/subagent-oar/README.zh.md @@ -104,7 +104,7 @@ kind: "package-reference" 依赖补丁对原生安装探测应用环境覆盖,并允许 Claude 显式使用 `--permission-mode`,并在存在该参数时关闭 OAR 强制的权限绕过。示例传入 `--permission-mode dontAsk --permission-prompts none`。Codex 接收 `-c sandbox_mode="workspace-write"`。OAR 将 Codex 审批策略设为 `never`。两条路径均不将原生审批请求转发到 DSH 交互界面。Codex 启动失败时会停止 app-server 并等待其退出,包括响应中缺少线程 id 的情况。 -只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。 +只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 取自 `OAR_FAILURE_CODES`:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 `code` 为 `ABORTED` 的 `AbortError` 拒绝。
diff --git a/packages/experimental/subagent-oar/package.json b/packages/experimental/subagent-oar/package.json index 2df967de2e..e2691b75e0 100644 --- a/packages/experimental/subagent-oar/package.json +++ b/packages/experimental/subagent-oar/package.json @@ -39,7 +39,8 @@ "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*" }, "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", diff --git a/packages/experimental/subagent-oar/src/index.ts b/packages/experimental/subagent-oar/src/index.ts index 3aa63f42fd..47b6c846cc 100644 --- a/packages/experimental/subagent-oar/src/index.ts +++ b/packages/experimental/subagent-oar/src/index.ts @@ -16,6 +16,8 @@ import { import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { startOarRun, type OarRunSpec } from './run.ts' +export { OAR_FAILURE_CODES, OarFailure, type OarFailureCode } from './run.ts' + export const name = 'experimental-subagent-oar' export const inject = ['subagents'] diff --git a/packages/experimental/subagent-oar/src/run.ts b/packages/experimental/subagent-oar/src/run.ts index b695d8f176..41eef568ef 100644 --- a/packages/experimental/subagent-oar/src/run.ts +++ b/packages/experimental/subagent-oar/src/run.ts @@ -16,7 +16,7 @@ import type { } from '@botiverse/oar' import { awaitTurnEnd } from '@botiverse/oar/observe' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertUsableCwd, @@ -27,6 +27,7 @@ import { type SubagentRun, type SubagentStopReason, } from '@deepseek-ai/dsh-subagent' +import { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' import { assertNever } from '@deepseek-ai/dsh-util-values' import { oarEnvironment } from './environment.ts' @@ -49,7 +50,7 @@ export interface OarRunSpec { } type FailureStage = 'installation' | 'startup' | 'turn' | 'abort' | 'dispose' -type FailureCategory = FailureClass | RejectionCode | 'not-found' | 'unsupported' | 'cancelled' | 'timeout' +type FailureCategory = FailureClass | RejectionCode | 'not-found' | 'unsupported' | 'timeout' const failureAdvice: Readonly> = { installation: 'Install and authenticate the selected runtime before retrying.', @@ -59,13 +60,58 @@ const failureAdvice: Readonly> = { dispose: 'The runtime may still be active; check it before starting another task.', } -class OarFailure extends Error { - constructor(readonly stage: FailureStage, readonly category: FailureCategory, options?: ErrorOptions) { - super(`OAR subagent failure (stage: ${stage}; category: ${category}). ${failureAdvice[stage]}`, options) +/** + * Every {@link OarFailure} code: + * - `OAR_INVALID_TASK` — the task is empty or contains a non-text block; send one non-empty text task. + * - `OAR_RUNTIME_UNAVAILABLE` — the selected runtime is unsupported, not installed, or its installation probe failed; + * install and authenticate it before retrying. + * - `OAR_START_FAILED` — the runtime could not open or publish a session; check its installation, authentication, and launch settings. + * - `OAR_TURN_FAILED` — the native turn failed or was rejected; check the runtime and its account before retrying. + * - `OAR_ABORT_FAILED` — the runtime did not accept interruption; session disposal was requested. + * - `OAR_DISPOSE_FAILED` — session disposal failed and the runtime may still be active; check it before starting another task. + */ +export const OAR_FAILURE_CODES = [ + 'OAR_INVALID_TASK', + 'OAR_RUNTIME_UNAVAILABLE', + 'OAR_START_FAILED', + 'OAR_TURN_FAILED', + 'OAR_ABORT_FAILED', + 'OAR_DISPOSE_FAILED', +] as const + +/** One code from {@link OAR_FAILURE_CODES}. */ +export type OarFailureCode = typeof OAR_FAILURE_CODES[number] + +const stageCodes: Readonly> = { + installation: 'OAR_RUNTIME_UNAVAILABLE', + startup: 'OAR_START_FAILED', + turn: 'OAR_TURN_FAILED', + abort: 'OAR_ABORT_FAILED', + dispose: 'OAR_DISPOSE_FAILED', +} + +/** OAR delegation failure carrying a stable {@link OarFailureCode}; native causes stay in `cause` and can contain secrets. */ +export class OarFailure extends HarnessError { + override readonly code: OarFailureCode + + /** + * @param message - safe summary without native detail. + * @param code - failure class. + * @param options - native cause, retained for local debugging. + */ + constructor(message: string, code: OarFailureCode, options?: ErrorOptions) { + super(message, code, options) this.name = 'OarFailure' + this.code = code } } +/** Build the safe stage and category summary for one native failure. */ +function stageFailure(stage: FailureStage, category: FailureCategory, options?: ErrorOptions): OarFailure { + const message = `OAR subagent failure (stage: ${stage}; category: ${category}). ${failureAdvice[stage]}` + return new OarFailure(message, stageCodes[stage], options) +} + function reportFailure(spec: OarRunSpec, error: OarFailure): void { try { spec.onError?.(error, 'error') @@ -78,20 +124,21 @@ function reportFailure(spec: OarRunSpec, error: OarFailure): void { * Validate one text task before opening a native session. * @param prompt - content supplied by the shared subagent service. * @returns the text blocks in their original order, without inserted separators. + * @throws {OarFailure} `OAR_INVALID_TASK` when the task is empty or contains a non-text block. */ export function textTask(prompt: readonly ContentBlock[]): string { if (prompt.length === 0) { - throw new Error('subagent-oar: the one-shot task must contain only text blocks') + throw new OarFailure('subagent-oar: the one-shot task must contain only text blocks', 'OAR_INVALID_TASK') } const texts: string[] = [] for (const block of prompt) { if (block.type !== 'text') { - throw new Error('subagent-oar: the one-shot task must contain only text blocks') + throw new OarFailure('subagent-oar: the one-shot task must contain only text blocks', 'OAR_INVALID_TASK') } texts.push(block.text) } if (texts.every(text => text.trim().length === 0)) { - throw new Error('subagent-oar: the one-shot task must not be empty') + throw new OarFailure('subagent-oar: the one-shot task must not be empty', 'OAR_INVALID_TASK') } return texts.join('') } @@ -101,15 +148,18 @@ function isAborted(signal: AbortSignal): boolean { return signal.aborted } -function cancellationFailure(): OarFailure { - return new OarFailure('startup', 'cancelled') +/** The caller cancelled delegation before the run was published. */ +function cancellationFailure(): HarnessError { + const error = new HarnessError('OAR subagent startup was cancelled', TOOL_ABORTED) + error.name = 'AbortError' + return error } async function disposeSession(session: Session, spec: OarRunSpec): Promise { try { await session.dispose() } catch (error: unknown) { - const failure = new OarFailure('dispose', 'unknown', { cause: error }) + const failure = stageFailure('dispose', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } @@ -125,7 +175,7 @@ function completedTurn(outcome: TurnOutcome, output: readonly ContentBlock[]): S return { output, stopReason: 'error', - diagnostic: new OarFailure('turn', outcome.failure).message, + diagnostic: stageFailure('turn', outcome.failure).message, } /* v8 ignore next -- OAR supplies the closed TurnOutcome union; native parsing belongs to its adapters. */ default: return assertNever(outcome) @@ -156,7 +206,7 @@ function publishRun( try { await session.abort() } catch (error: unknown) { - reportFailure(spec, new OarFailure('abort', 'unknown', { cause: error })) + reportFailure(spec, stageFailure('abort', 'unknown', { cause: error })) } } const interrupt = (reason: 'cancelled' | 'timeout'): void => { @@ -191,7 +241,7 @@ function publishRun( return { output: collectOutput(), stopReason: 'error', - diagnostic: new OarFailure('turn', admitted.code).message, + diagnostic: stageFailure('turn', admitted.code).message, } } const outcome = await awaitTurnEnd(session, admitted.seq, inputId) @@ -206,11 +256,11 @@ function publishRun( stopped.promise, ]) } catch (error: unknown) { - throw new OarFailure('turn', 'unknown', { cause: error }) + throw stageFailure('turn', 'unknown', { cause: error }) } }, collectOutput, - collectDiagnostic: () => new OarFailure('turn', 'unknown').message, + collectDiagnostic: () => stageFailure('turn', 'unknown').message, cancelled: () => phase === 'cancelled', onError: spec.onError, signal: request.signal, @@ -252,16 +302,16 @@ export async function startOarRun( try { installation = await spec.runtime.installation?.({ env: oarEnvironment(spec.env) }) } catch (error: unknown) { - const failure = new OarFailure('installation', 'unknown', { cause: error }) + const failure = stageFailure('installation', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } if (isAborted(request.signal)) throw cancellationFailure() if (installation === undefined || installation.kind === 'unsupported') { - throw new OarFailure('installation', 'unsupported') + throw stageFailure('installation', 'unsupported') } if (installation.kind === 'not_found') { - throw new OarFailure('installation', 'not-found') + throw stageFailure('installation', 'not-found') } let session: Session @@ -275,7 +325,7 @@ export async function startOarRun( }) } catch (error: unknown) { if (isAborted(request.signal)) throw cancellationFailure() - const failure = new OarFailure('startup', 'unknown', { cause: error }) + const failure = stageFailure('startup', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } @@ -288,7 +338,7 @@ export async function startOarRun( try { run = publishRun(session, prompt, request, spec) } catch (error: unknown) { - const failure = new OarFailure('startup', 'unknown', { cause: error }) + const failure = stageFailure('startup', 'unknown', { cause: error }) reportFailure(spec, failure) await disposeSession(session, spec) throw failure diff --git a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts index d58bd44436..f84a6ac614 100644 --- a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts +++ b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts @@ -112,7 +112,7 @@ describe('OAR provider composition', () => { const provider = ctx.subagents.getProvider('oar') const run = await provider!.start!(await request()) await expect(run.result).resolves.toMatchObject({ output: [{ type: 'text', text: 'registered answer' }] }) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) expect(options[0]).toMatchObject({ model: 'native-model', effort: 'high' }) } finally { await ctx.fiber.dispose() @@ -142,9 +142,10 @@ describe('OAR provider composition', () => { describe('OAR task input', () => { it('preserves consecutive text and rejects non-text or blank input', () => { expect(textTask([{ type: 'text', text: 'one' }, { type: 'text', text: 'two' }])).toBe('onetwo') - expect(() => textTask([])).toThrow() - expect(() => textTask([{ type: 'text', text: ' \n ' }])).toThrow() - expect(() => textTask([{ type: 'reasoning', text: 'private' }])).toThrow() + const invalid = { name: 'OarFailure', code: 'OAR_INVALID_TASK' } + expect(() => textTask([])).toThrow(expect.objectContaining(invalid)) + expect(() => textTask([{ type: 'text', text: ' \n ' }])).toThrow(expect.objectContaining(invalid)) + expect(() => textTask([{ type: 'reasoning', text: 'private' }])).toThrow(expect.objectContaining(invalid)) }) it('removes inherited credentials and retains explicit environment deletion', () => { @@ -234,7 +235,7 @@ describe('OAR one-shot execution', () => { const install = vi.fn>() const session = vi.fn(base.session) const runtime: Runtime = { ...base, install, session, installation: async () => ({ kind: 'not_found' }) } - await expect(startOarRun(await request(), spec(runtime))).rejects.toThrow() + await expect(startOarRun(await request(), spec(runtime))).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE' }) expect(install).not.toHaveBeenCalled() expect(session).not.toHaveBeenCalled() }) @@ -242,7 +243,7 @@ describe('OAR one-shot execution', () => { it('rejects a runtime with no installation probe', async () => { const base = scriptedRuntime({ turn: () => {} }) const { installation: _installation, ...runtime } = base - await expect(startOarRun(await request(), spec(runtime))).rejects.toThrow() + await expect(startOarRun(await request(), spec(runtime))).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE' }) }) it('does not open after cancellation wins installation probing', async () => { @@ -260,7 +261,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toThrow() + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED' }) await probed.promise controller.abort() release.resolve(undefined) @@ -282,7 +283,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toThrow() + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED' }) await entered.promise controller.abort() release.resolve(undefined) @@ -295,7 +296,9 @@ describe('OAR one-shot execution', () => { const probe = vi.fn(observed.runtime.installation) const controller = new AbortController() controller.abort() - await expect(startOarRun(await request(controller.signal), spec({ ...observed.runtime, installation: probe }))).rejects.toThrow() + await expect(startOarRun(await request(controller.signal), spec({ ...observed.runtime, installation: probe }))).rejects.toMatchObject({ + name: 'AbortError', code: 'ABORTED', + }) expect(probe).not.toHaveBeenCalled() }) @@ -384,7 +387,7 @@ describe('OAR one-shot execution', () => { const run = await startOarRun(await request(), spec(runtime, { onError })) const result = await run.result expect(result.output).toEqual([{ type: 'text', text: 'completed answer' }]) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) expect(onError).toHaveBeenCalled() }) it('selects the last non-empty identified root message', async () => { @@ -426,7 +429,9 @@ describe('OAR one-shot execution', () => { ...scriptedRuntime({ turn: () => {} }), installation: async () => { throw cause }, } - await expect(startOarRun(await request(), spec(runtime, { onError }))).rejects.toMatchObject({ cause }) + await expect(startOarRun(await request(), spec(runtime, { onError }))).rejects.toMatchObject({ + name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE', cause, + }) expect(onError).toHaveBeenCalledOnce() expect(onError.mock.calls[0]?.[0].message).toContain('stage: installation; category: unknown') expect(onError.mock.calls[0]?.[0].cause).toBe(cause) @@ -437,12 +442,16 @@ describe('OAR one-shot execution', () => { const controller = new AbortController() const base = scriptedRuntime({ turn: () => {} }) const runtime: Runtime = { ...base, session: async () => { throw new Error('PRIVATE_START_DETAIL') } } - await expect(startOarRun(await request(), spec(runtime, { effort: 'high' }))).rejects.toThrow('stage: startup; category: unknown') + await expect(startOarRun(await request(), spec(runtime, { effort: 'high' }))).rejects.toMatchObject({ + name: 'OarFailure', code: 'OAR_START_FAILED', message: expect.stringContaining('stage: startup; category: unknown') as string, + }) const canceled: Runtime = { ...base, session: async () => { controller.abort() throw new Error('PRIVATE_START_DETAIL') } } - await expect(startOarRun(await request(controller.signal), spec(canceled))).rejects.toThrow('category: cancelled') + await expect(startOarRun(await request(controller.signal), spec(canceled))).rejects.toMatchObject({ + name: 'AbortError', code: 'ABORTED', + }) }) it('cleans an opened session when event subscription fails', async () => { @@ -516,7 +525,9 @@ describe('OAR one-shot execution', () => { return unsubscribe } } } } - await expect(startOarRun(await request(controller.signal), spec(runtime))).rejects.toThrow('category: cancelled') + await expect(startOarRun(await request(controller.signal), spec(runtime))).rejects.toMatchObject({ + name: 'AbortError', code: 'ABORTED', + }) expect(observed.dispose).toHaveBeenCalledOnce() }) @@ -538,7 +549,7 @@ describe('OAR one-shot execution', () => { await active.promise controller.abort() await expect(run.result).resolves.toMatchObject({ stopReason: 'aborted' }) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) }) }) diff --git a/packages/experimental/subagent-oar/tsconfig.json b/packages/experimental/subagent-oar/tsconfig.json index 1b419fb0ca..648ba044ab 100644 --- a/packages/experimental/subagent-oar/tsconfig.json +++ b/packages/experimental/subagent-oar/tsconfig.json @@ -37,6 +37,9 @@ }, { "path": "../../subprocess/subprocess" + }, + { + "path": "../../core/tools" } ] } diff --git a/packages/experimental/tool-subagent-oar/src/index.ts b/packages/experimental/tool-subagent-oar/src/index.ts index aab8ac7266..f3eb638958 100644 --- a/packages/experimental/tool-subagent-oar/src/index.ts +++ b/packages/experimental/tool-subagent-oar/src/index.ts @@ -2,8 +2,8 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' -import type {} from '@deepseek-ai/dsh-subagent' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { SubagentError } from '@deepseek-ai/dsh-subagent' export const name = 'experimental-tool-subagent-oar' export const inject = ['tools', 'subagents'] @@ -84,12 +84,12 @@ export function apply(ctx: Context, config: Config): void { isConcurrencySafe: () => true, async execute(args, exec) { const parent = exec.agent - if (parent === undefined) throw new Error('subagent_oar requires a calling agent') + if (parent === undefined) throw new ToolContextUnavailableError('subagent_oar requires a calling agent') // The parameter enum admits only keys from this immutable configuration. const providerName = providers.get(args.runtime) as string const provider = ctx.subagents.getProvider(providerName) if (provider !== undefined && (provider.prepareContinuable !== undefined || provider.inheritsParentContext)) { - throw new Error('subagent_oar requires a one-shot provider with independent conversation context') + throw new SubagentError('subagent_oar requires a one-shot provider with independent conversation context', 'UNSUPPORTED_CAPABILITY') } const activation = await ctx.subagents.startActivation({ provider: providerName, diff --git a/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts b/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts index e9dcaf54a6..b9a49f3e57 100644 --- a/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts +++ b/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts @@ -94,6 +94,7 @@ it('fails visibly when the selected provider disappears', async (test) => { arguments: { runtime: 'missing', description: 'task', prompt: 'task' }, }) expect(result.isError).toBe(true) + expect(result.isError && result.error.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) expect(calls).toEqual([]) }) @@ -120,10 +121,12 @@ it('requires a caller and independently scoped one-shot providers', async (test) name: 'subagent_oar', arguments: args, callId: ToolCallId(randomUUID()), signal: test.signal, }) expect(noParent.isError).toBe(true) + expect(noParent.isError && noParent.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) const inherited = await executeToolFixture(ctx, { agent: parent, name: 'subagent_oar', arguments: args, callId: ToolCallId(randomUUID()), signal: test.signal, }) expect(inherited.isError).toBe(true) + expect(inherited.isError && inherited.error.info).toEqual({ name: 'SubagentError', code: 'UNSUPPORTED_CAPABILITY' }) expect(JSON.stringify(inherited.content)).toContain('independent conversation') }) From 2c45f0d705b45b3407e76ab6d0e276b1a38cb2f5 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:38:37 +0800 Subject: [PATCH 17/68] feat(worktree): add WorktreeError for create_worktree failures Invalid names and requests, existing branches or paths, locked registrations, failed, oversized, or timed-out commands, and a disposed service now throw WorktreeError with a closed WORKTREE_* code. The retained-artifact wrapper keeps the name and code of a HarnessError it wraps and keeps caller cancellation an AbortError. create_worktree throws ToolContextUnavailableError without a calling agent. Refs #7869 --- .../experimental/tool-worktree/src/index.ts | 4 +- .../tests/loader-composition.spec.ts | 7 +- .../experimental/worktree/README.i18n.yaml | 4 +- packages/experimental/worktree/README.md | 2 + packages/experimental/worktree/README.zh.md | 2 + packages/experimental/worktree/package.json | 6 +- packages/experimental/worktree/src/error.ts | 43 ++++++++ packages/experimental/worktree/src/index.ts | 72 +++++++++--- packages/experimental/worktree/src/process.ts | 104 ++++++++++-------- .../worktree/tests/checkout-safety.spec.ts | 8 +- .../worktree/tests/worktree.spec.ts | 87 +++++++++++---- packages/experimental/worktree/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 13 files changed, 259 insertions(+), 86 deletions(-) create mode 100644 packages/experimental/worktree/src/error.ts diff --git a/packages/experimental/tool-worktree/src/index.ts b/packages/experimental/tool-worktree/src/index.ts index 53f035f7d7..ad526e61ef 100644 --- a/packages/experimental/tool-worktree/src/index.ts +++ b/packages/experimental/tool-worktree/src/index.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-experimental-worktree' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' /** Cordis plugin name. */ export const name = 'tool-worktree' @@ -35,7 +35,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, async execute(args, exec) { - if (exec.agent === undefined) throw new Error('create_worktree requires a calling agent') + if (exec.agent === undefined) throw new ToolContextUnavailableError('create_worktree requires a calling agent') return ctx.worktrees.create(exec.agent, args, exec.signal) }, presentCall: args => ({ card: 'generic', title: 'create_worktree', rawInput: args }), diff --git a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts index 8341b9dd8a..ec0ef398c1 100644 --- a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts @@ -102,7 +102,12 @@ describe('worktree tool through real Loader composition', () => { }) expect(failure.isError).toBe(true) expect(failure.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')).toContain('requires a calling agent') - expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ card: 'generic', title: 'create_worktree', rawInput: { name: 'named' } }) + expect(failure.isError && failure.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) + const existing = await invoke('new-checkout') + expect(existing.isError && existing.error.info).toEqual({ name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS' }) + expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ + card: 'generic', title: 'create_worktree', rawInput: { name: 'named' }, + }) const entry = [...context.loader.entries()].find(candidate => candidate.options.name === 'cordis:@deepseek-ai/dsh-experimental-tool-worktree') await entry!.fiber!.dispose() expect(context.tools.schemas().some(tool => tool.name === 'create_worktree')).toBe(false) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 5e9a6604cb..24f4fb03b2 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: 7fb20cca0a3154e5 - zh: 41bf0aa2bf753c07 + en: 743828cee4516880 + zh: 76e9679e4467a100 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index e164f86600..f98f15119c 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -38,6 +38,8 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. +Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name, start revision, or restoration record that Git or the pool rules reject; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. + The default checkout directory is `/.agents/worktrees/`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Each Git and Node command runs under its own `timeoutMs` deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative `directory`, generated `namePrefix`, executable choices, process limits, and `retainOnArchive` are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree). ----- diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 5c497a2606..720bdc316f 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -38,6 +38,8 @@ kind: "package-reference" 每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 +预期失败抛出 `WorktreeError`,其 `code` 为:名称、起始修订或恢复记录被 Git 或池规则拒绝时为 `WORKTREE_INVALID_ARGUMENT`;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 + 默认检出目录是 `/.agents/worktrees/`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。每条 Git 和 Node 命令各自受 `timeoutMs` 时限约束,默认 5 分钟,使大仓库在较慢的文件系统上也能完成检出;取消仍会终止正在运行的命令。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序、进程限制与 `retainOnArchive` 可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。 ----- diff --git a/packages/experimental/worktree/package.json b/packages/experimental/worktree/package.json index 6f0a109d84..2304e938b3 100644 --- a/packages/experimental/worktree/package.json +++ b/packages/experimental/worktree/package.json @@ -54,7 +54,8 @@ "@deepseek-ai/dsh-settings": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-workspace": "workspace:*" + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -77,6 +78,7 @@ "@deepseek-ai/dsh-subprocess-local": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-workspace": "workspace:*" + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/worktree/src/error.ts b/packages/experimental/worktree/src/error.ts new file mode 100644 index 0000000000..dd55a69c0e --- /dev/null +++ b/packages/experimental/worktree/src/error.ts @@ -0,0 +1,43 @@ +/** Machine-routable worktree creation and restoration failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link WorktreeError} code: + * - `WORKTREE_INVALID_ARGUMENT` — the branch name, start revision, or restoration request violates a documented + * constraint; correct it and retry. + * - `WORKTREE_ALREADY_EXISTS` — the branch or checkout path already exists; choose another name or reuse the existing checkout. + * - `WORKTREE_LOCKED` — Git keeps the missing checkout's registration locked; unlock it before restoring. + * - `WORKTREE_COMMAND_FAILED` — a Git or directory-allocation command exited unsuccessfully; the message carries its status and stderr. + * - `WORKTREE_OUTPUT_TOO_LARGE` — a command's output exceeded the configured `maxOutputBytes`; raise the limit or inspect the repository. + * - `WORKTREE_TIMEOUT` — a command exceeded the configured `timeoutMs`; its effects are unknown, so inspect the repository before retrying. + * - `WORKTREE_UNAVAILABLE` — the worktree service was disposed; retry after it is loaded again. + */ +export const WORKTREE_ERROR_CODES = [ + 'WORKTREE_INVALID_ARGUMENT', + 'WORKTREE_ALREADY_EXISTS', + 'WORKTREE_LOCKED', + 'WORKTREE_COMMAND_FAILED', + 'WORKTREE_OUTPUT_TOO_LARGE', + 'WORKTREE_TIMEOUT', + 'WORKTREE_UNAVAILABLE', +] as const + +/** One code from {@link WORKTREE_ERROR_CODES}. */ +export type WorktreeErrorCode = typeof WORKTREE_ERROR_CODES[number] + +/** Worktree failure carrying a stable {@link WorktreeErrorCode}. */ +export class WorktreeError extends HarnessError { + override readonly code: WorktreeErrorCode + + /** + * @param message - names the operation and the safe next step. + * @param code - failure class. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: WorktreeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'WorktreeError' + this.code = code + } +} diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index b445ec72b7..e1da7dfa23 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -11,8 +11,10 @@ import { appendPluginRecord } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-working-directory' +import { HarnessError } from '@deepseek-ai/dsh-error' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { WorktreeReclamation } from './archive.ts' +import { WorktreeError } from './error.ts' import { PREPARE_DIRECTORY } from './directory.ts' import { generatedWorktreeName } from './name.ts' import { runCommand, scanCommand } from './process.ts' @@ -31,6 +33,7 @@ export type { export { generatedWorktreeName } from './name.ts' export { CREATED_RECORD, createdWorktreeSchema, worktreeProjection } from './projection.ts' export type { WorktreeProjectionState } from './projection.ts' +export { WORKTREE_ERROR_CODES, WorktreeError, type WorktreeErrorCode } from './error.ts' /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ export interface Config { @@ -121,7 +124,7 @@ export class WorktreeService extends Service { } } ctx.effect(() => async () => { - this.lifetime.abort(new Error('worktree service disposed')) + this.lifetime.abort(new WorktreeError('worktree service disposed', 'WORKTREE_UNAVAILABLE')) await Promise.allSettled(this.pending) }) // The Forge panel draws the retain switch on this row's Plugins page. @@ -155,6 +158,8 @@ export class WorktreeService extends Service { * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. + * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out + * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, @@ -186,6 +191,8 @@ export class WorktreeService extends Service { * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; it must not throw. * @returns the directory and whether the branch was created again. + * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, + * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async restore( agent: Agent, @@ -242,9 +249,9 @@ export class WorktreeService extends Service { private resolve(agent: Agent, request: CreateWorktreeRequest): WorktreeSpec { const branch = request.name ?? generatedWorktreeName(this.config.namePrefix, agent.session.id) - if (!relativePath(branch) || branch.startsWith('-')) throw new Error('worktree name must be a relative Git branch name') + if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree name must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT') const revision = request.from ?? 'HEAD' - if (revision.length === 0) throw new Error('worktree from must name a local commit, branch, or tag') + if (revision.length === 0) throw new WorktreeError('worktree from must name a local commit, branch, or tag', 'WORKTREE_INVALID_ARGUMENT') return { branch, revision } } @@ -258,19 +265,19 @@ export class WorktreeService extends Service { const cwd = await this.ctx.workingDirectory.ensure(agent, signal) const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) - await run(cwd, ['check-ref-format', `refs/heads/${branch}`]) + await assertBranchName(run, cwd, branch, 'worktree name') const rootOutput = await run(cwd, ['rev-parse', '--show-toplevel']) const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ''), { cwd, signal }) const repositoryRoot = this.ctx.fs.processPath(rootTarget) const base = await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${revision}^{commit}`]) const baseCommit = base.stdout.trim() const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]) - if (existing.exitCode === 0) throw new Error(`worktree branch already exists: ${branch}`) + if (existing.exitCode === 0) throw new WorktreeError(`worktree branch already exists: ${branch}`, 'WORKTREE_ALREADY_EXISTS') const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal }) const poolPath = this.ctx.fs.processPath(pool) const destination = await this.ctx.fs.resolve(branch, { cwd: poolPath, signal }) const path = this.ctx.fs.processPath(destination) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') try { await this.prepareDirectory(policy, repositoryRoot, poolPath, path, signal) await run(repositoryRoot, ['--work-tree', repositoryRoot, 'worktree', 'add', '--no-checkout', '-b', branch, '--', path, baseCommit]) @@ -282,7 +289,7 @@ export class WorktreeService extends Service { appendPluginRecord(agent.session, CREATED_RECORD, created) return created } catch (error) { - throw new Error(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + throw retainedFailure(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained.`, error, signal) } } @@ -295,18 +302,20 @@ export class WorktreeService extends Service { onPhase?.('prepare') const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) - if (!relativePath(branch) || branch.startsWith('-')) throw new Error('worktree branch must be a relative Git branch name') - if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new Error('worktree baseCommit must be a full commit object name') + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') + if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree branch must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT') + if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new WorktreeError('worktree baseCommit must be a full commit object name', 'WORKTREE_INVALID_ARGUMENT') const identity = await checkoutIdentity(this.ctx, this.config.directory, { path, branch, baseCommit, repositoryRoot }, run, signal) - if (identity === null) throw new Error('worktree restoration must use a canonical directory inside the configured pool of the source checkout root') - await run(repositoryRoot, ['check-ref-format', `refs/heads/${branch}`]) + if (identity === null) { + throw new WorktreeError('worktree restoration must use a canonical directory inside the configured pool of the source checkout root', 'WORKTREE_INVALID_ARGUMENT') + } + await assertBranchName(run, repositoryRoot, branch, 'worktree branch') await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`]) const scan = this.gitScanner(policy, signal) const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, scan, signal) if (fields !== undefined) { - if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new Error(`worktree is locked: ${path}`) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) + if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new WorktreeError(`worktree is locked: ${path}`, 'WORKTREE_LOCKED') + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') await run(repositoryRoot, ['worktree', 'remove', '--', path]) } const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]) @@ -323,7 +332,7 @@ export class WorktreeService extends Service { await run(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', 'HEAD'], undefined, overrides) return { path, branchRecreated } } catch (error) { - throw new Error(`Could not restore worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + throw retainedFailure(`Could not restore worktree ${branch} at ${path}. Any created checkout and branch are retained.`, error, signal) } } @@ -357,6 +366,39 @@ export class WorktreeService extends Service { } } +/** + * Reject a name Git does not accept as a branch. + * @param run - confined Git runner. + * @param directory - repository directory for the check. + * @param branch - candidate branch name. + * @param field - request field named in the failure. + */ +async function assertBranchName(run: GitRun, directory: string, branch: string, field: string): Promise { + const checked = await run(directory, ['check-ref-format', `refs/heads/${branch}`], [0, 1]) + if (checked.exitCode !== 0) throw new WorktreeError(`${field} must be a valid Git branch name`, 'WORKTREE_INVALID_ARGUMENT') +} + +/** + * Add retained-artifact context to a failure without changing its routable identity: + * a `HarnessError` keeps its `name` and `code`, and caller cancellation stays an `AbortError`. + * @param context - operation summary placed before the original message. + * @param error - failure thrown after allocation began. + * @param signal - operation cancellation. + * @returns the error to throw, with `error` as its cause. + */ +function retainedFailure(context: string, error: unknown, signal: AbortSignal): Error { + const message = `${context} ${error instanceof Error ? error.message : String(error)}` + if (error instanceof WorktreeError) return new WorktreeError(message, error.code, { cause: error }) + if (error instanceof HarnessError) { + const wrapped = new HarnessError(message, error.code, { cause: error }) + wrapped.name = error.name + return wrapped + } + const wrapped = new Error(message, { cause: error }) + if (signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))) wrapped.name = 'AbortError' + return wrapped +} + /** * Build the environment that disables every configured clean, smudge, and * process filter of the checkout for one command, without changing Git config. diff --git a/packages/experimental/worktree/src/process.ts b/packages/experimental/worktree/src/process.ts index f4bb56273a..5a66022b30 100644 --- a/packages/experimental/worktree/src/process.ts +++ b/packages/experimental/worktree/src/process.ts @@ -6,7 +6,8 @@ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type { SubprocessCollect, SubprocessCollectedOutputs, SubprocessHandle, SubprocessOutcome, SubprocessOutputReader, } from '@deepseek-ai/dsh-subprocess' -import { deadline } from '@deepseek-ai/dsh-timeout' +import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import { WorktreeError } from './error.ts' /** Resolved process resource limits owned by the worktree service. */ export interface ProcessConfig { @@ -37,6 +38,8 @@ const GIT_ENV: NodeJS.ProcessEnv = Object.fromEntries([ * @param allowedExitCodes - command-specific successful statuses. * @param env - command-local environment overrides, applied after Git selector removal. * @returns complete bounded stdout and the exit code. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, or `WORKTREE_TIMEOUT`; + * caller cancellation propagates its reason. */ export async function runCommand( ctx: Context, @@ -49,20 +52,22 @@ export async function runCommand( env: NodeJS.ProcessEnv = {}, ): Promise<{ stdout: string; exitCode: number }> { using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') - const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes }) - try { - const outcome = await child.done - timeout.signal.throwIfAborted() - // The spawn spec above collects both streams. - const captured = child.collected as Required - const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes) - const stdout = captured.stdout.readFrom(0) - if (stdout.lossy) throw new Error('worktree command output exceeds maxOutputBytes') - return { stdout: stdout.text, exitCode } - } finally { - child.terminate() - await child.waitForExit() - } + return await classifyTimeout(config, timeout.signal, async () => { + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes }) + try { + const outcome = await child.done + timeout.signal.throwIfAborted() + // The spawn spec above collects both streams. + const captured = child.collected as Required + const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes) + const stdout = captured.stdout.readFrom(0) + if (stdout.lossy) throw new WorktreeError('worktree command output exceeds maxOutputBytes', 'WORKTREE_OUTPUT_TOO_LARGE') + return { stdout: stdout.text, exitCode } + } finally { + child.terminate() + await child.waitForExit() + } + }) } /** @@ -81,6 +86,7 @@ export async function runCommand( * @param signal - operation cancellation. * @param onField - synchronous consumer of each field in order; false ends the command. * @returns true when `onField` ended the command, false when it exited successfully first. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED` or `WORKTREE_TIMEOUT`; caller cancellation propagates its reason. */ export async function scanCommand( ctx: Context, @@ -92,36 +98,38 @@ export async function scanCommand( onField: (field: string) => boolean, ): Promise { using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') - const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, 'pipe') - try { - // The spawn spec above pipes stdout and collects stderr. - const stdout = child.stdout as Readable - stdout.setEncoding('utf8') - let pending = '' - let stopped = false - for await (const chunk of stdout as AsyncIterable) { - const fields = (pending + chunk).split('\0') - pending = fields.splice(-1).join('') - if (!fields.every(field => onField(field))) { - stopped = true - break + return await classifyTimeout(config, timeout.signal, async () => { + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, 'pipe') + try { + // The spawn spec above pipes stdout and collects stderr. + const stdout = child.stdout as Readable + stdout.setEncoding('utf8') + let pending = '' + let stopped = false + for await (const chunk of stdout as AsyncIterable) { + const fields = (pending + chunk).split('\0') + pending = fields.splice(-1).join('') + if (!fields.every(field => onField(field))) { + stopped = true + break + } } - } - if (stopped) { + if (stopped) { + child.terminate() + await Promise.allSettled([child.done]) + timeout.signal.throwIfAborted() + return true + } + const outcome = await child.done + timeout.signal.throwIfAborted() + allowedExitCode(outcome, child.collected.stderr as SubprocessOutputReader, [0]) + return false + } finally { child.terminate() await Promise.allSettled([child.done]) - timeout.signal.throwIfAborted() - return true + await child.waitForExit() } - const outcome = await child.done - timeout.signal.throwIfAborted() - allowedExitCode(outcome, child.collected.stderr as SubprocessOutputReader, [0]) - return false - } finally { - child.terminate() - await Promise.allSettled([child.done]) - await child.waitForExit() - } + }) } /** Resolve, confine, and start one command whose stderr is collected within `maxOutputBytes`. */ @@ -154,11 +162,21 @@ async function spawnCommand( /** * The exit code of a command that exited with an allowed status. - * @throws when the command was signalled or exited with another status, quoting its stderr. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED` when the command was signalled or exited with another status, quoting its stderr. */ function allowedExitCode(outcome: SubprocessOutcome, stderr: SubprocessOutputReader, allowedExitCodes: readonly number[]): number { if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) { - throw new Error(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`) + throw new WorktreeError(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`, 'WORKTREE_COMMAND_FAILED') } return outcome.exitCode } + +/** Run one command under a deadline, converting its elapsed deadline into `WORKTREE_TIMEOUT`. */ +async function classifyTimeout(config: ProcessConfig, signal: AbortSignal, body: () => Promise): Promise { + try { + return await body() + } catch (error) { + if (timeoutOf(signal, 'WORKTREE_TIMEOUT') === undefined) throw error + throw new WorktreeError(`worktree command exceeded ${config.timeoutMs}ms; inspect the repository before retrying`, 'WORKTREE_TIMEOUT', { cause: error }) + } +} diff --git a/packages/experimental/worktree/tests/checkout-safety.spec.ts b/packages/experimental/worktree/tests/checkout-safety.spec.ts index 0ac4bd6a4d..7d4fe4a80d 100644 --- a/packages/experimental/worktree/tests/checkout-safety.spec.ts +++ b/packages/experimental/worktree/tests/checkout-safety.spec.ts @@ -121,7 +121,9 @@ describe('worktree checkout Git configuration', () => { ctx = await harness(root) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'invalid' })).rejects.toThrow(/Any created checkout and branch are retained.*bad config line/s) + await expect(ctx.worktrees.create(agent, { name: 'invalid' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_COMMAND_FAILED', message: expect.stringMatching(/Any created checkout and branch are retained.*bad config line/s) as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) await access(join(root, '.agents/worktrees/invalid/.git')) @@ -135,7 +137,9 @@ describe('worktree checkout Git configuration', () => { ctx = await harness(root, { maxOutputBytes: 256 }) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toThrow('output exceeds maxOutputBytes') + await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toMatchObject({ + code: 'WORKTREE_OUTPUT_TOO_LARGE', message: expect.stringContaining('output exceeds maxOutputBytes') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) await access(join(root, '.agents/worktrees/bounded/.git')) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index 33c9b84f21..0cc9b3bf6b 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -186,7 +186,9 @@ describe('creating and entering retained worktrees', () => { ctx = await harness(partial) const agent = testAgent(ctx, partial) - await expect(ctx.worktrees.create(agent, { name: 'local-only' })).rejects.toThrow('worktree command failed') + await expect(ctx.worktrees.create(agent, { name: 'local-only' })).rejects.toMatchObject({ + code: 'WORKTREE_COMMAND_FAILED', message: expect.stringContaining('worktree command failed') as string, + }) expect(await git(partial, 'rev-list', '--objects', '--missing=print', 'HEAD')).toBe(missing) expect(ctx.workingDirectory.get(agent.session)).toBe(partial) @@ -210,7 +212,9 @@ describe('creating and entering retained worktrees', () => { return resolveExecutable(command, env, signal) }) const operation = service.create(testAgent(ctx, root), { name: 'cancelled' }) - const rejection = expect(operation).rejects.toThrow('worktree service disposed') + const rejection = expect(operation).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) let disposal: Promise | undefined try { const signal = await entered.promise @@ -227,7 +231,9 @@ describe('creating and entering retained worktrees', () => { await disposal expect(disposed).toBe(true) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) - await expect(service.create(testAgent(ctx, root, 'after-disposal'))).rejects.toThrow('worktree service disposed') + await expect(service.create(testAgent(ctx, root, 'after-disposal'))).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) } finally { release.resolve(undefined) await Promise.allSettled([operation, rejection, disposal]) @@ -275,12 +281,24 @@ describe('creating and entering retained worktrees', () => { const agent = testAgent(ctx, root) await git(root, 'branch', 'existing') await mkdir(join(root, '.agents/worktrees/occupied'), { recursive: true }) - await expect(ctx.worktrees.create(agent, { name: 'existing' })).rejects.toThrow('branch already exists') - await expect(ctx.worktrees.create(agent, { name: 'occupied' })).rejects.toThrow('path already exists') - await expect(ctx.worktrees.create(agent, { name: 'missing', from: 'unavailable' })).rejects.toThrow('command failed') - await expect(ctx.worktrees.create(agent, { name: '../escape' })).rejects.toThrow('relative Git branch') - await expect(ctx.worktrees.create(agent, { name: 'invalid name' })).rejects.toThrow('command failed') - await expect(ctx.worktrees.create(agent, { from: '' })).rejects.toThrow('from must name') + await expect(ctx.worktrees.create(agent, { name: 'existing' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS', message: expect.stringContaining('branch already exists') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'occupied' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS', message: expect.stringContaining('path already exists') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'missing', from: 'unavailable' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_COMMAND_FAILED', + }) + await expect(ctx.worktrees.create(agent, { name: '../escape' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('relative Git branch') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'invalid name' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: 'worktree name must be a valid Git branch name', + }) + await expect(ctx.worktrees.create(agent, { from: '' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('from must name') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'worktree', 'list', '--porcelain')).not.toContain('/occupied') expect(await readdir(join(root, '.agents/worktrees'))).toEqual(['occupied']) @@ -292,7 +310,9 @@ describe('creating and entering retained worktrees', () => { const agent = testAgent(ctx, root) await ctx.workingDirectory.ensure(agent) vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(new Error('directory publication failed')) - await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toThrow('Any created checkout and branch are retained') + await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toMatchObject({ + name: 'Error', message: expect.stringContaining('Any created checkout and branch are retained') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'branch', '--list', 'retained')).toContain('retained') expect(await contents(join(root, '.agents/worktrees/retained/tracked.txt'))).toBe('initial\n') @@ -342,11 +362,26 @@ describe('creating and entering retained worktrees', () => { const root = await repo() ctx = await harness(root, { maxOutputBytes: 1 }) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toThrow('output exceeds maxOutputBytes') + await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toMatchObject({ + code: 'WORKTREE_OUTPUT_TOO_LARGE', message: 'worktree command output exceeds maxOutputBytes', + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) }) + it('reports an elapsed command deadline as a timeout', async () => { + const root = await repo() + ctx = await harness(root, { timeoutMs: 20 }) + const agent = testAgent(ctx, root) + vi.spyOn(ctx.subprocess, 'resolveExecutable').mockImplementation((_command, _env, signal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + })) + await expect(ctx.worktrees.create(agent, { name: 'slow' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_TIMEOUT', message: 'worktree command exceeded 20ms; inspect the repository before retrying', + }) + expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) + }) + it('retains a caller cancellation reason when allocation is cancelled before its child starts', async () => { const root = await repo() ctx = await harness(root) @@ -358,7 +393,9 @@ describe('creating and entering retained worktrees', () => { return resolveExecutable(command, env, signal) }) try { - await expect(ctx.worktrees.create(agent, { name: 'cancelled-allocation' }, controller.signal)).rejects.toThrow('caller stopped') + await expect(ctx.worktrees.create(agent, { name: 'cancelled-allocation' }, controller.signal)).rejects.toMatchObject({ + name: 'AbortError', message: expect.stringContaining('caller stopped') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) } finally { @@ -458,7 +495,9 @@ describe('restoring removed worktrees', () => { const created = await ctx.worktrees.create(agent, { name: 'topic' }) const spawn = vi.spyOn(ctx.subprocess, 'spawn') - await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow(`worktree path already exists: ${created.path}`) + await expect(ctx.worktrees.restore(agent, created)).rejects.toMatchObject({ + code: 'WORKTREE_ALREADY_EXISTS', message: `worktree path already exists: ${created.path}`, + }) expect(spawn).not.toHaveBeenCalled() }) @@ -469,7 +508,9 @@ describe('restoring removed worktrees', () => { const agent = testAgent(ctx, root) const path = join(root, '.agents/worktrees/vanished') const request: RestoreWorktreeRequest = { path, branch: 'vanished', baseCommit: 'f'.repeat(40), repositoryRoot: root } - await expect(ctx.worktrees.restore(agent, request)).rejects.toThrow('worktree command failed') + await expect(ctx.worktrees.restore(agent, request)).rejects.toMatchObject({ + code: 'WORKTREE_COMMAND_FAILED', message: expect.stringContaining('worktree command failed') as string, + }) await expect(access(path)).rejects.toMatchObject({ code: 'ENOENT' }) expect(await git(root, 'branch', '--list', 'vanished')).toBe('') expect(ctx.workingDirectory.get(agent.session)).toBe(root) @@ -489,7 +530,9 @@ describe('restoring removed worktrees', () => { }) try { await expect(ctx.worktrees.restore(agent, created, controller.signal)) - .rejects.toThrow(`Could not restore worktree topic at ${created.path}. Any created checkout and branch are retained. caller stopped`) + .rejects.toMatchObject({ + name: 'AbortError', message: `Could not restore worktree topic at ${created.path}. Any created checkout and branch are retained. caller stopped`, + }) await expect(access(created.path)).rejects.toMatchObject({ code: 'ENOENT' }) } finally { probe.mockRestore() @@ -509,7 +552,9 @@ describe('restoring removed worktrees', () => { await expect(service.restore(agent, request, AbortSignal.abort(new Error('cancelled')))).rejects.toThrow('cancelled') await fiber!.dispose() - await expect(service.restore(agent, request)).rejects.toThrow('worktree service disposed') + await expect(service.restore(agent, request)).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) expect(spawn).not.toHaveBeenCalled() expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) @@ -536,7 +581,7 @@ describe('restoration validation', () => { request.repositoryRoot = join(root, '.agents') request.path = join(request.repositoryRoot, '.agents/worktrees/topic') } - await expect(ctx.worktrees.restore(agent, request)).rejects.toThrow() + await expect(ctx.worktrees.restore(agent, request)).rejects.toMatchObject({ name: 'WorktreeError', code: 'WORKTREE_INVALID_ARGUMENT' }) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) await expect(access(created.path)).rejects.toMatchObject({ code: 'ENOENT' }) await expect(access(join(root, 'outside'))).rejects.toMatchObject({ code: 'ENOENT' }) @@ -550,7 +595,9 @@ describe('restoration validation', () => { await git(root, 'worktree', 'lock', created.path) await rm(created.path, { recursive: true, force: true }) const before = await git(root, 'worktree', 'list', '--porcelain') - await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow('worktree is locked') + await expect(ctx.worktrees.restore(agent, created)).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_LOCKED', message: expect.stringContaining('worktree is locked') as string, + }) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) }) }) @@ -567,7 +614,9 @@ it('rejects a restore path redirected outside the pool by a symlink', async () = await mkdir(outside) await symlink(outside, link, 'junction') const before = await git(root, 'worktree', 'list', '--porcelain') - await expect(ctx.worktrees.restore(agent, { ...created, path: join(link, 'topic') })).rejects.toThrow('configured pool') + await expect(ctx.worktrees.restore(agent, { ...created, path: join(link, 'topic') })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('configured pool') as string, + }) expect(await readdir(outside)).toEqual([]) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) }) diff --git a/packages/experimental/worktree/tsconfig.json b/packages/experimental/worktree/tsconfig.json index 82f74490dd..b62504acfa 100644 --- a/packages/experimental/worktree/tsconfig.json +++ b/packages/experimental/worktree/tsconfig.json @@ -55,6 +55,9 @@ }, { "path": "../../settings/settings" + }, + { + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1876116909..1281a6e650 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11900,6 +11900,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs From 067d7964e68a2154ce5dc65c59e696035ccd25a7 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:38:38 +0800 Subject: [PATCH 18/68] feat(tool-ralph): add RalphError and classify ralph failures Provider, workflow, result, and round failures now throw RalphError with a closed RALPH_* code; invalid objective and maxRounds throw ToolArgsError; a missing agent throws ToolContextUnavailableError; a workflow cancelled by the caller throws AbortError / ABORTED. Refs #7869 --- .../experimental/tool-ralph/README.i18n.yaml | 4 +- packages/experimental/tool-ralph/README.md | 2 +- packages/experimental/tool-ralph/README.zh.md | 2 +- packages/experimental/tool-ralph/src/index.ts | 93 ++++++++++++++----- .../tool-ralph/tests/integration.spec.ts | 1 + .../tool-ralph/tests/tool-ralph.spec.ts | 44 ++++++--- 6 files changed, 104 insertions(+), 42 deletions(-) diff --git a/packages/experimental/tool-ralph/README.i18n.yaml b/packages/experimental/tool-ralph/README.i18n.yaml index b3f96e6e46..fa33b13562 100644 --- a/packages/experimental/tool-ralph/README.i18n.yaml +++ b/packages/experimental/tool-ralph/README.i18n.yaml @@ -18,8 +18,8 @@ en: 13380e1170c6a3b5 zh: 2f2665f2ee5ff6f7 /deepseek-ai-dsh-tool-ralph/use-this-package/calling-the-tool: - en: f43e8fbcf272ac45 - zh: 46719b415d9ad4bf + en: 69037b1ef1e2606b + zh: bbc39d5be9b86989 /deepseek-ai-dsh-tool-ralph/use-this-package/what-each-round-sees: en: 2d8b861c4bcb9424 zh: 63c7b2d00c324727 diff --git a/packages/experimental/tool-ralph/README.md b/packages/experimental/tool-ralph/README.md index 0a9d944525..44b646cf6f 100644 --- a/packages/experimental/tool-ralph/README.md +++ b/packages/experimental/tool-ralph/README.md @@ -29,7 +29,7 @@ The `ralph` tool runs a fixed foreground loop: one fresh child per round works o ### Calling the tool -The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. +The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a code from `RALPH_ERROR_CODES`: `RALPH_ROUND_FAILED` for a failed child round, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. ### What each round sees diff --git a/packages/experimental/tool-ralph/README.zh.md b/packages/experimental/tool-ralph/README.zh.md index 8eedae966c..11f7094616 100644 --- a/packages/experimental/tool-ralph/README.zh.md +++ b/packages/experimental/tool-ralph/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 调用工具 -模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。 +模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 取自 `RALPH_ERROR_CODES`:子 agent Round 失败为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 ### 每个 Round 看到什么 diff --git a/packages/experimental/tool-ralph/src/index.ts b/packages/experimental/tool-ralph/src/index.ts index 48708c12ca..d942ec3548 100644 --- a/packages/experimental/tool-ralph/src/index.ts +++ b/packages/experimental/tool-ralph/src/index.ts @@ -7,16 +7,52 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow' export const name = 'tool-ralph' export const inject = ['tools', 'workflowEngine', 'subagents', 'systemPrompt'] +/** + * Every {@link RalphError} code: + * - `RALPH_PROVIDER_UNAVAILABLE` — the configured subagent provider is not registered; load it or change `subagentProvider`. + * - `RALPH_PROVIDER_UNSUPPORTED` — the configured provider lacks structured output or inherits parent context; + * configure a fresh structured-output provider. + * - `RALPH_WORKFLOW_FAILED` — the fixed workflow ended with an error or was cancelled without caller cancellation; report the message. + * - `RALPH_INVALID_RESULT` — the fixed workflow returned a malformed report or terminal value; do not trust the result. + * - `RALPH_ROUND_FAILED` — a round's child failed before producing a structured report; the message carries the last handoff. + */ +export const RALPH_ERROR_CODES = [ + 'RALPH_PROVIDER_UNAVAILABLE', + 'RALPH_PROVIDER_UNSUPPORTED', + 'RALPH_WORKFLOW_FAILED', + 'RALPH_INVALID_RESULT', + 'RALPH_ROUND_FAILED', +] as const + +/** One code from {@link RALPH_ERROR_CODES}. */ +export type RalphErrorCode = typeof RALPH_ERROR_CODES[number] + +/** Ralph loop failure carrying a stable {@link RalphErrorCode}. */ +export class RalphError extends HarnessError { + override readonly code: RalphErrorCode + + /** + * @param message - parent-facing failure text. + * @param code - failure class. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: RalphErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'RalphError' + this.code = code + } +} + /** Deployment policy for the fixed Ralph workflow. */ export interface Config { /** Fresh structured-output provider used for every round (default `spawn`). */ @@ -206,10 +242,10 @@ function resolveConfig(config: Config): ResolvedConfig { function resolveMaxRounds(requested: number | undefined, ceiling: number): number { const value = requested ?? ceiling if (!Number.isSafeInteger(value) || value < 1) { - throw new TypeError('Ralph maxRounds must be a positive safe integer') + throw new ToolArgsError(['Ralph maxRounds must be a positive safe integer']) } if (value > ceiling) { - throw new TypeError(`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`) + throw new ToolArgsError([`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`]) } return value } @@ -218,13 +254,13 @@ function resolveMaxRounds(requested: number | undefined, ceiling: number): numbe function requireFreshProvider(ctx: Context, name: string): SubagentProvider { const provider = ctx.subagents.getProvider(name) if (provider === undefined) { - throw new Error(`Ralph subagent provider "${name}" is not registered`) + throw new RalphError(`Ralph subagent provider "${name}" is not registered`, 'RALPH_PROVIDER_UNAVAILABLE') } if (!provider.capabilities.outputSchema) { - throw new Error(`Ralph subagent provider "${name}" does not support structured output`) + throw new RalphError(`Ralph subagent provider "${name}" does not support structured output`, 'RALPH_PROVIDER_UNSUPPORTED') } if (provider.inheritsParentContext) { - throw new Error(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`) + throw new RalphError(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`, 'RALPH_PROVIDER_UNSUPPORTED') } return provider } @@ -251,7 +287,7 @@ function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: || !normalizedList(value['nextSteps']) || typeof value['blocker'] !== 'string' || value['blocker'] !== value['blocker'].trim()) { - throw new Error('Ralph workflow returned a malformed round report') + throw new RalphError('Ralph workflow returned a malformed round report', 'RALPH_INVALID_RESULT') } const report: RalphRoundReport = { status: expectedStatus, @@ -261,18 +297,18 @@ function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: blocker: value['blocker'], } if (expectedStatus === 'continue' && (report.nextSteps.length === 0 || report.blocker !== '')) { - throw new Error('Ralph workflow returned an invalid continuing report') + throw new RalphError('Ralph workflow returned an invalid continuing report', 'RALPH_INVALID_RESULT') } if (expectedStatus === 'complete' && (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '')) { - throw new Error('Ralph workflow returned an invalid completion report') + throw new RalphError('Ralph workflow returned an invalid completion report', 'RALPH_INVALID_RESULT') } if (expectedStatus === 'blocked' && !normalizedText(report.blocker)) { - throw new Error('Ralph workflow returned an invalid blocked report') + throw new RalphError('Ralph workflow returned an invalid blocked report', 'RALPH_INVALID_RESULT') } const chars = JSON.stringify(report).length if (chars > maxChars) { - throw new Error(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`) + throw new RalphError(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`, 'RALPH_INVALID_RESULT') } return report } @@ -284,40 +320,40 @@ function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: numbe || !Number.isSafeInteger(value['roundsStarted']) || value['roundsStarted'] < 1 || value['roundsStarted'] > maxRounds) { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } const roundsStarted = value['roundsStarted'] switch (value['status']) { case 'complete': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } return { status: 'complete', roundsStarted, report: readReport(value['report'], 'complete', maxHandoffChars) } case 'blocked': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } return { status: 'blocked', roundsStarted, report: readReport(value['report'], 'blocked', maxHandoffChars) } case 'budget-limited': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } if (roundsStarted !== maxRounds) { - throw new Error('Ralph workflow returned budget-limited before the round limit') + throw new RalphError('Ralph workflow returned budget-limited before the round limit', 'RALPH_INVALID_RESULT') } return { status: 'budget-limited', roundsStarted, report: readReport(value['report'], 'continue', maxHandoffChars) } case 'round-failed': { if (Object.keys(value).sort().join(',') !== 'lastReport,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } if (roundsStarted === 1) { if (value['lastReport'] !== null) { - throw new Error('Ralph workflow returned an invalid first-round failure') + throw new RalphError('Ralph workflow returned an invalid first-round failure', 'RALPH_INVALID_RESULT') } return { status: 'round-failed', roundsStarted } } if (value['lastReport'] === null) { - throw new Error('Ralph workflow returned a round failure without its last handoff') + throw new RalphError('Ralph workflow returned a round failure without its last handoff', 'RALPH_INVALID_RESULT') } return { status: 'round-failed', @@ -326,7 +362,7 @@ function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: numbe } } default: - throw new Error('Ralph workflow returned an unknown terminal status') + throw new RalphError('Ralph workflow returned an unknown terminal status', 'RALPH_INVALID_RESULT') } } @@ -346,6 +382,13 @@ function stopReasonError(result: WorkflowResult): string | undefined { } } +/** The structured cancellation for a workflow the caller cancelled. */ +function ralphAborted(message: string): HarnessError { + const error = new HarnessError(message, TOOL_ABORTED) + error.name = 'AbortError' + return error +} + const TRUNCATION_NOTICE = '\n… [truncated]' /** Bound complete parent-facing text, including its envelope and truncation marker. */ @@ -435,10 +478,10 @@ export function apply(ctx: Context, config: Config): void { async execute(args, exec) { const parent = exec.agent if (parent === undefined) { - throw new Error('Ralph tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('Ralph tool requires a calling agent (exec.agent was undefined)') } const objective = args.objective.trim() - if (objective.length === 0) throw new Error('Ralph objective must be a non-empty string') + if (objective.length === 0) throw new ToolArgsError(['Ralph objective must be a non-empty string']) const maxRounds = resolveMaxRounds(args.maxRounds, resolved.maxRounds) void requireFreshProvider(ctx, resolved.subagentProvider) @@ -458,9 +501,9 @@ export function apply(ctx: Context, config: Config): void { try { const settled = await run.result const error = stopReasonError(settled) - if (error !== undefined) throw new Error(error) + if (error !== undefined) throw settled.stopReason === 'cancelled' && exec.signal.aborted ? ralphAborted(error) : new RalphError(error, 'RALPH_WORKFLOW_FAILED') const value = readRunResult(settled.value, maxRounds, resolved.maxHandoffChars) - if (value.status === 'round-failed') throw new Error(renderRoundFailure(value, resolved.maxResultChars)) + if (value.status === 'round-failed') throw new RalphError(renderRoundFailure(value, resolved.maxResultChars), 'RALPH_ROUND_FAILED') return { runId: run.id, agentsStarted: settled.agentsStarted, diff --git a/packages/experimental/tool-ralph/tests/integration.spec.ts b/packages/experimental/tool-ralph/tests/integration.spec.ts index ceaf88b223..0511218a7e 100644 --- a/packages/experimental/tool-ralph/tests/integration.spec.ts +++ b/packages/experimental/tool-ralph/tests/integration.spec.ts @@ -283,6 +283,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('Ralph workflow was cancelled') + expect(result.isError && result.error.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) expect(outcomes).toEqual(['cancelled']) expect(ctx.agents.get(children[0]!.id)).toBeUndefined() } finally { diff --git a/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts b/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts index ffa84f5e73..0bf78fd8bf 100644 --- a/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts +++ b/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts @@ -236,6 +236,7 @@ describe('dsh-tool-ralph', () => { expect(firstResult.isError).toBe(true) expect((firstResult.content[0] as { text: string }).text).toContain('Ralph round 1 child failed') expect((firstResult.content[0] as { text: string }).text).toContain('No previous handoff was available.') + expect(firstResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_ROUND_FAILED' }) const later = execute(ctx, { objective: 'Ship it.', maxRounds: 2 }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) }) @@ -254,8 +255,10 @@ describe('dsh-tool-ralph', () => { const failed = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) }) engine.settle({ value: null, stopReason: 'error', error: 'child report malformed', agentsStarted: 1 }) - expect(((await failed).content[0] as { text: string }).text) + const failedResult = await failed + expect((failedResult.content[0] as { text: string }).text) .toContain('Ralph workflow failed: child report malformed') + expect(failedResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_WORKFLOW_FAILED' }) const unknown = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) }) @@ -265,7 +268,9 @@ describe('dsh-tool-ralph', () => { const cancelled = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(3) }) engine.settle({ value: null, stopReason: 'cancelled', error: 'user stopped', agentsStarted: 0 }) - expect(((await cancelled).content[0] as { text: string }).text).toContain('cancelled (user stopped)') + const cancelledResult = await cancelled + expect((cancelledResult.content[0] as { text: string }).text).toContain('cancelled (user stopped)') + expect(cancelledResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_WORKFLOW_FAILED' }) const bare = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(4) }) @@ -280,7 +285,10 @@ describe('dsh-tool-ralph', () => { const pending = execute(ctx, { objective: 'Work.' }, { agent: parent, signal: controller.signal }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) }) controller.abort() - expect((await pending).isError).toBe(true) + const aborted = await pending + expect(aborted.isError).toBe(true) + expect(aborted.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) + expect((aborted.content[0] as { text: string }).text).toContain('Ralph workflow was cancelled (parent step aborted)') const already = new AbortController() already.abort() @@ -306,11 +314,17 @@ describe('dsh-tool-ralph', () => { it('rejects absent authority, empty objectives, bad round caps, and schema-invalid calls before start', async () => { const { ctx, engine, parent } = await setup({ config: { maxRounds: 3 } }) - expect((await execute(ctx, { objective: 'Work.' })).isError).toBe(true) - expect((await execute(ctx, { objective: ' ' }, { agent: parent })).isError).toBe(true) - for (const maxRounds of [0, 1.5, Number.NaN, 4]) { - expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).isError).toBe(true) + expect((await execute(ctx, { objective: 'Work.' })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) + expect((await execute(ctx, { objective: ' ' }, { agent: parent })).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) + for (const maxRounds of [0, 1.5, 4]) { + expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) } + expect((await execute(ctx, { objective: 'Work.', maxRounds: Number.NaN }, { agent: parent })).isError).toBe(true) const missing = await execute(ctx, {}, { agent: parent }) expect(missing.error?.info?.code).toBe('INVALID_ARGS') expect(engine.requests).toHaveLength(0) @@ -318,17 +332,20 @@ describe('dsh-tool-ralph', () => { it('rejects missing, unstructured, and parent-context-inheriting provider routes', async () => { const missing = await setup({ provider: false }) - expect(((await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent })).content[0] as { text: string }).text) - .toContain('is not registered') + const missingResult = await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent }) + expect((missingResult.content[0] as { text: string }).text).toContain('is not registered') + expect(missingResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNAVAILABLE' }) expect(missing.engine.requests).toHaveLength(0) const unstructured = await setup({ provider: new StubProvider({ outputSchema: false }) }) - expect(((await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent })).content[0] as { text: string }).text) - .toContain('does not support structured output') + const unstructuredResult = await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent }) + expect((unstructuredResult.content[0] as { text: string }).text).toContain('does not support structured output') + expect(unstructuredResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNSUPPORTED' }) const inherited = await setup({ provider: new StubProvider({ inheritsParentContext: true }) }) - expect(((await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent })).content[0] as { text: string }).text) - .toContain('inherits parent context') + const inheritedResult = await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent }) + expect((inheritedResult.content[0] as { text: string }).text).toContain('inherits parent context') + expect(inheritedResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNSUPPORTED' }) }) it('rejects invalid direct-apply config before touching injected services', () => { @@ -370,6 +387,7 @@ describe('dsh-tool-ralph', () => { ) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain(testCase.message) + expect(result.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_INVALID_RESULT' }) } }) From f0e23def7991b419efb670f50f7c3fc46773441f Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:38:39 +0800 Subject: [PATCH 19/68] feat(tool-terminal): classify terminal tool failures A missing agent or jobs service throws ToolContextUnavailableError, empty type or sessionId throws ToolArgsError, disabled background sends throw JobError JOB_BACKGROUND_DISABLED, and a cancelled foreground send throws AbortError / ABORTED. Refs #7869 --- .../tool-terminal/README.i18n.yaml | 4 +-- packages/experimental/tool-terminal/README.md | 2 +- .../experimental/tool-terminal/README.zh.md | 2 +- .../experimental/tool-terminal/src/index.ts | 25 ++++++++++++------- .../tool-terminal/tests/tools.spec.ts | 20 ++++++++++----- 5 files changed, 34 insertions(+), 19 deletions(-) diff --git a/packages/experimental/tool-terminal/README.i18n.yaml b/packages/experimental/tool-terminal/README.i18n.yaml index 9c42634e60..918803c164 100644 --- a/packages/experimental/tool-terminal/README.i18n.yaml +++ b/packages/experimental/tool-terminal/README.i18n.yaml @@ -30,8 +30,8 @@ en: 2ad49d4f69deb06d zh: 5f29972b5feec7e3 /deepseek-ai-dsh-tool-terminal/use-this-package/observable-outcomes-and-failures: - en: 321a982fdbbf4ada - zh: 8c2636e5379815e1 + en: a4231b8c3bfaedfc + zh: 7955c1d1a842e867 /deepseek-ai-dsh-tool-terminal/understand-the-implementation: en: 6302fca8fef89136 zh: 6327d56edb798ab2 diff --git a/packages/experimental/tool-terminal/README.md b/packages/experimental/tool-terminal/README.md index 03f213dff3..d50fdfe6c0 100644 --- a/packages/experimental/tool-terminal/README.md +++ b/packages/experimental/tool-terminal/README.md @@ -65,7 +65,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Observable outcomes and failures -A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. +A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Failed calls carry a structured error identity: an empty `type` or `sessionId` is a `ToolArgsError` (`INVALID_ARGS`), a call without a calling Agent or a background send without the jobs service is a `ToolContextUnavailableError`, a background send with `enableRunInBackground: false` is a `JobError` (`JOB_BACKGROUND_DISABLED`), a cancelled foreground send is an `AbortError`, and terminal service failures keep their `TerminalError` code. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. ----- diff --git a/packages/experimental/tool-terminal/README.zh.md b/packages/experimental/tool-terminal/README.zh.md index 097ede5cf7..2b595e88f7 100644 --- a/packages/experimental/tool-terminal/README.zh.md +++ b/packages/experimental/tool-terminal/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" ### 可观察结果与失败 -前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 +前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。失败的调用带有结构化错误标识:`type` 或 `sessionId` 为空时为 `ToolArgsError`(`INVALID_ARGS`),没有调用方 Agent 或后台发送缺少 jobs 服务时为 `ToolContextUnavailableError`,`enableRunInBackground: false` 时的后台发送为 `JobError`(`JOB_BACKGROUND_DISABLED`),被取消的前台发送为 `AbortError`,终端服务失败保留其 `TerminalError` code。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 ----- diff --git a/packages/experimental/tool-terminal/src/index.ts b/packages/experimental/tool-terminal/src/index.ts index f966141c8b..5133ba9490 100644 --- a/packages/experimental/tool-terminal/src/index.ts +++ b/packages/experimental/tool-terminal/src/index.ts @@ -9,11 +9,11 @@ import { resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' import { TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@deepseek-ai/dsh-terminal' -import type {} from '@deepseek-ai/dsh-jobs' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { JobError } from '@deepseek-ai/dsh-jobs' +import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import { sendSource } from './background.ts' import { boundTerminalText, renderList, renderRead, renderSend, renderSpawn } from './render.ts' @@ -118,13 +118,20 @@ const BACKGROUND_JOB_OUTPUT_SCHEMA = { } as const function requireAgent(agent: Agent | undefined): Agent { - if (agent === undefined) throw new Error('terminal tools require an initiating agent') + if (agent === undefined) throw new ToolContextUnavailableError('terminal tools require an initiating agent') return agent } +/** The structured cancellation for a foreground send the caller cancelled. */ +function sendAborted(): HarnessError { + const error = new HarnessError('terminal send aborted', TOOL_ABORTED) + error.name = 'AbortError' + return error +} + function sessionId(args: SessionArgs): TerminalSessionIdType { if (args.sessionId.length === 0) { - throw new Error('sessionId must be a non-empty string') + throw new ToolArgsError(['sessionId must be a non-empty string']) } return TerminalSessionId(args.sessionId) } @@ -183,7 +190,7 @@ export function apply(ctx: Context, config: Config = {}): void { render: (_args, value) => [{ type: 'text', text: renderSpawn(value, maxResultBytes) }], }, async execute(args: SpawnArgs, exec) { - if (args.type.length === 0) throw new Error('type must be a non-empty string') + if (args.type.length === 0) throw new ToolArgsError(['type must be a non-empty string']) const owner = requireAgent(exec.agent) const cwd = await ctx.workingDirectory.ensure(owner, exec.signal) const result = await ctx.terminals.spawn(owner, { @@ -253,9 +260,9 @@ export function apply(ctx: Context, config: Config = {}): void { const id = sessionId(args) const request = { text: args.text, submit: args.submit ?? true } if (args.run_in_background === true) { - if (!enableRunInBackground) throw new Error('background terminal sends are disabled by tool-terminal configuration') + if (!enableRunInBackground) throw new JobError('background terminal sends are disabled by tool-terminal configuration', 'JOB_BACKGROUND_DISABLED') const jobs = ctx.get('jobs') - if (jobs === undefined) throw new Error('background terminal sends require @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + if (jobs === undefined) throw new ToolContextUnavailableError('background terminal sends require @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') let cancelRequested = false let operation: TerminalSendOperation | undefined const jobId = jobs.start({ @@ -284,7 +291,7 @@ export function apply(ctx: Context, config: Config = {}): void { } const operation = ctx.terminals.startSend(owner, id, { ...request, signal: exec.signal }) const result = await operation.done - if (exec.signal.aborted) throw new Error('terminal send aborted') + if (exec.signal.aborted) throw sendAborted() return { kind: 'foreground' as const, ...result } }, presentCall(args) { diff --git a/packages/experimental/tool-terminal/tests/tools.spec.ts b/packages/experimental/tool-terminal/tests/tools.spec.ts index c56fca958b..9447fa564e 100644 --- a/packages/experimental/tool-terminal/tests/tools.spec.ts +++ b/packages/experimental/tool-terminal/tests/tools.spec.ts @@ -292,17 +292,21 @@ describe('tool-terminal foreground API', () => { it('fails without an initiating agent and rejects background before writing', async () => { const { ctx, agent, stub } = await setup(false) - expect((await call(ctx, 'terminal_open', { type: 'stub' })).isError).toBe(true) + expect((await call(ctx, 'terminal_open', { type: 'stub' })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) await call(ctx, 'terminal_open', { type: 'stub' }, agent) const result = await call(ctx, 'terminal_send', { sessionId: 'pty-1', text: 'sleep 1', run_in_background: true }, agent) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(stub.sessions[0]?.operation).toBeUndefined() }) it('validates required values and forwards optional spawn/read arguments', async () => { const { ctx, agent } = await setup(false) - expect((await call(ctx, 'terminal_open', { type: '' }, agent)).isError).toBe(true) - expect((await call(ctx, 'terminal_send', { sessionId: '', text: 'x' }, agent)).isError).toBe(true) + expect((await call(ctx, 'terminal_open', { type: '' }, agent)).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect((await call(ctx, 'terminal_send', { sessionId: '', text: 'x' }, agent)).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) expect((await call(ctx, 'terminal_send', { sessionId: 1, text: 'x' }, agent)).isError).toBe(true) expect((await call(ctx, 'terminal_send', { sessionId: 'pty-1', text: 1 }, agent)).isError).toBe(true) await call(ctx, 'terminal_open', { type: 'stub', name: 'named', cwd: '/tmp' }, agent) @@ -320,7 +324,9 @@ describe('tool-terminal foreground API', () => { expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [], isError: false })).toBeUndefined() expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }], isError: false })).toBeUndefined() expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [undefined as never], isError: false })).toBeUndefined() - expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'ok' }], isError: false })).toEqual({ card: 'terminal', output: 'ok' }) + expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'ok' }], isError: false })).toEqual({ + card: 'terminal', output: 'ok', + }) expect(ctx.tools.get('terminal_open')?.presentCall?.({ type: 'stub' })).toMatchObject({ card: 'generic', title: 'Open terminal stub' }) expect(ctx.tools.get('terminal_open')?.presentCall?.({ type: 'stub', name: 'main' })).toMatchObject({ card: 'generic', title: 'Open terminal main' }) @@ -338,7 +344,7 @@ describe('tool-terminal foreground API', () => { await call(disabled.ctx, 'terminal_open', { type: 'stub' }, disabled.agent) expect((await call(disabled.ctx, 'terminal_send', { sessionId: 'pty-1', text: 'work', run_in_background: true, - }, disabled.agent)).isError).toBe(true) + }, disabled.agent)).error?.info).toEqual({ name: 'JobError', code: 'JOB_BACKGROUND_DISABLED' }) const defaults = await setupBase(false) ToolPty.apply(defaults.ctx) @@ -503,7 +509,9 @@ describe('tool-terminal task integration', () => { await expect.poll(() => stub.sessions[0]!.operation).toBeDefined() controller.abort() stub.sessions[0]!.operation?.cancel() - expect((await pending).isError).toBe(true) + const cancelled = await pending + expect(cancelled.isError).toBe(true) + expect(cancelled.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) }) it('renders the already-closing kill result', async () => { From 546237ff5676bf116144e2193e55e471fa19af37 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:40:29 +0800 Subject: [PATCH 20/68] feat(browser-use-runtime): add BrowserSessionError for browser ownership failures Foreign-Session tools, a reserved attached browser, a non-live owner, a closing Session browser, and failed cleanup now throw BrowserSessionError with a closed BROWSER_* code. A browser MCP call without an Agent throws ToolContextUnavailableError, and a non-Error abort reason becomes AbortError / ABORTED. Refs #7869 --- .../browser-use-runtime/README.i18n.yaml | 4 +- .../browser-use-runtime/README.md | 4 +- .../browser-use-runtime/README.zh.md | 4 +- .../browser-use-runtime/package.json | 3 +- .../browser-use-runtime/src/error.ts | 38 +++++++++++++++++++ .../browser-use-runtime/src/index.ts | 26 ++++++++++--- .../browser-use-runtime/src/mcp.ts | 11 +++--- .../browser-use-runtime/tests/mcp.spec.ts | 16 ++++---- .../tests/resources.spec.ts | 29 ++++++++------ .../browser-use-runtime/tsconfig.json | 3 ++ 10 files changed, 104 insertions(+), 34 deletions(-) create mode 100644 packages/experimental/browser-use-runtime/src/error.ts diff --git a/packages/experimental/browser-use-runtime/README.i18n.yaml b/packages/experimental/browser-use-runtime/README.i18n.yaml index e89da1dd02..b4aaa9d246 100644 --- a/packages/experimental/browser-use-runtime/README.i18n.yaml +++ b/packages/experimental/browser-use-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: f14f34fce35a8d90 /deepseek-ai-dsh-experimental-browser-use-runtime/use-this-package: - en: 192b3471ff924145 - zh: 7bcb9ca2498ee9a0 + en: de962a9af11ddaf2 + zh: 9e39d3d6b5dcd53e /deepseek-ai-dsh-experimental-browser-use-runtime/understand-the-implementation: en: ad923b17fcb5421c zh: c2449382d6e0c7ff diff --git a/packages/experimental/browser-use-runtime/README.md b/packages/experimental/browser-use-runtime/README.md index 6b2ac99b98..c35ba358ae 100644 --- a/packages/experimental/browser-use-runtime/README.md +++ b/packages/experimental/browser-use-runtime/README.md @@ -29,13 +29,15 @@ This public experimental library is a dependency of the browser providers. It ha Native providers construct `SessionResources` from the package root, supplying resource acquisition and cleanup callbacks. Calls pass the exact live Agent to `run()`; stale owners and a second owner of an exclusive attachment fail before acquisition. Canceling an acquisition wait leaves initialization available to other callers in the same Session; Session disposal aborts and awaits that initialization. Providers keep their registration until `dispose()` finishes. +Ownership failures throw `BrowserSessionError`, exported with its closed `BROWSER_SESSION_ERROR_CODES` list: `BROWSER_OWNER_NOT_LIVE` for a stale owner or a disposing provider, `BROWSER_LOCKED` for a second owner of an exclusive attachment, `BROWSER_CLOSED` for an operation interrupted because its Session's browser closed, `BROWSER_CLEANUP_FAILED` for a failed `dispose()` whose `cause` is an `AggregateError` of each close failure, and `BROWSER_FOREIGN_SESSION` for an MCP call from a Session without its own connection. A canceled wait whose abort reason is not an `Error` rejects with an `AbortError` that carries the `ABORTED` code. + MCP providers use `mountSessionMcp` from `@deepseek-ai/dsh-experimental-browser-use-runtime/mcp`, supplying their fixed server name, executable, arguments, and ownership policy. The mounting context must provide `workingDirectory`. Acquisition uses the [working-directory service](../../session/working-directory/README.md) to validate or recover the current directory and set the MCP server process's initial directory. Retained servers keep that directory when the Session later selects another. The helper awaits one scoped client startup and discovery attempt within each future Agent's `agent/created` event. Agent creation or resume completes after discovery, before queued input runs; a successful client remains owned by that Session across turns. A busy attachment skips startup permanently for that live activation while its other work continues. Releasing the attachment does not retry skipped activations; a newly created or resumed Agent can acquire it. Startup failure or cancellation rejects Agent creation or resume and triggers creation rollback, including client cleanup. Reconnection is disabled. Loading or reloading a provider applies only to future Agent activations. Callers can inspect prompt assembly and scoped tool definitions after awaited Agent creation or resume completes. -Browser tools and resource requests targeting this server use the same queue and require the calling Session's own connection. Other MCP servers remain usable. Inherited server instructions are omitted without ownership; the shared server-name inventory keeps its normal scope behavior. +Browser tools and resource requests targeting this server use the same queue and require the calling Session's own connection; a call without a calling Agent fails with `ToolContextUnavailableError`. Other MCP servers remain usable. Inherited server instructions are omitted without ownership; the shared server-name inventory keeps its normal scope behavior. ----- diff --git a/packages/experimental/browser-use-runtime/README.zh.md b/packages/experimental/browser-use-runtime/README.zh.md index f1cdc018a4..2489cb9db2 100644 --- a/packages/experimental/browser-use-runtime/README.zh.md +++ b/packages/experimental/browser-use-runtime/README.zh.md @@ -29,13 +29,15 @@ kind: "package-library" 原生提供方从包根入口构造 `SessionResources`,提供资源获取与清理回调。调用向 `run()` 传递确切的实时 Agent;失效的所有者与独占附加的第二个所有者在获取资源前失败。取消资源获取等待不会终止初始化,同一 Session 的其他调用方仍可继续等待;释放 Session 会中止并等待该初始化结束。提供方将注册保留到 `dispose()` 完成。 +所有权失败抛出 `BrowserSessionError`,与封闭的 `BROWSER_SESSION_ERROR_CODES` 列表一同导出:`BROWSER_OWNER_NOT_LIVE` 表示所有者失效或提供方正在释放,`BROWSER_LOCKED` 表示独占附加出现第二个所有者,`BROWSER_CLOSED` 表示操作因其 Session 的浏览器关闭而中断,`BROWSER_CLEANUP_FAILED` 表示 `dispose()` 失败,其 `cause` 是汇总各项关闭失败的 `AggregateError`,`BROWSER_FOREIGN_SESSION` 表示没有自己连接的 Session 发起了 MCP 调用。取消等待且中止原因不是 `Error` 时,以带 `ABORTED` 代码的 `AbortError` 拒绝。 + MCP 提供方使用 `@deepseek-ai/dsh-experimental-browser-use-runtime/mcp` 中的 `mountSessionMcp`,提供固定服务器名称、可执行文件、参数与所有权策略。挂载上下文必须提供 `workingDirectory`。获取连接时通过[工作目录服务](../../session/working-directory/README.zh.md)验证或恢复当前目录,并将其设为 MCP 服务器进程的初始目录。Session 后续选择其他目录时,保留的服务器继续使用该目录。辅助库在每个后续 Agent 的 `agent/created` 事件中等待一次有作用域的客户端启动与发现尝试。Agent 创建或恢复在发现完成后结束,随后才运行排队输入;成功的客户端跨轮次归该 Session 所有。 附加连接被占用时,本次激活永久跳过启动,但其他工作继续运行。连接释放不会触发被跳过激活的重试;新创建或恢复的 Agent 可以获取连接。启动失败或取消会拒绝 Agent 创建或恢复,并触发包含客户端清理的创建回滚。重连已禁用。加载或重新加载提供方只作用于后续的 Agent 激活。 调用方在等待 Agent 创建或恢复完成后,即可检查提示词组装和作用域工具定义。 -指向此服务器的浏览器工具调用与资源请求使用同一队列,且要求调用 Session 自己拥有连接。其他 MCP 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。 +指向此服务器的浏览器工具调用与资源请求使用同一队列,且要求调用 Session 自己拥有连接;没有调用方 Agent 的调用以 `ToolContextUnavailableError` 失败。其他 MCP 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。 ----- diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index 24d0d467ed..44f3dcb82c 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -42,7 +42,8 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" diff --git a/packages/experimental/browser-use-runtime/src/error.ts b/packages/experimental/browser-use-runtime/src/error.ts new file mode 100644 index 0000000000..857785f875 --- /dev/null +++ b/packages/experimental/browser-use-runtime/src/error.ts @@ -0,0 +1,38 @@ +/** Machine-routable browser ownership failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link BrowserSessionError} code: + * - `BROWSER_FOREIGN_SESSION` — the browser tool or resource belongs to another Session's browser; this activation cannot use it. + * - `BROWSER_LOCKED` — another live Session reserves the attached browser; wait for its release or use a new activation later. + * - `BROWSER_OWNER_NOT_LIVE` — the calling Agent is no longer the live owner, or the provider is disposing; stop using the browser. + * - `BROWSER_CLOSED` — the Session's browser closed while the operation was admitted; a later call acquires a new browser. + * - `BROWSER_CLEANUP_FAILED` — closing one or more browsers failed; the cause lists each failure and ownership is retained. + */ +export const BROWSER_SESSION_ERROR_CODES = [ + 'BROWSER_FOREIGN_SESSION', + 'BROWSER_LOCKED', + 'BROWSER_OWNER_NOT_LIVE', + 'BROWSER_CLOSED', + 'BROWSER_CLEANUP_FAILED', +] as const + +/** One code from {@link BROWSER_SESSION_ERROR_CODES}. */ +export type BrowserSessionErrorCode = typeof BROWSER_SESSION_ERROR_CODES[number] + +/** Browser ownership failure carrying a stable {@link BrowserSessionErrorCode}. */ +export class BrowserSessionError extends HarnessError { + override readonly code: BrowserSessionErrorCode + + /** + * @param message - names the provider, the ownership problem, and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: BrowserSessionErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'BrowserSessionError' + this.code = code + } +} diff --git a/packages/experimental/browser-use-runtime/src/index.ts b/packages/experimental/browser-use-runtime/src/index.ts index 131c20f68f..b2ac6b2872 100644 --- a/packages/experimental/browser-use-runtime/src/index.ts +++ b/packages/experimental/browser-use-runtime/src/index.ts @@ -6,6 +6,11 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import { BrowserSessionError } from './error.ts' + +export { BROWSER_SESSION_ERROR_CODES, BrowserSessionError, type BrowserSessionErrorCode } from './error.ts' /** One provider-owned browser or connection and its quiescent cleanup. */ export interface OwnedSessionResource { @@ -37,10 +42,17 @@ interface Entry { closing?: Promise } +/** The cancellation thrown for a non-`Error` abort reason, classified like the registry's own cancellation. */ +function operationCanceled(reason: unknown): HarnessError { + const error = new HarnessError('browser operation canceled', TOOL_ABORTED, { cause: reason }) + error.name = 'AbortError' + return error +} + /** Stop a caller's wait while retaining handlers on the resource owner's work. */ function awaitOperation(operation: Promise, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { - const aborted = (): void => { reject(signal.reason instanceof Error ? signal.reason : new Error('browser operation canceled', { cause: signal.reason })) } + const aborted = (): void => { reject(signal.reason instanceof Error ? signal.reason : operationCanceled(signal.reason)) } signal.addEventListener('abort', aborted, { once: true }) void operation.then((value) => { signal.removeEventListener('abort', aborted) @@ -140,19 +152,23 @@ export class SessionResources { return this.disposing ??= Promise.resolve().then(async () => { const settled = await Promise.allSettled([...this.entries].map(([agent, entry]) => this.closeEntry(agent, entry))) const errors = settled.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : []) - if (errors.length > 0) throw new AggregateError(errors, `${this.options.label}: browser cleanup failed`) + if (errors.length > 0) { + throw new BrowserSessionError(`${this.options.label}: browser cleanup failed`, 'BROWSER_CLEANUP_FAILED', { + cause: new AggregateError(errors, `${this.options.label}: browser cleanup failed`), + }) + } await Promise.all([...this.ownerCleanups.values()].map(close => close())) }) } private entry(agent: Agent): Entry { if (this.disposing !== undefined || this.disposedOwners.has(agent) || this.ctx.get('agents')?.get(agent.id) !== agent) { - throw new Error(`${this.options.label}: Session is not a live browser owner`) + throw new BrowserSessionError(`${this.options.label}: Session is not a live browser owner`, 'BROWSER_OWNER_NOT_LIVE') } const current = this.entries.get(agent) if (current !== undefined) return current if (this.options.exclusive && this.entries.size > 0) { - throw new Error(`${this.options.label}: attached browser is already reserved by another Session`) + throw new BrowserSessionError(`${this.options.label}: attached browser is already reserved by another Session`, 'BROWSER_LOCKED') } if (!this.ownerCleanups.has(agent)) { const cleanup = agent.ctx.effect(() => async () => { @@ -184,7 +200,7 @@ export class SessionResources { private closeEntry(agent: Agent, entry: Entry): Promise { return entry.closing ??= Promise.resolve().then(async () => { - entry.controller.abort(new Error(`${this.options.label}: Session browser is closing`)) + entry.controller.abort(new BrowserSessionError(`${this.options.label}: Session browser is closing`, 'BROWSER_CLOSED')) const resource = await entry.ready.catch(() => undefined) try { await resource?.close() diff --git a/packages/experimental/browser-use-runtime/src/mcp.ts b/packages/experimental/browser-use-runtime/src/mcp.ts index cdaa4599b2..5e96a19588 100644 --- a/packages/experimental/browser-use-runtime/src/mcp.ts +++ b/packages/experimental/browser-use-runtime/src/mcp.ts @@ -7,9 +7,9 @@ import { BrowserUseProviderName } from '@deepseek-ai/dsh-browser-use/brand' import * as McpClient from '@deepseek-ai/dsh-mcp-client' import { createScope } from '@deepseek-ai/dsh-scope' import type { Scope } from '@deepseek-ai/dsh-scope' -import { SessionResources } from './index.ts' +import { BrowserSessionError, SessionResources } from './index.ts' import type {} from '@deepseek-ai/dsh-browser-use' -import type {} from '@deepseek-ai/dsh-tools' +import { ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-working-directory' @@ -141,7 +141,7 @@ export function mountSessionMcp(ctx: Context, options: SessionMcpOptions): void if (!exec.name.startsWith(toolPrefix)) return next() if (exec.agent !== agent) { if (ctx.tools.get(exec.name, exec.agent) !== ctx.tools.get(exec.name, agent)) return next() - throw new Error(`${options.name}: browser tool belongs to another Session`) + throw new BrowserSessionError(`${options.name}: browser tool belongs to another Session`, 'BROWSER_FOREIGN_SESSION') } return next() }) @@ -199,8 +199,9 @@ export function mountSessionMcp(ctx: Context, options: SessionMcpOptions): void && (exec.arguments as { server?: unknown }).server === options.name if (!exec.name.startsWith(toolPrefix) && !ownResource) return next() const agent = exec.agent - if (agent === undefined || clients.get(agent)?.status !== 'ready') { - throw new Error(`${options.name}: browser tool belongs to another Session`) + if (agent === undefined) throw new ToolContextUnavailableError(`${options.name}: browser tools require a calling Agent`) + if (clients.get(agent)?.status !== 'ready') { + throw new BrowserSessionError(`${options.name}: browser tool belongs to another Session`, 'BROWSER_FOREIGN_SESSION') } return resources.run(agent, exec.signal, async (_scope, combined) => { const original = exec.signal diff --git a/packages/experimental/browser-use-runtime/tests/mcp.spec.ts b/packages/experimental/browser-use-runtime/tests/mcp.spec.ts index b1cd831164..80a9041c48 100644 --- a/packages/experimental/browser-use-runtime/tests/mcp.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/mcp.spec.ts @@ -118,6 +118,8 @@ async function warm(ctx: Context, agent: Agent, signal = new AbortController().s return ctx.systemPrompt.assemble({ agent, scope: agent, signal }) } +const FOREIGN = { name: 'BrowserSessionError', code: 'BROWSER_FOREIGN_SESSION' } + function execute(ctx: Context, agent: Agent, name = TOOL) { return executeToolFixture(ctx, { agent, name, arguments: name === TOOL ? { label: 'direct' } : {}, callId: ToolCallId('direct'), signal: new AbortController().signal }) } @@ -238,7 +240,7 @@ describe('Session MCP Loader composition', () => { expect(model.requests.map(request => request.tools?.map(tool => tool.name))).toEqual([['unrelated'], ['unrelated']]) for (const { agent } of [second, child]) { expect(ctx.tools.schemas(agent).map(tool => tool.name)).toEqual(['unrelated']) - expect((await execute(ctx, agent)).isError).toBe(true) + expect((await execute(ctx, agent)).error?.info).toEqual(FOREIGN) expect((await execute(ctx, agent, 'unrelated')).isError).toBe(false) expect((await warm(ctx, agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) } @@ -249,13 +251,13 @@ describe('Session MCP Loader composition', () => { }) expect(ctx.tools.schemas(child.agent).filter(tool => tool.name.startsWith('mcp__browser-fixture__'))).toEqual([]) expect((await warm(ctx, child.agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) - expect((await execute(ctx, child.agent, 'mcp__browser-fixture__late')).isError).toBe(true) + expect((await execute(ctx, child.agent, 'mcp__browser-fixture__late')).error?.info).toEqual(FOREIGN) expect((await events(root)).filter(event => event.event === 'initialize')).toHaveLength(1) expect((await events(root)).filter(event => event.event === 'call')).toEqual([]) expect((await execute(ctx, first.agent)).isError).toBe(false) await first.dispose() expect((await warm(ctx, child.agent)).tools.some(tool => tool.name === TOOL)).toBe(false) - expect((await execute(ctx, child.agent)).isError).toBe(true) + expect((await execute(ctx, child.agent)).error?.info).toEqual(FOREIGN) expect((await warm(ctx, second.agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) const successor = await ctx.agents.create({ sessionId: SessionId('successor') }) expect((await warm(ctx, successor.agent)).tools.some(tool => tool.name === TOOL)).toBe(true) @@ -366,9 +368,9 @@ describe('Session MCP Loader composition', () => { expect(renderPrompt(blocked)).not.toContain('BROWSER_FIXTURE_INSTRUCTION') expect(renderPrompt(blocked)).toContain('browser-fixture') for (const name of ['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource']) { - expect((await resource(ctx, child.agent, name)).isError).toBe(true) + expect((await resource(ctx, child.agent, name)).error?.info).toEqual(FOREIGN) } - expect((await resource(ctx, undefined)).isError).toBe(true) + expect((await resource(ctx, undefined)).error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect((await events(root)).filter(event => event.event === 'resource')).toEqual([]) expect((await resource(ctx, child.agent, 'read_mcp_resource', 'docs')).value) .toEqual({ contents: [{ uri: 'docs://memo', text: 'Independent document.' }] }) @@ -378,7 +380,7 @@ describe('Session MCP Loader composition', () => { expect(browserState(await resource(ctx, parent.agent)).counter).toBe(0) await parent.dispose() expect(renderPrompt(await warm(ctx, child.agent))).not.toContain('BROWSER_FIXTURE_INSTRUCTION') - expect((await resource(ctx, child.agent)).isError).toBe(true) + expect((await resource(ctx, child.agent)).error?.info).toEqual(FOREIGN) const successor = await ctx.agents.create({ sessionId: SessionId('resource-successor') }) expect(renderPrompt(await warm(ctx, successor.agent))).toContain('BROWSER_FIXTURE_INSTRUCTION') expect(browserState(await resource(ctx, successor.agent)).counter).toBe(0) @@ -400,7 +402,7 @@ describe('Session MCP Loader composition', () => { name: 'mcp__browser-fixture__parent_only', description: 'A browser operation available only in the parent.', parameters: { type: 'object' }, output: { schema: { type: 'boolean' }, render: () => [] }, execute: parentOnly, }) - expect((await execute(ctx, child.agent, 'mcp__browser-fixture__parent_only')).isError).toBe(true) + expect((await execute(ctx, child.agent, 'mcp__browser-fixture__parent_only')).error?.info).toEqual(FOREIGN) expect(parentOnly).not.toHaveBeenCalled() const parentState = browserState(await resource(ctx, parent.agent)) const childState = browserState(await resource(ctx, child.agent)) diff --git a/packages/experimental/browser-use-runtime/tests/resources.spec.ts b/packages/experimental/browser-use-runtime/tests/resources.spec.ts index 4524b98b32..d47fc361ec 100644 --- a/packages/experimental/browser-use-runtime/tests/resources.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/resources.spec.ts @@ -5,10 +5,15 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { unsupportedModel, unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import { Session, SessionId } from '@deepseek-ai/dsh-session' import { afterEach, describe, expect, it, vi } from 'vitest' -import { SessionResources } from '../src/index.ts' +import { BrowserSessionError, SessionResources } from '../src/index.ts' +import type { BrowserSessionErrorCode } from '../src/index.ts' const contexts: Context[] = [] +function browserError(code: BrowserSessionErrorCode, message: string) { + return { constructor: BrowserSessionError, name: 'BrowserSessionError', code, message: expect.stringContaining(message) as string } +} + async function fixture() { const ctx = new Context() contexts.push(ctx) @@ -50,13 +55,13 @@ describe('Session browser resource ownership', () => { expect(open).toHaveBeenCalledTimes(2) await a.dispose() expect(close).toHaveBeenCalledTimes(1) - await expect(resources.get(a.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(a.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) const resumed = await owner('a') expect(await resources.get(resumed.agent)).not.toBe(first) await resources.dispose() expect(close).toHaveBeenCalledTimes(3) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) }) it('reserves an attached browser while acquisition or cleanup is pending', async () => { @@ -78,14 +83,14 @@ describe('Session browser resource ownership', () => { const first = resources.get(a.agent) expect(resources.available(a.agent)).toBe(true) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) opened.resolve(undefined) await first const disposing = a.dispose() await closing.promise expect(resources.available(a.agent)).toBe(false) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) released.resolve(undefined) await disposing expect(resources.available(b.agent)).toBe(true) @@ -259,7 +264,7 @@ describe('Session browser resource ownership', () => { const resources = new SessionResources(ctx, { label: 'test', exclusive: false, open }) const controller = new AbortController() const waiting = resources.get(a.agent, controller.signal) - const canceled = expect(waiting).rejects.toMatchObject({ message: 'browser operation canceled', cause: 'stop' }) + const canceled = expect(waiting).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED', message: 'browser operation canceled', cause: 'stop' }) await entered.promise controller.abort('stop') await canceled @@ -285,7 +290,7 @@ describe('Session browser resource ownership', () => { async open() { entered.resolve(undefined); await release.promise; return { value: {}, close } }, }) const acquiring = resources.get(a.agent) - const rejected = expect(acquiring).rejects.toThrow('closing') + const rejected = expect(acquiring).rejects.toMatchObject(browserError('BROWSER_CLOSED', 'closing')) await entered.promise const ownerDisposal = a.dispose() const providerDisposal = resources.dispose() @@ -314,7 +319,7 @@ describe('Session browser resource ownership', () => { await stopped.promise signal.throwIfAborted() }) - const rejected = expect(call).rejects.toThrow('closing') + const rejected = expect(call).rejects.toMatchObject(browserError('BROWSER_CLOSED', 'closing')) await running.promise await resources.dispose() await rejected @@ -330,9 +335,9 @@ describe('Session browser resource ownership', () => { }) await resources.get(a.agent) await a.dispose() - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') - await expect(resources.dispose()).rejects.toThrow('browser cleanup failed') - await expect(resources.get(b.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) + await expect(resources.dispose()).rejects.toMatchObject(browserError('BROWSER_CLEANUP_FAILED', 'browser cleanup failed')) + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) }) }) @@ -355,6 +360,6 @@ it('reports early disposal cleanup failure while retaining the owned resource', await canceled await a.dispose() expect(warning).toHaveBeenCalledWith(expect.stringContaining('cleanup during Session cancellation failed')) - await expect(resources.dispose()).rejects.toThrow('browser cleanup failed') + await expect(resources.dispose()).rejects.toMatchObject(browserError('BROWSER_CLEANUP_FAILED', 'browser cleanup failed')) warning.mockRestore() }) diff --git a/packages/experimental/browser-use-runtime/tsconfig.json b/packages/experimental/browser-use-runtime/tsconfig.json index 801c322d86..e1f7d1b38a 100644 --- a/packages/experimental/browser-use-runtime/tsconfig.json +++ b/packages/experimental/browser-use-runtime/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../../core/tools" }, + { + "path": "../../llm/llm" + }, { "path": "../../core/scope" }, From 3e7c9118b1dff53441dfd825fce51c73e200a8cf Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:40:30 +0800 Subject: [PATCH 21/68] feat(stagehand): add StagehandError and carry codes across the worker Act failures, missing tabs, unclassified SDK failures, worker failures, and drain failures now throw StagehandError with a closed STAGEHAND_* code; StagehandDrainError becomes its subclass. Worker replies carry name and code and the host rebuilds the same class. Arguments are checked before dispatch and fail as ToolArgsError; a call without a live Agent throws ToolContextUnavailableError. Refs #7869 --- .../README.i18n.yaml | 4 +- .../browser-use-stagehand-native/README.md | 2 + .../browser-use-stagehand-native/README.zh.md | 2 + .../browser-use-stagehand-native/package.json | 3 +- .../browser-use-stagehand-native/src/error.ts | 61 +++++++++++++++++++ .../browser-use-stagehand-native/src/index.ts | 13 +++- .../src/native.ts | 10 +-- .../src/worker-client.ts | 8 +-- .../src/worker-rpc.ts | 40 +++++++++--- .../tests/provider.spec.ts | 25 +++++--- .../tests/worker-client.spec.ts | 17 ++++-- .../tests/worker-rpc.spec.ts | 35 +++++++++-- .../tests/worker.spec.ts | 8 ++- .../tsconfig.json | 1 + 14 files changed, 182 insertions(+), 47 deletions(-) create mode 100644 packages/experimental/browser-use-stagehand-native/src/error.ts diff --git a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml index 21daa32757..2468113b23 100644 --- a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml +++ b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml @@ -24,8 +24,8 @@ en: fea3ad16a77fc478 zh: cf551a8a2d183f93 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/understand-the-implementation: - en: 123351a7c3d46f3e - zh: bf1cc2628edeb8d7 + en: 649a4ff1f1e46827 + zh: 1a1b929b9208388a /deepseek-ai-dsh-experimental-browser-use-stagehand-native/further-exploration: en: eff8f4541eb26ca7 zh: 76a61fe9bd48df2a diff --git a/packages/experimental/browser-use-stagehand-native/README.md b/packages/experimental/browser-use-stagehand-native/README.md index b6726b3650..e280c1f1ba 100644 --- a/packages/experimental/browser-use-stagehand-native/README.md +++ b/packages/experimental/browser-use-stagehand-native/README.md @@ -89,6 +89,8 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite The host owns each launched Chromium process and its temporary profile before waiting for CDP readiness. Chromium receives the standard scrubbed child environment, preserving paths, locale, and proxy settings while excluding credential-shaped variables and DSH identity. Both modes connect the SDK inside a dedicated Worker. The Worker receives no ambient environment except the explicit source TypeScript configuration path, so its CDP connection does not inherit host proxy settings. SDK close waits for active operations. Cleanup terminates the connection Worker after the configured SDK grace; launch also kills and awaits its owned Chromium process before removing the profile. Attached external browsers remain open. Cleanup failures follow the [ownership limits](#known-limitations-and-deferred-work) below. +Failed calls carry `error.name` and `error.code` on `tool/result`. The host validates arguments before dispatch and rejects ones the method's schema refuses with `ToolArgsError` (`INVALID_ARGS`); a call without an exact live Agent fails with `ToolContextUnavailableError`, and ownership failures use the runtime's `BrowserSessionError` codes. Other failures throw `StagehandError`, exported with its closed `STAGEHAND_ERROR_CODES` list: `STAGEHAND_ACT_FAILED` when Stagehand reports an unsuccessful action, `STAGEHAND_TAB_NOT_FOUND` for an unavailable tab, `STAGEHAND_OPERATION_FAILED` for any other SDK or browser failure, `STAGEHAND_WORKER_FAILED` when the Worker exits, closes, or breaks the message protocol, and `STAGEHAND_CLEANUP_FAILED` from the `StagehandDrainError` subclass when SDK requests do not drain. Worker replies carry a `StagehandError`'s name and code beside its message, and the host rebuilds the same code; any other Worker failure, including an unknown name or code, becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. + The [native runtime](src/native.ts) passes the explicit model configuration to Stagehand's public initialization API. The adapter pins Zod to the version required by Stagehand because extraction passes Zod schemas to the SDK. Stagehand owns the model requests, response validation, and token accounting inside its browser extension. DSH records browser tool inputs and returned data, including SDK result metadata, through the existing Session log. Underlying inference request/response capture and integration into DSH Session usage accounting are deferred.
diff --git a/packages/experimental/browser-use-stagehand-native/README.zh.md b/packages/experimental/browser-use-stagehand-native/README.zh.md index d980760c27..3f5bb0c538 100644 --- a/packages/experimental/browser-use-stagehand-native/README.zh.md +++ b/packages/experimental/browser-use-stagehand-native/README.zh.md @@ -89,6 +89,8 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite 宿主在等待 CDP 就绪前即拥有启动的 Chromium 进程及其临时配置目录。Chromium 接收标准清理后的子进程环境,保留路径、区域设置和代理配置,排除凭据形式的变量及 DSH 身份信息。两种模式都在独立 Worker 中连接 SDK。Worker 除显式的源码 TypeScript 配置路径外不接收宿主环境,因此其 CDP 连接不继承宿主代理设置。SDK 关闭会等待活动操作。清理在配置的 SDK 宽限时间后终止连接 Worker;启动模式还会终止并等待自有 Chromium 进程退出,再移除配置目录。外部连接的浏览器保持运行。清理失败遵循下方的[所有权限制](#known-limitations-and-deferred-work)。 +失败调用在 `tool/result` 上带有 `error.name` 与 `error.code`。宿主在派发前验证参数,方法 schema 拒绝的参数以 `ToolArgsError`(`INVALID_ARGS`)失败;没有确切实时 Agent 的调用以 `ToolContextUnavailableError` 失败,所有权失败使用运行时库的 `BrowserSessionError` 代码。其他失败抛出 `StagehandError`,与封闭的 `STAGEHAND_ERROR_CODES` 列表一同导出:Stagehand 报告动作未成功时为 `STAGEHAND_ACT_FAILED`,标签页不可用时为 `STAGEHAND_TAB_NOT_FOUND`,其他 SDK 或浏览器失败为 `STAGEHAND_OPERATION_FAILED`,Worker 退出、关闭或违反消息协议时为 `STAGEHAND_WORKER_FAILED`,SDK 请求未能结束时由 `StagehandDrainError` 子类给出 `STAGEHAND_CLEANUP_FAILED`。Worker 回复在消息旁携带 `StagehandError` 的名称和代码,宿主据此重建相同代码;其他 Worker 失败,包括未知名称或代码,以 Worker 的消息成为 `STAGEHAND_OPERATION_FAILED`。 + [原生运行时](src/native.ts)将显式模型配置传入 Stagehand 的公开初始化 API。适配器将 Zod 固定为 Stagehand 要求的版本,因为提取操作会向 SDK 传递 Zod schema。Stagehand 在其浏览器扩展中负责模型请求、响应验证与 token 计量。DSH 通过现有 Session 日志记录浏览器工具输入和返回数据,包括 SDK 结果元数据。底层推理请求/响应捕获及其与 DSH Session 用量计量的集成均属暂缓工作。
diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index 6af18876c5..1072476172 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -41,7 +41,8 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-browser-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "dependencies": { "@browserbasehq/stagehand": "4.4.0", diff --git a/packages/experimental/browser-use-stagehand-native/src/error.ts b/packages/experimental/browser-use-stagehand-native/src/error.ts new file mode 100644 index 0000000000..b70b19cc98 --- /dev/null +++ b/packages/experimental/browser-use-stagehand-native/src/error.ts @@ -0,0 +1,61 @@ +/** Machine-routable Stagehand browser failures, shared by the host and its browser Worker. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link StagehandError} code: + * - `STAGEHAND_ACT_FAILED` — Stagehand reported that a natural-language action did not succeed; inspect the page and + * rephrase or retry. + * - `STAGEHAND_TAB_NOT_FOUND` — the requested tab, or an active tab, is unavailable; list tabs and select a current pageId. + * - `STAGEHAND_OPERATION_FAILED` — the Stagehand SDK or browser failed the operation in a way this provider does not + * classify; the message carries the SDK's text. + * - `STAGEHAND_WORKER_FAILED` — the browser Worker exited, closed, or broke its message protocol; a later call reconnects. + * - `STAGEHAND_CLEANUP_FAILED` — SDK requests did not drain before the Worker terminated; the connection is not reused. + */ +export const STAGEHAND_ERROR_CODES = [ + 'STAGEHAND_ACT_FAILED', + 'STAGEHAND_TAB_NOT_FOUND', + 'STAGEHAND_OPERATION_FAILED', + 'STAGEHAND_WORKER_FAILED', + 'STAGEHAND_CLEANUP_FAILED', +] as const + +/** One code from {@link STAGEHAND_ERROR_CODES}. */ +export type StagehandErrorCode = typeof STAGEHAND_ERROR_CODES[number] + +/** + * Narrow a code received across the Worker boundary. + * @param code - untrusted code from a Worker reply. + * @returns whether the code is one of {@link STAGEHAND_ERROR_CODES}. + */ +export function isStagehandErrorCode(code: unknown): code is StagehandErrorCode { + return (STAGEHAND_ERROR_CODES as readonly unknown[]).includes(code) +} + +/** Stagehand browser failure carrying a stable {@link StagehandErrorCode}. */ +export class StagehandError extends HarnessError { + override readonly code: StagehandErrorCode + + /** + * @param message - names the browser operation and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: StagehandErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'StagehandError' + this.code = code + } +} + +/** SDK requests did not drain before their connection Worker terminated; code `STAGEHAND_CLEANUP_FAILED`. */ +export class StagehandDrainError extends StagehandError { + /** + * @param message - the drain failure and its underlying cleanup error. + * @param options - standard `cause` chaining. + */ + constructor(message: string, options?: ErrorOptions) { + super(message, 'STAGEHAND_CLEANUP_FAILED', options) + this.name = 'StagehandDrainError' + } +} diff --git a/packages/experimental/browser-use-stagehand-native/src/index.ts b/packages/experimental/browser-use-stagehand-native/src/index.ts index a8e5a26dd9..b167bbc567 100644 --- a/packages/experimental/browser-use-stagehand-native/src/index.ts +++ b/packages/experimental/browser-use-stagehand-native/src/index.ts @@ -9,14 +9,17 @@ import { BrowserUseProviderName } from '@deepseek-ai/dsh-browser-use/brand' import { SessionResources } from '@deepseek-ai/dsh-experimental-browser-use-runtime' import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client' import { z } from 'zod' -import { browserInputs, stagehandModelSchema, StagehandDrainError } from './native.ts' +import { browserInputs, stagehandModelSchema } from './native.ts' +import { StagehandDrainError } from './error.ts' import type { BrowserMethod, NativeBrowserRuntime, StagehandModelConfig } from './native.ts' import { openBrowserWorker } from './worker-client.ts' import { launchChromium } from './launch.ts' import type {} from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-browser-use' import type {} from '@deepseek-ai/dsh-system-prompt' -import type {} from '@deepseek-ai/dsh-tools' +import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' + +export { STAGEHAND_ERROR_CODES, StagehandDrainError, StagehandError, type StagehandErrorCode } from './error.ts' /** Cordis identity for the native Stagehand provider. */ export const name = 'experimental-browser-use-stagehand-native' @@ -178,6 +181,10 @@ function mountTools(ctx: Context, resources: SessionResources): description: descriptions[method], inputSchema: { ...z.record(z.string(), z.json()).parse(z.toJSONSchema(browserInputs[method])), type: 'object' }, async call(args) { + const parsed = browserInputs[method].safeParse(args) + if (!parsed.success) { + throw new ToolArgsError(parsed.error.issues.map(issue => `${['arguments', ...issue.path].join('.')}: ${issue.message}`)) + } const agent = ctx.agents.requireInitiator() const resource = await resources.get(agent) return resource.native.execute(method, args, resource.operationSignal) @@ -189,7 +196,7 @@ function mountTools(ctx: Context, resources: SessionResources): if (!names.has(exec.name)) return next() const agent = exec.agent if (agent === undefined || ctx.agents.get(agent.id) !== agent) { - throw new Error('Stagehand browser tools require an exact live Agent') + throw new ToolContextUnavailableError('Stagehand browser tools require an exact live Agent') } return resources.run(agent, exec.signal, async (resource, activeSignal) => { const upstreamSignal = exec.signal diff --git a/packages/experimental/browser-use-stagehand-native/src/native.ts b/packages/experimental/browser-use-stagehand-native/src/native.ts index 34cab652b2..8710615734 100644 --- a/packages/experimental/browser-use-stagehand-native/src/native.ts +++ b/packages/experimental/browser-use-stagehand-native/src/native.ts @@ -4,6 +4,9 @@ import { StagehandClientCreateConfigSchema } from '@browserbasehq/stagehand' import type { ModelConfig, Page, StagehandBrowser } from '@browserbasehq/stagehand' import { assertNever } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' +import { StagehandError } from './error.ts' + +export { StagehandDrainError } from './error.ts' /** Profile-owned model settings accepted by the pinned Stagehand SDK. */ export interface StagehandModelConfig { @@ -67,9 +70,6 @@ export const browserInputs = { /** Closed set of native browser operations. */ export type BrowserMethod = keyof typeof browserInputs -/** SDK requests did not drain before their connection Worker terminated. */ -export class StagehandDrainError extends Error {} - /** Native browser operations and SDK cleanup owned by one live Session. */ export interface NativeBrowserRuntime { /** @@ -131,7 +131,7 @@ export async function openNativeBrowser(config: NativeBrowserConfig): Promise candidate.pageId === pageId) - if (page === undefined) throw new Error('Stagehand browser tab is unavailable; list tabs to select a current pageId') + if (page === undefined) throw new StagehandError('Stagehand browser tab is unavailable; list tabs to select a current pageId', 'STAGEHAND_TAB_NOT_FOUND') return page } diff --git a/packages/experimental/browser-use-stagehand-native/src/worker-client.ts b/packages/experimental/browser-use-stagehand-native/src/worker-client.ts index 103c8dd81c..10b37e7d1f 100644 --- a/packages/experimental/browser-use-stagehand-native/src/worker-client.ts +++ b/packages/experimental/browser-use-stagehand-native/src/worker-client.ts @@ -1,7 +1,7 @@ /** Isolated Stagehand Workers own CDP connections; the host owns browser processes. */ import { Worker } from 'node:worker_threads' -import { StagehandDrainError } from './native.ts' +import { StagehandDrainError, StagehandError } from './error.ts' import type { NativeBrowserConfig, NativeBrowserRuntime } from './native.ts' import { request } from './worker-rpc.ts' @@ -32,8 +32,8 @@ export async function openBrowserWorker( let termination: Promise | undefined const terminate = () => termination ??= worker.terminate() const lifetime = new AbortController() - worker.once('error', (error) => { lifetime.abort(error) }) - worker.once('exit', (code) => { lifetime.abort(new Error(`Stagehand browser Worker exited (${code})`)) }) + worker.once('error', (error) => { lifetime.abort(new StagehandError(error.message, 'STAGEHAND_WORKER_FAILED', { cause: error })) }) + worker.once('exit', (code) => { lifetime.abort(new StagehandError(`Stagehand browser Worker exited (${code})`, 'STAGEHAND_WORKER_FAILED')) }) let closing: Promise | undefined const close = () => closing ??= (async () => { let timeout: ReturnType | undefined @@ -71,7 +71,7 @@ export async function openBrowserWorker( async execute(method, args, signal) { signal?.throwIfAborted() lifetime.signal.throwIfAborted() - if (closing !== undefined) throw new Error('Stagehand browser Worker is closed') + if (closing !== undefined) throw new StagehandError('Stagehand browser Worker is closed', 'STAGEHAND_WORKER_FAILED') const canceled = () => { void close().catch((error: unknown) => { lifetime.abort(error) }) } signal?.addEventListener('abort', canceled, { once: true }) try { diff --git a/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts b/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts index 75c201ace6..5e96aa9afc 100644 --- a/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts +++ b/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts @@ -3,12 +3,28 @@ import { MessageChannel, MessagePort } from 'node:worker_threads' import type { Worker } from 'node:worker_threads' import { z } from 'zod' +import { isStagehandErrorCode, StagehandError } from './error.ts' const responseSchema = z.discriminatedUnion('ok', [ z.object({ ok: z.literal(true), value: z.unknown() }).strict(), - z.object({ ok: z.literal(false), error: z.string() }).strict(), + z.object({ ok: z.literal(false), error: z.string(), name: z.string().optional(), code: z.string().optional() }).strict(), ]) +/** + * Rebuild a Worker operation failure on the host. A {@link StagehandError} + * keeps its code; any other failure, including an unknown name or code, + * becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. + */ +function operationFailure(failure: { error: string; name?: string | undefined; code?: string | undefined }): StagehandError { + return failure.name === 'StagehandError' && isStagehandErrorCode(failure.code) + ? new StagehandError(failure.error, failure.code) + : new StagehandError(failure.error, 'STAGEHAND_OPERATION_FAILED') +} + +function workerFailure(message: string, cause?: unknown): StagehandError { + return new StagehandError(message, 'STAGEHAND_WORKER_FAILED', cause === undefined ? undefined : { cause }) +} + /** Transferable reply channel paired with a validated operation payload. */ export const requestSchema = z.object({ method: z.string(), @@ -22,29 +38,32 @@ export const requestSchema = z.object({ * @param method - operation understood by the receiver. * @param args - structured-cloneable request data. * @param signal - owning Worker lifetime, when observed by the caller. - * @returns the receiver's value, rejecting malformed responses and peer shutdown. + * @returns the receiver's value. Malformed responses and peer shutdown reject with `STAGEHAND_WORKER_FAILED`; + * a receiver failure rejects as rebuilt by its `StagehandError` code. */ export async function request(target: MessagePort | Worker, method: string, args?: unknown, signal?: AbortSignal): Promise { signal?.throwIfAborted() const { port1, port2 } = new MessageChannel() const result = Promise.withResolvers() const abort = () => { - result.reject(signal?.reason instanceof Error ? signal.reason : new Error('Stagehand Worker request canceled')) + result.reject(signal?.reason instanceof Error ? signal.reason : workerFailure('Stagehand Worker request canceled', signal?.reason)) } + const transportFailure = (error: Error): void => { result.reject(workerFailure(error.message, error)) } try { signal?.addEventListener('abort', abort, { once: true }) port1.once('message', (raw: unknown) => { const response = responseSchema.safeParse(raw) - if (!response.success) result.reject(response.error) + if (!response.success) result.reject(workerFailure('Stagehand Worker returned a malformed response', response.error)) else if (response.data.ok) result.resolve(response.data.value) - else result.reject(new Error(response.data.error)) + else result.reject(operationFailure(response.data)) }) - port1.once('messageerror', result.reject) - port1.once('close', () => { result.reject(new Error('Stagehand Worker reply channel closed')) }) + port1.once('messageerror', transportFailure) + port1.once('close', () => { result.reject(workerFailure('Stagehand Worker reply channel closed')) }) try { target.postMessage({ method, args, reply: port2 }, [port2]) } catch (error) { - result.reject(error) + // postMessage reports clone and transfer failures as DOMException instances. + transportFailure(error as Error) } return await result.promise } finally { @@ -56,6 +75,7 @@ export async function request(target: MessagePort | Worker, method: string, args /** * Validate and answer one request without leaving rejected callbacks unobserved. + * A rejected {@link StagehandError} sends its `name` and `code` beside the message. * @param raw - untrusted message received from the Worker boundary. * @param execute - owner that validates and executes the method arguments. * @returns after the response has been posted and the reply port released. @@ -65,7 +85,9 @@ export async function answer(raw: unknown, execute: (method: string, args: unkno try { reply.postMessage({ ok: true, value: await execute(method, args) }) } catch (error) { - reply.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) }) + reply.postMessage(error instanceof StagehandError + ? { ok: false, error: error.message, name: error.name, code: error.code } + : { ok: false, error: error instanceof Error ? error.message : String(error) }) } finally { reply.close() } diff --git a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts index 7dac15931f..efb18d1bed 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts @@ -42,6 +42,7 @@ vi.mock('../src/launch.ts', async (importActual) => { }) vi.mock('../src/worker-client.ts', async () => { const { openNativeBrowser } = await import('../src/native.ts') + const { StagehandError } = await import('../src/error.ts') return { async openBrowserWorker(config: NativeBrowserConfig, signal: AbortSignal, warn: (message: string) => void) { acquisition.signal = signal @@ -54,7 +55,7 @@ vi.mock('../src/worker-client.ts', async () => { })() return { async execute(method: import('../src/native.ts').BrowserMethod, args: unknown, signal?: AbortSignal) { - if (closing !== undefined) throw new Error('Fixture connection is closed') + if (closing !== undefined) throw new StagehandError('Fixture connection is closed', 'STAGEHAND_WORKER_FAILED') const cancel = () => { void close().catch(() => {}) } signal?.addEventListener('abort', cancel, { once: true }) try { return await native.execute(method, args) } finally { signal?.removeEventListener('abort', cancel) } @@ -90,6 +91,8 @@ beforeEach(async () => { afterEach(async () => { await ctx.fiber.dispose() }) +const INVALID_ARGS = { name: 'ToolArgsError', code: 'INVALID_ARGS' } + function execute(agent: Agent, suffix: string, args: unknown, signal = new AbortController().signal) { return executeToolFixture(ctx, { agent, name: `stagehand_${suffix}`, arguments: args, callId: ToolCallId(`test-${suffix}`), signal }) } @@ -119,11 +122,14 @@ it('lazily launches distinct browsers and preserves each Session tab state', asy it('reserves an attached browser for one live owner and rejects model connection overrides', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'attach', cdpEndpoint: 'http://localhost:9222' }) expect((await execute(first, 'tabs', { action: 'list' })).isError).toBe(false) - expect((await execute(second, 'tabs', { action: 'list' })).isError).toBe(true) + expect((await execute(second, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'BrowserSessionError', code: 'BROWSER_LOCKED' }) expect(fixture.browsers).toHaveLength(1) expect(fixture.browsers[0]?.options).toEqual({ cdpUrl: 'http://localhost:9222' }) - expect((await execute(first, 'navigate', { url: 'https://example.com', cdpEndpoint: 'http://other' })).isError).toBe(true) - expect((await execute(first, 'act', { instruction: 'click', model: 'other' })).isError).toBe(true) + expect((await execute(first, 'navigate', { url: 'https://example.com', cdpEndpoint: 'http://other' })).error?.info).toEqual(INVALID_ARGS) + expect((await execute(first, 'act', { instruction: 'click', model: 'other' })).error?.info).toEqual(INVALID_ARGS) + const malformed = await execute(first, 'navigate', { url: 'not a url' }) + expect(malformed.error?.info).toEqual(INVALID_ARGS) + expect(malformed.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: arguments.url: Invalid URL' }]) }) it('uses its independent model for actions, observations, and a caller-selected extraction schema', async () => { @@ -142,14 +148,15 @@ it('uses its independent model for actions, observations, and a caller-selected fixture.actResult = { success: false, message: 'Fixture button unavailable' } fixture.result = { extraction: 'Missing button' } const refused = await execute(first, 'act', { instruction: 'Click the missing button' }) - expect(refused.isError).toBe(true) + expect(refused.error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_ACT_FAILED' }) expect(JSON.stringify(refused.content)).toContain('Fixture button unavailable') }) it('refuses unavailable tabs and calls without an exact live Agent', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) - expect((await execute(first, 'navigate', { url: 'https://example.com', pageId: 'missing' })).isError).toBe(true) - expect((await executeToolFixture(ctx, { name: 'stagehand_tabs', arguments: { action: 'list' }, callId: ToolCallId('agentless'), signal: new AbortController().signal })).isError).toBe(true) + expect((await execute(first, 'navigate', { url: 'https://example.com', pageId: 'missing' })).error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_TAB_NOT_FOUND' }) + expect((await executeToolFixture(ctx, { name: 'stagehand_tabs', arguments: { action: 'list' }, callId: ToolCallId('agentless'), signal: new AbortController().signal })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) ctx.tools.register({ name: 'unrelated', description: 'An independent tool.', parameters: { type: 'object' }, output: { schema: { type: 'boolean' }, render: () => [{ type: 'text', text: 'independent' }] }, execute: async () => true }) const unrelated = await executeToolFixture(ctx, { agent: first, name: 'unrelated', arguments: {}, callId: ToolCallId('unrelated'), signal: new AbortController().signal }) expect(unrelated.isError).toBe(false) @@ -413,8 +420,8 @@ it('blocks reconnection and another owner after canceled native work fails to dr release.resolve() } expect((await operation).isError).toBe(true) - expect((await execute(first, 'tabs', { action: 'list' })).isError).toBe(true) - expect((await execute(second, 'tabs', { action: 'list' })).isError).toBe(true) + expect((await execute(first, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED' }) + expect((await execute(second, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'BrowserSessionError', code: 'BROWSER_LOCKED' }) expect(fixture.browsers).toHaveLength(1) await provider.dispose() expect(fixture.browsers[0]?.closed).toBe(false) diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts index d5eeaca667..f20b9f3f27 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts @@ -8,6 +8,10 @@ import { openBrowserWorker } from '../src/worker-client.ts' import type { NativeBrowserConfig, NativeBrowserRuntime } from '../src/native.ts' import { nativeModel } from './fixtures/stagehand.ts' +function workerFailed(message: RegExp) { + return { name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringMatching(message) as string } +} + const state = vi.hoisted(() => ({ workers: [] as Worker[], entries: [] as string[] })) vi.mock('node:worker_threads', async (importActual) => { const actual = await importActual() @@ -94,18 +98,19 @@ it('terminates a Worker whose initialization overlaps acquisition cancellation', it('fails active and later operations when the Worker exits', async () => { const runtime = await open('crash') const exited = once(state.workers[0]!, 'exit') - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow(/Worker (exited|reply channel closed)/u) + await expect(runtime.execute('tabs', { action: 'list' })) + .rejects.toMatchObject(workerFailed(/Worker (exited|reply channel closed)/u)) await exited - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow('Worker exited (23)') - await expect(runtime.close()).rejects.toThrow('Worker exited (23)') + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/Worker exited \(23\)/u)) + await expect(runtime.close()).rejects.toMatchObject({ name: 'StagehandDrainError', code: 'STAGEHAND_CLEANUP_FAILED', message: expect.stringContaining('Worker exited (23)') as string }) }) it.each(['closing', 'close-failure'])('rejects cleanup after an undrained extension (%s) even though its Worker terminates', async (scenario) => { const runtime = await openBrowserWorker({ ...config(scenario), shutdownGraceMs: 20 }, new AbortController().signal, warn) runtimes.push(runtime) const closing = runtime.close() - const rejected = expect(closing).rejects.toThrow(/cleanup timed out|did not drain/u) - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow('Worker is closed') + const rejected = expect(closing).rejects.toMatchObject({ name: 'StagehandDrainError', code: 'STAGEHAND_CLEANUP_FAILED', message: expect.stringMatching(/cleanup timed out|did not drain/u) as string }) + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/Worker is closed/u)) await rejected expect(warn).toHaveBeenCalledWith(expect.stringContaining('SDK cleanup did not finish')) expect(state.workers[0]?.threadId).toBe(-1) @@ -114,7 +119,7 @@ it.each(['closing', 'close-failure'])('rejects cleanup after an undrained extens it('rejects cleanup after a Worker crashes', async () => { const runtime = await open('error') - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow() + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/./u)) await expect(runtime.close()).rejects.toThrow() expect(state.workers[0]?.threadId).toBe(-1) }) diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts index e67c50be26..9fbf5ec3eb 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts @@ -4,6 +4,7 @@ import { getEventListeners, once } from 'node:events' import { MessageChannel } from 'node:worker_threads' import type { MessagePort } from 'node:worker_threads' import { afterEach, expect, it, vi } from 'vitest' +import { StagehandError } from '../src/error.ts' import { answer, request, requestSchema } from '../src/worker-rpc.ts' const cleanups: Array<() => Promise> = [] @@ -51,13 +52,37 @@ it.each([new Error('Browser operation failed'), 'Browser operation refused'])( const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'navigate', { url: 'https://example.com' }) - const rejected = expect(result).rejects.toThrow(failure instanceof Error ? failure.message : failure) + const rejected = expect(result).rejects.toMatchObject({ + constructor: StagehandError, code: 'STAGEHAND_OPERATION_FAILED', message: failure instanceof Error ? failure.message : failure, + }) const raw = await incoming await answer(raw, async () => { throw failure }) await rejected }, ) +it('rebuilds a StagehandError from its transported name and code', async () => { + const { port1, port2 } = channel() + const incoming = receive(port2) + const result = request(port1, 'act', { instruction: 'Click the button.' }) + const rejected = expect(result).rejects.toMatchObject({ constructor: StagehandError, name: 'StagehandError', code: 'STAGEHAND_ACT_FAILED', message: 'Button missing' }) + await answer(await incoming, async () => { throw new StagehandError('Button missing', 'STAGEHAND_ACT_FAILED') }) + await rejected +}) + +it.each([ + { ok: false, error: 'Unknown failure', name: 'StagehandError', code: 'STAGEHAND_UNKNOWN' }, + { ok: false, error: 'Foreign failure', name: 'OtherError', code: 'STAGEHAND_ACT_FAILED' }, +])('classifies an unknown transported identity as an operation failure: %j', async (response) => { + const { port1, port2 } = channel() + const incoming = receive(port2) + const result = request(port1, 'act', { instruction: 'Click the button.' }) + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED', message: response.error }) + const { reply } = requestSchema.parse(await incoming) + reply.postMessage(response) + await rejected +}) + it.each([ { ok: true, value: 'unexpected', extra: true }, { ok: false, error: 42 }, @@ -66,7 +91,7 @@ it.each([ const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'tabs', { action: 'list' }) - const rejected = expect(result).rejects.toThrow() + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: 'Stagehand Worker returned a malformed response' }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -79,7 +104,7 @@ it('rejects peer shutdown before a response instead of leaving the request pendi const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'observe', { instruction: 'Find a button.' }) - const rejected = expect(result).rejects.toThrow('Worker reply channel closed') + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringContaining('Worker reply channel closed') as string }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -94,7 +119,7 @@ it.each([new Error('Session disposed'), 'canceled'])( const incoming = receive(port2) const controller = new AbortController() const result = request(port1, 'act', { instruction: 'Click the button.' }, controller.signal) - const rejected = expect(result).rejects.toThrow(reason instanceof Error ? reason.message : 'Worker request canceled') + const rejected = expect(result).rejects.toMatchObject(reason instanceof Error ? reason : { name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: 'Stagehand Worker request canceled' }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -120,7 +145,7 @@ it('does not dispatch an already canceled request', async () => { it('reports clone failure when request arguments cannot cross a Worker boundary', async () => { const { port1 } = channel() - await expect(request(port1, 'extract', { callback() {} })).rejects.toThrow(/clone/u) + await expect(request(port1, 'extract', { callback() {} })).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringMatching(/clone/u) as string }) }) it('rejects malformed request envelopes before invoking the operation', async () => { diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts index 6ca927c88c..a6f38dbff1 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts @@ -36,8 +36,10 @@ it('dispatches browser arguments using the independently configured native model await request(peer, 'ready') expect(await request(peer, 'navigate', { url: 'https://fixture.example' })).toMatchObject({ content: [{ type: 'text' }] }) expect(await request(peer, 'extract', { instruction: 'Read the heading' })).toMatchObject({ content: [{ type: 'text' }] }) - await expect(request(peer, 'navigate', { url: 'invalid' })).rejects.toThrow() - await expect(request(peer, 'unavailable')).rejects.toThrow() + await expect(request(peer, 'navigate', { url: 'https://fixture.example', pageId: 'missing' })) + .rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_TAB_NOT_FOUND', message: expect.stringContaining('tab is unavailable') as string }) + await expect(request(peer, 'navigate', { url: 'invalid' })).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED' }) + await expect(request(peer, 'unavailable')).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED' }) await request(peer, 'close') expect(fixture.models).toEqual([{ modelName: 'openai/gpt-5.4-mini', apiKey: 'fixture-model-key' }]) expect(fixture.browsers[0]?.stagehandClosed).toBe(true) @@ -48,7 +50,7 @@ it('reports initialization failure without closing an external browser', async ( const { fixture, peer } = await prepare() fixture.createError = new Error('Fixture extension unavailable') await import('../src/worker.ts') - await expect(request(peer, 'ready')).rejects.toThrow('Fixture extension unavailable') + await expect(request(peer, 'ready')).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED', message: 'Fixture extension unavailable' }) expect(fixture.browsers[0]?.closed).toBe(false) }) diff --git a/packages/experimental/browser-use-stagehand-native/tsconfig.json b/packages/experimental/browser-use-stagehand-native/tsconfig.json index b4da4ee4b2..b2fddda9b2 100644 --- a/packages/experimental/browser-use-stagehand-native/tsconfig.json +++ b/packages/experimental/browser-use-stagehand-native/tsconfig.json @@ -9,6 +9,7 @@ { "path": "../../core/agent" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, + { "path": "../../llm/llm" }, { "path": "../../mcp/mcp-client" }, { "path": "../../subprocess/subprocess" }, { "path": "../../util/values" }, From e327098b9e1ab1bac9b9e12b4ae56a511e7f27e1 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:40:31 +0800 Subject: [PATCH 22/68] feat(cua-driver-native): add CuaDriverError for driver call failures A failed native callTool now throws CuaDriverError CUA_DRIVER_FAILED with the SDK error as cause, unless the call was cancelled, and a result that is not JSON throws CUA_DRIVER_INVALID_RESULT. Refs #7869 --- .../README.i18n.yaml | 4 +-- .../computer-use-cua-driver-native/README.md | 3 ++ .../README.zh.md | 3 ++ .../package.json | 3 +- .../src/error.ts | 33 +++++++++++++++++++ .../src/index.ts | 14 ++++++-- .../tests/fixtures/cua-driver.ts | 3 ++ .../tests/provider.spec.ts | 33 +++++++++++++++++++ .../tsconfig.json | 1 + 9 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 packages/experimental/computer-use-cua-driver-native/src/error.ts diff --git a/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml b/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml index 6cd4a52c83..5ebb61d5c9 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml +++ b/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml @@ -27,8 +27,8 @@ en: c3022cbadb94589b zh: b426ea3dbeafd352 /deepseek-ai-dsh-experimental-computer-use-cua-driver-native/understand-the-implementation: - en: b397becc466ba383 - zh: 758a149cf002bd11 + en: 2affc3aae95c8e1b + zh: 392fa0f65037e291 /deepseek-ai-dsh-experimental-computer-use-cua-driver-native/further-exploration: en: d24023319ead888c zh: ab28be480aced0a9 diff --git a/packages/experimental/computer-use-cua-driver-native/README.md b/packages/experimental/computer-use-cua-driver-native/README.md index 3d5fb83810..2d7a304444 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.md +++ b/packages/experimental/computer-use-cua-driver-native/README.md @@ -63,9 +63,12 @@ The provider reserves the shared computer-use registration before loading native | File | Role | |---|---| | [src/index.ts](src/index.ts) | Native runtime ownership, catalog validation, tool registration, and provider guidance | +| [src/error.ts](src/error.ts) | `CuaDriverError` and its closed code list | Tool definitions reuse the existing MCP result adapter. Cua Driver's JSON catalog determines the schemas; its raw result supplies canonical text, structured output, and image bytes. The computer-use service carries only the provider name and exclusive registration. +A rejected native call throws `CuaDriverError` with `CUA_DRIVER_FAILED`, keeping the SDK's message and its error as `cause`; once the call or the provider is canceled, the cancellation propagates instead. A raw result that is not JSON throws `CUA_DRIVER_INVALID_RESULT`. Upstream tool refusals reported in a result stay with the MCP result adapter. + ----- diff --git a/packages/experimental/computer-use-cua-driver-native/README.zh.md b/packages/experimental/computer-use-cua-driver-native/README.zh.md index 5fba221cc0..58b5769d6e 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.zh.md +++ b/packages/experimental/computer-use-cua-driver-native/README.zh.md @@ -63,9 +63,12 @@ env -u NODE_USE_ENV_PROXY DSH_COMPUTER_USE_NATIVE_E2E=1 node node_modules/vitest | 文件 | 职责 | |---|---| | [src/index.ts](src/index.ts) | 原生运行时所有权、目录校验、工具注册和提供者指导文本 | +| [src/error.ts](src/error.ts) | `CuaDriverError` 及其封闭代码列表 | 工具定义复用现有 MCP 结果适配器。Cua Driver 的 JSON 目录决定 schema,其原始结果提供规范文本、结构化输出和图像字节。电脑操作服务只保存提供者名称并保证独占注册。 +原生调用被拒绝时抛出带 `CUA_DRIVER_FAILED` 的 `CuaDriverError`,保留 SDK 的消息并以其错误作为 `cause`;调用或提供者已取消时改为传播取消。原始结果不是 JSON 时抛出 `CUA_DRIVER_INVALID_RESULT`。结果中报告的上游工具拒绝仍由 MCP 结果适配器处理。 + ----- diff --git a/packages/experimental/computer-use-cua-driver-native/package.json b/packages/experimental/computer-use-cua-driver-native/package.json index 7538c33097..b1c66876ce 100644 --- a/packages/experimental/computer-use-cua-driver-native/package.json +++ b/packages/experimental/computer-use-cua-driver-native/package.json @@ -35,7 +35,8 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-computer-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-mcp-client": "workspace:*", diff --git a/packages/experimental/computer-use-cua-driver-native/src/error.ts b/packages/experimental/computer-use-cua-driver-native/src/error.ts new file mode 100644 index 0000000000..e6c2fe30c7 --- /dev/null +++ b/packages/experimental/computer-use-cua-driver-native/src/error.ts @@ -0,0 +1,33 @@ +/** Machine-routable Cua Driver SDK failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link CuaDriverError} code: + * - `CUA_DRIVER_FAILED` — the native SDK rejected the tool call; the message carries the SDK's text. + * Inspect fresh desktop state before retrying. + * - `CUA_DRIVER_INVALID_RESULT` — the native SDK returned a result that is not JSON; report it rather than retrying unchanged. + */ +export const CUA_DRIVER_ERROR_CODES = [ + 'CUA_DRIVER_FAILED', + 'CUA_DRIVER_INVALID_RESULT', +] as const + +/** One code from {@link CUA_DRIVER_ERROR_CODES}. */ +export type CuaDriverErrorCode = typeof CUA_DRIVER_ERROR_CODES[number] + +/** Cua Driver native SDK failure carrying a stable {@link CuaDriverErrorCode}; the SDK's error is its `cause`. */ +export class CuaDriverError extends HarnessError { + override readonly code: CuaDriverErrorCode + + /** + * @param message - names the failed Cua Driver tool or the SDK's own message. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: CuaDriverErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'CuaDriverError' + this.code = code + } +} diff --git a/packages/experimental/computer-use-cua-driver-native/src/index.ts b/packages/experimental/computer-use-cua-driver-native/src/index.ts index 539f170fec..f1323c2e8d 100644 --- a/packages/experimental/computer-use-cua-driver-native/src/index.ts +++ b/packages/experimental/computer-use-cua-driver-native/src/index.ts @@ -12,6 +12,9 @@ import type { CuaDriver as NativeDriver } from '@trycua/cua-driver' import type {} from '@deepseek-ai/dsh-computer-use' import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tools' +import { CuaDriverError } from './error.ts' + +export { CUA_DRIVER_ERROR_CODES, CuaDriverError, type CuaDriverErrorCode } from './error.ts' /** Cordis plugin identity for the native Cua Driver provider. */ export const name = 'experimental-computer-use-cua-driver-native' @@ -109,9 +112,16 @@ export async function apply(ctx: Context): Promise { async call(args, execution) { const combined = AbortSignal.any([execution.signal, lifetime.signal]) combined.throwIfAborted() - const result = await activeDriver.callTool(tool.name, JSON.stringify(args), { signal: combined }) + const result = await activeDriver.callTool(tool.name, JSON.stringify(args), { signal: combined }).catch((error: unknown) => { + combined.throwIfAborted() + throw new CuaDriverError(error instanceof Error ? error.message : String(error), 'CUA_DRIVER_FAILED', { cause: error }) + }) combined.throwIfAborted() - return JSON.parse(result.rawJson) as unknown + try { + return JSON.parse(result.rawJson) as unknown + } catch (error) { + throw new CuaDriverError(`Cua Driver tool "${tool.name}" returned a result that is not JSON`, 'CUA_DRIVER_INVALID_RESULT', { cause: error }) + } }, }) inner.tools.register(definition) diff --git a/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts b/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts index fe0f35a288..42fb547b27 100644 --- a/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts +++ b/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts @@ -37,6 +37,7 @@ export const fixture: { createError?: Error list?: (signal?: AbortSignal) => Promise call?: (name: string, args: Record, signal?: AbortSignal) => Promise + rawJson?: string shutdown?: () => Promise } = { creates: 0, destroys: 0, shutdowns: 0, clicked: false, calls: [] } @@ -50,6 +51,7 @@ export function resetFixture(): void { delete fixture.createError delete fixture.list delete fixture.call + delete fixture.rawJson delete fixture.shutdown } @@ -68,6 +70,7 @@ export class CuaDriver { async callTool(name: string, argsJson: string, options?: { signal: AbortSignal }): Promise<{ rawJson: string }> { const args = JSON.parse(argsJson) as Record fixture.calls.push({ name, args, ...options ? { signal: options.signal } : {} }) + if (fixture.rawJson !== undefined) return { rawJson: fixture.rawJson } if (fixture.call) return { rawJson: JSON.stringify(await fixture.call(name, args, options?.signal)) } if (name === 'get_window_state') { return { rawJson: JSON.stringify({ diff --git a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts index d5f14a52e1..bd19df1021 100644 --- a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts +++ b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts @@ -98,6 +98,39 @@ describe('Cua Driver native provider', () => { expect(result.content).toEqual([{ type: 'text', text: 'Error: background_unavailable' }]) }) + it.each([new Error('native helper unavailable'), 'native helper unavailable'])('classifies a native SDK call failure: %s', async (failure) => { + fixture.call = async () => { throw failure } + await ctx.plugin(NativeProvider) + const result = await execute('click', { pid: 9, window_id: 7 }) + expect(result.error?.info).toEqual({ name: 'CuaDriverError', code: 'CUA_DRIVER_FAILED' }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: native helper unavailable' }]) + }) + + it('reports cancellation instead of a native failure once the caller cancels', async () => { + const called: PromiseWithResolvers = Promise.withResolvers() + fixture.call = async (_name, _args, signal) => { + called.resolve() + await new Promise(resolve => signal?.addEventListener('abort', resolve, { once: true })) + throw new Error('native call interrupted') + } + await ctx.plugin(NativeProvider) + const controller = new AbortController() + const result = executeToolFixture(ctx, { + name: 'cua_driver_native__click', callId: ToolCallId('native-cancel'), arguments: { pid: 9, window_id: 7 }, signal: controller.signal, + }) + await called.promise + controller.abort(new Error('Stop clicking')) + expect((await result).error).toEqual({ message: 'Stop clicking', info: { name: 'AbortError', code: 'ABORTED' } }) + }) + + it('classifies a native result that is not JSON', async () => { + fixture.rawJson = '{not json' + await ctx.plugin(NativeProvider) + const result = await execute('click', { pid: 9, window_id: 7 }) + expect(result.error?.info).toEqual({ name: 'CuaDriverError', code: 'CUA_DRIVER_INVALID_RESULT' }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: Cua Driver tool "click" returned a result that is not JSON' }]) + }) + it('leaves an unrelated tool running when the native provider unloads', async () => { const started = Promise.withResolvers() const settled = Promise.withResolvers() diff --git a/packages/experimental/computer-use-cua-driver-native/tsconfig.json b/packages/experimental/computer-use-cua-driver-native/tsconfig.json index dfb656c176..abc6329753 100644 --- a/packages/experimental/computer-use-cua-driver-native/tsconfig.json +++ b/packages/experimental/computer-use-cua-driver-native/tsconfig.json @@ -11,6 +11,7 @@ { "path": "../../computer-use/computer-use" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, + { "path": "../../llm/llm" }, { "path": "../../mcp/mcp-client" } ] } From e1d409f7b20180a951840d8c7e67683327598d2c Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:40:32 +0800 Subject: [PATCH 23/68] docs(subsystems): note worktree and liveshare failure identities Refs #7869 --- docs/subsystems/liveshare.i18n.yaml | 4 ++-- docs/subsystems/liveshare.md | 2 +- docs/subsystems/liveshare.zh.md | 2 +- docs/subsystems/worktrees.i18n.yaml | 4 ++-- docs/subsystems/worktrees.md | 2 +- docs/subsystems/worktrees.zh.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/subsystems/liveshare.i18n.yaml b/docs/subsystems/liveshare.i18n.yaml index 608e65a930..fde693bc1e 100644 --- a/docs/subsystems/liveshare.i18n.yaml +++ b/docs/subsystems/liveshare.i18n.yaml @@ -18,8 +18,8 @@ en: 6b1346e73ab6eab9 zh: 888cfc08c6bc8522 /liveshare/constraining-a-shared-session: - en: 7607ed3f99df06cc - zh: 290c9b8ed064da00 + en: c336c48190726a6c + zh: f4119a1156d75728 /liveshare/viewer-states: en: b8bcb009e419fa25 zh: 31c4662b52e99ea7 diff --git a/docs/subsystems/liveshare.md b/docs/subsystems/liveshare.md index 604ef23c12..15f986bc99 100644 --- a/docs/subsystems/liveshare.md +++ b/docs/subsystems/liveshare.md @@ -38,7 +38,7 @@ Child tool guards recheck the share’s current mode, expiry, viewer admission, Every share lets its viewer drive the *source* Session through the normal prompt path, and any share at either tier installs the bounded sandbox while it is active. `installSourceSessionAccess` registers a confined replacement for every view-surface tool the deployment ships in that Session's own scope, and bounded `edit` and `write` replacements whenever any share over the Session allows writing. The layer is mounted on the Session, but it confines only the turns a share viewer starts: `agent/pre-step` records, in Host memory, whether a turn's admitted input names a share viewer, and the guard and the replacements read that answer for every execution of that turn. A viewer-started turn runs those replacements and nothing else; a turn the owner starts keeps the Session's own tools, including `bash` and its unrestricted filesystem tools. The answer is decided when the turn is admitted and never written to the Session log; a restart recomputes it from the next admitted step. An owner's steering input inside a viewer's turn stays confined with it. Stopping every share over the Session disposes the layer, which restores the Session's own tools; narrowing the last write share to `view` re-installs the read-only layer. -The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. +The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A guard refusal records `LiveshareForkDeniedError` with a `FORK_*` code on the failed call, and a confined file tool refuses a target outside the grant with `FsError` `FS_SANDBOX_DENIED`. Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs. diff --git a/docs/subsystems/liveshare.zh.md b/docs/subsystems/liveshare.zh.md index 4c26825027..bd7754105c 100644 --- a/docs/subsystems/liveshare.zh.md +++ b/docs/subsystems/liveshare.zh.md @@ -38,7 +38,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检 每个分享都让它的 viewer 通过正常 prompt 路径驱动*源*会话,任一档位的分享在活跃期间都会安装有界沙箱。`installSourceSessionAccess` 在该会话自身作用域中为部署提供的每个读取与检索面工具注册受限替代,并在任一同会话分享允许写入时再注册有界 `edit` 与 `write` 替代。执行层挂在会话上,但只约束分享查看者发起的轮次:`agent/pre-step` 在 Host 内存中记录一个轮次的已准入输入是否带有 share-viewer principal,守卫与替代定义对该轮次的每次执行读取这一结论。查看者发起的轮次只能运行这些替代定义;所有者自己发起的轮次保留会话原生工具,包括 `bash` 与不受限的文件工具。该结论在轮次准入时确定,不写入会话日志;重启后从下一个准入步骤重新计算。所有者在查看者轮次中追加的输入仍留在该受限轮次内。该会话的所有分享停止后执行层被释放,会话恢复自己的工具;最后一个可写分享降为 `view` 时重装只读层。 -安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。 +安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。守卫拒绝会在失败调用上记录 `LiveshareForkDeniedError` 及 `FORK_*` code,受限文件工具以 `FsError` `FS_SANDBOX_DENIED` 拒绝授权范围外的目标。 每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。 diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index 23dde9244e..a6b14d164b 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -6,8 +6,8 @@ en: 3a3d69d2b12a78f9 zh: a7a7d12487968bbc /git-worktrees/creation-and-retention: - en: 53f643c5d30e00b2 - zh: ba9e52efc62c7656 + en: 4c28ae6baae4ef5f + zh: 0c83d90ea3cd3c2e /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 492a1dbb1a..dff4b4a63c 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -10,7 +10,7 @@ The calling Session's current directory selects the source repository. Creation The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. -Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. +Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. Worktree failures throw `WorktreeError` with a `WORKTREE_*` code; a failure after allocation keeps the wrapped error's `name` and `code`, and caller cancellation stays an `AbortError`. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. ## Request and result diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index d96ef21893..51cbf41431 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -10,7 +10,7 @@ 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 -通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 +通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。worktree 失败抛出带 `WORKTREE_*` code 的 `WorktreeError`;分配开始后的失败保留被包装错误的 `name` 与 `code`,调用方取消仍为 `AbortError`。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 ## 请求与结果 From 4f9699b72620cfa3b4028f3ce2844307899c1ee4 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:44:46 +0800 Subject: [PATCH 24/68] test(liveshare): type asymmetric message matchers Refs #7869 --- .../liveshare/tests/fork-denial.ts | 2 +- .../tests/fork-enforcement-unit.spec.ts | 64 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/packages/experimental/liveshare/tests/fork-denial.ts b/packages/experimental/liveshare/tests/fork-denial.ts index c025c61126..a06f38c6b2 100644 --- a/packages/experimental/liveshare/tests/fork-denial.ts +++ b/packages/experimental/liveshare/tests/fork-denial.ts @@ -10,7 +10,7 @@ import type { LiveshareForkDeniedCode } from '../src/host/fork-errors.ts' */ export function denial(reason: string | RegExp, code: LiveshareForkDeniedCode): unknown { return { - reason: typeof reason === 'string' ? expect.stringContaining(reason) : expect.stringMatching(reason), + reason: (typeof reason === 'string' ? expect.stringContaining(reason) : expect.stringMatching(reason)) as string, info: { name: 'LiveshareForkDeniedError', code }, } } diff --git a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts index 304db1bc7e..6fc984aee5 100644 --- a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts +++ b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts @@ -114,10 +114,10 @@ describe('confined fork tools', () => { const h = harness({ read }) installForkEnforcement(h.target as never, h.failure) const confined = h.registered.get('read')! - await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') }) - await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') }) + await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') as string }) await expect(confined.execute({ file_path: 'outside.txt' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) // The grant itself decides, so a path the fake reports inside succeeds and runs the deployment body. const inside = await confined.execute({ file_path: 'inside.ts' }, { signal: undefined }) expect(inside).toBe('ran') @@ -125,7 +125,7 @@ describe('confined fork tools', () => { h.forks.enforcementInstalled.mockReturnValue(false) await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') }) + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) }) it('refuses a read it could not register and keeps the registration error', () => { @@ -156,15 +156,15 @@ describe('confined fork tools', () => { // The body runs the deployment's own argument checks itself, because it replaces its execution. await expect(edit.execute('not a record', { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) - await expect(edit.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) + await expect(edit.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: '', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'a' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) // The containment check runs inside the body too, so a target the guard did not see is still refused. await expect(edit.execute({ file_path: '../outside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) expect(h.fs.editText).not.toHaveBeenCalled() const result = await edit.execute({ @@ -184,7 +184,7 @@ describe('confined fork tools', () => { h.forks.enforcementInstalled.mockReturnValue(false) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') }) + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) }) it('refuses a write-capable child when the deployment ships no write to replace', () => { @@ -211,14 +211,14 @@ describe('confined fork tools', () => { const confined = h.registered.get('write')! await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute('not a record', { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute({ file_path: '../outside', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) h.forks.enforcementInstalled.mockReturnValue(false) await expect(confined.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') }) + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) h.forks.enforcementInstalled.mockReturnValue(true) const result = await confined.execute({ file_path: 'inside.ts', content: 'hello' }, { signal: undefined }) @@ -611,7 +611,7 @@ describe('source-session sandbox', () => { ['present', { files: [{ path: 'inside.ts' }, { path: 'outside/secret.txt' }] }], ] for (const [name, args] of outsideCalls) { - await expect(h.call(name, args)).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + await expect(h.call(name, args)).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) } const malformed: [string, unknown][] = [ @@ -623,7 +623,7 @@ describe('source-session sandbox', () => { ['present', { files: 'not a list' }], ] for (const [name, args] of malformed) { - await expect(h.call(name, args)).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('with the paths it declares') }) + await expect(h.call(name, args)).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('with the paths it declares') as string }) } // A resolution the filesystem refuses is the refusal: no verdict is guessed from the spelling. @@ -642,9 +642,9 @@ describe('source-session sandbox', () => { // There is no owner bypass: the sandbox belongs to the Session, so every turn reads through it. await expect(confined.execute({ file_path: 'x' }, { signal: undefined })).resolves.toBe('ran') expect(refresh).toHaveBeenCalledTimes(1) - await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') }) - await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') }) - await expect(confined.execute({ file_path: 'outside' }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') as string }) + await expect(confined.execute({ file_path: 'outside' }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).resolves.toBe('ran') // Every call re-reads the grants before it consumes them, including one it then refuses. expect(refresh).toHaveBeenCalledTimes(5) @@ -685,19 +685,19 @@ describe('source-session sandbox', () => { expect(installSourceSessionAccess(h.target as never)).toMatchObject({ readConfined: true, writeConfined: true }) const confined = h.installed.get('write')! - await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') }) - await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') }) + await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute({ file_path: '../outside', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) const narrowing = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: vi.fn().mockReturnValueOnce(true).mockReturnValue(false) } }) expect(installSourceSessionAccess(narrowing.target as never).writeConfined).toBe(true) await expect(narrowing.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) const blocked = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: () => false } }) installSourceSessionAccess(blocked.target as never) await expect(blocked.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) h.target.write = { mayWrite: () => true } const result = await confined.execute({ file_path: 'inside.ts', content: 'hello' }, { signal: undefined }) @@ -714,15 +714,15 @@ describe('source-session sandbox', () => { const edit = h.installed.get('edit')! await expect(edit.execute({ file_path: 'inside.ts', old_string: '', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: '', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'a' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'outside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') }) + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) // The intent comes from the shipped waterfall, and the edit is written under the Session policy. const result = await edit.execute({ file_path: 'inside.ts', old_string: 'old', new_string: 'new', replace_all: true }, { signal: undefined }) expect(result).toEqual({ path: '/granted/inside.ts', before: 'old', after: 'new' }) @@ -743,9 +743,9 @@ describe('source-session sandbox', () => { installSourceSessionAccess(closedEdit.target as never) await expect(closedEdit.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') }) + }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) // The replacement's own argument check refuses arguments it cannot read. - await expect(edit.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') }) + await expect(edit.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) // A share that narrows while the edit intent awaits stops the edit before it reaches the backend. const narrowing = sourceHarness({ @@ -755,7 +755,7 @@ describe('source-session sandbox', () => { installSourceSessionAccess(narrowing.target as never) await expect(narrowing.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') }) + }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) expect(narrowing.fs.editText).not.toHaveBeenCalled() }) From 686547b41f3d024dcac8887709ff5e9f1b92e30c Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:44:47 +0800 Subject: [PATCH 25/68] test(snapshots): record hook and cua error identities Hook denials and blocks now persist HookError HOOK_DENIED / HOOK_BLOCKED and cua refusals persist NativeError with their native codes on tool/result; model-visible content is unchanged. Refs #7869 --- snapshots/session/cua-native/session.v4.jsonl | 30 +++++++++---------- .../hook-cc-posttool-block/session.v4.jsonl | 2 +- .../hook-cc-pretool-deny/session.v4.jsonl | 2 +- .../session.v4.jsonl | 2 +- .../hook-codex-pretool-block/session.v4.jsonl | 2 +- .../packed-chunks/writer.expected.jsonl | 2 +- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index db5e234368..5c5ed32c52 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -19,17 +19,17 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032889794,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032889794,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1794032889794,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032889794,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032889811,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032889811,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032889811,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032889811,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032889830,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032889830,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794032889830,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032889830,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032889846,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032889846,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1794032889846,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032889846,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -104,12 +104,12 @@ {"type":"step/start","data":{"turn":1,"step":19}} {"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890186,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890186,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032890186,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890186,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAccessibilityTree"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAccessibilityTree"}],"isError":true,"id":"{{message:41}}"},"error":{"name":"NativeError","code":"STALE_SNAPSHOT"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} {"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890203,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890203,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794032890203,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890203,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"},"error":{"name":"NativeError","code":"STALE_SNAPSHOT"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} {"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890219,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890219,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1794032890219,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890219,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -139,22 +139,22 @@ {"type":"step/start","data":{"turn":1,"step":26}} {"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890301,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890301,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1794032890301,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890301,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} {"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890319,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890319,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1794032890319,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890319,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} {"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890336,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890336,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1794032890336,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890336,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} {"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890353,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890353,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1794032890353,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890353,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} {"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890372,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890372,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794032890372,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890372,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -174,7 +174,7 @@ {"type":"step/start","data":{"turn":1,"step":33}} {"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890424,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890424,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032890424,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890424,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"},"error":{"name":"NativeError","code":"CAPTURE_BUSY"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} {"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890441,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890441,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032890441,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890441,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -224,7 +224,7 @@ {"type":"step/start","data":{"turn":1,"step":43}} {"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890662,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890662,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1794032890662,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890662,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-unavailable"},"toolCallId":"cua-hover-unavailable","content":[{"type":"text","text":"Error: HOVER_UNAVAILABLE: No AX alternate UI at this target. No input was sent and the pointer did not move."}],"isError":true,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-unavailable"},"toolCallId":"cua-hover-unavailable","content":[{"type":"text","text":"Error: HOVER_UNAVAILABLE: No AX alternate UI at this target. No input was sent and the pointer did not move."}],"isError":true,"id":"{{message:89}}"},"error":{"name":"NativeError","code":"HOVER_UNAVAILABLE"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} {"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-explicit-pointer-move","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true,\"useSystemPointer\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890679,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890679,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-explicit-pointer-move","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true,\"useSystemPointer\":true}}"}}},{"type":"chunk","time":1794032890679,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890679,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -249,7 +249,7 @@ {"type":"step/start","data":{"turn":1,"step":48}} {"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890746,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890746,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1794032890746,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890747,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:99}}"},"error":{"name":"NativeError","code":"PASTE_NOT_CONSUMED"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} {"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890765,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890765,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032890765,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890765,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -284,12 +284,12 @@ {"type":"step/start","data":{"turn":1,"step":55}} {"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890862,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890862,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794032890862,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890862,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:113}}"},"error":{"name":"NativeError","code":"NATIVE_PROTOCOL"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} {"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032890881,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032890881,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1794032890881,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032890881,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:115}}"},"error":{"name":"NativeError","code":"APP_ACCESS_DENIED"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} {"type":"step/start","data":{"turn":1,"step":57}} {"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032891018,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032891018,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1794032891018,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032891018,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -299,7 +299,7 @@ {"type":"step/start","data":{"turn":1,"step":58}} {"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032891165,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794032891165,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1794032891165,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032891165,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:119}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REVOKED"}},"sourceEventSeqs":[299],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":58}} {"type":"step/start","data":{"turn":1,"step":59}} {"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794032891180,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794032891180,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1794032891180,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794032891180,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-cc-posttool-block/session.v4.jsonl b/snapshots/session/hook-cc-posttool-block/session.v4.jsonl index a1e627dea7..67e8f5a68d 100644 --- a/snapshots/session/hook-cc-posttool-block/session.v4.jsonl +++ b/snapshots/session/hook-cc-posttool-block/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"echo HELLO","startedAt":1791427832187,"toolCall":{"callId":"call_00_VAByyMjsct4c7P6k1ysX9256","rootCallId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"finishedAt":1791427832190,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"claude-code","handlerId":"claude-code:PostToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"claude-code:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by policy: retry once","durationMs":7.767333000000008}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","content":[{"type":"text","text":"tool output rejected by policy: retry once"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","content":[{"type":"text","text":"tool output rejected by policy: retry once"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The first call was rejected by policy. The user said to retry once. Let me retry."},{"type":"tool-call","id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Echo HELLO to stdout\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":59,"outputTokens":89,"cacheReadTokens":3328,"reasoningTokens":21},"stream":[{"type":"chunk","time":1791427832215,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791427832215,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," first"," call"," was"," rejected"," by"," policy","."," The"," user"," said"," to"," ret","ry"," once","."," Let"," me"," ret","ry","."]},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427832215,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","args":["","{","\"","command","\"",": ","\"","echo"," HE","LL","O","\"",", ","\"","description","\"",": ","\"","E","cho"," HE","LL","O"," to"," stdout","\"","}"]},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The first call was rejected by policy. The user said to retry once. Let me retry."}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Echo HELLO to stdout\"}"}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"usage","usage":{"inputTokens":59,"outputTokens":89,"cacheReadTokens":3328,"reasoningTokens":21}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl b/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl index 8351089e37..7f3c3460fd 100644 --- a/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl +++ b/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_JliP571Bh0QQ8QExbSPk0080","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"claude-code","handlerId":"claude-code:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"claude-code:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by policy in this session","durationMs":4.3560419999998885}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."},{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21},"stream":[{"type":"chunk","time":1788699376419,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699376419,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy","."," I"," need"," to"," report"," this"," error"," verb","atim"," back"," to"," the"," user","."]},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699376419,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," returned",":\n\n",">"," Error",":"," bash"," is"," disabled"," by"," policy"," in"," this"," session","\n\n","I"," cannot"," run"," the"," command"," because"," the"," bash"," tool"," is"," disabled"," by"," policy","."]},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"usage","usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-codex-posttool-block/session.v4.jsonl b/snapshots/session/hook-codex-posttool-block/session.v4.jsonl index d5ac303791..8b28942d0e 100644 --- a/snapshots/session/hook-codex-posttool-block/session.v4.jsonl +++ b/snapshots/session/hook-codex-posttool-block/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"echo HELLO","startedAt":1791427839150,"toolCall":{"callId":"call_00_1rmSWHhVchVg7PDTmegT0421","rootCallId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"finishedAt":1791427839153,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"codex","handlerId":"codex:PostToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"codex:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by codex policy: summarize instead","durationMs":3.2890840000000026}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The tool output was rejected by codex policy. Let me quote what I got back."},{"type":"text","text":"```\ntool output rejected by codex policy: summarize instead\n```"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":44,"outputTokens":39,"cacheReadTokens":3328,"reasoningTokens":18},"stream":[{"type":"chunk","time":1791427839171,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791427839171,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," output"," was"," rejected"," by"," code","x"," policy","."," Let"," me"," quote"," what"," I"," got"," back","."]},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791427839171,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["```\n","<","tool","_result",">","tool"," output"," rejected"," by"," code","x"," policy",":"," summarize"," instead","\n","```"]},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The tool output was rejected by codex policy. Let me quote what I got back."}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"```\ntool output rejected by codex policy: summarize instead\n```"}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"usage","usage":{"inputTokens":44,"outputTokens":39,"cacheReadTokens":3328,"reasoningTokens":18}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-codex-pretool-block/session.v4.jsonl b/snapshots/session/hook-codex-pretool-block/session.v4.jsonl index db5b065f89..fba7fa8a20 100644 --- a/snapshots/session/hook-codex-pretool-block/session.v4.jsonl +++ b/snapshots/session/hook-codex-pretool-block/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_tv0SMeLXaTuyuVrOxnV97085","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"codex","handlerId":"codex:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"codex:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by codex policy in this session","durationMs":4.577334000000064}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_tv0SMeLXaTuyuVrOxnV97085"},"toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","content":[{"type":"text","text":"Error: bash is disabled by codex policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_tv0SMeLXaTuyuVrOxnV97085"},"toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","content":[{"type":"text","text":"Error: bash is disabled by codex policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The bash tool is disabled by policy in this session. I need to report this result verbatim to the user."},{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash is disabled by codex policy in this session\n```"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":171,"outputTokens":49,"cacheReadTokens":2816,"reasoningTokens":23},"stream":[{"type":"chunk","time":1788699385953,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699385953,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy"," in"," this"," session","."," I"," need"," to"," report"," this"," result"," verb","atim"," to"," the"," user","."]},{"type":"chunk","time":1788699385953,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699385953,"index":1,"dt":[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," result"," I"," got"," back"," verb","atim"," is",":\n\n","```\n","Error",":"," bash"," is"," disabled"," by"," code","x"," policy"," in"," this"," session","\n","```"]},{"type":"chunk","time":1788699385954,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy in this session. I need to report this result verbatim to the user."}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash is disabled by codex policy in this session\n```"}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"usage","usage":{"inputTokens":171,"outputTokens":49,"cacheReadTokens":2816,"reasoningTokens":23}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/packed-chunks/writer.expected.jsonl b/snapshots/session/packed-chunks/writer.expected.jsonl index 15643d81a2..d7a236f20c 100644 --- a/snapshots/session/packed-chunks/writer.expected.jsonl +++ b/snapshots/session/packed-chunks/writer.expected.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_JliP571Bh0QQ8QExbSPk0080","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"claude-code","handlerId":"claude-code:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"claude-code:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by policy in this session","durationMs":4.6690830000000005}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."},{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21},"stream":[{"type":"chunk","time":1793597716898,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793597716898,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy","."," I"," need"," to"," report"," this"," error"," verb","atim"," back"," to"," the"," user","."]},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793597716899,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," returned",":\n\n",">"," Error",":"," bash"," is"," disabled"," by"," policy"," in"," this"," session","\n\n","I"," cannot"," run"," the"," command"," because"," the"," bash"," tool"," is"," disabled"," by"," policy","."]},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"usage","usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} From 44b38cf77542d974010d62022a22bb8db2e5dd8e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:48:43 +0800 Subject: [PATCH 26/68] refactor(cua): report request refinement failures with prettified issues Refs #7869 --- packages/experimental/cua/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 48f31d9a46..7d85bf1fe0 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -95,7 +95,7 @@ function executionAgent(execution: Readonly): Agent { /** Parse the tool request; refinements the parameter schema cannot express fail as argument errors. */ function parseRequest(schema: z.ZodType, args: unknown): T { const parsed = schema.safeParse(args) - if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => `${issue.path.join('.') || ''}: ${issue.message}`)) + if (!parsed.success) throw new ToolArgsError([z.prettifyError(parsed.error)]) return parsed.data } From da75bed05f3da201c8e6b65cb049dad30c97c522 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:48:44 +0800 Subject: [PATCH 27/68] test(worktree): cover classified and cancelled retained-artifact failures Refs #7869 --- .../worktree/tests/worktree.spec.ts | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index 0cc9b3bf6b..e2da8a2268 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -5,6 +5,7 @@ import { pathToFileURL } from 'node:url' import { pluginRecordOf } from '@deepseek-ai/dsh-session' import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' +import { FsError } from '@deepseek-ai/dsh-fs' import WorktreeService from '../src/index.ts' import type { RestoreWorktreeRequest } from '../src/index.ts' import { contents, git, harness, repository, testAgent } from './harness.ts' @@ -304,14 +305,17 @@ describe('creating and entering retained worktrees', () => { expect(await readdir(join(root, '.agents/worktrees'))).toEqual(['occupied']) }) - it('retains the checkout and branch if publishing the new cwd fails', async () => { + it.each([ + ['an unclassified failure', new Error('directory publication failed'), { name: 'Error' }], + ['a classified failure', new FsError('directory publication failed', 'FS_NOT_FOUND'), { name: 'FsError', code: 'FS_NOT_FOUND' }], + ])('retains the checkout and branch if publishing the new cwd fails with %s', async (_label, failure, identity) => { const root = await repo() ctx = await harness(root) const agent = testAgent(ctx, root) await ctx.workingDirectory.ensure(agent) - vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(new Error('directory publication failed')) + vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(failure) await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toMatchObject({ - name: 'Error', message: expect.stringContaining('Any created checkout and branch are retained') as string, + ...identity, message: expect.stringContaining('Any created checkout and branch are retained') as string, }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'branch', '--list', 'retained')).toContain('retained') @@ -382,6 +386,24 @@ describe('creating and entering retained worktrees', () => { expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) }) + it.each([ + ['a separate AbortError', () => new DOMException('publication aborted', 'AbortError'), 'AbortError'], + ['a distinct failure', () => new Error('publication failed during cancellation'), 'Error'], + ])('classifies %s thrown after caller cancellation', async (_label, failure, name) => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + await ctx.workingDirectory.ensure(agent) + const controller = new AbortController() + vi.spyOn(ctx.workingDirectory, 'set').mockImplementationOnce(() => { + controller.abort('caller stopped') + return Promise.reject(failure()) + }) + await expect(ctx.worktrees.create(agent, { name: 'cancelled-publication' }, controller.signal)).rejects.toMatchObject({ + name, message: expect.stringContaining('Any created checkout and branch are retained') as string, + }) + }) + it('retains a caller cancellation reason when allocation is cancelled before its child starts', async () => { const root = await repo() ctx = await harness(root) From fa02022df39f202a2285969e4677a24a38eb8f46 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:52:29 +0800 Subject: [PATCH 28/68] chore(deps): classify HarnessError and tool error exports as peer-required CUA and Liveshare now import HarnessError and the tool registry's error classes at runtime; tool failures keep their identity only when these resolve to the registry's own peer instance. Refs #7869 --- scripts/package-dependency-policy.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 4ad6448e20..3e6ae6d4cb 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -91,10 +91,14 @@ const PEER_REQUIRED_HOST_EXPORTS = { '@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName', 'CREATED_RECORD', 'createdWorktreeSchema'], // The forge panel matches ctx.fs failures with `instanceof FsError`. '@deepseek-ai/dsh-fs': ['FsError'], + // The tool registry records a failure's name and code only for `instanceof HarnessError`. + '@deepseek-ai/dsh-llm': ['HarnessError'], '@deepseek-ai/dsh-scope': ['carrierKeyOf', 'createScope', 'scopeOf', 'scopeTarget'], // appendPluginRecord writes through the Session class's private log; pluginRecordOf is stateless. '@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'], '@deepseek-ai/dsh-session-persistence': ['SessionPersistenceNotFoundError'], + // Tool failures from CUA and Liveshare carry the registry's own error classes and cancellation code. + '@deepseek-ai/dsh-tools': ['TOOL_ABORTED', 'ToolArgsError', 'ToolContextUnavailableError'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. '@deepseek-ai/dsh-timeout': ['deadline'], } as const satisfies HostDependencyExports From da34438d1a4290b560b89164b2ed92e477472380 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:52:30 +0800 Subject: [PATCH 29/68] docs: regenerate config and Cordis catalogs Refs #7869 --- docs/config-catalog.md | 12 ++++++------ docs/config-catalog.zh.md | 12 ++++++------ docs/subsystems/worktrees.md | 4 ++++ docs/subsystems/worktrees.zh.md | 4 ++++ packages/extensions/tool-cordis/src/api-catalog.ts | 2 ++ 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 19b1bb2f25..3fb3f49217 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -987,7 +987,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:28`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:31`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1471,7 +1471,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1559,7 +1559,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1722,7 +1722,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1761,7 +1761,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4453,7 +4453,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:57`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 833ddbce39..19a4e87d53 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -989,7 +989,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:28`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:31`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1473,7 +1473,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1561,7 +1561,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1724,7 +1724,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1763,7 +1763,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4455,7 +4455,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:57`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index dff4b4a63c..a837e99625 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. + * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out + * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; it must not throw. * @returns the directory and whether the branch was created again. + * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, + * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index 51cbf41431..3d2b4d7286 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. + * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out + * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; it must not throw. * @returns the directory and whether the branch was created again. + * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, + * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 1dadef01ab..528ff7d55d 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4835,12 +4835,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.', parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name and local revision; defaults are generated name and HEAD.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], returns: 'canonical checkout path, branch name, pinned commit, and source repository root.', + throws: ['{WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, { signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Only the missing target\'s unlocked registration is removed, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.', parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], returns: 'the directory and whether the branch was created again.', + throws: ['{WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, { signature: 'async cleanupOf(session: Session, revision: number | null): Promise', From de3370cfc8978ac335d92c5bb379b650d962fa84 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 22:06:32 +0800 Subject: [PATCH 30/68] refactor(experimental): keep error code lists off plugin entries verify-plugin-entry-exports rejects new value exports from a plugin entry, so the stagehand, cua-driver, subagent-oar, ralph, and worktree entries export only their error classes and code types; the closed code lists stay in internal modules and READMEs name the codes directly. RalphError moves to its own module. Refs #7869 --- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- .../README.i18n.yaml | 4 +- .../browser-use-stagehand-native/README.md | 2 +- .../browser-use-stagehand-native/README.zh.md | 2 +- .../browser-use-stagehand-native/src/index.ts | 2 +- .../src/index.ts | 2 +- .../subagent-oar/README.i18n.yaml | 4 +- packages/experimental/subagent-oar/README.md | 2 +- .../experimental/subagent-oar/README.zh.md | 2 +- .../experimental/subagent-oar/src/index.ts | 2 +- .../experimental/tool-ralph/README.i18n.yaml | 4 +- packages/experimental/tool-ralph/README.md | 2 +- packages/experimental/tool-ralph/README.zh.md | 2 +- packages/experimental/tool-ralph/src/error.ts | 39 ++++++++++++++++++ packages/experimental/tool-ralph/src/index.ts | 40 ++----------------- packages/experimental/worktree/src/index.ts | 2 +- 17 files changed, 63 insertions(+), 56 deletions(-) create mode 100644 packages/experimental/tool-ralph/src/error.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3fb3f49217..d7fdc650b0 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4453,7 +4453,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:57`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:25`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -4606,7 +4606,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-terminal` - `inject`: `terminals` · `tools` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/experimental/tool-terminal/src/index.ts:38`](../packages/experimental/tool-terminal/src/index.ts) +- `source`: [`packages/experimental/tool-terminal/src/index.ts:39`](../packages/experimental/tool-terminal/src/index.ts) ```ts config-catalog /** Model-facing terminal tool configuration. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 19a4e87d53..4216b20b96 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4455,7 +4455,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:57`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:25`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -4608,7 +4608,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-terminal` - `inject`: `terminals` · `tools` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/experimental/tool-terminal/src/index.ts:38`](../packages/experimental/tool-terminal/src/index.ts) +- `source`: [`packages/experimental/tool-terminal/src/index.ts:39`](../packages/experimental/tool-terminal/src/index.ts) ```ts config-catalog /** Model-facing terminal tool configuration. */ diff --git a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml index 2468113b23..1ed9d62414 100644 --- a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml +++ b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml @@ -24,8 +24,8 @@ en: fea3ad16a77fc478 zh: cf551a8a2d183f93 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/understand-the-implementation: - en: 649a4ff1f1e46827 - zh: 1a1b929b9208388a + en: 73d71db97181cced + zh: b399d77fd05fbdb2 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/further-exploration: en: eff8f4541eb26ca7 zh: 76a61fe9bd48df2a diff --git a/packages/experimental/browser-use-stagehand-native/README.md b/packages/experimental/browser-use-stagehand-native/README.md index e280c1f1ba..2acddfa04c 100644 --- a/packages/experimental/browser-use-stagehand-native/README.md +++ b/packages/experimental/browser-use-stagehand-native/README.md @@ -89,7 +89,7 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite The host owns each launched Chromium process and its temporary profile before waiting for CDP readiness. Chromium receives the standard scrubbed child environment, preserving paths, locale, and proxy settings while excluding credential-shaped variables and DSH identity. Both modes connect the SDK inside a dedicated Worker. The Worker receives no ambient environment except the explicit source TypeScript configuration path, so its CDP connection does not inherit host proxy settings. SDK close waits for active operations. Cleanup terminates the connection Worker after the configured SDK grace; launch also kills and awaits its owned Chromium process before removing the profile. Attached external browsers remain open. Cleanup failures follow the [ownership limits](#known-limitations-and-deferred-work) below. -Failed calls carry `error.name` and `error.code` on `tool/result`. The host validates arguments before dispatch and rejects ones the method's schema refuses with `ToolArgsError` (`INVALID_ARGS`); a call without an exact live Agent fails with `ToolContextUnavailableError`, and ownership failures use the runtime's `BrowserSessionError` codes. Other failures throw `StagehandError`, exported with its closed `STAGEHAND_ERROR_CODES` list: `STAGEHAND_ACT_FAILED` when Stagehand reports an unsuccessful action, `STAGEHAND_TAB_NOT_FOUND` for an unavailable tab, `STAGEHAND_OPERATION_FAILED` for any other SDK or browser failure, `STAGEHAND_WORKER_FAILED` when the Worker exits, closes, or breaks the message protocol, and `STAGEHAND_CLEANUP_FAILED` from the `StagehandDrainError` subclass when SDK requests do not drain. Worker replies carry a `StagehandError`'s name and code beside its message, and the host rebuilds the same code; any other Worker failure, including an unknown name or code, becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. +Failed calls carry `error.name` and `error.code` on `tool/result`. The host validates arguments before dispatch and rejects ones the method's schema refuses with `ToolArgsError` (`INVALID_ARGS`); a call without an exact live Agent fails with `ToolContextUnavailableError`, and ownership failures use the runtime's `BrowserSessionError` codes. Other failures throw `StagehandError` with a closed set of codes: `STAGEHAND_ACT_FAILED` when Stagehand reports an unsuccessful action, `STAGEHAND_TAB_NOT_FOUND` for an unavailable tab, `STAGEHAND_OPERATION_FAILED` for any other SDK or browser failure, `STAGEHAND_WORKER_FAILED` when the Worker exits, closes, or breaks the message protocol, and `STAGEHAND_CLEANUP_FAILED` from the `StagehandDrainError` subclass when SDK requests do not drain. Worker replies carry a `StagehandError`'s name and code beside its message, and the host rebuilds the same code; any other Worker failure, including an unknown name or code, becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. The [native runtime](src/native.ts) passes the explicit model configuration to Stagehand's public initialization API. The adapter pins Zod to the version required by Stagehand because extraction passes Zod schemas to the SDK. Stagehand owns the model requests, response validation, and token accounting inside its browser extension. DSH records browser tool inputs and returned data, including SDK result metadata, through the existing Session log. Underlying inference request/response capture and integration into DSH Session usage accounting are deferred. diff --git a/packages/experimental/browser-use-stagehand-native/README.zh.md b/packages/experimental/browser-use-stagehand-native/README.zh.md index 3f5bb0c538..efa263afe5 100644 --- a/packages/experimental/browser-use-stagehand-native/README.zh.md +++ b/packages/experimental/browser-use-stagehand-native/README.zh.md @@ -89,7 +89,7 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite 宿主在等待 CDP 就绪前即拥有启动的 Chromium 进程及其临时配置目录。Chromium 接收标准清理后的子进程环境,保留路径、区域设置和代理配置,排除凭据形式的变量及 DSH 身份信息。两种模式都在独立 Worker 中连接 SDK。Worker 除显式的源码 TypeScript 配置路径外不接收宿主环境,因此其 CDP 连接不继承宿主代理设置。SDK 关闭会等待活动操作。清理在配置的 SDK 宽限时间后终止连接 Worker;启动模式还会终止并等待自有 Chromium 进程退出,再移除配置目录。外部连接的浏览器保持运行。清理失败遵循下方的[所有权限制](#known-limitations-and-deferred-work)。 -失败调用在 `tool/result` 上带有 `error.name` 与 `error.code`。宿主在派发前验证参数,方法 schema 拒绝的参数以 `ToolArgsError`(`INVALID_ARGS`)失败;没有确切实时 Agent 的调用以 `ToolContextUnavailableError` 失败,所有权失败使用运行时库的 `BrowserSessionError` 代码。其他失败抛出 `StagehandError`,与封闭的 `STAGEHAND_ERROR_CODES` 列表一同导出:Stagehand 报告动作未成功时为 `STAGEHAND_ACT_FAILED`,标签页不可用时为 `STAGEHAND_TAB_NOT_FOUND`,其他 SDK 或浏览器失败为 `STAGEHAND_OPERATION_FAILED`,Worker 退出、关闭或违反消息协议时为 `STAGEHAND_WORKER_FAILED`,SDK 请求未能结束时由 `StagehandDrainError` 子类给出 `STAGEHAND_CLEANUP_FAILED`。Worker 回复在消息旁携带 `StagehandError` 的名称和代码,宿主据此重建相同代码;其他 Worker 失败,包括未知名称或代码,以 Worker 的消息成为 `STAGEHAND_OPERATION_FAILED`。 +失败调用在 `tool/result` 上带有 `error.name` 与 `error.code`。宿主在派发前验证参数,方法 schema 拒绝的参数以 `ToolArgsError`(`INVALID_ARGS`)失败;没有确切实时 Agent 的调用以 `ToolContextUnavailableError` 失败,所有权失败使用运行时库的 `BrowserSessionError` 代码。其他失败抛出 `StagehandError`,其代码为封闭集合:Stagehand 报告动作未成功时为 `STAGEHAND_ACT_FAILED`,标签页不可用时为 `STAGEHAND_TAB_NOT_FOUND`,其他 SDK 或浏览器失败为 `STAGEHAND_OPERATION_FAILED`,Worker 退出、关闭或违反消息协议时为 `STAGEHAND_WORKER_FAILED`,SDK 请求未能结束时由 `StagehandDrainError` 子类给出 `STAGEHAND_CLEANUP_FAILED`。Worker 回复在消息旁携带 `StagehandError` 的名称和代码,宿主据此重建相同代码;其他 Worker 失败,包括未知名称或代码,以 Worker 的消息成为 `STAGEHAND_OPERATION_FAILED`。 [原生运行时](src/native.ts)将显式模型配置传入 Stagehand 的公开初始化 API。适配器将 Zod 固定为 Stagehand 要求的版本,因为提取操作会向 SDK 传递 Zod schema。Stagehand 在其浏览器扩展中负责模型请求、响应验证与 token 计量。DSH 通过现有 Session 日志记录浏览器工具输入和返回数据,包括 SDK 结果元数据。底层推理请求/响应捕获及其与 DSH Session 用量计量的集成均属暂缓工作。 diff --git a/packages/experimental/browser-use-stagehand-native/src/index.ts b/packages/experimental/browser-use-stagehand-native/src/index.ts index b167bbc567..7555ba4e14 100644 --- a/packages/experimental/browser-use-stagehand-native/src/index.ts +++ b/packages/experimental/browser-use-stagehand-native/src/index.ts @@ -19,7 +19,7 @@ import type {} from '@deepseek-ai/dsh-browser-use' import type {} from '@deepseek-ai/dsh-system-prompt' import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' -export { STAGEHAND_ERROR_CODES, StagehandDrainError, StagehandError, type StagehandErrorCode } from './error.ts' +export { StagehandDrainError, StagehandError, type StagehandErrorCode } from './error.ts' /** Cordis identity for the native Stagehand provider. */ export const name = 'experimental-browser-use-stagehand-native' diff --git a/packages/experimental/computer-use-cua-driver-native/src/index.ts b/packages/experimental/computer-use-cua-driver-native/src/index.ts index f1323c2e8d..49ce130f60 100644 --- a/packages/experimental/computer-use-cua-driver-native/src/index.ts +++ b/packages/experimental/computer-use-cua-driver-native/src/index.ts @@ -14,7 +14,7 @@ import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tools' import { CuaDriverError } from './error.ts' -export { CUA_DRIVER_ERROR_CODES, CuaDriverError, type CuaDriverErrorCode } from './error.ts' +export { CuaDriverError, type CuaDriverErrorCode } from './error.ts' /** Cordis plugin identity for the native Cua Driver provider. */ export const name = 'experimental-computer-use-cua-driver-native' diff --git a/packages/experimental/subagent-oar/README.i18n.yaml b/packages/experimental/subagent-oar/README.i18n.yaml index 2e84d2d507..d090889de6 100644 --- a/packages/experimental/subagent-oar/README.i18n.yaml +++ b/packages/experimental/subagent-oar/README.i18n.yaml @@ -27,8 +27,8 @@ en: cfc28b43567604a6 zh: 04ef0d698c3b47f7 /deepseek-ai-dsh-experimental-subagent-oar/understand-the-implementation: - en: a4796b50843f54b1 - zh: 388e911d67c62249 + en: e5ce31f92e58083e + zh: f0c6a7ac7001cd16 /deepseek-ai-dsh-experimental-subagent-oar/further-exploration: en: 089fe63b9b457247 zh: 482382e68e5c4e2e diff --git a/packages/experimental/subagent-oar/README.md b/packages/experimental/subagent-oar/README.md index 74131a2d5f..38fbf04620 100644 --- a/packages/experimental/subagent-oar/README.md +++ b/packages/experimental/subagent-oar/README.md @@ -104,7 +104,7 @@ The example mounts two instances of the same provider and the [external delegati The dependency patch applies environment overrides to native installation probes. It permits Claude's explicit `--permission-mode` and suppresses OAR's forced permission bypass when that argument is present. The example passes `--permission-mode dontAsk --permission-prompts none`. Codex receives `-c sandbox_mode="workspace-write"`. OAR sets Codex approval policy to `never`. Neither path forwards native approval requests to a DSH interaction UI. Codex startup failure stops app-server and waits for its exit, including a response without a thread id. -Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. Provider failures throw `OarFailure` with a `code` from `OAR_FAILURE_CODES`: `OAR_INVALID_TASK` for an empty or non-text task, `OAR_RUNTIME_UNAVAILABLE` for a missing, unsupported, or unprobeable runtime, `OAR_START_FAILED` for session startup, and `OAR_DISPOSE_FAILED` for session disposal; `OAR_TURN_FAILED` and `OAR_ABORT_FAILED` classify turn and interruption failures reported to the observer. Cancellation before the run starts rejects with an `AbortError` whose `code` is `ABORTED`. +Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. Provider failures throw `OarFailure` with a closed `code`: `OAR_INVALID_TASK` for an empty or non-text task, `OAR_RUNTIME_UNAVAILABLE` for a missing, unsupported, or unprobeable runtime, `OAR_START_FAILED` for session startup, and `OAR_DISPOSE_FAILED` for session disposal; `OAR_TURN_FAILED` and `OAR_ABORT_FAILED` classify turn and interruption failures reported to the observer. Cancellation before the run starts rejects with an `AbortError` whose `code` is `ABORTED`. diff --git a/packages/experimental/subagent-oar/README.zh.md b/packages/experimental/subagent-oar/README.zh.md index 09d2a0db76..f82726ff29 100644 --- a/packages/experimental/subagent-oar/README.zh.md +++ b/packages/experimental/subagent-oar/README.zh.md @@ -104,7 +104,7 @@ kind: "package-reference" 依赖补丁对原生安装探测应用环境覆盖,并允许 Claude 显式使用 `--permission-mode`,并在存在该参数时关闭 OAR 强制的权限绕过。示例传入 `--permission-mode dontAsk --permission-prompts none`。Codex 接收 `-c sandbox_mode="workspace-write"`。OAR 将 Codex 审批策略设为 `never`。两条路径均不将原生审批请求转发到 DSH 交互界面。Codex 启动失败时会停止 app-server 并等待其退出,包括响应中缺少线程 id 的情况。 -只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 取自 `OAR_FAILURE_CODES`:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 `code` 为 `ABORTED` 的 `AbortError` 拒绝。 +只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 为封闭集合:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 `code` 为 `ABORTED` 的 `AbortError` 拒绝。 diff --git a/packages/experimental/subagent-oar/src/index.ts b/packages/experimental/subagent-oar/src/index.ts index 47b6c846cc..6ea224c68e 100644 --- a/packages/experimental/subagent-oar/src/index.ts +++ b/packages/experimental/subagent-oar/src/index.ts @@ -16,7 +16,7 @@ import { import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { startOarRun, type OarRunSpec } from './run.ts' -export { OAR_FAILURE_CODES, OarFailure, type OarFailureCode } from './run.ts' +export { OarFailure, type OarFailureCode } from './run.ts' export const name = 'experimental-subagent-oar' export const inject = ['subagents'] diff --git a/packages/experimental/tool-ralph/README.i18n.yaml b/packages/experimental/tool-ralph/README.i18n.yaml index fa33b13562..22b7d8af28 100644 --- a/packages/experimental/tool-ralph/README.i18n.yaml +++ b/packages/experimental/tool-ralph/README.i18n.yaml @@ -18,8 +18,8 @@ en: 13380e1170c6a3b5 zh: 2f2665f2ee5ff6f7 /deepseek-ai-dsh-tool-ralph/use-this-package/calling-the-tool: - en: 69037b1ef1e2606b - zh: bbc39d5be9b86989 + en: 0c20532fc70c454e + zh: 19434818da6d244e /deepseek-ai-dsh-tool-ralph/use-this-package/what-each-round-sees: en: 2d8b861c4bcb9424 zh: 63c7b2d00c324727 diff --git a/packages/experimental/tool-ralph/README.md b/packages/experimental/tool-ralph/README.md index 44b646cf6f..e0841486fa 100644 --- a/packages/experimental/tool-ralph/README.md +++ b/packages/experimental/tool-ralph/README.md @@ -29,7 +29,7 @@ The `ralph` tool runs a fixed foreground loop: one fresh child per round works o ### Calling the tool -The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a code from `RALPH_ERROR_CODES`: `RALPH_ROUND_FAILED` for a failed child round, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. +The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a closed code: `RALPH_ROUND_FAILED` for a failed child round, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. ### What each round sees diff --git a/packages/experimental/tool-ralph/README.zh.md b/packages/experimental/tool-ralph/README.zh.md index 11f7094616..35651684f8 100644 --- a/packages/experimental/tool-ralph/README.zh.md +++ b/packages/experimental/tool-ralph/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 调用工具 -模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 取自 `RALPH_ERROR_CODES`:子 agent Round 失败为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 +模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 为封闭集合:子 agent Round 失败为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 ### 每个 Round 看到什么 diff --git a/packages/experimental/tool-ralph/src/error.ts b/packages/experimental/tool-ralph/src/error.ts new file mode 100644 index 0000000000..5b0b1cb10e --- /dev/null +++ b/packages/experimental/tool-ralph/src/error.ts @@ -0,0 +1,39 @@ +/** Machine-routable Ralph loop failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link RalphError} code: + * - `RALPH_PROVIDER_UNAVAILABLE` — the configured subagent provider is not registered; load it or change `subagentProvider`. + * - `RALPH_PROVIDER_UNSUPPORTED` — the configured provider lacks structured output or inherits parent context; + * configure a fresh structured-output provider. + * - `RALPH_WORKFLOW_FAILED` — the fixed workflow ended with an error or was cancelled without caller cancellation; report the message. + * - `RALPH_INVALID_RESULT` — the fixed workflow returned a malformed report or terminal value; do not trust the result. + * - `RALPH_ROUND_FAILED` — a round's child failed before producing a structured report; the message carries the last handoff. + */ +export const RALPH_ERROR_CODES = [ + 'RALPH_PROVIDER_UNAVAILABLE', + 'RALPH_PROVIDER_UNSUPPORTED', + 'RALPH_WORKFLOW_FAILED', + 'RALPH_INVALID_RESULT', + 'RALPH_ROUND_FAILED', +] as const + +/** One code from {@link RALPH_ERROR_CODES}. */ +export type RalphErrorCode = typeof RALPH_ERROR_CODES[number] + +/** Ralph loop failure carrying a stable {@link RalphErrorCode}. */ +export class RalphError extends HarnessError { + override readonly code: RalphErrorCode + + /** + * @param message - parent-facing failure text. + * @param code - failure class. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: RalphErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'RalphError' + this.code = code + } +} diff --git a/packages/experimental/tool-ralph/src/index.ts b/packages/experimental/tool-ralph/src/index.ts index d942ec3548..75d36b3e87 100644 --- a/packages/experimental/tool-ralph/src/index.ts +++ b/packages/experimental/tool-ralph/src/index.ts @@ -7,7 +7,9 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { RalphError } from './error.ts' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' @@ -17,41 +19,7 @@ import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow' export const name = 'tool-ralph' export const inject = ['tools', 'workflowEngine', 'subagents', 'systemPrompt'] -/** - * Every {@link RalphError} code: - * - `RALPH_PROVIDER_UNAVAILABLE` — the configured subagent provider is not registered; load it or change `subagentProvider`. - * - `RALPH_PROVIDER_UNSUPPORTED` — the configured provider lacks structured output or inherits parent context; - * configure a fresh structured-output provider. - * - `RALPH_WORKFLOW_FAILED` — the fixed workflow ended with an error or was cancelled without caller cancellation; report the message. - * - `RALPH_INVALID_RESULT` — the fixed workflow returned a malformed report or terminal value; do not trust the result. - * - `RALPH_ROUND_FAILED` — a round's child failed before producing a structured report; the message carries the last handoff. - */ -export const RALPH_ERROR_CODES = [ - 'RALPH_PROVIDER_UNAVAILABLE', - 'RALPH_PROVIDER_UNSUPPORTED', - 'RALPH_WORKFLOW_FAILED', - 'RALPH_INVALID_RESULT', - 'RALPH_ROUND_FAILED', -] as const - -/** One code from {@link RALPH_ERROR_CODES}. */ -export type RalphErrorCode = typeof RALPH_ERROR_CODES[number] - -/** Ralph loop failure carrying a stable {@link RalphErrorCode}. */ -export class RalphError extends HarnessError { - override readonly code: RalphErrorCode - - /** - * @param message - parent-facing failure text. - * @param code - failure class. - * @param options - standard `cause` chaining. - */ - constructor(message: string, code: RalphErrorCode, options?: ErrorOptions) { - super(message, code, options) - this.name = 'RalphError' - this.code = code - } -} +export { RalphError, type RalphErrorCode } from './error.ts' /** Deployment policy for the fixed Ralph workflow. */ export interface Config { diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index e1da7dfa23..5de7e32034 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -33,7 +33,7 @@ export type { export { generatedWorktreeName } from './name.ts' export { CREATED_RECORD, createdWorktreeSchema, worktreeProjection } from './projection.ts' export type { WorktreeProjectionState } from './projection.ts' -export { WORKTREE_ERROR_CODES, WorktreeError, type WorktreeErrorCode } from './error.ts' +export { WorktreeError, type WorktreeErrorCode } from './error.ts' /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ export interface Config { From d93a16ac337c0bd7cd5703ae24819002cd81257f Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 22:06:33 +0800 Subject: [PATCH 31/68] refactor(experimental): import HarnessError from dsh-error Every HarnessError import this branch adds now comes from the dependency-free @deepseek-ai/dsh-error package, declared as a peer and dev dependency with its tsconfig reference; dsh-llm peers added only for the base class are dropped, and the dependency policy classifies the dsh-error export once. Refs #7869 --- docs/module-graph.md | 36 +++++++++++++------ docs/module-graph.zh.md | 36 +++++++++++++------ .../browser-use-runtime/package.json | 5 +-- .../browser-use-runtime/src/error.ts | 2 +- .../browser-use-runtime/src/index.ts | 2 +- .../browser-use-runtime/tsconfig.json | 2 +- .../browser-use-stagehand-native/package.json | 5 +-- .../browser-use-stagehand-native/src/error.ts | 2 +- .../tsconfig.json | 2 +- .../claude-code-mods/package.json | 6 ++-- .../claude-code-mods/src/host-ops.ts | 3 +- .../claude-code-mods/tsconfig.json | 3 ++ .../package.json | 5 +-- .../src/error.ts | 2 +- .../tsconfig.json | 2 +- packages/experimental/cua/package.json | 7 ++-- packages/experimental/cua/src/index.ts | 3 +- .../experimental/cua/src/native-client.ts | 2 +- .../cua/tests/native-client.spec.ts | 3 +- packages/experimental/cua/tsconfig.host.json | 3 ++ packages/experimental/liveshare/package.json | 7 ++-- .../liveshare/src/host/fork-errors.ts | 2 +- .../experimental/liveshare/tsconfig.host.json | 5 ++- .../experimental/subagent-oar/package.json | 6 ++-- packages/experimental/subagent-oar/src/run.ts | 3 +- .../experimental/subagent-oar/tsconfig.json | 3 ++ packages/experimental/tool-ralph/package.json | 6 ++-- .../experimental/tool-ralph/tsconfig.json | 3 ++ .../experimental/tool-terminal/package.json | 6 ++-- .../experimental/tool-terminal/src/index.ts | 3 +- .../experimental/tool-terminal/tsconfig.json | 3 ++ packages/experimental/worktree/src/error.ts | 2 +- pnpm-lock.yaml | 27 ++++++++++++++ scripts/package-dependency-policy.ts | 2 -- 34 files changed, 149 insertions(+), 60 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 7b28621265..2e71ff98d6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -500,7 +500,6 @@ flowchart TD pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths pkg_credentials_local --> pkg_launch_environment - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -959,8 +958,10 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use @@ -974,9 +975,11 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools pkg_experimental_cua_macos --> pkg_agent @@ -985,6 +988,10 @@ flowchart TD pkg_experimental_cua_macos --> pkg_system_prompt pkg_experimental_cua_macos --> pkg_tools pkg_experimental_cua_macos --> pkg_user_questions + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1000,6 +1007,7 @@ flowchart TD pkg_terminal_panel --> pkg_terminal pkg_terminal_panel --> pkg_tools pkg_tool_terminal --> pkg_agent + pkg_tool_terminal --> pkg_error pkg_tool_terminal --> pkg_jobs pkg_tool_terminal --> pkg_llm pkg_tool_terminal --> pkg_output_retention @@ -1270,6 +1278,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1277,6 +1286,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1289,6 +1299,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1433,10 +1444,12 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent pkg_experimental_subagent_oar --> pkg_subprocess + pkg_experimental_subagent_oar --> pkg_tools pkg_experimental_tool_subagent_oar --> pkg_subagent pkg_experimental_tool_subagent_oar --> pkg_tools pkg_experimental_tool_worktree --> pkg_experimental_worktree @@ -1449,6 +1462,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1705,7 +1719,6 @@ flowchart TD | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1831,16 +1844,17 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-cua-macos`](../packages/experimental/cua-macos) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) | | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | @@ -1885,9 +1899,9 @@ flowchart TD | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1906,11 +1920,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 4ddd93c256..989b3ab104 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -502,7 +502,6 @@ flowchart TD pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths pkg_credentials_local --> pkg_launch_environment - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -961,8 +960,10 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use @@ -976,9 +977,11 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools pkg_experimental_cua_macos --> pkg_agent @@ -987,6 +990,10 @@ flowchart TD pkg_experimental_cua_macos --> pkg_system_prompt pkg_experimental_cua_macos --> pkg_tools pkg_experimental_cua_macos --> pkg_user_questions + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1002,6 +1009,7 @@ flowchart TD pkg_terminal_panel --> pkg_terminal pkg_terminal_panel --> pkg_tools pkg_tool_terminal --> pkg_agent + pkg_tool_terminal --> pkg_error pkg_tool_terminal --> pkg_jobs pkg_tool_terminal --> pkg_llm pkg_tool_terminal --> pkg_output_retention @@ -1272,6 +1280,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1279,6 +1288,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1291,6 +1301,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1435,10 +1446,12 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent pkg_experimental_subagent_oar --> pkg_subprocess + pkg_experimental_subagent_oar --> pkg_tools pkg_experimental_tool_subagent_oar --> pkg_subagent pkg_experimental_tool_subagent_oar --> pkg_tools pkg_experimental_tool_worktree --> pkg_experimental_worktree @@ -1451,6 +1464,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1707,7 +1721,6 @@ flowchart TD | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1833,16 +1846,17 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-cua-macos`](../packages/experimental/cua-macos) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) | | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | @@ -1887,9 +1901,9 @@ flowchart TD | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1908,11 +1922,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index 44f3dcb82c..38d372eac0 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -43,7 +43,7 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -71,6 +71,7 @@ "@deepseek-ai/dsh-attachment-local": "workspace:*", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-fs-local": "workspace:*" + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/browser-use-runtime/src/error.ts b/packages/experimental/browser-use-runtime/src/error.ts index 857785f875..04ab420089 100644 --- a/packages/experimental/browser-use-runtime/src/error.ts +++ b/packages/experimental/browser-use-runtime/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable browser ownership failures. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link BrowserSessionError} code: diff --git a/packages/experimental/browser-use-runtime/src/index.ts b/packages/experimental/browser-use-runtime/src/index.ts index b2ac6b2872..9ce3e315e6 100644 --- a/packages/experimental/browser-use-runtime/src/index.ts +++ b/packages/experimental/browser-use-runtime/src/index.ts @@ -6,7 +6,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' import { BrowserSessionError } from './error.ts' diff --git a/packages/experimental/browser-use-runtime/tsconfig.json b/packages/experimental/browser-use-runtime/tsconfig.json index e1f7d1b38a..8bc88ea018 100644 --- a/packages/experimental/browser-use-runtime/tsconfig.json +++ b/packages/experimental/browser-use-runtime/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../core/tools" }, { - "path": "../../llm/llm" + "path": "../../util/error" }, { "path": "../../core/scope" diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index 1072476172..91bbf937dd 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -42,7 +42,7 @@ "@deepseek-ai/dsh-browser-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@browserbasehq/stagehand": "4.4.0", @@ -71,6 +71,7 @@ "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "tsx": "^4.23.13" + "tsx": "^4.23.13", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/browser-use-stagehand-native/src/error.ts b/packages/experimental/browser-use-stagehand-native/src/error.ts index b70b19cc98..e5db840212 100644 --- a/packages/experimental/browser-use-stagehand-native/src/error.ts +++ b/packages/experimental/browser-use-stagehand-native/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable Stagehand browser failures, shared by the host and its browser Worker. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link StagehandError} code: diff --git a/packages/experimental/browser-use-stagehand-native/tsconfig.json b/packages/experimental/browser-use-stagehand-native/tsconfig.json index b2fddda9b2..164d09e637 100644 --- a/packages/experimental/browser-use-stagehand-native/tsconfig.json +++ b/packages/experimental/browser-use-stagehand-native/tsconfig.json @@ -9,7 +9,7 @@ { "path": "../../core/agent" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, - { "path": "../../llm/llm" }, + { "path": "../../util/error" }, { "path": "../../mcp/mcp-client" }, { "path": "../../subprocess/subprocess" }, { "path": "../../util/values" }, diff --git a/packages/experimental/claude-code-mods/package.json b/packages/experimental/claude-code-mods/package.json index c2381389ae..ce87f9514b 100644 --- a/packages/experimental/claude-code-mods/package.json +++ b/packages/experimental/claude-code-mods/package.json @@ -74,7 +74,8 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -104,6 +105,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*" + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 1f314b93f2..2f22010ead 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -14,7 +14,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-subprocess' import type { CommandDefinition } from '@deepseek-ai/dsh-commands' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' -import { createUserMessage, HarnessError, ToolCallId } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' import type { WorkingDirectoryService } from '@deepseek-ai/dsh-working-directory' diff --git a/packages/experimental/claude-code-mods/tsconfig.json b/packages/experimental/claude-code-mods/tsconfig.json index 2b285b1ded..4d7e12e921 100644 --- a/packages/experimental/claude-code-mods/tsconfig.json +++ b/packages/experimental/claude-code-mods/tsconfig.json @@ -61,6 +61,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/computer-use-cua-driver-native/package.json b/packages/experimental/computer-use-cua-driver-native/package.json index b1c66876ce..43fc478322 100644 --- a/packages/experimental/computer-use-cua-driver-native/package.json +++ b/packages/experimental/computer-use-cua-driver-native/package.json @@ -36,7 +36,7 @@ "@deepseek-ai/dsh-computer-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-mcp-client": "workspace:*", @@ -60,6 +60,7 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/computer-use-cua-driver-native/src/error.ts b/packages/experimental/computer-use-cua-driver-native/src/error.ts index e6c2fe30c7..fac0c7a07a 100644 --- a/packages/experimental/computer-use-cua-driver-native/src/error.ts +++ b/packages/experimental/computer-use-cua-driver-native/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable Cua Driver SDK failures. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link CuaDriverError} code: diff --git a/packages/experimental/computer-use-cua-driver-native/tsconfig.json b/packages/experimental/computer-use-cua-driver-native/tsconfig.json index abc6329753..a78ee90ea3 100644 --- a/packages/experimental/computer-use-cua-driver-native/tsconfig.json +++ b/packages/experimental/computer-use-cua-driver-native/tsconfig.json @@ -11,7 +11,7 @@ { "path": "../../computer-use/computer-use" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, - { "path": "../../llm/llm" }, + { "path": "../../util/error" }, { "path": "../../mcp/mcp-client" } ] } diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 5e0c3bf604..09d57068d5 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -100,8 +100,8 @@ "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", @@ -163,7 +163,8 @@ "@deepseek-ai/dsh-storage-json": "workspace:*", "@deepseek-ai/dsh-client-ui-user-questions": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*" + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dsh": { "client": { diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 7d85bf1fe0..7c2fcc7c48 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -9,7 +9,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { ComputerUseProviderName } from '@deepseek-ai/dsh-computer-use/brand' import { admitEncodedImages } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index f723c237bd..667682ca81 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto' import assert from 'node:assert/strict' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index c6b9acdde0..b50cc12759 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -1,6 +1,7 @@ /** Controlled connection streams exercise the platform-independent native protocol client. */ import { PassThrough, Writable } from 'node:stream' -import { HarnessError, ToolCallId } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { ToolCallId } from '@deepseek-ai/dsh-llm' import type { NativeChannel } from '../src/native-client.ts' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { z } from 'zod' diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..4bf0b7ddda 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -74,6 +74,9 @@ }, { "path": "../../boot/config-editor" + }, + { + "path": "../../util/error" } ], "exclude": [ diff --git a/packages/experimental/liveshare/package.json b/packages/experimental/liveshare/package.json index e62fb0404f..bc3617b8d1 100644 --- a/packages/experimental/liveshare/package.json +++ b/packages/experimental/liveshare/package.json @@ -76,8 +76,8 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -150,7 +150,8 @@ "@deepseek-ai/dsh-workspace": "workspace:*", "@types/ws": "^8.18.1", "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-error": "workspace:*" }, "dsh": { "bundle": { diff --git a/packages/experimental/liveshare/src/host/fork-errors.ts b/packages/experimental/liveshare/src/host/fork-errors.ts index 472432b337..a62dac482a 100644 --- a/packages/experimental/liveshare/src/host/fork-errors.ts +++ b/packages/experimental/liveshare/src/host/fork-errors.ts @@ -1,6 +1,6 @@ /** Structured refusals of tool use by a forked or shared Session's viewer-driven turns. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link LiveshareForkDeniedError} code: diff --git a/packages/experimental/liveshare/tsconfig.host.json b/packages/experimental/liveshare/tsconfig.host.json index 193a22ba67..3db1885611 100644 --- a/packages/experimental/liveshare/tsconfig.host.json +++ b/packages/experimental/liveshare/tsconfig.host.json @@ -32,6 +32,9 @@ { "path": "../../session/session-projection" }, { "path": "../liveshare-protocol/tsconfig.host.json" }, { "path": "../../client/modules" }, - { "path": "../../host/frontend-static" } + { "path": "../../host/frontend-static" }, + { + "path": "../../util/error" + } ] } diff --git a/packages/experimental/subagent-oar/package.json b/packages/experimental/subagent-oar/package.json index e2691b75e0..1e12579aeb 100644 --- a/packages/experimental/subagent-oar/package.json +++ b/packages/experimental/subagent-oar/package.json @@ -40,7 +40,8 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -71,6 +72,7 @@ "@deepseek-ai/dsh-tool-jobs": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", - "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*" + "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/subagent-oar/src/run.ts b/packages/experimental/subagent-oar/src/run.ts index 41eef568ef..1305a5d17c 100644 --- a/packages/experimental/subagent-oar/src/run.ts +++ b/packages/experimental/subagent-oar/src/run.ts @@ -16,7 +16,8 @@ import type { } from '@botiverse/oar' import { awaitTurnEnd } from '@botiverse/oar/observe' import { brandString } from '@deepseek-ai/dsh-brand' -import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertUsableCwd, diff --git a/packages/experimental/subagent-oar/tsconfig.json b/packages/experimental/subagent-oar/tsconfig.json index 648ba044ab..2fe8a20db4 100644 --- a/packages/experimental/subagent-oar/tsconfig.json +++ b/packages/experimental/subagent-oar/tsconfig.json @@ -40,6 +40,9 @@ }, { "path": "../../core/tools" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/tool-ralph/package.json b/packages/experimental/tool-ralph/package.json index 3c0e7e9d78..5a587189ae 100644 --- a/packages/experimental/tool-ralph/package.json +++ b/packages/experimental/tool-ralph/package.json @@ -38,7 +38,8 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-workflow": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -60,6 +61,7 @@ "@deepseek-ai/dsh-workflow": "workspace:*", "@deepseek-ai/dsh-workflow-ptc": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-session-projection": "workspace:*" + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/tool-ralph/tsconfig.json b/packages/experimental/tool-ralph/tsconfig.json index 77ebc9e761..148e3f53b6 100644 --- a/packages/experimental/tool-ralph/tsconfig.json +++ b/packages/experimental/tool-ralph/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../workflow/workflow" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/tool-terminal/package.json b/packages/experimental/tool-terminal/package.json index fabe723ad9..1992387595 100644 --- a/packages/experimental/tool-terminal/package.json +++ b/packages/experimental/tool-terminal/package.json @@ -43,7 +43,8 @@ "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis-plugin-include": "workspace:~", @@ -68,6 +69,7 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-session-projection": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/tool-terminal/src/index.ts b/packages/experimental/tool-terminal/src/index.ts index 5133ba9490..114491fdc6 100644 --- a/packages/experimental/tool-terminal/src/index.ts +++ b/packages/experimental/tool-terminal/src/index.ts @@ -9,7 +9,8 @@ import { resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@deepseek-ai/dsh-terminal' import { JobError } from '@deepseek-ai/dsh-jobs' diff --git a/packages/experimental/tool-terminal/tsconfig.json b/packages/experimental/tool-terminal/tsconfig.json index a9bb35d5ca..10f4e0e1cd 100644 --- a/packages/experimental/tool-terminal/tsconfig.json +++ b/packages/experimental/tool-terminal/tsconfig.json @@ -40,6 +40,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/worktree/src/error.ts b/packages/experimental/worktree/src/error.ts index dd55a69c0e..57a2b394f8 100644 --- a/packages/experimental/worktree/src/error.ts +++ b/packages/experimental/worktree/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable worktree creation and restoration failures. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link WorktreeError} code: diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1281a6e650..ce560e21c9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8802,6 +8802,9 @@ importers: '@deepseek-ai/dsh-browser-use': specifier: workspace:* version: link:../../browser-use/browser-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local @@ -8902,6 +8905,9 @@ importers: '@deepseek-ai/dsh-browser-use': specifier: workspace:* version: link:../../browser-use/browser-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -8966,6 +8972,9 @@ importers: '@deepseek-ai/dsh-commands': specifier: workspace:* version: link:../../interaction/commands + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs @@ -9699,6 +9708,9 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -9903,6 +9915,9 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local @@ -10698,6 +10713,9 @@ importers: '@deepseek-ai/dsh-cua': specifier: workspace:* version: link:../cua + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-experimental-api-speech-to-text': specifier: workspace:* version: link:../api-speech-to-text @@ -11175,6 +11193,9 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../boot/app-boot + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-experimental-tool-subagent-oar': specifier: workspace:* version: link:../tool-subagent-oar @@ -11307,6 +11328,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -11457,6 +11481,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-jobs': specifier: workspace:* version: link:../../jobs/jobs diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 3e6ae6d4cb..0c2ef16300 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -91,8 +91,6 @@ const PEER_REQUIRED_HOST_EXPORTS = { '@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName', 'CREATED_RECORD', 'createdWorktreeSchema'], // The forge panel matches ctx.fs failures with `instanceof FsError`. '@deepseek-ai/dsh-fs': ['FsError'], - // The tool registry records a failure's name and code only for `instanceof HarnessError`. - '@deepseek-ai/dsh-llm': ['HarnessError'], '@deepseek-ai/dsh-scope': ['carrierKeyOf', 'createScope', 'scopeOf', 'scopeTarget'], // appendPluginRecord writes through the Session class's private log; pluginRecordOf is stateless. '@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'], From 9b4b278b3e00496db3f0855f1692e95c0b0d6540 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 15:03:39 +0800 Subject: [PATCH 32/68] fix(tools): classify cancellation thrown by a tools/execute wrapper After caller cancellation, a tools/execute wrapper that throws the caller signal's reason or an AbortError without HarnessError identity now keeps its message and carries AbortError with ABORTED, or ABORTED_BEFORE_DISPATCH when the body never started, matching a tool body that throws the same value. A wrapper's HarnessError and other failures stay unchanged. Browser tools that run behind such a wrapper now report caller cancellation as ABORTED. Refs #7869 --- ...19-cooperative-tool-cancellation.i18n.yaml | 4 +-- ...026-07-19-cooperative-tool-cancellation.md | 2 +- ...-07-19-cooperative-tool-cancellation.zh.md | 2 +- .agents/skills/dsh-error-handling/SKILL.md | 2 +- docs/subsystems/tools.i18n.yaml | 4 +-- docs/subsystems/tools.md | 2 +- docs/subsystems/tools.zh.md | 2 +- packages/core/tools/README.i18n.yaml | 4 +-- packages/core/tools/README.md | 2 +- packages/core/tools/README.zh.md | 2 +- packages/core/tools/src/pipeline.ts | 17 +++++++++-- packages/core/tools/tests/tools.spec.ts | 30 +++++++++++++++++++ .../tests/provider.spec.ts | 6 ++-- 13 files changed, 62 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index cccd955846..510cb78fd5 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -15,8 +15,8 @@ en: 0e1399cad4151f87 zh: 960fa0ccbe0f8fea /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/cancellation-codes-record-whether-dispatch-occurred: - en: 86c5566581c1d3d6 - zh: 3cb71fbb97bdb291 + en: 4d8436958c27f98e + zh: cd4ed8238428a2c4 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/pre-aborted-entry-short-circuits-after-materialization: en: 53362db6a0c71698 zh: 311de45ca26d3fdc diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 3f4fbcc597..72a99de358 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -32,7 +32,7 @@ An around-dispatch wrapper may replace `exec.signal` for its delegated lifetime `ABORTED_BEFORE_DISPATCH` carries `{ name: 'AbortError' }` and model text `Error: tool call aborted before dispatch`. It applies whenever cancellation prevents body invocation, including pre-aborted entry, cancellation during pre-policy or approval, an aborted wrapper signal, a wrapper success overtaken by caller cancellation before delegation, and agent-loop siblings skipped after turn cancellation. -`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A denial, wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. +`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, with `ABORTED_BEFORE_DISPATCH` when the body never started. A denial, other wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. ### Pre-aborted entry short-circuits after materialization diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index 15856a1cce..d098a385da 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -32,7 +32,7 @@ Status: implemented `ABORTED_BEFORE_DISPATCH` 携带 `{ name: 'AbortError' }` 和模型可见文本 `Error: tool call aborted before dispatch`。凡取消阻止工具主体调用时都使用该结果,包括进入时已中止、前置策略或审批期间取消、包装层信号已中止、包装层在委托前返回的成功结果被调用方取消抢先,以及轮次取消后 agent loop(智能体循环)跳过的同批调用。 -`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。拒绝、包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 +`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。拒绝、其他包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 ### 进入时已中止会在物化后短路 diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index 930c19adfd..68ef32e230 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -17,7 +17,7 @@ Convert foreign failures where the dependency is owned. Node errno, SDK, protoco ## Tool failures -The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: +The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body or a `tools/execute` wrapper throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: - Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`. - Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`. diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index 7259adff93..bcefbfdd3b 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: 0900eea6efe5a500 - zh: 13fa6eb7dbd8c9dd + en: a6d9db4237438b2a + zh: 1fe07dedc426c5eb /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index bc2aadbeca..64ae21eeb3 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -532,7 +532,7 @@ interface ToolErrorInfo { } ``` -The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. +The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`, and a `tools/execute` wrapper that throws such a value after caller cancellation gets the same identity, with `ABORTED_BEFORE_DISPATCH` when the body never started; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. On success the registry snapshots and validates the body value, freezes it, and invokes the pure renderer plus the optional presentation metadata projector for native and nested calls. It separately materializes the durable presentation fields immediately before `tools/result`; an invalid value, renderer/projector failure, or non-JSON presentation becomes a JSON-safe `isError`. The final live observer therefore sees the exact execution-local value beside fields safe for the later durable append. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 0edd8063a6..34d5e414c6 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -532,7 +532,7 @@ interface ToolErrorInfo { } ``` -结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 +结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`,`tools/execute` 包装器在调用方取消后抛出这类值时也得到同样的标识,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 成功时,注册表会快照并校验函数体返回值,将其冻结,然后调用纯渲染器,并为原生与嵌套调用执行可选的展示元数据投影器。注册表会在 `tools/result` 之前另行物化持久展示字段;无效值、渲染器/投影器失败或非 JSON 展示都会转为 JSON 安全的 `isError`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index e5f5ba4c3e..734e06e239 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -45,8 +45,8 @@ en: 2dee0a37e0c1fa38 zh: 0963cba32685612e /deepseek-ai-dsh-tools/understand-the-implementation/execution-and-cancellation: - en: c6db8efb31370459 - zh: 07aec8a6230d943a + en: 5f289c5a05345776 + zh: c2b488e03fa38deb /deepseek-ai-dsh-tools/understand-the-implementation/ptc-mode: en: 83cf9a5077158879 zh: 80508a70a3674226 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 9d40ba281c..49a6ee15ee 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -125,7 +125,7 @@ The registry holds typed `ToolDefinition`s in scoped layers and projects them on ### Execution and cancellation -Each typed invocation materializes and freezes parsed arguments, assigns an opaque correlation token, and runs policy and dispatch. A pre-execute denial may attach `ToolErrorInfo` beside its model-facing reason; the native and PTC durable projections preserve the structured name, code, and optional user-facing reason without adding that detail to model content. Cancellation is cooperative and quiescent: every tool body receives the caller-owned `exec.signal` and must observe it; cancellation before body invocation is `ABORTED_BEFORE_DISPATCH`, after invocation it replaces only a successful outcome with `ABORTED`, and a thrown signal reason or `Error` named `AbortError` without `HarnessError` identity keeps its message but carries `ABORTED`. Denials, wrapper failures, tool failures, post-policy failures, and timeout-owned `TOOL_TIMEOUT` remain more specific. Unknown and throwing tools become structured errors (`UNKNOWN_TOOL`), so a call fails without ending the turn. +Each typed invocation materializes and freezes parsed arguments, assigns an opaque correlation token, and runs policy and dispatch. A pre-execute denial may attach `ToolErrorInfo` beside its model-facing reason; the native and PTC durable projections preserve the structured name, code, and optional user-facing reason without adding that detail to model content. Cancellation is cooperative and quiescent: every tool body receives the caller-owned `exec.signal` and must observe it; cancellation before body invocation is `ABORTED_BEFORE_DISPATCH`, after invocation it replaces only a successful outcome with `ABORTED`, and a thrown signal reason or `Error` named `AbortError` without `HarnessError` identity keeps its message but carries `ABORTED`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, as `ABORTED_BEFORE_DISPATCH` when the body never started. Denials, other wrapper failures, tool failures, post-policy failures, and timeout-owned `TOOL_TIMEOUT` remain more specific. Unknown and throwing tools become structured errors (`UNKNOWN_TOOL`), so a call fails without ending the turn. ### PTC mode diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 9de1e6d70b..6391015547 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -125,7 +125,7 @@ Agent 步骤的并发上限使用 [agent-loop 配置](../agent-loop/README.zh.md ### 执行与取消 -每次类型化调用都会实体化并冻结解析后的参数、分配不透明关联 token,再运行策略与分发。pre-execute 拒绝可以在模型可见原因旁附带 `ToolErrorInfo`;原生与 PTC 持久投影会保留结构化名称、代码与可选用户可见原因,但不会把该详情加入模型内容。取消采用协作式并等待完全停稳:每个工具主体都收到调用方拥有的 `exec.signal` 且必须观测它;调用主体前的取消为 `ABORTED_BEFORE_DISPATCH`,调用主体后的取消只能把成功结果替换为 `ABORTED`,抛出的 signal reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error`,保留其 message 并携带 `ABORTED`。拒绝、包装层失败、工具失败、后置策略失败与超时产生的 `TOOL_TIMEOUT` 仍保留更具体的结果。未知工具与抛出异常的工具都会变成结构化错误(`UNKNOWN_TOOL`),因此调用会失败而不会结束轮次。 +每次类型化调用都会实体化并冻结解析后的参数、分配不透明关联 token,再运行策略与分发。pre-execute 拒绝可以在模型可见原因旁附带 `ToolErrorInfo`;原生与 PTC 持久投影会保留结构化名称、代码与可选用户可见原因,但不会把该详情加入模型内容。取消采用协作式并等待完全停稳:每个工具主体都收到调用方拥有的 `exec.signal` 且必须观测它;调用主体前的取消为 `ABORTED_BEFORE_DISPATCH`,调用主体后的取消只能把成功结果替换为 `ABORTED`,抛出的 signal reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error`,保留其 message 并携带 `ABORTED`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。拒绝、其他包装层失败、工具失败、后置策略失败与超时产生的 `TOOL_TIMEOUT` 仍保留更具体的结果。未知工具与抛出异常的工具都会变成结构化错误(`UNKNOWN_TOOL`),因此调用会失败而不会结束轮次。 ### PTC mode diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index 1a13c08748..9db8bfc610 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -295,7 +295,11 @@ export class ToolExecutionPipeline { /** * Run around-dispatch and the tool body. Tool and unknown-tool failures still * receive post-execute; pipeline failures are already final. Started bodies - * drain on cancellation before a successful outcome becomes `ABORTED`. + * drain on cancellation before a successful outcome becomes `ABORTED`. After + * caller cancellation, a wrapper that throws the caller signal's reason or an + * `Error` named `AbortError` without `HarnessError` identity keeps its message + * and gains `ABORTED`, or `ABORTED_BEFORE_DISPATCH` when the body never + * started; a wrapper's `HarnessError` and other failures stay unchanged. * @param exec - the execution returned by this pipeline's prepare stage. * @returns whether the result still needs post-execute. */ @@ -327,10 +331,19 @@ export class ToolExecutionPipeline { : resultWithDeferredContexts, } } catch (error: unknown) { - return { kind: 'final-result', result: toolErrorResult(error) } + return { kind: 'final-result', result: this.wrapperFailureResult(exec, error) } } } + /** Classify a failure thrown around dispatch; see {@link dispatch}. */ + private wrapperFailureResult(exec: ToolRunContext, error: unknown): ToolExecutionResult { + const state = this.cancellationStates.get(exec) + /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */ + if (state === undefined) throw new Error('tool registry scheduler invariant violated: missing cancellation state') + if (!isAborted(state.callerSignal) || !isUnclassifiedCancellation(error, state.callerSignal)) return toolErrorResult(error) + return toolErrorResult(error, { name: 'AbortError', code: state.bodyInvoked ? TOOL_ABORTED : TOOL_ABORTED_BEFORE_DISPATCH }) + } + /** * Run post-execute when required, apply definition-owned content finalization, * and publish the lossless, frozen result. Policy and finalization failures diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index 8f4455c621..9ecf9af34e 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -2195,6 +2195,36 @@ describe('ToolRuntime', () => { }) }) + it.each([ + ['the caller reason after the body ran', true, (signal: AbortSignal): never => { throw signal.reason as Error }, { name: 'AbortError', code: TOOL_ABORTED }], + ['the caller reason before the body ran', false, (signal: AbortSignal): never => { throw signal.reason as Error }, { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH }], + ['an AbortError after the body ran', true, (): never => { throw new DOMException('wrapper stopped', 'AbortError') }, { name: 'AbortError', code: TOOL_ABORTED }], + ['a HarnessError after the body ran', true, (): never => { throw new HarnessError('wrapper failed', 'WRAPPER_FAILED') }, { name: 'HarnessError', code: 'WRAPPER_FAILED' }], + ['a plain failure after the body ran', true, (): never => { throw new Error('wrapper broke') }, undefined], + ])('classifies %s thrown by a tools/execute listener after cancellation', async (_label, delegate, fail, info) => { + const ctx = await setup() + ctx.tools.register(echoTool) + const controller = new AbortController() + ctx.on('tools/execute', async (exec, next) => { + if (delegate) await next() + controller.abort(new Error('caller stopped')) + return fail(exec.signal) + }) + + const result = await executeToolFixture(ctx, { signal: controller.signal, callId: ToolCallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual(info) + }) + + it('keeps a plain tools/execute listener failure without info when the caller did not cancel', async () => { + const ctx = await setup() + ctx.tools.register(echoTool) + ctx.on('tools/execute', async () => { throw new DOMException('wrapper stopped', 'AbortError') }) + + const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: ToolCallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result.error).toEqual({ message: 'wrapper stopped' }) + }) + it('returns an isError result when a tools/pre-execute listener throws', async () => { const ctx = await setup() ctx.tools.register(echoTool) diff --git a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts index efb18d1bed..5ff749fdb1 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts @@ -248,7 +248,9 @@ it.each(['cancel', 'dispose'] as const)('drains native inference before completi } finally { release.resolve() await disposal - expect((await operation).isError).toBe(true) + const settled = await operation + expect(settled.isError).toBe(true) + if (reason === 'cancel') expect(settled.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) } expect(fixture.browsers[0]?.stagehandClosed).toBe(true) expect(fixture.browsers[0]?.closed).toBe(false) @@ -419,7 +421,7 @@ it('blocks reconnection and another owner after canceled native work fails to dr } finally { release.resolve() } - expect((await operation).isError).toBe(true) + expect((await operation).error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) expect((await execute(first, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED' }) expect((await execute(second, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'BrowserSessionError', code: 'BROWSER_LOCKED' }) expect(fixture.browsers).toHaveLength(1) From 996ed36e079fdcbc2cffe4beb5a8a5012e3742f3 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:28:55 +0800 Subject: [PATCH 33/68] fix(liveshare): give each refusal one identity across guard and tools A path outside the granted workspace is FsError FS_SANDBOX_DENIED whether the guard or a confined tool refuses it, and a share that no longer allows writing is LiveshareForkDeniedError FORK_TOOL_NOT_PERMITTED like a lapsed fork permission. The module contract now describes the structured denial, and the refusal table follows the imports. Refs #7869 --- docs/subsystems/liveshare.i18n.yaml | 4 +-- docs/subsystems/liveshare.md | 2 +- docs/subsystems/liveshare.zh.md | 2 +- .../experimental/liveshare/README.i18n.yaml | 4 +-- packages/experimental/liveshare/README.md | 2 +- packages/experimental/liveshare/README.zh.md | 2 +- .../liveshare/src/host/fork-enforcement.ts | 8 +++--- .../liveshare/src/host/fork-errors.ts | 28 +++++++++++++------ .../liveshare/src/host/fork-tool-guard.ts | 20 +++++++------ .../liveshare/tests/fork-denial.ts | 12 ++++++++ .../tests/fork-enforcement-unit.spec.ts | 16 +++++------ .../readonly-fork-enforcement-wiring.spec.ts | 6 ++-- .../tests/readonly-fork-tool-guard.spec.ts | 4 +-- .../tests/write-current-policy.spec.ts | 1 + 14 files changed, 68 insertions(+), 43 deletions(-) diff --git a/docs/subsystems/liveshare.i18n.yaml b/docs/subsystems/liveshare.i18n.yaml index fde693bc1e..40240826c1 100644 --- a/docs/subsystems/liveshare.i18n.yaml +++ b/docs/subsystems/liveshare.i18n.yaml @@ -18,8 +18,8 @@ en: 6b1346e73ab6eab9 zh: 888cfc08c6bc8522 /liveshare/constraining-a-shared-session: - en: c336c48190726a6c - zh: f4119a1156d75728 + en: 7fbb31bbc29817d6 + zh: 0a9542ab1d48a9e6 /liveshare/viewer-states: en: b8bcb009e419fa25 zh: 31c4662b52e99ea7 diff --git a/docs/subsystems/liveshare.md b/docs/subsystems/liveshare.md index 15f986bc99..6705717b81 100644 --- a/docs/subsystems/liveshare.md +++ b/docs/subsystems/liveshare.md @@ -38,7 +38,7 @@ Child tool guards recheck the share’s current mode, expiry, viewer admission, Every share lets its viewer drive the *source* Session through the normal prompt path, and any share at either tier installs the bounded sandbox while it is active. `installSourceSessionAccess` registers a confined replacement for every view-surface tool the deployment ships in that Session's own scope, and bounded `edit` and `write` replacements whenever any share over the Session allows writing. The layer is mounted on the Session, but it confines only the turns a share viewer starts: `agent/pre-step` records, in Host memory, whether a turn's admitted input names a share viewer, and the guard and the replacements read that answer for every execution of that turn. A viewer-started turn runs those replacements and nothing else; a turn the owner starts keeps the Session's own tools, including `bash` and its unrestricted filesystem tools. The answer is decided when the turn is admitted and never written to the Session log; a restart recomputes it from the next admitted step. An owner's steering input inside a viewer's turn stays confined with it. Stopping every share over the Session disposes the layer, which restores the Session's own tools; narrowing the last write share to `view` re-installs the read-only layer. -The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A guard refusal records `LiveshareForkDeniedError` with a `FORK_*` code on the failed call, and a confined file tool refuses a target outside the grant with `FsError` `FS_SANDBOX_DENIED`. +The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A refusal records the same identity whether the guard or a confined tool decides: a path outside the grant is `FsError` `FS_SANDBOX_DENIED`, and other grant refusals are `LiveshareForkDeniedError` with a `FORK_*` code. Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs. diff --git a/docs/subsystems/liveshare.zh.md b/docs/subsystems/liveshare.zh.md index bd7754105c..a274d8957d 100644 --- a/docs/subsystems/liveshare.zh.md +++ b/docs/subsystems/liveshare.zh.md @@ -38,7 +38,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检 每个分享都让它的 viewer 通过正常 prompt 路径驱动*源*会话,任一档位的分享在活跃期间都会安装有界沙箱。`installSourceSessionAccess` 在该会话自身作用域中为部署提供的每个读取与检索面工具注册受限替代,并在任一同会话分享允许写入时再注册有界 `edit` 与 `write` 替代。执行层挂在会话上,但只约束分享查看者发起的轮次:`agent/pre-step` 在 Host 内存中记录一个轮次的已准入输入是否带有 share-viewer principal,守卫与替代定义对该轮次的每次执行读取这一结论。查看者发起的轮次只能运行这些替代定义;所有者自己发起的轮次保留会话原生工具,包括 `bash` 与不受限的文件工具。该结论在轮次准入时确定,不写入会话日志;重启后从下一个准入步骤重新计算。所有者在查看者轮次中追加的输入仍留在该受限轮次内。该会话的所有分享停止后执行层被释放,会话恢复自己的工具;最后一个可写分享降为 `view` 时重装只读层。 -安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。守卫拒绝会在失败调用上记录 `LiveshareForkDeniedError` 及 `FORK_*` code,受限文件工具以 `FsError` `FS_SANDBOX_DENIED` 拒绝授权范围外的目标。 +安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。无论由守卫还是受限工具判定,拒绝都记录同一标识:授权范围外的路径为 `FsError` `FS_SANDBOX_DENIED`,其他授权拒绝为 `LiveshareForkDeniedError` 及 `FORK_*` code。 每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。 diff --git a/packages/experimental/liveshare/README.i18n.yaml b/packages/experimental/liveshare/README.i18n.yaml index 63c8c1f377..3ee1afd4ce 100644 --- a/packages/experimental/liveshare/README.i18n.yaml +++ b/packages/experimental/liveshare/README.i18n.yaml @@ -33,8 +33,8 @@ en: 2052fd7c4e9c3f98 zh: 5ef2ac5ad9ec7990 /deepseek-ai-dsh-experimental-liveshare/understand-the-implementation: - en: d0a82a564982ae39 - zh: 83ff49b7b0db4f20 + en: 37d649ff38fca348 + zh: c73e526eac1e3778 /deepseek-ai-dsh-experimental-liveshare/further-exploration: en: 0570170704bbe5b6 zh: 832f86024b26e5b3 diff --git a/packages/experimental/liveshare/README.md b/packages/experimental/liveshare/README.md index 944139a44f..70a67fb833 100644 --- a/packages/experimental/liveshare/README.md +++ b/packages/experimental/liveshare/README.md @@ -109,7 +109,7 @@ The Owner Gateway decides each call on the Session and Workspace it names and re The viewer page is the Owner's own Web shell. The Liveshare server fetches the Owner's rendered index document through an `asset` read and places the carrier script from [viewer-carrier.ts](../liveshare-protocol/src/viewer-carrier.ts) first in it. Shell assets, client plugin bundles, and the three exact top-level files the index references against the document base — `manifest.webmanifest`, `favicon.svg`, and `favicon-dark.svg` — arrive through the same read, from the Owner's frontend reader and client module registry, so the page runs every Owner plugin at the Owner's version. Source maps are refused on every asset path, and that check is the authoritative one: an `asset` read forwarded through the Liveshare server arrives here unread, so the Liveshare server's own same-named rule covers its page-resource route only. The served document also drops its manifest link, which a browser would otherwise fetch without credentials. The carrier converts Connection calls and Gateway streams into `POST {base}/__share/rpc` requests, and forwards the read-only page-origin owner routes the Liveshare server cannot answer — `/open-in-app/apps` and `/api/present.host` — through that channel instead of leaving them to the Liveshare server's tail. The Liveshare server supplies the authenticated actor outside the opaque body. The Owner's read handler dispatches each reader's calls and streams into its own Connection and Gateway as one Peer per share and reader, whose `share-viewer` principal carries the share and the server-asserted identity. The Gateway decides that Peer's calls, and the Session notifications it forwards to it, through [`dsh-api-remote-access`](../../api/remote-access/README.md) from the `share-viewer` policy this package registers: a served reader holds read roles on the shared Session, its own forks, and the Workspaces holding them, fork and write roles whose conditions apply the share's tier and its own fork switch, and nothing else; attachment upload rides the read roles. The read handler keeps the share-lifecycle refusals, Liveshare server authority refresh, cold Session preparation, and fork orchestration, reads the policy's write rules before it prepares or dispatches a prompt or stop, and disposes a reader's Peer when its grant ends, the share stops or expires, or a re-check refuses it. Preparing a share's source Session also starts when a reader asks for its page or opens a stream, so a host that restarted before that Session's agent was live still gains the actions it drives with; a share whose Session cannot be confined states that instead of the read-only fact. This package's browser face mounts the viewer surfaces when the carrier's `__DSH_LIVESHARE_VIEWER__` global is present and the Share action otherwise. The served index assigns the reader's own access snapshot to the global that every index sets to the owner baseline, and the page then follows the reader's `remoteAccess/follow` snapshot; CSS hiding is not authorization. -Fork requests bind the actor, share, source, operation identity, and completed prefix. A durable reservation and the recorded child let a retry of a recorded operation replay the same child; the owner's `SessionForkRequest` mints the child id, so a request interrupted after the child was created but before it was recorded forks again. Registry mutations are asynchronous and resolve only after locked read-modify-write and atomic publication; callers must await reservation, recording, and revocation. Cold activation uses the Host’s ordinary Agent lookup, with serial `agent/created` enforcement before queued input can run, not a Remote `session/prepare` endpoint. The child scope retains one fail-closed guard; reconnection replaces its enforcement installation, and releasing an old installation cannot remove its successor. Guard refusals record `LiveshareForkDeniedError` with a `FORK_*` code from [fork-errors.ts](src/host/fork-errors.ts), such as `FORK_TOOL_NOT_PERMITTED` or `FORK_PATH_OUTSIDE_WORKSPACE`; inside the confined replacements, a target outside the grant or a share that no longer allows writing fails with `FsError` `FS_SANDBOX_DENIED`, arguments the replacement cannot confine fail with `ToolArgsError`, and a tool whose permission lapsed fails with `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED`. +Fork requests bind the actor, share, source, operation identity, and completed prefix. A durable reservation and the recorded child let a retry of a recorded operation replay the same child; the owner's `SessionForkRequest` mints the child id, so a request interrupted after the child was created but before it was recorded forks again. Registry mutations are asynchronous and resolve only after locked read-modify-write and atomic publication; callers must await reservation, recording, and revocation. Cold activation uses the Host’s ordinary Agent lookup, with serial `agent/created` enforcement before queued input can run, not a Remote `session/prepare` endpoint. The child scope retains one fail-closed guard; reconnection replaces its enforcement installation, and releasing an old installation cannot remove its successor. Refusals carry one identity per condition whether the guard or a confined replacement decides: a path outside the granted workspace is `FsError` `FS_SANDBOX_DENIED`; a tool, or a write, that the fork's limit or the share's current grant does not admit is `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED`; the guard's other refusals use the remaining `FORK_*` codes in [fork-errors.ts](src/host/fork-errors.ts); and arguments a replacement cannot confine fail with `ToolArgsError`. A reader's prompt reaches the Session as a `user-rpc` message whose `source.principal` names that reader, and the pre-step re-checks every entering message's viewer against the Relay's admission before it reaches the model. Execution is confined per turn: while any share over the Session is active, a turn whose admitted input names a share viewer runs the Host's confined replacements for the read and search surface (`read`, `read_image`, `glob`, `grep`, `present`), keeps the deployment's own definitions of the tools with no local file effect (`todo_write`, `skill`, `web_search`, `web_fetch`), admits the PTC transport `run_code` from the selected executor, and, when some share may write, its bounded `edit` and `write`. Every other tool is refused to that turn, and every path a permitted call declares is resolved and checked against the granted root. An owner-started turn keeps the Session's native tools until the last share stops or expires. The turn decision is Host memory only, recomputed for each turn and never appended to the Session log. Each operation re-reads the shares' current Relay grants and checks the resolved target against the granted root. A reader's stop is dispatched through the Gateway like a prompt: the `share-viewer` policy admits it while the share's tier is established and the Session is confined, and the owner's own Session controller stops whatever turn the Session is running, including one the owner started. Reads and writes preserve the normal write-observation policy. See the [LiveShare subsystem](../../../docs/subsystems/liveshare.md) for the execution rules. diff --git a/packages/experimental/liveshare/README.zh.md b/packages/experimental/liveshare/README.zh.md index 8d5d8a7cb9..91343b4ad3 100644 --- a/packages/experimental/liveshare/README.zh.md +++ b/packages/experimental/liveshare/README.zh.md @@ -109,7 +109,7 @@ Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒 查看页就是 Owner 自己的 Web shell。Liveshare 服务端通过 `asset` 读取取得 Owner 渲染好的 index 文档,并把 [viewer-carrier.ts](../liveshare-protocol/src/viewer-carrier.ts) 生成的载体脚本放在文档最前面。Shell 资源、客户端插件 bundle,以及 index 相对文档基准引用的三个确切顶层文件(`manifest.webmanifest`、`favicon.svg`、`favicon-dark.svg`)都经同一读取取得,来自 Owner 的前端读取服务和客户端模块注册表,因此页面以 Owner 的版本运行 Owner 的全部插件。任何 asset 路径上的 source map 都被拒绝,且该判定是权威的:经 Liveshare 服务端转发的 `asset` 读取会原样到达这里,因此 Liveshare 服务端侧的同名规则只覆盖它自己的页面资源路由;被服务的文档还会去掉自己的 manifest 链接,否则浏览器会不带凭据地抓取它。载体把 Connection 调用和 Gateway 流转换为 `POST {base}/__share/rpc` 请求,并把 Liveshare 服务端无法作答的只读页面源 Owner 路由(`/open-in-app/apps` 与 `/api/present.host`)也经该通道转发,而不是留给 Liveshare 服务端尾部。Liveshare 服务端在不透明请求体之外提供已认证主体。Owner 读取处理器把每位读者的调用和流以「每个分享、每位读者一个 Peer」分派进自己的 Connection 与 Gateway,该 Peer 的 `share-viewer` principal 携带分享与服务端断言的身份。Gateway 依据本包注册的 `share-viewer` 策略,经 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md) 判定该 Peer 的调用以及转发给它的会话通知:受服务的读者持有共享会话、其自己的 fork 及包含它们的工作区上的读取角色,持有条件按分享档位与其自身 fork 开关判定的 fork 与写入角色,此外别无授权;附件上传随读取角色生效。读取处理器保留分享生命周期拒绝、Liveshare 服务端授权刷新、冷会话准备和 fork 编排,在准备或分派提示词与停止之前读取策略的写入规则,并在授权结束、分享停止或过期、或复检拒绝时释放读者的 Peer。读者索取页面或打开流时也会开始准备该分享的源会话,因此宿主重启时该会话的 agent 尚未存活也能补上驱动所需的层;无法被 confine 的分享会如实说明该状态,而不再声明只读。存在载体写入的 `__DSH_LIVESHARE_VIEWER__` 全局变量时,本包的浏览器端挂载查看页界面,否则挂载分享操作。读者收到的 index 把读者自己的访问快照赋给每个 index 设为所有者基线的同一全局变量,页面随后跟随读者的 `remoteAccess/follow` 快照;CSS 隐藏不构成授权。 -Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。持久化预留记录与已记录的分叉会话使重试已记录的操作时重放同一分叉会话;owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在分叉会话已创建、但尚未记录时中断的请求会再次 fork。注册表变更为异步操作,仅在加锁的读取、修改与原子发布后完成;调用方必须等待预留、记录与撤销。冷态激活使用 Host 常规 Agent lookup,由串行 `agent/created` 在排队输入运行前安装限制,不使用 Remote `session/prepare` 端点。分叉会话作用域保留单个默认拒绝的 guard;重连替换其限制安装,释放旧安装不会移除继任。guard 拒绝记录 `LiveshareForkDeniedError` 及 [fork-errors.ts](src/host/fork-errors.ts) 中的 `FORK_*` code,例如 `FORK_TOOL_NOT_PERMITTED` 或 `FORK_PATH_OUTSIDE_WORKSPACE`;在受限替换工具内,授权范围外的目标或已不允许写入的分享以 `FsError` `FS_SANDBOX_DENIED` 失败,替换工具无法限制的参数以 `ToolArgsError` 失败,权限已失效的工具以 `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED` 失败。 +Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。持久化预留记录与已记录的分叉会话使重试已记录的操作时重放同一分叉会话;owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在分叉会话已创建、但尚未记录时中断的请求会再次 fork。注册表变更为异步操作,仅在加锁的读取、修改与原子发布后完成;调用方必须等待预留、记录与撤销。冷态激活使用 Host 常规 Agent lookup,由串行 `agent/created` 在排队输入运行前安装限制,不使用 Remote `session/prepare` 端点。分叉会话作用域保留单个默认拒绝的 guard;重连替换其限制安装,释放旧安装不会移除继任。无论由 guard 还是受限替换工具判定,同一种拒绝只有一个标识:授权工作区外的路径为 `FsError` `FS_SANDBOX_DENIED`;fork 的限制或分享当前授权不允许的工具或写入为 `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED`;guard 的其他拒绝使用 [fork-errors.ts](src/host/fork-errors.ts) 中其余的 `FORK_*` code;替换工具无法限制的参数以 `ToolArgsError` 失败。 读者的提示词以 `user-rpc` 消息进入会话,其 `source.principal` 指明该读者;pre-step 在每条进入消息到达模型前,按 Relay 的准入重新检查其查看者。执行按轮次受限:只要有分享处于活跃状态,已准入输入中带有 share-viewer principal 的轮次就运行 Host 挂载的读取与检索面(`read`、`read_image`、`glob`、`grep`、`present`)受限替代、保留无本地文件副作用工具(`todo_write`、`skill`、`web_search`、`web_fetch`)的原生定义、放行选定执行器提供的 PTC 传输工具 `run_code`,以及(当某个分享允许写入时)有界 `edit` 与 `write`。其余所有工具对该轮次一律拒绝,且每次允许的调用声明的每个路径都会解析并按获授根目录检查。所有者自己发起的轮次保留会话原生工具,直到最后一个分享停止或过期。该轮次判定只存在于 Host 内存,按轮次重算,不写入会话日志。每次操作都会重新读取分享当前的 Relay 授权,并按获授根目录检查解析后的目标。读者的停止与提示词一样经 Gateway 分派:`share-viewer` 策略在分享档位确立且会话受沙箱限制时放行,随后由所有者自己的会话控制器停止该会话当前运行的轮次,包括所有者发起的轮次。读写保留正常写入观察策略。执行规则见 [LiveShare 子系统](../../../docs/subsystems/liveshare.zh.md)。 diff --git a/packages/experimental/liveshare/src/host/fork-enforcement.ts b/packages/experimental/liveshare/src/host/fork-enforcement.ts index f97838505a..2e48ce170e 100644 --- a/packages/experimental/liveshare/src/host/fork-enforcement.ts +++ b/packages/experimental/liveshare/src/host/fork-enforcement.ts @@ -265,7 +265,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS await target.refreshAuthorization?.() // The Session's current shares decide, not the tier the layer was installed for: a share can // narrow to view while this layer stays mounted. - if (!gate.mayWrite()) throw new FsError('this share does not allow writing this Session', 'FS_SANDBOX_DENIED') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const input = isRecord(args) ? args : {} const requested = input.file_path const content = input.content @@ -282,7 +282,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS const policy = target.resolvePolicy() // The shares can narrow while the intent awaited: the final refresh above reads the new state, so // ask the gate again before anything is written instead of trusting the earlier verdict. - if (!gate.mayWrite()) throw new FsError('this share does not allow writing this Session', 'FS_SANDBOX_DENIED') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const outcome = await fs.writeText(candidate, content, intent, exec.signal, policy) // The published version is this caller's own next basis, exactly as the shipped write records it: // without it a second write of the same file would meet a policy that saw nothing since the read. @@ -302,7 +302,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS register(FORK_EDIT_TOOL, deploymentEdit, async (args, exec) => { if (!confined(exec)) return await deploymentEdit.execute(args, exec) await target.refreshAuthorization?.() - if (!gate.mayWrite()) throw new FsError('this share does not allow writing this Session', 'FS_SANDBOX_DENIED') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const edit = sharedEditArguments(args) if (edit === undefined) { throw new ToolArgsError(['a shared session may only edit a named file by replacing non-empty text']) @@ -314,7 +314,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS const intent = await context.waterfall('fs/edit-intent', candidate, exec, () => undefined) await target.refreshAuthorization?.() const policy = target.resolvePolicy() - if (!gate.mayWrite()) throw new FsError('this share does not allow writing this Session', 'FS_SANDBOX_DENIED') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const outcome = await fs.editText( candidate, { oldString: edit.oldString, newString: edit.newString, replaceAll: edit.replaceAll }, diff --git a/packages/experimental/liveshare/src/host/fork-errors.ts b/packages/experimental/liveshare/src/host/fork-errors.ts index a62dac482a..5de4bbe04b 100644 --- a/packages/experimental/liveshare/src/host/fork-errors.ts +++ b/packages/experimental/liveshare/src/host/fork-errors.ts @@ -7,12 +7,12 @@ import { HarnessError } from '@deepseek-ai/dsh-error' * - `FORK_LIMITS_UNINSTALLED` — no execution limit is installed for the calling fork; nothing it runs can be vouched for. * - `FORK_CHILD_UNKNOWN` — the call cannot be attributed to a fork child. * - `FORK_CHILD_MISMATCH` — the call reaches into a Session other than the fork it came from. - * - `FORK_TOOL_NOT_PERMITTED` — the fork's limit or the share's current grant does not admit the tool. + * - `FORK_TOOL_NOT_PERMITTED` — the fork's limit or the share's current grant does not admit the tool or its write. * - `FORK_PATHS_UNKNOWN` — the tool's filesystem effect could not be established, so it could not be authorized. - * - `FORK_PATH_OUTSIDE_WORKSPACE` — a path leaves the workspace the fork was granted. * - * The model should not retry a refused call unchanged; only `FORK_PATH_OUTSIDE_WORKSPACE` and - * `FORK_PATHS_UNKNOWN` can succeed with other arguments. + * The model should not retry a refused call unchanged; only `FORK_PATHS_UNKNOWN` can succeed with other arguments. + * A path outside the granted workspace is a filesystem refusal instead: the guard and the confined tools both + * record it as `FsError` with `FS_SANDBOX_DENIED`. */ export const LIVESHARE_FORK_DENIED_CODES = [ 'FORK_LIMITS_UNINSTALLED', @@ -20,16 +20,15 @@ export const LIVESHARE_FORK_DENIED_CODES = [ 'FORK_CHILD_MISMATCH', 'FORK_TOOL_NOT_PERMITTED', 'FORK_PATHS_UNKNOWN', - 'FORK_PATH_OUTSIDE_WORKSPACE', ] as const /** One code from {@link LIVESHARE_FORK_DENIED_CODES}. */ export type LiveshareForkDeniedCode = typeof LIVESHARE_FORK_DENIED_CODES[number] -/** Error name recorded on every liveshare fork refusal, thrown or returned by a guard. */ +/** Error name recorded on every liveshare grant refusal, thrown or returned by a guard. */ export const LIVESHARE_FORK_DENIED_ERROR_NAME = 'LiveshareForkDeniedError' -/** A tool use the fork's execution limit refused inside a tool body. */ +/** A tool use the fork's execution limit or the share's grant refused inside a tool body. */ export class LiveshareForkDeniedError extends HarnessError { override readonly code: LiveshareForkDeniedCode @@ -47,11 +46,13 @@ export class LiveshareForkDeniedError extends HarnessError { /** A guard refusal: the model-facing reason and the structured identity the tool runtime records. */ export interface ForkToolDenial { readonly reason: string - readonly info: { readonly name: typeof LIVESHARE_FORK_DENIED_ERROR_NAME; readonly code: LiveshareForkDeniedCode } + readonly info: + | { readonly name: typeof LIVESHARE_FORK_DENIED_ERROR_NAME; readonly code: LiveshareForkDeniedCode } + | { readonly name: 'FsError'; readonly code: 'FS_SANDBOX_DENIED' } } /** - * Build a guard refusal. + * Build a guard refusal of the grant. * @param reason - Model-facing refusal. * @param code - The refused condition. * @returns The refusal in the structure `ToolGuard` denials take. @@ -59,3 +60,12 @@ export interface ForkToolDenial { export function forkToolDenial(reason: string, code: LiveshareForkDeniedCode): ForkToolDenial { return { reason, info: { name: LIVESHARE_FORK_DENIED_ERROR_NAME, code } } } + +/** + * Build a guard refusal of a path outside the granted workspace, with the identity the confined tools throw. + * @param reason - Model-facing refusal. + * @returns The refusal in the structure `ToolGuard` denials take. + */ +export function outsideWorkspaceDenial(reason: string): ForkToolDenial { + return { reason, info: { name: 'FsError', code: 'FS_SANDBOX_DENIED' } } +} diff --git a/packages/experimental/liveshare/src/host/fork-tool-guard.ts b/packages/experimental/liveshare/src/host/fork-tool-guard.ts index 0bbd01c2fe..a75de9cba3 100644 --- a/packages/experimental/liveshare/src/host/fork-tool-guard.ts +++ b/packages/experimental/liveshare/src/host/fork-tool-guard.ts @@ -3,23 +3,22 @@ * * It is registered on one child's context, so it speaks for that child alone: it refuses anything the * ceiling does not permit, and it decides paths through the host's real filesystem authorization - * rather than by comparing strings or trusting a tool name. The return value is the reason string the - * tool runtime expects, and a refusal is monotonic — nothing downstream can turn it back into an - * allow. + * rather than by comparing strings or trusting a tool name. A refusal is a `ToolGuard` denial: the + * model-facing reason with the structured error identity the tool runtime records, and it is + * monotonic — nothing downstream can turn it back into an allow. */ import { forkToolDecision, type ForkToolDecision, type ForkToolRefusal } from './fork-ceiling.ts' -import { forkToolDenial, type ForkToolDenial, type LiveshareForkDeniedCode } from './fork-errors.ts' +import { forkToolDenial, outsideWorkspaceDenial, type ForkToolDenial, type LiveshareForkDeniedCode } from './fork-errors.ts' +import type { ForkCeiling } from './fork-policy.ts' -/** The recorded code for each refusal a fork tool decision names. */ -const REFUSAL_CODES: Readonly> = { +/** The recorded code for each grant refusal a fork tool decision names; a path outside the workspace is a filesystem refusal. */ +const REFUSAL_CODES: Readonly, LiveshareForkDeniedCode>> = { 'fork-ceiling-uninstalled': 'FORK_LIMITS_UNINSTALLED', 'fork-tool-not-permitted': 'FORK_TOOL_NOT_PERMITTED', 'fork-child-mismatch': 'FORK_CHILD_MISMATCH', - 'fork-path-outside-workspace': 'FORK_PATH_OUTSIDE_WORKSPACE', 'fork-paths-unknown': 'FORK_PATHS_UNKNOWN', } -import type { ForkCeiling } from './fork-policy.ts' /** One tool execution as the runtime presents it to a guard. */ export interface ForkToolExecution { @@ -175,7 +174,10 @@ export function forkToolGuard( ...describe(execution), ...(execution.token === undefined ? {} : { token: execution.token }), }, ports) - return decision.ok ? undefined : forkToolDenial(decision.message, REFUSAL_CODES[decision.code]) + if (decision.ok) return undefined + return decision.code === 'fork-path-outside-workspace' + ? outsideWorkspaceDenial(decision.message) + : forkToolDenial(decision.message, REFUSAL_CODES[decision.code]) } } diff --git a/packages/experimental/liveshare/tests/fork-denial.ts b/packages/experimental/liveshare/tests/fork-denial.ts index a06f38c6b2..479d76bcba 100644 --- a/packages/experimental/liveshare/tests/fork-denial.ts +++ b/packages/experimental/liveshare/tests/fork-denial.ts @@ -14,3 +14,15 @@ export function denial(reason: string | RegExp, code: LiveshareForkDeniedCode): info: { name: 'LiveshareForkDeniedError', code }, } } + +/** + * Match a guard refusal of a path outside the granted workspace. + * @param reason - Text the model-facing reason contains, or a pattern it matches. + * @returns An asymmetric matcher for `toEqual`. + */ +export function outsideDenial(reason: string | RegExp): unknown { + return { + reason: (typeof reason === 'string' ? expect.stringContaining(reason) : expect.stringMatching(reason)) as string, + info: { name: 'FsError', code: 'FS_SANDBOX_DENIED' }, + } +} diff --git a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts index 6fc984aee5..8f363f6c26 100644 --- a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts +++ b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts @@ -13,7 +13,7 @@ import { preflightForkChild, } from '../src/host/fork-enforcement.ts' import type { ForkEnforcementFailure } from '../src/host/fork-enforcement.ts' -import { denial } from './fork-denial.ts' +import { denial, outsideDenial } from './fork-denial.ts' import type { ForkToolDenial } from '../src/host/fork-errors.ts' interface RegisteredTool { @@ -243,7 +243,7 @@ describe('confined fork tools', () => { h.target.authorized = () => true expect(guard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } })) - .toEqual(denial('may only read inside the workspace', 'FORK_PATH_OUTSIDE_WORKSPACE')) + .toEqual(outsideDenial('may only read inside the workspace')) // A definition visible from both registries is trusted even though this host did not install it. const visible = harness({ read }) @@ -251,7 +251,7 @@ describe('confined fork tools', () => { visible.forks.enforcedCeiling.mockReturnValue(READ_ONLY_FORK_CEILING) const visibleGuard = visible.guard() expect(visibleGuard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } })) - .toEqual(denial('may only read inside the workspace', 'FORK_PATH_OUTSIDE_WORKSPACE')) + .toEqual(outsideDenial('may only read inside the workspace')) expect(visibleGuard?.({ name: 'write', arguments: {}, agent: { id: 'child-1' } })) .toEqual(denial('may not use write', 'FORK_TOOL_NOT_PERMITTED')) @@ -275,7 +275,7 @@ describe('confined fork tools', () => { ((value: Record, next: () => unknown) => Promise) | undefined await preExecute?.({ token, arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } }, () => 'next') expect(h.guard()?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' }, token })) - .toEqual(denial('may only read inside the workspace', 'FORK_PATH_OUTSIDE_WORKSPACE')) + .toEqual(outsideDenial('may only read inside the workspace')) }) it('admits the PTC transport for a fork child while nested calls stay separately judged', () => { @@ -692,12 +692,12 @@ describe('source-session sandbox', () => { const narrowing = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: vi.fn().mockReturnValueOnce(true).mockReturnValue(false) } }) expect(installSourceSessionAccess(narrowing.target as never).writeConfined).toBe(true) await expect(narrowing.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) const blocked = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: () => false } }) installSourceSessionAccess(blocked.target as never) await expect(blocked.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) h.target.write = { mayWrite: () => true } const result = await confined.execute({ file_path: 'inside.ts', content: 'hello' }, { signal: undefined }) @@ -743,7 +743,7 @@ describe('source-session sandbox', () => { installSourceSessionAccess(closedEdit.target as never) await expect(closedEdit.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) + }, { signal: undefined })).rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) // The replacement's own argument check refuses arguments it cannot read. await expect(edit.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) @@ -755,7 +755,7 @@ describe('source-session sandbox', () => { installSourceSessionAccess(narrowing.target as never) await expect(narrowing.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('does not allow writing') as string }) + }, { signal: undefined })).rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) expect(narrowing.fs.editText).not.toHaveBeenCalled() }) diff --git a/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts b/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts index 364e8beedc..2f1f7ff433 100644 --- a/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts +++ b/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts @@ -29,7 +29,7 @@ import { import { ForkRegistry } from '../src/host/fork-registry.ts' import { SHARED_TOOL_PROFILES } from '../src/host/shared-tools.ts' import type { ForkToolExecution } from '../src/host/fork-tool-guard.ts' -import { denial } from './fork-denial.ts' +import { denial, outsideDenial } from './fork-denial.ts' import type { ForkToolDenial } from '../src/host/fork-errors.ts' const child = 'child-1' @@ -338,12 +338,12 @@ describe('fork enforcement wiring', () => { agent: { id: child }, token: Symbol('another-execution'), } - expect(captured.guard?.(other)).toEqual(denial(/workspace/u, 'FORK_PATH_OUTSIDE_WORKSPACE')) + expect(captured.guard?.(other)).toEqual(outsideDenial(/workspace/u)) // A path the resolution did not confirm is refused for that same execution. const outside: ForkToolExecution = { ...inside, arguments: { file_path: '/etc/passwd' } } await captured.preExecute?.(outside, () => Promise.resolve({ kind: 'allow' })) - expect(captured.guard?.(outside)).toEqual(denial(/workspace/u, 'FORK_PATH_OUTSIDE_WORKSPACE')) + expect(captured.guard?.(outside)).toEqual(outsideDenial(/workspace/u)) }) it('refuses a child whose scope cannot register the confined read, and keeps the prompt gate closed', async () => { diff --git a/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts b/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts index 48e81aa1c1..8ee08cfd81 100644 --- a/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts +++ b/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts @@ -13,7 +13,7 @@ import { type ForkToolExecution, } from '../src/host/fork-tool-guard.ts' import { READ_ONLY_FORK_CEILING, WRITE_FORK_CEILING } from '../src/host/fork-policy.ts' -import { denial } from './fork-denial.ts' +import { denial, outsideDenial } from './fork-denial.ts' import { forkToolDenial, type ForkToolDenial } from '../src/host/fork-errors.ts' const child = 'child-1' @@ -271,7 +271,7 @@ describe('fork tool guard', () => { const guard = forkToolGuard(host, () => READ_ONLY_FORK_CEILING, describeTool) // The path check runs through the host's resolution, not a prefix comparison in the guard. - expect(guard(execution('read', { path: '/etc/passwd' }))).toEqual(denial(/may only read inside the workspace/u, 'FORK_PATH_OUTSIDE_WORKSPACE')) + expect(guard(execution('read', { path: '/etc/passwd' }))).toEqual(outsideDenial(/may only read inside the workspace/u)) expect(refused).toContain('/etc/passwd') // Acting capabilities are refused before any path is even considered. for (const tool of ['bash', 'pwsh', 'cua', 'plugin_manager', 'schedule_create', 'write', 'edit', 'subagent']) { diff --git a/packages/experimental/liveshare/tests/write-current-policy.spec.ts b/packages/experimental/liveshare/tests/write-current-policy.spec.ts index 7907bbf8d0..47065ac7a5 100644 --- a/packages/experimental/liveshare/tests/write-current-policy.spec.ts +++ b/packages/experimental/liveshare/tests/write-current-policy.spec.ts @@ -255,6 +255,7 @@ describe('LiveShare current write policy', () => { const result = await pending expect(result.isError).toBe(true) expect(text(result)).toContain('does not allow writing this Session') + expect(result.error?.info).toEqual({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED' }) // The final gate asked again after the refresh; trusting the first verdict would have let this write // reach fs.writeText. expect(mayWriteChecks).toBe(2) From 5e5ef5091fbeabe439e5b93476479f095dc0d139 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:28:57 +0800 Subject: [PATCH 34/68] refactor(experimental): let the registry classify caller cancellation Cancellation thrown after the caller cancels is now a plain error named AbortError, which the tool registry records as ABORTED, instead of a HarnessError built with the registry's code. subagent-oar no longer depends on dsh-tools, TOOL_ABORTED leaves the dependency policy, and cua argument failures list one violation per issue again. Refs #7869 --- .../experimental/browser-use-runtime/src/index.ts | 8 +++----- .../browser-use-runtime/tests/resources.spec.ts | 2 +- packages/experimental/cua/src/index.ts | 11 +++++------ packages/experimental/subagent-oar/README.i18n.yaml | 4 ++-- packages/experimental/subagent-oar/README.md | 2 +- packages/experimental/subagent-oar/README.zh.md | 2 +- packages/experimental/subagent-oar/package.json | 1 - packages/experimental/subagent-oar/src/run.ts | 7 ++----- .../subagent-oar/tests/subagent-oar.spec.ts | 10 +++++----- packages/experimental/subagent-oar/tsconfig.json | 3 --- packages/experimental/tool-ralph/README.i18n.yaml | 4 ++-- packages/experimental/tool-ralph/README.md | 2 +- packages/experimental/tool-ralph/README.zh.md | 2 +- packages/experimental/tool-ralph/src/index.ts | 13 +++++-------- packages/experimental/tool-terminal/package.json | 6 ++---- packages/experimental/tool-terminal/src/index.ts | 11 ++++------- packages/experimental/tool-terminal/tsconfig.json | 3 --- scripts/package-dependency-policy.ts | 4 ++-- 18 files changed, 37 insertions(+), 58 deletions(-) diff --git a/packages/experimental/browser-use-runtime/src/index.ts b/packages/experimental/browser-use-runtime/src/index.ts index 9ce3e315e6..256d292b22 100644 --- a/packages/experimental/browser-use-runtime/src/index.ts +++ b/packages/experimental/browser-use-runtime/src/index.ts @@ -6,8 +6,6 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError } from '@deepseek-ai/dsh-error' -import { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' import { BrowserSessionError } from './error.ts' export { BROWSER_SESSION_ERROR_CODES, BrowserSessionError, type BrowserSessionErrorCode } from './error.ts' @@ -42,9 +40,9 @@ interface Entry { closing?: Promise } -/** The cancellation thrown for a non-`Error` abort reason, classified like the registry's own cancellation. */ -function operationCanceled(reason: unknown): HarnessError { - const error = new HarnessError('browser operation canceled', TOOL_ABORTED, { cause: reason }) +/** The cancellation thrown for a non-`Error` abort reason; the tool registry records it as `ABORTED`. */ +function operationCanceled(reason: unknown): Error { + const error = new Error('browser operation canceled', { cause: reason }) error.name = 'AbortError' return error } diff --git a/packages/experimental/browser-use-runtime/tests/resources.spec.ts b/packages/experimental/browser-use-runtime/tests/resources.spec.ts index d47fc361ec..5f7ffb2a99 100644 --- a/packages/experimental/browser-use-runtime/tests/resources.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/resources.spec.ts @@ -264,7 +264,7 @@ describe('Session browser resource ownership', () => { const resources = new SessionResources(ctx, { label: 'test', exclusive: false, open }) const controller = new AbortController() const waiting = resources.get(a.agent, controller.signal) - const canceled = expect(waiting).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED', message: 'browser operation canceled', cause: 'stop' }) + const canceled = expect(waiting).rejects.toMatchObject({ name: 'AbortError', message: 'browser operation canceled', cause: 'stop' }) await entered.promise controller.abort('stop') await canceled diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 7c2fcc7c48..5e9c036750 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -9,7 +9,6 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { ComputerUseProviderName } from '@deepseek-ai/dsh-computer-use/brand' import { admitEncodedImages } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import { HarnessError } from '@deepseek-ai/dsh-error' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' @@ -26,7 +25,7 @@ import { CuaCoordinates } from './coordinates.ts' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type { PromptSection } from '@deepseek-ai/dsh-system-prompt' -import { TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, ToolContextUnavailableError, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/dsh-computer-use' import type {} from '@deepseek-ai/dsh-ptc-runtime' @@ -96,13 +95,13 @@ function executionAgent(execution: Readonly): Agent { /** Parse the tool request; refinements the parameter schema cannot express fail as argument errors. */ function parseRequest(schema: z.ZodType, args: unknown): T { const parsed = schema.safeParse(args) - if (!parsed.success) throw new ToolArgsError([z.prettifyError(parsed.error)]) + if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`)) return parsed.data } -/** Native cancellation after the caller cancelled keeps its diagnostic under the registry's cancellation identity. */ -function callerCancelled(error: NativeError): HarnessError { - const cancelled = new HarnessError(error.message, TOOL_ABORTED, { cause: error }) +/** Native cancellation after the caller cancelled keeps its diagnostic; the tool registry records it as `ABORTED`. */ +function callerCancelled(error: NativeError): Error { + const cancelled = new Error(error.message, { cause: error }) cancelled.name = 'AbortError' return cancelled } diff --git a/packages/experimental/subagent-oar/README.i18n.yaml b/packages/experimental/subagent-oar/README.i18n.yaml index d090889de6..3b536bf9b8 100644 --- a/packages/experimental/subagent-oar/README.i18n.yaml +++ b/packages/experimental/subagent-oar/README.i18n.yaml @@ -27,8 +27,8 @@ en: cfc28b43567604a6 zh: 04ef0d698c3b47f7 /deepseek-ai-dsh-experimental-subagent-oar/understand-the-implementation: - en: e5ce31f92e58083e - zh: f0c6a7ac7001cd16 + en: ba50ae754617fbaf + zh: d808f24ea87fe549 /deepseek-ai-dsh-experimental-subagent-oar/further-exploration: en: 089fe63b9b457247 zh: 482382e68e5c4e2e diff --git a/packages/experimental/subagent-oar/README.md b/packages/experimental/subagent-oar/README.md index 38fbf04620..7a52ac5be6 100644 --- a/packages/experimental/subagent-oar/README.md +++ b/packages/experimental/subagent-oar/README.md @@ -104,7 +104,7 @@ The example mounts two instances of the same provider and the [external delegati The dependency patch applies environment overrides to native installation probes. It permits Claude's explicit `--permission-mode` and suppresses OAR's forced permission bypass when that argument is present. The example passes `--permission-mode dontAsk --permission-prompts none`. Codex receives `-c sandbox_mode="workspace-write"`. OAR sets Codex approval policy to `never`. Neither path forwards native approval requests to a DSH interaction UI. Codex startup failure stops app-server and waits for its exit, including a response without a thread id. -Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. Provider failures throw `OarFailure` with a closed `code`: `OAR_INVALID_TASK` for an empty or non-text task, `OAR_RUNTIME_UNAVAILABLE` for a missing, unsupported, or unprobeable runtime, `OAR_START_FAILED` for session startup, and `OAR_DISPOSE_FAILED` for session disposal; `OAR_TURN_FAILED` and `OAR_ABORT_FAILED` classify turn and interruption failures reported to the observer. Cancellation before the run starts rejects with an `AbortError` whose `code` is `ABORTED`. +Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. Provider failures throw `OarFailure` with a closed `code`: `OAR_INVALID_TASK` for an empty or non-text task, `OAR_RUNTIME_UNAVAILABLE` for a missing, unsupported, or unprobeable runtime, `OAR_START_FAILED` for session startup, and `OAR_DISPOSE_FAILED` for session disposal; `OAR_TURN_FAILED` and `OAR_ABORT_FAILED` classify turn and interruption failures reported to the observer. Cancellation before the run starts rejects with a `DOMException` named `AbortError`, which the tool registry records as `ABORTED`. diff --git a/packages/experimental/subagent-oar/README.zh.md b/packages/experimental/subagent-oar/README.zh.md index f82726ff29..8f0d6b9cd5 100644 --- a/packages/experimental/subagent-oar/README.zh.md +++ b/packages/experimental/subagent-oar/README.zh.md @@ -104,7 +104,7 @@ kind: "package-reference" 依赖补丁对原生安装探测应用环境覆盖,并允许 Claude 显式使用 `--permission-mode`,并在存在该参数时关闭 OAR 强制的权限绕过。示例传入 `--permission-mode dontAsk --permission-prompts none`。Codex 接收 `-c sandbox_mode="workspace-write"`。OAR 将 Codex 审批策略设为 `never`。两条路径均不将原生审批请求转发到 DSH 交互界面。Codex 启动失败时会停止 app-server 并等待其退出,包括响应中缺少线程 id 的情况。 -只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 为封闭集合:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 `code` 为 `ABORTED` 的 `AbortError` 拒绝。 +只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 为封闭集合:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 name 为 `AbortError` 的 `DOMException` 拒绝,工具注册表将其记为 `ABORTED`。 diff --git a/packages/experimental/subagent-oar/package.json b/packages/experimental/subagent-oar/package.json index 1e12579aeb..283877b4e2 100644 --- a/packages/experimental/subagent-oar/package.json +++ b/packages/experimental/subagent-oar/package.json @@ -40,7 +40,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { diff --git a/packages/experimental/subagent-oar/src/run.ts b/packages/experimental/subagent-oar/src/run.ts index 1305a5d17c..0f5584c426 100644 --- a/packages/experimental/subagent-oar/src/run.ts +++ b/packages/experimental/subagent-oar/src/run.ts @@ -28,7 +28,6 @@ import { type SubagentRun, type SubagentStopReason, } from '@deepseek-ai/dsh-subagent' -import { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' import { assertNever } from '@deepseek-ai/dsh-util-values' import { oarEnvironment } from './environment.ts' @@ -150,10 +149,8 @@ function isAborted(signal: AbortSignal): boolean { } /** The caller cancelled delegation before the run was published. */ -function cancellationFailure(): HarnessError { - const error = new HarnessError('OAR subagent startup was cancelled', TOOL_ABORTED) - error.name = 'AbortError' - return error +function cancellationFailure(): DOMException { + return new DOMException('OAR subagent startup was cancelled', 'AbortError') } async function disposeSession(session: Session, spec: OarRunSpec): Promise { diff --git a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts index f84a6ac614..f9833ad14f 100644 --- a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts +++ b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts @@ -261,7 +261,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError' }) await probed.promise controller.abort() release.resolve(undefined) @@ -283,7 +283,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError' }) await entered.promise controller.abort() release.resolve(undefined) @@ -297,7 +297,7 @@ describe('OAR one-shot execution', () => { const controller = new AbortController() controller.abort() await expect(startOarRun(await request(controller.signal), spec({ ...observed.runtime, installation: probe }))).rejects.toMatchObject({ - name: 'AbortError', code: 'ABORTED', + name: 'AbortError', }) expect(probe).not.toHaveBeenCalled() }) @@ -450,7 +450,7 @@ describe('OAR one-shot execution', () => { throw new Error('PRIVATE_START_DETAIL') } } await expect(startOarRun(await request(controller.signal), spec(canceled))).rejects.toMatchObject({ - name: 'AbortError', code: 'ABORTED', + name: 'AbortError', }) }) @@ -526,7 +526,7 @@ describe('OAR one-shot execution', () => { } } } } await expect(startOarRun(await request(controller.signal), spec(runtime))).rejects.toMatchObject({ - name: 'AbortError', code: 'ABORTED', + name: 'AbortError', }) expect(observed.dispose).toHaveBeenCalledOnce() }) diff --git a/packages/experimental/subagent-oar/tsconfig.json b/packages/experimental/subagent-oar/tsconfig.json index 2fe8a20db4..7476070bbb 100644 --- a/packages/experimental/subagent-oar/tsconfig.json +++ b/packages/experimental/subagent-oar/tsconfig.json @@ -38,9 +38,6 @@ { "path": "../../subprocess/subprocess" }, - { - "path": "../../core/tools" - }, { "path": "../../util/error" } diff --git a/packages/experimental/tool-ralph/README.i18n.yaml b/packages/experimental/tool-ralph/README.i18n.yaml index 22b7d8af28..7cfcc7b211 100644 --- a/packages/experimental/tool-ralph/README.i18n.yaml +++ b/packages/experimental/tool-ralph/README.i18n.yaml @@ -18,8 +18,8 @@ en: 13380e1170c6a3b5 zh: 2f2665f2ee5ff6f7 /deepseek-ai-dsh-tool-ralph/use-this-package/calling-the-tool: - en: 0c20532fc70c454e - zh: 19434818da6d244e + en: 577c4a894c1edf7a + zh: 48d401ba4c6769b9 /deepseek-ai-dsh-tool-ralph/use-this-package/what-each-round-sees: en: 2d8b861c4bcb9424 zh: 63c7b2d00c324727 diff --git a/packages/experimental/tool-ralph/README.md b/packages/experimental/tool-ralph/README.md index e0841486fa..65acbde9ff 100644 --- a/packages/experimental/tool-ralph/README.md +++ b/packages/experimental/tool-ralph/README.md @@ -29,7 +29,7 @@ The `ralph` tool runs a fixed foreground loop: one fresh child per round works o ### Calling the tool -The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a closed code: `RALPH_ROUND_FAILED` for a failed child round, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. +The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a closed code: `RALPH_ROUND_FAILED` for a child round that ends without a structured report, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, including a child report that fails validation inside the workflow because the workflow returns its errors only as text, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. ### What each round sees diff --git a/packages/experimental/tool-ralph/README.zh.md b/packages/experimental/tool-ralph/README.zh.md index 35651684f8..4660e2d919 100644 --- a/packages/experimental/tool-ralph/README.zh.md +++ b/packages/experimental/tool-ralph/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 调用工具 -模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 为封闭集合:子 agent Round 失败为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 +模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 为封闭集合:子 agent Round 结束时没有结构化报告为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,其中包括在 workflow 内校验失败的子 agent 报告,因为 workflow 只以文本返回错误,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 ### 每个 Round 看到什么 diff --git a/packages/experimental/tool-ralph/src/index.ts b/packages/experimental/tool-ralph/src/index.ts index 75d36b3e87..aeef0b6d18 100644 --- a/packages/experimental/tool-ralph/src/index.ts +++ b/packages/experimental/tool-ralph/src/index.ts @@ -7,14 +7,13 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { HarnessError } from '@deepseek-ai/dsh-error' -import { RalphError } from './error.ts' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' -import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow' +import { RalphError } from './error.ts' export const name = 'tool-ralph' export const inject = ['tools', 'workflowEngine', 'subagents', 'systemPrompt'] @@ -350,11 +349,9 @@ function stopReasonError(result: WorkflowResult): string | undefined { } } -/** The structured cancellation for a workflow the caller cancelled. */ -function ralphAborted(message: string): HarnessError { - const error = new HarnessError(message, TOOL_ABORTED) - error.name = 'AbortError' - return error +/** The cancellation for a workflow the caller cancelled; the tool registry records it as `ABORTED`. */ +function ralphAborted(message: string): DOMException { + return new DOMException(message, 'AbortError') } const TRUNCATION_NOTICE = '\n… [truncated]' diff --git a/packages/experimental/tool-terminal/package.json b/packages/experimental/tool-terminal/package.json index 1992387595..fabe723ad9 100644 --- a/packages/experimental/tool-terminal/package.json +++ b/packages/experimental/tool-terminal/package.json @@ -43,8 +43,7 @@ "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis-plugin-include": "workspace:~", @@ -69,7 +68,6 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-session-projection": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/experimental/tool-terminal/src/index.ts b/packages/experimental/tool-terminal/src/index.ts index 114491fdc6..638182ebdb 100644 --- a/packages/experimental/tool-terminal/src/index.ts +++ b/packages/experimental/tool-terminal/src/index.ts @@ -9,12 +9,11 @@ import { resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError } from '@deepseek-ai/dsh-error' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@deepseek-ai/dsh-terminal' import { JobError } from '@deepseek-ai/dsh-jobs' -import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import { sendSource } from './background.ts' import { boundTerminalText, renderList, renderRead, renderSend, renderSpawn } from './render.ts' @@ -123,11 +122,9 @@ function requireAgent(agent: Agent | undefined): Agent { return agent } -/** The structured cancellation for a foreground send the caller cancelled. */ -function sendAborted(): HarnessError { - const error = new HarnessError('terminal send aborted', TOOL_ABORTED) - error.name = 'AbortError' - return error +/** The cancellation for a foreground send the caller cancelled; the tool registry records it as `ABORTED`. */ +function sendAborted(): DOMException { + return new DOMException('terminal send aborted', 'AbortError') } function sessionId(args: SessionArgs): TerminalSessionIdType { diff --git a/packages/experimental/tool-terminal/tsconfig.json b/packages/experimental/tool-terminal/tsconfig.json index 10f4e0e1cd..a9bb35d5ca 100644 --- a/packages/experimental/tool-terminal/tsconfig.json +++ b/packages/experimental/tool-terminal/tsconfig.json @@ -40,9 +40,6 @@ }, { "path": "../../session/working-directory" - }, - { - "path": "../../util/error" } ] } diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 0c2ef16300..17bff44ca7 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -95,8 +95,8 @@ const PEER_REQUIRED_HOST_EXPORTS = { // appendPluginRecord writes through the Session class's private log; pluginRecordOf is stateless. '@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'], '@deepseek-ai/dsh-session-persistence': ['SessionPersistenceNotFoundError'], - // Tool failures from CUA and Liveshare carry the registry's own error classes and cancellation code. - '@deepseek-ai/dsh-tools': ['TOOL_ABORTED', 'ToolArgsError', 'ToolContextUnavailableError'], + // Error classes have instance identity; CUA and Liveshare throw the registry's own copy so `instanceof` against it matches. + '@deepseek-ai/dsh-tools': ['ToolArgsError', 'ToolContextUnavailableError'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. '@deepseek-ai/dsh-timeout': ['deadline'], } as const satisfies HostDependencyExports From 9a37ccab16ddf42fbb1d41b79238f0041682a9c2 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:28:58 +0800 Subject: [PATCH 35/68] docs(cua): explain IMAGE_MODEL_UNSUPPORTED on NativeError Refs #7869 --- .../cua-macos/tests/provider-lifecycle.spec.ts | 8 ++++---- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 485b13bd27..bafb67e096 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -26,7 +26,7 @@ import UserQuestions, { UserQuestionError } from '@deepseek-ai/dsh-user-question import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' -import { LlmAdapter, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { LlmAdapter, LlmError, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import Subprocess from '@deepseek-ai/dsh-subprocess' import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' @@ -671,7 +671,7 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) const saved = vi.spyOn(f.ctx.attachments, 'saveImages') const resolve = vi.spyOn(f.ctx.llm, 'resolveModelInfo') - if (route === 'provider-error') resolve.mockRejectedValue(new Error('model lookup failed')) + if (route === 'provider-error') resolve.mockRejectedValue(new LlmError('model lookup failed', 'UNKNOWN_MODEL')) else resolve.mockResolvedValue({ provider: 'image-fixture', id: 'vision', name: 'Vision', ...route === 'text-only' ? { inputModalities: ['text'] } : {}, }) @@ -679,10 +679,10 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain(route === 'unresolved' ? 'model route could not be resolved' - : route === 'provider-error' ? 'model lookup failed' : 'declare image input') + : route === 'provider-error' ? 'model lookup failed' : 'IMAGE_MODEL_UNSUPPORTED: CUA screenshots require model') expect(result.error?.info).toEqual(route === 'unresolved' ? { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } - : route === 'provider-error' ? undefined : { name: 'NativeError', code: 'IMAGE_MODEL_UNSUPPORTED' }) + : route === 'provider-error' ? { name: 'LlmError', code: 'UNKNOWN_MODEL' } : { name: 'NativeError', code: 'IMAGE_MODEL_UNSUPPORTED' }) expect(native.request).not.toHaveBeenCalled() expect(saved).not.toHaveBeenCalled() }, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 2b980c8662..66c472ea80 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: 588271340c0d2969 - zh: b368d49754564764 + en: 3d14b1f943e5750a + zh: 9b2fe4c4cdbb689f /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index edadba8d3b..b8015369ce 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -37,7 +37,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Observation methods emit and return their result. Use `void await app.getAccessibilityTree()` for one visible copy, or use `emit:false` and print the returned text once. `window.getScreenshot()` returns `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. -`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `IMAGE_MODEL_UNSUPPORTED` for a model without image input; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. +`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `IMAGE_MODEL_UNSUPPORTED` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 5e59834920..669599dd9b 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" 观察方法会输出并返回结果。使用 `void await app.getAccessibilityTree()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。`window.getScreenshot()` 返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 -`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `IMAGE_MODEL_UNSUPPORTED`;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 +`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `IMAGE_MODEL_UNSUPPORTED`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 From 65945ec65dcb71f192c8effc6eceb836dc427197 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:28:59 +0800 Subject: [PATCH 36/68] fix(stagehand): validate arguments before acquiring a browser Refs #7869 --- .../browser-use-stagehand-native/src/index.ts | 9 +++++---- .../browser-use-stagehand-native/tests/provider.spec.ts | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/experimental/browser-use-stagehand-native/src/index.ts b/packages/experimental/browser-use-stagehand-native/src/index.ts index 7555ba4e14..86b2a7c6eb 100644 --- a/packages/experimental/browser-use-stagehand-native/src/index.ts +++ b/packages/experimental/browser-use-stagehand-native/src/index.ts @@ -181,10 +181,6 @@ function mountTools(ctx: Context, resources: SessionResources): description: descriptions[method], inputSchema: { ...z.record(z.string(), z.json()).parse(z.toJSONSchema(browserInputs[method])), type: 'object' }, async call(args) { - const parsed = browserInputs[method].safeParse(args) - if (!parsed.success) { - throw new ToolArgsError(parsed.error.issues.map(issue => `${['arguments', ...issue.path].join('.')}: ${issue.message}`)) - } const agent = ctx.agents.requireInitiator() const resource = await resources.get(agent) return resource.native.execute(method, args, resource.operationSignal) @@ -198,6 +194,11 @@ function mountTools(ctx: Context, resources: SessionResources): if (agent === undefined || ctx.agents.get(agent.id) !== agent) { throw new ToolContextUnavailableError('Stagehand browser tools require an exact live Agent') } + // Arguments are checked before the browser is acquired, so an invalid first call launches nothing. + const parsed = browserInputs[exec.name.slice('stagehand_'.length) as BrowserMethod].safeParse(exec.arguments) + if (!parsed.success) { + throw new ToolArgsError(parsed.error.issues.map(issue => `${['arguments', ...issue.path].join('.')}: ${issue.message}`)) + } return resources.run(agent, exec.signal, async (resource, activeSignal) => { const upstreamSignal = exec.signal exec.signal = activeSignal diff --git a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts index 5ff749fdb1..aa35d4ce4b 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts @@ -132,6 +132,12 @@ it('reserves an attached browser for one live owner and rejects model connection expect(malformed.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: arguments.url: Invalid URL' }]) }) +it('rejects invalid arguments before acquiring a browser', async () => { + await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) + expect((await execute(first, 'navigate', { url: 'not a url' })).error?.info).toEqual(INVALID_ARGS) + expect(fixture.browsers).toEqual([]) +}) + it('uses its independent model for actions, observations, and a caller-selected extraction schema', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) expect((await execute(first, 'act', { instruction: 'Click the fixture button' })).isError).toBe(false) From dbe423e1ee177c58f4986b13d738ebc059b15c2a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:29:00 +0800 Subject: [PATCH 37/68] feat(claude-code-mods): export ModUnansweredError Refs #7869 --- packages/experimental/claude-code-mods/src/host-ops.ts | 2 +- packages/experimental/claude-code-mods/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 2f22010ead..1db9e90bdf 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -78,7 +78,7 @@ const storeDomainSpec = defineDomain({ }) /** A call to a mod-registered tool that no `tool.call` hook answered; code `MOD_UNANSWERED`. */ -class ModUnansweredError extends HarnessError { +export class ModUnansweredError extends HarnessError { constructor(message: string) { super(message, 'MOD_UNANSWERED') this.name = 'ModUnansweredError' diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index bcce9050c3..1402af313e 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -47,7 +47,7 @@ export type { BoxProps, ButtonProps, TextProps, UiElement, UiElements, UiNode } export { defineMod, type ModConfig, type ModPlugin, type ModSpec } from './define-mod.ts' export { DEFAULT_TOOL_ALIASES } from './tool-names.ts' export { KNOWN_EVENTS } from './matcher.ts' -export { MODS_API_VERSION } from './host-ops.ts' +export { ModUnansweredError, MODS_API_VERSION } from './host-ops.ts' /** Plugin config: the limits mod hooks run under. */ export interface Config { From bbc0ab304936aed80071b92c167420c4a26e9e74 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:29:00 +0800 Subject: [PATCH 38/68] docs(worktree): narrow WORKTREE_INVALID_ARGUMENT and note rebuilt subclasses Refs #7869 --- packages/experimental/worktree/README.i18n.yaml | 4 ++-- packages/experimental/worktree/README.md | 2 +- packages/experimental/worktree/README.zh.md | 2 +- packages/experimental/worktree/src/index.ts | 2 ++ 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 24f4fb03b2..b97e443ecd 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: 743828cee4516880 - zh: 76e9679e4467a100 + en: e33f2d32037ef164 + zh: 18528ef31803c6d0 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index f98f15119c..30cfcfca04 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -38,7 +38,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. -Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name, start revision, or restoration record that Git or the pool rules reject; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. +Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name Git or the pool rules reject, an empty start revision, or a restoration record that violates a documented constraint, while a start revision or base commit Git cannot resolve fails as `WORKTREE_COMMAND_FAILED`; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. The default checkout directory is `/.agents/worktrees/`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Each Git and Node command runs under its own `timeoutMs` deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative `directory`, generated `namePrefix`, executable choices, process limits, and `retainOnArchive` are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree). diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 720bdc316f..28fc6fb0b0 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -38,7 +38,7 @@ kind: "package-reference" 每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 -预期失败抛出 `WorktreeError`,其 `code` 为:名称、起始修订或恢复记录被 Git 或池规则拒绝时为 `WORKTREE_INVALID_ARGUMENT`;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 +预期失败抛出 `WorktreeError`,其 `code` 为:名称被 Git 或池规则拒绝、起始修订为空或恢复记录违反文档约束时为 `WORKTREE_INVALID_ARGUMENT`,Git 无法解析的起始修订或基础提交则以 `WORKTREE_COMMAND_FAILED` 失败;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 默认检出目录是 `/.agents/worktrees/`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。每条 Git 和 Node 命令各自受 `timeoutMs` 时限约束,默认 5 分钟,使大仓库在较慢的文件系统上也能完成检出;取消仍会终止正在运行的命令。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序、进程限制与 `retainOnArchive` 可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 5de7e32034..8e2c5b5ade 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -381,6 +381,8 @@ async function assertBranchName(run: GitRun, directory: string, branch: string, /** * Add retained-artifact context to a failure without changing its routable identity: * a `HarnessError` keeps its `name` and `code`, and caller cancellation stays an `AbortError`. + * A `HarnessError` subclass other than `WorktreeError` is rebuilt as a plain `HarnessError`, so + * callers route on `name` and `code` rather than on `instanceof` the original subclass. * @param context - operation summary placed before the original message. * @param error - failure thrown after allocation began. * @param signal - operation cancellation. From c9e8e267fe47ec9718d825d4f145ef289d22255a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:29:01 +0800 Subject: [PATCH 39/68] docs(upgrade-guide): record experimental tool error identity changes Refs #7869 --- .../guide.i18n.yaml | 16 +++++++++++ .../experimental-tool-error-codes/guide.md | 28 +++++++++++++++++++ .../experimental-tool-error-codes/guide.zh.md | 28 +++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml new file mode 100644 index 0000000000..fef3857b59 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md +/: + en: 4d6f7a78d1415f20 + zh: a5a906f4f1266243 +/experimental-plugin-failures-carry-error-codes: + en: 075d975981aa61d4 + zh: 244a36616232b8e1 +/experimental-plugin-failures-carry-error-codes/change: + en: 24c062b512a0f397 + zh: 93261e864b83a6f7 +/experimental-plugin-failures-carry-error-codes/migration: + en: 6365d4f60118cf64 + zh: c2f1378dee8ea4b4 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md new file mode 100644 index 0000000000..24c2821847 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental and hook plugin tool failures record error codes, NativeError, OarFailure, and StagehandDrainError become HarnessError subclasses, and browser cleanup rejects with BrowserSessionError." +--- + +# Experimental plugin failures carry error codes + +English | [中文](guide.zh.md) + +## Change + +Tool failures from the CUA, browser-use, Cua Driver, worktree, Ralph, terminal, OAR subagent, Liveshare, Claude Code and Codex hook, and claude-code-mods plugins now record `error: { name, code }` on `tool/result`; previously most of these results had no `error`. The [package READMEs](../../../../packages/experimental/README.md) list each class and code. + +Code that handles these failures in-process sees these changes: + +- `NativeError` from `@deepseek-ai/dsh-cua` and `OarFailure` from `@deepseek-ai/dsh-experimental-subagent-oar` now extend `HarnessError` from `@deepseek-ai/dsh-error`. `NativeError` keeps its name, codes, and `CODE: message` text. `OarFailure` drops its `stage` and `category` fields; the same summary stays in `message`, and `code` names the stage. Cancellation before an OAR run starts rejects with a `DOMException` named `AbortError` instead of an `OarFailure`. +- `StagehandDrainError` from `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` now extends `StagehandError` and has the code `STAGEHAND_CLEANUP_FAILED`. +- `SessionResources.dispose()` from `@deepseek-ai/dsh-experimental-browser-use-runtime` rejects with `BrowserSessionError` (`BROWSER_CLEANUP_FAILED`) whose `cause` is the `AggregateError` it previously threw; `instanceof AggregateError` no longer matches. +- Liveshare guard functions return `{ reason, info }` instead of a reason string. +- Argument failures that now throw `ToolArgsError` show `invalid arguments: ` before the message the model sees, and a CUA screenshot request for a model without image input shows `IMAGE_MODEL_UNSUPPORTED: ` before its message. + +## Migration + +1. If analytics or retry rules read `tool/result` `error`, add the new names and codes from the package READMEs. Earlier Session logs keep results without `error`. +2. Replace `instanceof AggregateError` checks on `SessionResources.dispose()` rejections with `instanceof BrowserSessionError` and read the individual failures from `error.cause.errors`. +3. Replace reads of `OarFailure.stage` or `category` with `error.code`. +4. If code catches `HarnessError` before `NativeError`, `OarFailure`, or `StagehandDrainError`, move the specific check first where the handling differs. +5. Confirm with `pnpm run typecheck` and your own failure-path tests. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md new file mode 100644 index 0000000000..13c75c7f60 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental 与 hook 插件的工具失败带上错误 code,NativeError、OarFailure 与 StagehandDrainError 改为 HarnessError 子类,浏览器清理失败改为以 BrowserSessionError 拒绝。" +--- + +# Experimental 插件的失败带上错误 code + +[English](guide.md) | 中文 + +## 变更 + +CUA、browser-use、Cua Driver、worktree、Ralph、终端、OAR 子 agent、Liveshare、Claude Code 与 Codex hook,以及 claude-code-mods 插件的工具失败现在会在 `tool/result` 上记录 `error: { name, code }`;此前这些结果大多没有 `error`。各[包 README](../../../../packages/experimental/README.zh.md) 列出了每个类和 code。 + +在进程内处理这些失败的代码会看到以下变化: + +- `@deepseek-ai/dsh-cua` 的 `NativeError` 与 `@deepseek-ai/dsh-experimental-subagent-oar` 的 `OarFailure` 现在继承 `@deepseek-ai/dsh-error` 的 `HarnessError`。`NativeError` 的 name、code 与 `CODE: message` 文本不变。`OarFailure` 去掉了 `stage` 与 `category` 字段;同样的摘要保留在 `message` 中,`code` 标明阶段。OAR 运行开始前的取消改为以 name 为 `AbortError` 的 `DOMException` 拒绝,不再是 `OarFailure`。 +- `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` 的 `StagehandDrainError` 现在继承 `StagehandError`,code 为 `STAGEHAND_CLEANUP_FAILED`。 +- `@deepseek-ai/dsh-experimental-browser-use-runtime` 的 `SessionResources.dispose()` 改为以 `BrowserSessionError`(`BROWSER_CLEANUP_FAILED`)拒绝,其 `cause` 是此前直接抛出的 `AggregateError`;`instanceof AggregateError` 不再成立。 +- Liveshare 的 guard 函数改为返回 `{ reason, info }`,不再返回原因字符串。 +- 改为抛出 `ToolArgsError` 的参数失败,模型看到的 message 前多了 `invalid arguments: `;为不支持图片输入的模型请求 CUA 截图时,message 前多了 `IMAGE_MODEL_UNSUPPORTED: `。 + +## 迁移 + +1. 如果分析或重试规则读取 `tool/result` 的 `error`,按包 README 补充新的 name 与 code。较早的 Session 日志中这些结果仍没有 `error`。 +2. 把对 `SessionResources.dispose()` 拒绝值的 `instanceof AggregateError` 检查改为 `instanceof BrowserSessionError`,并从 `error.cause.errors` 读取各个失败。 +3. 把读取 `OarFailure.stage` 或 `category` 的代码改为读取 `error.code`。 +4. 如果代码在 `NativeError`、`OarFailure` 或 `StagehandDrainError` 之前捕获 `HarnessError`,在处理方式不同的地方把具体类的检查移到前面。 +5. 用 `pnpm run typecheck` 和自己的失败路径测试确认迁移完成。 From 4eda73d1e275aa8acd66e2a5f4260fa869e5075a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:29:02 +0800 Subject: [PATCH 40/68] docs: regenerate config catalog and module graph Refs #7869 --- docs/config-catalog.md | 4 ++-- docs/config-catalog.zh.md | 4 ++-- docs/module-graph.md | 6 ++---- docs/module-graph.zh.md | 6 ++---- pnpm-lock.yaml | 3 --- 5 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d7fdc650b0..b9761c3c5d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4453,7 +4453,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:25`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -4606,7 +4606,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-terminal` - `inject`: `terminals` · `tools` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/experimental/tool-terminal/src/index.ts:39`](../packages/experimental/tool-terminal/src/index.ts) +- `source`: [`packages/experimental/tool-terminal/src/index.ts:38`](../packages/experimental/tool-terminal/src/index.ts) ```ts config-catalog /** Model-facing terminal tool configuration. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4216b20b96..1f9d4ad1cf 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4455,7 +4455,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:25`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -4608,7 +4608,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-terminal` - `inject`: `terminals` · `tools` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/experimental/tool-terminal/src/index.ts:39`](../packages/experimental/tool-terminal/src/index.ts) +- `source`: [`packages/experimental/tool-terminal/src/index.ts:38`](../packages/experimental/tool-terminal/src/index.ts) ```ts config-catalog /** Model-facing terminal tool configuration. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index 2e71ff98d6..dd6b077054 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1007,7 +1007,6 @@ flowchart TD pkg_terminal_panel --> pkg_terminal pkg_terminal_panel --> pkg_tools pkg_tool_terminal --> pkg_agent - pkg_tool_terminal --> pkg_error pkg_tool_terminal --> pkg_jobs pkg_tool_terminal --> pkg_llm pkg_tool_terminal --> pkg_output_retention @@ -1449,7 +1448,6 @@ flowchart TD pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent pkg_experimental_subagent_oar --> pkg_subprocess - pkg_experimental_subagent_oar --> pkg_tools pkg_experimental_tool_subagent_oar --> pkg_subagent pkg_experimental_tool_subagent_oar --> pkg_tools pkg_experimental_tool_worktree --> pkg_experimental_worktree @@ -1854,7 +1852,7 @@ flowchart TD | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) | | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | @@ -1920,7 +1918,7 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 989b3ab104..a09935ab65 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1009,7 +1009,6 @@ flowchart TD pkg_terminal_panel --> pkg_terminal pkg_terminal_panel --> pkg_tools pkg_tool_terminal --> pkg_agent - pkg_tool_terminal --> pkg_error pkg_tool_terminal --> pkg_jobs pkg_tool_terminal --> pkg_llm pkg_tool_terminal --> pkg_output_retention @@ -1451,7 +1450,6 @@ flowchart TD pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent pkg_experimental_subagent_oar --> pkg_subprocess - pkg_experimental_subagent_oar --> pkg_tools pkg_experimental_tool_subagent_oar --> pkg_subagent pkg_experimental_tool_subagent_oar --> pkg_tools pkg_experimental_tool_worktree --> pkg_experimental_worktree @@ -1856,7 +1854,7 @@ flowchart TD | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) | | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | @@ -1922,7 +1920,7 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ce560e21c9..e331f90d51 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11481,9 +11481,6 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit - '@deepseek-ai/dsh-error': - specifier: workspace:* - version: link:../../util/error '@deepseek-ai/dsh-jobs': specifier: workspace:* version: link:../../jobs/jobs From f86265f1cad98e1c22d36bac1cee890bc96af13d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 16:49:31 +0800 Subject: [PATCH 41/68] refactor(cua): use MODEL_DOES_NOT_SUPPORT_IMAGES for models without image input The repository already names this condition MODEL_DOES_NOT_SUPPORT_IMAGES in attachment rejections, client labels, and office tools, so the cua screenshot refusal reuses it instead of a second code. Refs #7869 --- .../v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml | 4 ++-- .../v0.2.2-rc.1/experimental-tool-error-codes/guide.md | 2 +- .../v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md | 2 +- .../experimental/cua-macos/tests/provider-lifecycle.spec.ts | 4 ++-- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 2 +- packages/experimental/cua/src/native-client.ts | 2 +- 9 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml index fef3857b59..97e12e6ba3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 075d975981aa61d4 zh: 244a36616232b8e1 /experimental-plugin-failures-carry-error-codes/change: - en: 24c062b512a0f397 - zh: 93261e864b83a6f7 + en: d5878c5ce6fbfb76 + zh: 2f2d29a1f3a9d6f3 /experimental-plugin-failures-carry-error-codes/migration: en: 6365d4f60118cf64 zh: c2f1378dee8ea4b4 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md index 24c2821847..c4e579dd36 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md @@ -17,7 +17,7 @@ Code that handles these failures in-process sees these changes: - `StagehandDrainError` from `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` now extends `StagehandError` and has the code `STAGEHAND_CLEANUP_FAILED`. - `SessionResources.dispose()` from `@deepseek-ai/dsh-experimental-browser-use-runtime` rejects with `BrowserSessionError` (`BROWSER_CLEANUP_FAILED`) whose `cause` is the `AggregateError` it previously threw; `instanceof AggregateError` no longer matches. - Liveshare guard functions return `{ reason, info }` instead of a reason string. -- Argument failures that now throw `ToolArgsError` show `invalid arguments: ` before the message the model sees, and a CUA screenshot request for a model without image input shows `IMAGE_MODEL_UNSUPPORTED: ` before its message. +- Argument failures that now throw `ToolArgsError` show `invalid arguments: ` before the message the model sees, and a CUA screenshot request for a model without image input shows `MODEL_DOES_NOT_SUPPORT_IMAGES: ` before its message. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md index 13c75c7f60..41e8ba1902 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md @@ -17,7 +17,7 @@ CUA、browser-use、Cua Driver、worktree、Ralph、终端、OAR 子 agent、Liv - `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` 的 `StagehandDrainError` 现在继承 `StagehandError`,code 为 `STAGEHAND_CLEANUP_FAILED`。 - `@deepseek-ai/dsh-experimental-browser-use-runtime` 的 `SessionResources.dispose()` 改为以 `BrowserSessionError`(`BROWSER_CLEANUP_FAILED`)拒绝,其 `cause` 是此前直接抛出的 `AggregateError`;`instanceof AggregateError` 不再成立。 - Liveshare 的 guard 函数改为返回 `{ reason, info }`,不再返回原因字符串。 -- 改为抛出 `ToolArgsError` 的参数失败,模型看到的 message 前多了 `invalid arguments: `;为不支持图片输入的模型请求 CUA 截图时,message 前多了 `IMAGE_MODEL_UNSUPPORTED: `。 +- 改为抛出 `ToolArgsError` 的参数失败,模型看到的 message 前多了 `invalid arguments: `;为不支持图片输入的模型请求 CUA 截图时,message 前多了 `MODEL_DOES_NOT_SUPPORT_IMAGES: `。 ## 迁移 diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index bafb67e096..b3fd48429f 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -679,10 +679,10 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain(route === 'unresolved' ? 'model route could not be resolved' - : route === 'provider-error' ? 'model lookup failed' : 'IMAGE_MODEL_UNSUPPORTED: CUA screenshots require model') + : route === 'provider-error' ? 'model lookup failed' : 'MODEL_DOES_NOT_SUPPORT_IMAGES: CUA screenshots require model') expect(result.error?.info).toEqual(route === 'unresolved' ? { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } - : route === 'provider-error' ? { name: 'LlmError', code: 'UNKNOWN_MODEL' } : { name: 'NativeError', code: 'IMAGE_MODEL_UNSUPPORTED' }) + : route === 'provider-error' ? { name: 'LlmError', code: 'UNKNOWN_MODEL' } : { name: 'NativeError', code: 'MODEL_DOES_NOT_SUPPORT_IMAGES' }) expect(native.request).not.toHaveBeenCalled() expect(saved).not.toHaveBeenCalled() }, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 66c472ea80..e64ff7e781 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: 3d14b1f943e5750a - zh: 9b2fe4c4cdbb689f + en: 865cdaa6a79e84fb + zh: 61cc20003428c55b /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index b8015369ce..372713c9ec 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -37,7 +37,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Observation methods emit and return their result. Use `void await app.getAccessibilityTree()` for one visible copy, or use `emit:false` and print the returned text once. `window.getScreenshot()` returns `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. -`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `IMAGE_MODEL_UNSUPPORTED` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. +`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `MODEL_DOES_NOT_SUPPORT_IMAGES` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 669599dd9b..3361078e52 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" 观察方法会输出并返回结果。使用 `void await app.getAccessibilityTree()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。`window.getScreenshot()` 返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 -`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `IMAGE_MODEL_UNSUPPORTED`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 +`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 5e9c036750..f9bb0f5eb0 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -137,7 +137,7 @@ async function screenshotStore(ctx: Context, execution: Readonly) const info = await llm.resolveModelInfo(provider, model, execution.signal) execution.signal.throwIfAborted() if (!info.inputModalities?.includes('image')) { - throw new NativeError('IMAGE_MODEL_UNSUPPORTED', `CUA screenshots require model "${model}" to declare image input`) + throw new NativeError('MODEL_DOES_NOT_SUPPORT_IMAGES', `CUA screenshots require model "${model}" to declare image input`) } return { attachments, target: (image: ImageAttachmentRef) => llm.imageRequestTarget(provider, model, image) } } diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index 667682ca81..6b377d25a5 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -23,7 +23,7 @@ const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal( * Native refusal, transport failure, or host-side CUA refusal with a stable machine-readable code. * The helper supplies its own codes, such as `APP_ACCESS_DENIED` or `STALE_SNAPSHOT`, so consumers * tolerate unknown codes; the host adds `NATIVE_*` transport codes, application-access codes, - * and `IMAGE_MODEL_UNSUPPORTED` for a screenshot requested by a model without image input. + * and `MODEL_DOES_NOT_SUPPORT_IMAGES` for a screenshot requested by a model without image input. */ export class NativeError extends HarnessError { /** From 4dc50c135db03f36e9175289908e83195e020621 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 17:28:04 +0800 Subject: [PATCH 42/68] chore(ptc-runtime): carry PtcRuntimeError from #8168 These six files match deepseek-harness#8168 at c9aa6745371 byte for byte, so ptc-runtime-python can classify its runtime failures before that pull request lands; whichever lands first makes this part of the other a no-op. Refs #7869 --- .../ptc-runtime/ptc-runtime/README.i18n.yaml | 4 +-- packages/ptc-runtime/ptc-runtime/README.md | 2 +- packages/ptc-runtime/ptc-runtime/README.zh.md | 2 +- packages/ptc-runtime/ptc-runtime/package.json | 6 ++-- packages/ptc-runtime/ptc-runtime/src/index.ts | 36 +++++++++++++++++-- .../ptc-runtime/ptc-runtime/tsconfig.json | 3 ++ pnpm-lock.yaml | 3 ++ 7 files changed, 47 insertions(+), 9 deletions(-) diff --git a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml index bce60e0d33..143eb3376c 100644 --- a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml @@ -27,8 +27,8 @@ en: 4e46c1672701b8df zh: 0353c5855c9ff6be /deepseek-ai-dsh-ptc-runtime/use-this-package/what-can-go-wrong: - en: 44f9fdf2c8e2cacc - zh: 99dd555a49075f88 + en: 35129568fa436d64 + zh: 0f4138ad427ef486 /deepseek-ai-dsh-ptc-runtime/understand-the-implementation: en: 686d570f5e669fa4 zh: 2075cf27c30f251a diff --git a/packages/ptc-runtime/ptc-runtime/README.md b/packages/ptc-runtime/ptc-runtime/README.md index eb9a2e3c6d..c02a80223a 100644 --- a/packages/ptc-runtime/ptc-runtime/README.md +++ b/packages/ptc-runtime/ptc-runtime/README.md @@ -52,7 +52,7 @@ Binding-global and error-class names are language-portable: they must match `[A- ### What can go wrong -Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal. +Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal. Contract misuse rejects with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for an invalid request or spec, `PTC_RUNTIME_UNAVAILABLE` after disposal or while a retained environment's cleanup is incomplete, and `PTC_RUNTIME_CONFLICT` for a concurrent run for one owner or a retained environment launched under another sandbox policy. ----- diff --git a/packages/ptc-runtime/ptc-runtime/README.zh.md b/packages/ptc-runtime/ptc-runtime/README.zh.md index 0fef2d6b77..75d5c8cd89 100644 --- a/packages/ptc-runtime/ptc-runtime/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime/README.zh.md @@ -52,7 +52,7 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配 `[A-Za ### 可能出什么问题 -失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。 +失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。契约误用以 `PtcRuntimeError` 拒绝:无效的请求或 spec 为 `PTC_RUNTIME_INVALID_ARGUMENT`,资源释放后或保留环境清理未完成时为 `PTC_RUNTIME_UNAVAILABLE`,同一所有者的并发运行或保留环境以其他沙箱策略启动时为 `PTC_RUNTIME_CONFLICT`。 ----- diff --git a/packages/ptc-runtime/ptc-runtime/package.json b/packages/ptc-runtime/ptc-runtime/package.json index 58c01c7fd5..b4d17a979f 100644 --- a/packages/ptc-runtime/ptc-runtime/package.json +++ b/packages/ptc-runtime/ptc-runtime/package.json @@ -31,10 +31,12 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-sandbox": "workspace:*" + "@deepseek-ai/dsh-sandbox": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-sandbox": "workspace:*" + "@deepseek-ai/dsh-sandbox": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/ptc-runtime/ptc-runtime/src/index.ts b/packages/ptc-runtime/ptc-runtime/src/index.ts index 2fa080fcde..8bdc78221c 100644 --- a/packages/ptc-runtime/ptc-runtime/src/index.ts +++ b/packages/ptc-runtime/ptc-runtime/src/index.ts @@ -5,6 +5,7 @@ */ import { Context, Service } from '@deepseek-ai/cordis' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from './types.ts' import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' @@ -95,10 +96,39 @@ declare module '@deepseek-ai/cordis' { } } +/** + * Every {@link PtcRuntimeError} code: + * - `PTC_RUNTIME_UNAVAILABLE`: the runtime was disposed, or a retained environment's cleanup is + * incomplete; release the owner or reload the runtime before running more programs. + * - `PTC_RUNTIME_CONFLICT`: a program is already running for the same state owner, or the owner's + * retained environment was launched under a different sandbox policy; wait, or release the owner. + * - `PTC_RUNTIME_INVALID_ARGUMENT`: the consumer passed a request or spec that violates this contract, + * such as a relative `cwd` or an unresolved spec. + */ +export const PTC_RUNTIME_ERROR_CODES = [ + 'PTC_RUNTIME_UNAVAILABLE', + 'PTC_RUNTIME_CONFLICT', + 'PTC_RUNTIME_INVALID_ARGUMENT', +] as const + +/** One {@link PtcRuntimeError} code. */ +export type PtcRuntimeErrorCode = typeof PTC_RUNTIME_ERROR_CODES[number] + +/** Contract misuse a {@link PtcRuntime} rejects; `code` is one of {@link PTC_RUNTIME_ERROR_CODES}. */ +export class PtcRuntimeError extends HarnessError { + override readonly code: PtcRuntimeErrorCode + + constructor(message: string, code: PtcRuntimeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'PtcRuntimeError' + this.code = code + } +} + /** * Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate - * failures resolve in {@link PtcRunResult}; only Service Definition contract misuse rejects. Implementations bridge - * structured-cloneable bindings, materialize each declared namespace rejection + * failures resolve in {@link PtcRunResult}; only Service Definition contract misuse rejects, with + * {@link PtcRuntimeError}. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection * class, treat programs as hostile peers, isolate distinct state owners, and * terminate and await in-flight runs during disposal. */ @@ -154,7 +184,7 @@ export abstract class PtcRuntime extends Service { * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. * @returns Complete directory, deadline and supported authority for run. - * @throws When an explicit choice is invalid or unsupported by this provider. + * @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}. */ abstract resolve(request: PtcRunRequest): PtcRunSpec diff --git a/packages/ptc-runtime/ptc-runtime/tsconfig.json b/packages/ptc-runtime/ptc-runtime/tsconfig.json index de6feb55b9..b1ac16cc8d 100644 --- a/packages/ptc-runtime/ptc-runtime/tsconfig.json +++ b/packages/ptc-runtime/ptc-runtime/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../sandbox/sandbox" + }, + { + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e331f90d51..c97f9f08ba 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14163,6 +14163,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-sandbox': specifier: workspace:* version: link:../../sandbox/sandbox From 91a9ca82e58fe5d55d008d4ead2221042d177522 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 17:42:08 +0800 Subject: [PATCH 43/68] feat(ptc-runtime-python): reject caller misuse with PtcRuntimeError A call after disposal now rejects with PTC_RUNTIME_UNAVAILABLE, and an unsupported timeout, a relative cwd, a missing sandbox policy, and an invalid binding or error class reject with PTC_RUNTIME_INVALID_ARGUMENT, matching the Node provider. Messages are unchanged; load-time configuration errors and the fd-3 invariant stay plain errors. Refs #7869 --- .../guide.i18n.yaml | 4 +-- .../experimental-tool-error-codes/guide.md | 1 + .../experimental-tool-error-codes/guide.zh.md | 1 + .../ptc-runtime-python/README.i18n.yaml | 4 +-- .../experimental/ptc-runtime-python/README.md | 2 +- .../ptc-runtime-python/README.zh.md | 2 +- .../ptc-runtime-python/src/index.ts | 30 ++++++++-------- .../ptc-runtime-python/tests/runtime.spec.ts | 34 +++++++++---------- 8 files changed, 40 insertions(+), 38 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml index 97e12e6ba3..13f20ee758 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 075d975981aa61d4 zh: 244a36616232b8e1 /experimental-plugin-failures-carry-error-codes/change: - en: d5878c5ce6fbfb76 - zh: 2f2d29a1f3a9d6f3 + en: 98bbff2056476763 + zh: 390a61ff8faeeec0 /experimental-plugin-failures-carry-error-codes/migration: en: 6365d4f60118cf64 zh: c2f1378dee8ea4b4 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md index c4e579dd36..50ee9c88ba 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md @@ -14,6 +14,7 @@ Tool failures from the CUA, browser-use, Cua Driver, worktree, Ralph, terminal, Code that handles these failures in-process sees these changes: - `NativeError` from `@deepseek-ai/dsh-cua` and `OarFailure` from `@deepseek-ai/dsh-experimental-subagent-oar` now extend `HarnessError` from `@deepseek-ai/dsh-error`. `NativeError` keeps its name, codes, and `CODE: message` text. `OarFailure` drops its `stage` and `category` fields; the same summary stays in `message`, and `code` names the stage. Cancellation before an OAR run starts rejects with a `DOMException` named `AbortError` instead of an `OarFailure`. +- `PythonPtcRuntime` from `@deepseek-ai/dsh-experimental-ptc-runtime-python` rejects caller misuse with `PtcRuntimeError` from `@deepseek-ai/dsh-ptc-runtime` (`PTC_RUNTIME_INVALID_ARGUMENT` or `PTC_RUNTIME_UNAVAILABLE`) instead of a plain `Error`; messages are unchanged. - `StagehandDrainError` from `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` now extends `StagehandError` and has the code `STAGEHAND_CLEANUP_FAILED`. - `SessionResources.dispose()` from `@deepseek-ai/dsh-experimental-browser-use-runtime` rejects with `BrowserSessionError` (`BROWSER_CLEANUP_FAILED`) whose `cause` is the `AggregateError` it previously threw; `instanceof AggregateError` no longer matches. - Liveshare guard functions return `{ reason, info }` instead of a reason string. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md index 41e8ba1902..74e5b3e7c7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md @@ -14,6 +14,7 @@ CUA、browser-use、Cua Driver、worktree、Ralph、终端、OAR 子 agent、Liv 在进程内处理这些失败的代码会看到以下变化: - `@deepseek-ai/dsh-cua` 的 `NativeError` 与 `@deepseek-ai/dsh-experimental-subagent-oar` 的 `OarFailure` 现在继承 `@deepseek-ai/dsh-error` 的 `HarnessError`。`NativeError` 的 name、code 与 `CODE: message` 文本不变。`OarFailure` 去掉了 `stage` 与 `category` 字段;同样的摘要保留在 `message` 中,`code` 标明阶段。OAR 运行开始前的取消改为以 name 为 `AbortError` 的 `DOMException` 拒绝,不再是 `OarFailure`。 +- `@deepseek-ai/dsh-experimental-ptc-runtime-python` 的 `PythonPtcRuntime` 对调用方误用改为以 `@deepseek-ai/dsh-ptc-runtime` 的 `PtcRuntimeError`(`PTC_RUNTIME_INVALID_ARGUMENT` 或 `PTC_RUNTIME_UNAVAILABLE`)拒绝,不再是普通 `Error`;message 不变。 - `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` 的 `StagehandDrainError` 现在继承 `StagehandError`,code 为 `STAGEHAND_CLEANUP_FAILED`。 - `@deepseek-ai/dsh-experimental-browser-use-runtime` 的 `SessionResources.dispose()` 改为以 `BrowserSessionError`(`BROWSER_CLEANUP_FAILED`)拒绝,其 `cause` 是此前直接抛出的 `AggregateError`;`instanceof AggregateError` 不再成立。 - Liveshare 的 guard 函数改为返回 `{ reason, info }`,不再返回原因字符串。 diff --git a/packages/experimental/ptc-runtime-python/README.i18n.yaml b/packages/experimental/ptc-runtime-python/README.i18n.yaml index b2a4ea1f60..8924924265 100644 --- a/packages/experimental/ptc-runtime-python/README.i18n.yaml +++ b/packages/experimental/ptc-runtime-python/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package: - en: 4695160db934a010 - zh: 90dcd69e2aab43b3 + en: 8c92675234e417ea + zh: 336502466e3c8790 /deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package/what-you-get: en: ca7b9cc958069c7f zh: 8a4ac72d02ad76eb diff --git a/packages/experimental/ptc-runtime-python/README.md b/packages/experimental/ptc-runtime-python/README.md index 9ca77841c6..2e82fdc7fd 100644 --- a/packages/experimental/ptc-runtime-python/README.md +++ b/packages/experimental/ptc-runtime-python/README.md @@ -25,7 +25,7 @@ Run model-generated Python in a fresh CPython 3.10+ process on macOS or Linux un ## Use this package -Choose this published experimental package only in an explicit composition. Register `PythonPtcRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `PtcRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, unavailable confinement, and substrate death). It rejects only for caller misuse, such as malformed bindings, unresolved execution options, or a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`. +Choose this published experimental package only in an explicit composition. Register `PythonPtcRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `PtcRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, unavailable confinement, and substrate death). It rejects only for caller misuse, with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for malformed bindings, a relative `cwd`, or unresolved or unsupported execution options, and `PTC_RUNTIME_UNAVAILABLE` for a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`. The composition must supply `sandbox` and `sandboxPolicy` for this local execution host. `resolve(request)` accepts an explicit `sandboxPolicy` or resolves the shared deployment policy, and defaults `cwd` to that policy's workspace root. PTC mode supplies the calling Session's policy and directory. The configured `maxWallMs` remains the execution deadline; explicit `timeoutMs` overrides are unsupported. diff --git a/packages/experimental/ptc-runtime-python/README.zh.md b/packages/experimental/ptc-runtime-python/README.zh.md index c987c9b48d..683e5541c1 100644 --- a/packages/experimental/ptc-runtime-python/README.zh.md +++ b/packages/experimental/ptc-runtime-python/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -仅在显式组合中选择这个已发布的实验包。将 `PythonPtcRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `PtcRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止、约束不可用与执行基底终止)。仅有调用方误用会 reject,例如 binding 不合法、执行选项未解析,或在 dispose 后调用。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。 +仅在显式组合中选择这个已发布的实验包。将 `PythonPtcRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `PtcRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止、约束不可用与执行基底终止)。仅有调用方误用会 reject,错误为 `PtcRuntimeError`:binding 不合法、`cwd` 不是绝对路径、执行选项未解析或不受支持时为 `PTC_RUNTIME_INVALID_ARGUMENT`,在 dispose 后调用时为 `PTC_RUNTIME_UNAVAILABLE`。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。 组合必须为此本地执行宿主提供 `sandbox` 和 `sandboxPolicy`。`resolve(request)` 接受显式 `sandboxPolicy`,或解析共享部署策略,并将 `cwd` 默认设为该策略的工作区根目录。PTC mode 提供调用 Session 的策略和目录。配置的 `maxWallMs` 仍是执行截止时间;不支持显式 `timeoutMs` 覆盖。 diff --git a/packages/experimental/ptc-runtime-python/src/index.ts b/packages/experimental/ptc-runtime-python/src/index.ts index 1e12cd1e5f..9c54b8e5fc 100644 --- a/packages/experimental/ptc-runtime-python/src/index.ts +++ b/packages/experimental/ptc-runtime-python/src/index.ts @@ -18,7 +18,7 @@ import { getHeapStatistics } from 'node:v8' import type { Duplex } from 'node:stream' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { PtcRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcRuntime, PtcRuntimeError, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcBindingErrorClass, PtcBindingFunction, PtcJsonValue, PtcRunFailure, PtcRunRequest, PtcRunResult, PtcRunSandbox, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -977,11 +977,11 @@ export class PythonPtcRuntime extends PtcRuntime { * @throws When a requested timeout is unsupported, cwd is relative, or the provider is disposed. */ resolve(request: PtcRunRequest): PtcRunSpec { - if (this.disposed) throw new Error('dsh-ptc-runtime-python: resolve() after disposal') - if (request.timeoutMs !== undefined) throw new Error('dsh-ptc-runtime-python: per-call timeout is unsupported') + if (this.disposed) throw new PtcRuntimeError('dsh-ptc-runtime-python: resolve() after disposal', 'PTC_RUNTIME_UNAVAILABLE') + if (request.timeoutMs !== undefined) throw new PtcRuntimeError('dsh-ptc-runtime-python: per-call timeout is unsupported', 'PTC_RUNTIME_INVALID_ARGUMENT') const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve() const cwd = request.cwd ?? sandboxPolicy.workspaceRoot - if (!isAbsolute(cwd)) throw new Error('dsh-ptc-runtime-python: cwd must be absolute') + if (!isAbsolute(cwd)) throw new PtcRuntimeError('dsh-ptc-runtime-python: cwd must be absolute', 'PTC_RUNTIME_INVALID_ARGUMENT') return { ...request, cwd, sandboxPolicy, timeoutMs: this.config.maxWallMs } } @@ -991,10 +991,10 @@ export class PythonPtcRuntime extends PtcRuntime { * @returns Captured output, confinement facts, and the program outcome. */ async run(request: PtcRunSpec): Promise { - if (request.sandboxPolicy === undefined) throw new Error('dsh-ptc-runtime-python: run requires a resolved sandbox policy') - if (request.timeoutMs !== this.config.maxWallMs) throw new Error('dsh-ptc-runtime-python: unsupported execution timeout') - if (!isAbsolute(request.cwd)) throw new Error('dsh-ptc-runtime-python: cwd must be absolute') - if (this.disposed) throw new Error('dsh-ptc-runtime-python: run() after disposal') + if (request.sandboxPolicy === undefined) throw new PtcRuntimeError('dsh-ptc-runtime-python: run requires a resolved sandbox policy', 'PTC_RUNTIME_INVALID_ARGUMENT') + if (request.timeoutMs !== this.config.maxWallMs) throw new PtcRuntimeError('dsh-ptc-runtime-python: unsupported execution timeout', 'PTC_RUNTIME_INVALID_ARGUMENT') + if (!isAbsolute(request.cwd)) throw new PtcRuntimeError('dsh-ptc-runtime-python: cwd must be absolute', 'PTC_RUNTIME_INVALID_ARGUMENT') + if (this.disposed) throw new PtcRuntimeError('dsh-ptc-runtime-python: run() after disposal', 'PTC_RUNTIME_UNAVAILABLE') const bindings = this.validateBindings(request) const policy = request.sandboxPolicy const sandbox: PtcRunSandbox = { mode: policy.mode, denied: false } @@ -1071,10 +1071,10 @@ export class PythonPtcRuntime extends PtcRuntime { const injectedGlobals = new Set() const claimGlobal = (name: string, role: string): void => { if (RUNTIME_OWNED_GLOBALS.has(name)) { - throw new Error(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with a runtime-owned global`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with a runtime-owned global`, 'PTC_RUNTIME_INVALID_ARGUMENT') } if (injectedGlobals.has(name)) { - throw new Error(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with another injected global`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with another injected global`, 'PTC_RUNTIME_INVALID_ARGUMENT') } injectedGlobals.add(name) } @@ -1090,10 +1090,10 @@ export class PythonPtcRuntime extends PtcRuntime { // the plain copy makes validation and the boot frame agree. const global = namespace.global if (!IDENTIFIER.test(global) || RESERVED_NAMES.has(global)) { - throw new Error(`dsh-ptc-runtime-python: binding global ${JSON.stringify(global)} is not a usable Python identifier`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: binding global ${JSON.stringify(global)} is not a usable Python identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT') } if (bindings.has(global)) { - throw new Error(`dsh-ptc-runtime-python: duplicate binding global ${JSON.stringify(global)}`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: duplicate binding global ${JSON.stringify(global)}`, 'PTC_RUNTIME_INVALID_ARGUMENT') } claimGlobal(global, 'binding global') // The error class becomes a program global and its member property an @@ -1105,17 +1105,17 @@ export class PythonPtcRuntime extends PtcRuntime { const name = errorClass.name const memberNameProperty = errorClass.memberNameProperty if (!IDENTIFIER.test(name) || RESERVED_NAMES.has(name)) { - throw new Error(`dsh-ptc-runtime-python: errorClass.name ${JSON.stringify(name)} is not a usable Python identifier`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: errorClass.name ${JSON.stringify(name)} is not a usable Python identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT') } // Any non-empty own attribute name is settable via setattr (the // program reads exotic names like `tool-name` with getattr), matching // the seam contract and the Node backend — only the seam-excluded // and protocol-reserved members below are refused. if (memberNameProperty.length === 0) { - throw new Error('dsh-ptc-runtime-python: errorClass.memberNameProperty must be a non-empty attribute name') + throw new PtcRuntimeError('dsh-ptc-runtime-python: errorClass.memberNameProperty must be a non-empty attribute name', 'PTC_RUNTIME_INVALID_ARGUMENT') } if (EXCEPTION_RESERVED_MEMBERS.has(memberNameProperty) || DUNDER.test(memberNameProperty)) { - throw new Error(`dsh-ptc-runtime-python: errorClass.memberNameProperty ${JSON.stringify(memberNameProperty)} is a reserved error member and cannot be assigned`) + throw new PtcRuntimeError(`dsh-ptc-runtime-python: errorClass.memberNameProperty ${JSON.stringify(memberNameProperty)} is a reserved error member and cannot be assigned`, 'PTC_RUNTIME_INVALID_ARGUMENT') } claimGlobal(name, 'errorClass.name') validatedErrorClass = { name, memberNameProperty } diff --git a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts index 29a547ae7a..9402a4302e 100644 --- a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts @@ -85,15 +85,15 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => { const cwd = await makeTempDir('dsh-py-resolved-cwd-') const spec = runtime.resolve({ ...request, cwd }) expect(spec.cwd).toBe(cwd) - expect(() => runtime.resolve({ ...request, cwd: 'relative' })).toThrow('cwd must be absolute') - expect(() => runtime.resolve({ ...request, timeoutMs: 1 })).toThrow('per-call timeout is unsupported') - expect(() => runtime.resolve({ ...request, timeoutMs: null })).toThrow('per-call timeout is unsupported') + expect(() => runtime.resolve({ ...request, cwd: 'relative' })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('cwd must be absolute') as string })) + expect(() => runtime.resolve({ ...request, timeoutMs: 1 })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('per-call timeout is unsupported') as string })) + expect(() => runtime.resolve({ ...request, timeoutMs: null })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('per-call timeout is unsupported') as string })) const sandboxPolicy = { mode: 'danger-full-access' as const, workspaceRoot: cwd } expect(runtime.resolve({ ...request, sandboxPolicy }).sandboxPolicy).toBe(sandboxPolicy) - await expect(runtime.run({ ...request, cwd, timeoutMs: 30_000 })).rejects.toThrow('run requires a resolved sandbox policy') - await expect(runtime.run({ ...spec, cwd: 'relative' })).rejects.toThrow('cwd must be absolute') - await expect(runtime.run({ ...spec, timeoutMs: 1 })).rejects.toThrow('unsupported execution timeout') - await expect(runtime.run({ ...spec, timeoutMs: null })).rejects.toThrow('unsupported execution timeout') + await expect(runtime.run({ ...request, cwd, timeoutMs: 30_000 })).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('run requires a resolved sandbox policy') as string })) + await expect(runtime.run({ ...spec, cwd: 'relative' })).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('cwd must be absolute') as string })) + await expect(runtime.run({ ...spec, timeoutMs: 1 })).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('unsupported execution timeout') as string })) + await expect(runtime.run({ ...spec, timeoutMs: null })).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringContaining('unsupported execution timeout') as string })) const result = await runtime.run(runtime.resolve({ ...request, cwd, program: 'import os\nreturn os.getcwd()' })) expect(result.error).toBeUndefined() expect(result.value).toBe(realpathSync(cwd)) @@ -527,11 +527,11 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => { await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: '1bad', functions: {} }], - }))).rejects.toThrow(/is not a usable Python identifier/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/is not a usable Python identifier/) as string })) await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'class', functions: {} }], - }))).rejects.toThrow(/is not a usable Python identifier/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/is not a usable Python identifier/) as string })) }) it('rejects duplicate binding namespaces', async () => { @@ -542,15 +542,15 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => { { global: 'tools', functions: {} }, { global: 'tools', functions: {} }, ], - }))).rejects.toThrow(/duplicate binding global/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/duplicate binding global/) as string })) }) it('rejects run() after disposal, and unregisters ctx.ptcRuntime', async () => { const { ctx, fiber, runtime } = await setup() const spec = runtime.resolve({ program: 'return 1', bindings: [] }) await fiber.dispose() - await expect(runtime.run(spec)).rejects.toThrow(/after disposal/) - expect(() => runtime.resolve({ program: 'return 1', bindings: [] })).toThrow(/after disposal/) + await expect(runtime.run(spec)).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE', message: expect.stringMatching(/after disposal/) as string })) + expect(() => runtime.resolve({ program: 'return 1', bindings: [] })).toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE', message: expect.stringMatching(/after disposal/) as string })) expect(ctx.get('ptcRuntime')).toBeUndefined() }) @@ -2605,7 +2605,7 @@ describe('PythonPtcRuntime — programs and bindings', () => { await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'tools', memberNameProperty: 'toolName' } }], - }))).rejects.toThrow(/collides with another injected global/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/collides with another injected global/) as string })) }) it('rejects a namespace global colliding with a runtime-owned name at the seam', async () => { @@ -2622,7 +2622,7 @@ describe('PythonPtcRuntime — programs and bindings', () => { await expect(runtime.run(runtime.resolve({ program: 'x = 1', bindings: [{ global, functions: {} }], - }))).rejects.toThrow(/collides with a runtime-owned global/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/collides with a runtime-owned global/) as string })) } }) @@ -2649,7 +2649,7 @@ describe('PythonPtcRuntime — programs and bindings', () => { await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolCallError', memberNameProperty: '' } }], - }))).rejects.toThrow(/memberNameProperty must be a non-empty attribute name/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/memberNameProperty must be a non-empty attribute name/) as string })) }) it('resolves a basename pythonBin to an absolute path (runs a real program)', async () => { @@ -2793,7 +2793,7 @@ describe('PythonPtcRuntime — programs and bindings', () => { functions: {}, errorClass: { name: 'class', memberNameProperty: 'toolName' }, }], - }))).rejects.toThrow(/errorClass.name "class" is not a usable Python identifier/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/errorClass.name "class" is not a usable Python identifier/) as string })) }) it('routes a declared inherited-attribute name through the bridge via subscript', async () => { @@ -5431,7 +5431,7 @@ describe('PythonPtcRuntime — hostile peer', () => { await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global, functions: {} }], - }))).rejects.toThrow(/is not a usable Python identifier/) + }))).rejects.toThrow(expect.objectContaining({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_INVALID_ARGUMENT', message: expect.stringMatching(/is not a usable Python identifier/) as string })) } }) From 6d33e6e9d13827afd4eb8711f6580b746d8ea783 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 17:42:09 +0800 Subject: [PATCH 44/68] docs: regenerate Cordis catalog for PtcRuntimeError Refs #7869 --- docs/subsystems/ptc-runtime.md | 4 ++-- docs/subsystems/ptc-runtime.zh.md | 4 ++-- packages/extensions/tool-cordis/src/api-catalog.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index b1820bc264..e4d299abfe 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -225,7 +225,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. ```ts cordis-catalog /** @@ -241,7 +241,7 @@ release(owner: object): Promise * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. * @returns Complete directory, deadline and supported authority for run. - * @throws When an explicit choice is invalid or unsupported by this provider. + * @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}. */ abstract resolve(request: PtcRunRequest): PtcRunSpec diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index 9aee80d258..2760112064 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -225,7 +225,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. ```ts cordis-catalog /** @@ -241,7 +241,7 @@ release(owner: object): Promise * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. * @returns Complete directory, deadline and supported authority for run. - * @throws When an explicit choice is invalid or unsupported by this provider. + * @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}. */ abstract resolve(request: PtcRunRequest): PtcRunSpec diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 528ff7d55d..de5c40c2c9 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2557,7 +2557,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'ptcRuntime', summary: 'Registers one `ctx.ptcRuntime` implementation.', - description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.', + description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.', methods: [ { signature: 'abstract readonly language: string', @@ -2581,7 +2581,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Resolve supported options and provider defaults before execution.', parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }], returns: 'Complete directory, deadline and supported authority for run.', - throws: ['When an explicit choice is invalid or unsupported by this provider.'], + throws: ['When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.'], }, { signature: 'abstract run(spec: PtcRunSpec): Promise', From 891adb1c57e301adb561648edea33ab9d2221864 Mon Sep 17 00:00:00 2001 From: zhc Date: Mon, 9 Nov 2026 17:50:38 +0800 Subject: [PATCH 45/68] refactor(ui): rename model menu detail slot from page to pane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型菜单二级位置在组件内部一直称为 pane,对外 API 统一改用同一术语: - slot `conversation.input.model.page` → `conversation.input.model.pane` - `openPage` → `openPane`,`ModelMenuPageRef` → `ModelMenuPaneRef`,`data-model-menu-page` → `data-model-menu-pane` - `Pane` 中插件面板分支改为 `{ kind: 'detail'; pane }` - Team 贡献组件 `TeamModePage*` → `TeamModePane*`,样式类 `.page` → `.pane` - 同步 JSDoc、README(中英)、测试标题与文件名,重新生成 slot catalog --- apps/web/tests/agent-team-panel.e2e.ts | 2 +- .../client/ui-agent-team/README.i18n.yaml | 8 ++-- packages/client/ui-agent-team/README.md | 4 +- packages/client/ui-agent-team/README.zh.md | 4 +- .../src/client/TeamModeToggle.module.css | 2 +- .../src/client/TeamModeToggle.tsx | 28 ++++++------- .../client/ui-agent-team/src/client/mount.ts | 10 ++--- .../tests/browser-plugin.client.spec.ts | 12 +++--- .../tests/team-mode.client.spec.tsx | 38 +++++++++--------- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../src/client/ModelSelect.tsx | 40 +++++++++---------- .../ui-model-selection/src/client/index.ts | 2 +- .../ui-model-selection/src/client/slots.ts | 24 +++++------ ...ec.tsx => model-menu-pane.client.spec.tsx} | 12 +++--- .../src/client/slot-catalog.ts | 18 ++++----- .../tests/providers.client.spec.ts | 2 +- 18 files changed, 107 insertions(+), 107 deletions(-) rename packages/client/ui-model-selection/tests/{model-menu-page.client.spec.tsx => model-menu-pane.client.spec.tsx} (94%) diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 957930cfaa..39b0217f3b 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -127,7 +127,7 @@ describe('web e2e: agent teamwork panel', () => { await scaffold?.close() }) - it('shows the explanation and switch only on the second page and returns to the summary', async () => { + it('shows the explanation and switch only on the detail pane and returns to the summary', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) const trigger = page.getByRole('button', { name: /^Select model/u }) await trigger.click() diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index d4db291eb9..3d1d210aeb 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: 39906df046b7fa3b - zh: 9a79438ab5c0811f + en: ffbcd39a17cd2fb1 + zh: db21ca6ca1cdf853 /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 /deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: - en: 7eda4383f70987f8 - zh: 84de71637336d63c + en: 24377b9e51d557de + zh: 9205961784386745 /deepseek-ai-dsh-client-ui-agent-team/further-exploration: en: 4d9214370681b02e zh: 4acb21b9ecf25e85 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index d6dbd2a057..24a7572af0 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings page shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the page focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. @@ -47,7 +47,7 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
Implementation internals — click to expand -The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns page navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.page` with key `agent-team`. Disposing the plugin fiber removes its registrations. +The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations. The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index e3ce5014d4..ba3a240d1e 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置页将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置页时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 @@ -47,7 +47,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
实现细节——点击展开 -Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责页面导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.page` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 +Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index f05212b2d6..17797b2eb3 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -51,7 +51,7 @@ color: var(--dsw-alias-menu-icon); } -.page { +.pane { display: flex; flex-direction: column; min-width: 0; diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index aff18015a7..0033b8fdb9 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -9,8 +9,8 @@ import type {} from '@deepseek-ai/dsh-agent' import type { NS } from './locales.ts' import css from './TeamModeToggle.module.css' -/** Session selection callbacks supplied to the Team settings page. */ -export interface TeamModePageInjected { +/** Session selection callbacks supplied to the Team settings pane. */ +export interface TeamModePaneInjected { /** Save the selection; null means success, otherwise the string describes the failure. */ selectTeamMode: (enabled: boolean) => Promise /** Open a Session-targeted confirmation outside this menu. */ @@ -20,13 +20,13 @@ export interface TeamModePageInjected { /** Full props of the model-menu Team summary. */ export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> & PropsLocale -/** Full props of the model-menu Team settings page. */ -export type TeamModePageProps = PropsRuntime<'conversation.input.model.page'> - & PropsLocale & TeamModePageInjected +/** Full props of the model-menu Team settings pane. */ +export type TeamModePaneProps = PropsRuntime<'conversation.input.model.pane'> + & PropsLocale & TeamModePaneInjected /** * Show the saved Team state and open its settings without changing the mode. - * @param props - Session projection, page navigation, and locale. + * @param props - Session projection, pane navigation, and locale. * @returns the summary when Team mode is available on a root Session. */ export function TeamModeToggle(props: TeamModeToggleProps) { @@ -36,7 +36,7 @@ export function TeamModeToggle(props: TeamModeToggleProps) { return } -function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeToggleProps) { +function RootTeamModeSummary({ useProjection, locked, openPane, t }: TeamModeToggleProps) { const mode = useProjection('agentTeam') if (mode === undefined) return null return ( @@ -44,9 +44,9 @@ function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeTog type="button" role="menuitem" className={css.summary} - data-model-menu-page="agent-team" + data-model-menu-pane="agent-team" disabled={locked} - onClick={() => { openPage({ key: 'agent-team', title: t('command.title') }) }} + onClick={() => { openPane({ key: 'agent-team', title: t('command.title') }) }} > {t('command.title')} {t(mode.enabled ? 'mode.on' : 'mode.off')} @@ -60,17 +60,17 @@ function RootTeamModeSummary({ useProjection, locked, openPage, t }: TeamModeTog * @param props - Session projections, mode operations, menu dismissal, and locale. * @returns the Team settings content when its projection is available. */ -export function TeamModePage(props: TeamModePageProps) { +export function TeamModePane(props: TeamModePaneProps) { const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') if (addressedChild || listedChild) return null - return + return } /** Read and change the selection only for root Sessions. */ -function RootTeamModePage({ +function RootTeamModePane({ useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, -}: TeamModePageProps) { +}: TeamModePaneProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) @@ -90,7 +90,7 @@ function RootTeamModePage({ }).finally(() => { setPending(false) }) } return ( -
+
{t('mode.label')} diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 8f22910564..c2dec89b0a 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -11,7 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' -import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from './TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from './TeamModeToggle.tsx' import { TeamBoard } from './TeamBoard.tsx' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -59,13 +59,13 @@ export function registerAgentTeamUi(ctx: ClientContext): void { id: 'agent-team', locale: NS, }, TeamModeToggle)) - yield scope.slots.inject('conversation.input.model.page', () => scope.slots.register({ - name: 'conversation.input.model.page', key: 'agent-team', locale: NS, - inject: (sessionId): TeamModePageInjected => ({ + yield scope.slots.inject('conversation.input.model.pane', () => scope.slots.register({ + name: 'conversation.input.model.pane', key: 'agent-team', locale: NS, + inject: (sessionId): TeamModePaneInjected => ({ selectTeamMode: enabled => selectTeamMode(sessionId, enabled), requestDisableConfirmation: () => { disableRequest.set({ sessionId }) }, }), - }, TeamModePage)) + }, TeamModePane)) }) }) ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index c5bab1fe0a..d89b10d71b 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModePage, TeamModeToggle, type TeamModePageInjected } from '../src/client/TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { TeamBoard } from '../src/client/TeamBoard.tsx' @@ -62,19 +62,19 @@ describe('task-board browser plugin', () => { await b.fiber.dispose() }) - it('registers the summary and settings page when Agent Teams arrives and reports each execution outcome', async () => { + it('registers the summary and settings pane when Agent Teams arrives and reports each execution outcome', async () => { const b = await bench() b.ctx.slots.register({ name: 'conversation.input.model', children: { 'conversation.input.model.options': { kind: 'list', scope: 'session' }, - 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, + 'conversation.input.model.pane': { kind: 'keyed', scope: 'session' }, }, } as never, () => null) const entry = () => b.ctx.slots.entries('conversation.input.model.options') .find(candidate => candidate.component === TeamModeToggle) - const page = () => b.ctx.slots.entries('conversation.input.model.page') - .find(candidate => candidate.component === TeamModePage) + const page = () => b.ctx.slots.entries('conversation.input.model.pane') + .find(candidate => candidate.component === TeamModePane) expect(entry()).toBeUndefined() expect(page()).toBeUndefined() const setEnabled = vi.fn() @@ -85,7 +85,7 @@ describe('task-board browser plugin', () => { expect(page()).toMatchObject({ options: { key: 'agent-team' }, locale: 'agent-team' }) const injected = page()!.inject as (sessionId: SessionId) => Record const value: object = injected(SessionId('chosen-session')) - const mode = value as TeamModePageInjected + const mode = value as TeamModePaneInjected setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) await expect(mode.selectTeamMode(true)).resolves.toBeNull() expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', true) diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index 11d0a253b2..372d372e82 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -4,12 +4,12 @@ import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { SessionId } from '@deepseek-ai/dsh-session' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModePage, TeamModeToggle, type TeamModePageProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' afterEach(cleanup) -type TestProps = TeamModePageProps & TeamModeToggleProps +type TestProps = TeamModePaneProps & TeamModeToggleProps function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TestProps { return { @@ -19,7 +19,7 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, openPage: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), + locked: false, openPane: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), } as TestProps @@ -33,12 +33,12 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dic const summary = screen.getByRole('menuitem', { name: new RegExp(dictionary['command.title']) }) expect(summary.textContent).toBe(dictionary['command.title'] + dictionary[enabled ? 'mode.on' : 'mode.off']) if (locale === 'zh') expect(summary.textContent).toBe(`智能体团队协作${enabled ? '开启' : '关闭'}`) - expect(summary.getAttribute('data-model-menu-page')).toBe('agent-team') + expect(summary.getAttribute('data-model-menu-pane')).toBe('agent-team') expect(screen.queryByRole('switch')).toBeNull() expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() expect(screen.queryByText(dictionary['mode.description'])).toBeNull() fireEvent.click(summary) - expect(input.openPage).toHaveBeenCalledExactlyOnceWith({ key: 'agent-team', title: dictionary['command.title'] }) + expect(input.openPane).toHaveBeenCalledExactlyOnceWith({ key: 'agent-team', title: dictionary['command.title'] }) expect(input.selectTeamMode).not.toHaveBeenCalled() expect(input.requestDisableConfirmation).not.toHaveBeenCalled() expect(input.dismiss).not.toHaveBeenCalled() @@ -54,14 +54,14 @@ it('keeps summary state projection-owned and blocks navigation while locked', () const summary = screen.getByRole('menuitem') expect(summary.hasAttribute('disabled')).toBe(true) fireEvent.click(summary) - expect(lockedInput.openPage).not.toHaveBeenCalled() + expect(lockedInput.openPane).not.toHaveBeenCalled() }) it('allows reading settings from the summary while model history loads', () => { const input = props(false, undefined, undefined, 'loading') render() fireEvent.click(screen.getByRole('menuitem')) - expect(input.openPage).toHaveBeenCalledOnce() + expect(input.openPane).toHaveBeenCalledOnce() expect(input.selectTeamMode).not.toHaveBeenCalled() }) @@ -69,7 +69,7 @@ it.each([false, true])('blocks repeated writes while waiting for persisted mode const pending = Promise.withResolvers() onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) const select = vi.fn(() => pending.promise) - const view = render() + const view = render() const toggle = screen.getByRole('switch', { name: '开启智能体团队协作' }) toggle.focus() fireEvent.click(toggle) @@ -82,7 +82,7 @@ it.each([false, true])('blocks repeated writes while waiting for persisted mode await act(async () => { pending.resolve(null) }) expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) expect(toggle.hasAttribute('disabled')).toBe(false) - view.rerender() + view.rerender() expect(toggle.getAttribute('aria-checked')).toBe(String(!enabled)) }) @@ -92,7 +92,7 @@ it.each(['returned', 'error', 'string'])('reports rejected mode writes through t if (failure === 'string') throw 'offline' return 'offline' })) - render() + render() const toggle = screen.getByRole('switch') toggle.focus() await act(async () => { fireEvent.click(toggle) }) @@ -103,9 +103,9 @@ it.each(['returned', 'error', 'string'])('reports rejected mode writes through t it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => [false, true].map(locked => ({ locale, dictionary, locked })), -))('shows the full $locale explanation in the settings page (locked: $locked)', ({ dictionary, locked }) => { +))('shows the full $locale explanation in the settings pane (locked: $locked)', ({ dictionary, locked }) => { const input = props(false) - render() + render() const description = screen.getByText(dictionary['mode.description'], { exact: true }) expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() @@ -120,7 +120,7 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dic it('dismisses the menu before requesting disable confirmation after a recorded model request', () => { const input = props(true, undefined, undefined, true) - render() + render() fireEvent.click(screen.getByRole('switch')) expect(input.dismiss).toHaveBeenCalledOnce() expect(input.dismiss).toHaveBeenCalledBefore(vi.mocked(input.requestDisableConfirmation)) @@ -131,7 +131,7 @@ it('dismisses the menu before requesting disable confirmation after a recorded m it.each([false, true])('enables directly regardless of model history (requested: %s)', async (requested) => { const input = props(false, undefined, undefined, requested) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(true) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() @@ -140,7 +140,7 @@ it.each([false, true])('enables directly regardless of model history (requested: it('disables directly when a model is selected but no request has been recorded', async () => { const input = props(true) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(false) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() @@ -149,7 +149,7 @@ it('disables directly when a model is selected but no request has been recorded' it('waits for model history before allowing the settings switch to change', () => { const input = props(true, undefined, undefined, 'loading') - render() + render() expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) fireEvent.click(screen.getByRole('switch')) expect(input.selectTeamMode).not.toHaveBeenCalled() @@ -158,7 +158,7 @@ it('waits for model history before allowing the settings switch to change', () = it.each([ { name: 'summary', Component: TeamModeToggle }, - { name: 'settings page', Component: TeamModePage }, + { name: 'settings pane', Component: TeamModePane }, ])('hides the $name until the Team projection is available', ({ Component }) => { const { container } = render() expect(container.textContent).toBe('') @@ -168,7 +168,7 @@ it.each([ it.each([ { name: 'summary', Component: TeamModeToggle }, - { name: 'settings page', Component: TeamModePage }, + { name: 'settings pane', Component: TeamModePane }, ].flatMap(entry => (['addressed', 'listed'] as const).map(child => ({ ...entry, child }))))( 'hides the $name on a $child child Session', ({ Component, child }) => { const input = props(false, undefined, child) @@ -177,6 +177,6 @@ it.each([ expect(container.textContent).toBe('') expect(useProjection).not.toHaveBeenCalled() expect(input.selectTeamMode).not.toHaveBeenCalled() - expect(input.openPage).not.toHaveBeenCalled() + expect(input.openPane).not.toHaveBeenCalled() }, ) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index a3a5c13bdf..67ffdadf02 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 353daeed6290d445 - zh: b5f0febc130c8a8b + en: b4c2e8c1f7ab4de5 + zh: 5dd0e14aa5f9d334 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: c1d14a925c92950f zh: f80f8169bc283c60 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index 27a6529389..3303f8bbae 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -61,7 +61,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPage({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.page` slot; the invoking button's `data-model-menu-page` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail pages share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail page as a group named by `title`; the page places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail page without activating its switch. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPane({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.pane` slot; the invoking button's `data-model-menu-pane` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail panes share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail pane as a group named by `title`; the pane places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail pane without activating its switch. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 7337e1136c..1abd873ddd 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -61,7 +61,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPage({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.page` 的内容;入口按钮的 `data-model-menu-page` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级页共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级页呈现为以 `title` 命名的分组;页面自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级页而不激活开关。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPane({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.pane` 的内容;入口按钮的 `data-model-menu-pane` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级面板共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级面板呈现为以 `title` 命名的分组;面板自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级面板而不激活开关。 ----- diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index f062b4d8ba..a1510d832b 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -40,16 +40,16 @@ import { IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelMenuControls, ModelMenuPageRef, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuControls, ModelMenuPaneRef, ModelSelectInjected } from './slots.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail page. */ +/** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail pane. */ type Pane = | { kind: 'root' } | { kind: 'model' } | { kind: 'effort' } - | { kind: 'page'; page: ModelMenuPageRef } + | { kind: 'detail'; pane: ModelMenuPaneRef } /** Any pane reached by drilling from the root menu. */ type DrilledPane = Exclude @@ -74,7 +74,7 @@ interface EffortChoice { export function ModelSelect( { locked, available, directory, load, select, resolveText, t, renderSlot }: ModelSelectInjected & Pick, 'locked'> & PropsLocale<'model'> - & Omit, 'SessionProvider'>, + & Omit, 'SessionProvider'>, ) { const state = useSyncExternalStore( fn => directory.subscribe(fn), @@ -201,8 +201,8 @@ export function ModelSelect( paneFocus.current = null if (!open || intent === null) return if (intent === 'drill') { - if (pane.kind === 'page') { - // A detail page places its own initial focus (autoFocus commits before + if (pane.kind === 'detail') { + // A detail pane places its own initial focus (autoFocus commits before // this effect); otherwise the surface keeps the menu's keys reachable. if (menuRef.current?.contains(document.activeElement) !== true) (menuRef.current ?? triggerRef.current)?.focus() return @@ -220,9 +220,9 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = intent.kind === 'page' - ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) - .find(button => button.dataset.modelMenuPage === intent.page.key) + const cell = intent.kind === 'detail' + ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-pane]') ?? []) + .find(button => button.dataset.modelMenuPane === intent.pane.key) : itemRefs.current[intent.kind === 'effort' ? 1 : 0] ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() }, [open, pane, showSearch]) @@ -310,12 +310,12 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (pane.kind === 'page' || (pane.kind !== 'root' && currentChoice !== undefined)) back(pane) + if (pane.kind === 'detail' || (pane.kind !== 'root' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (pane.kind === 'page' && event.key === 'Tab') { + if (pane.kind === 'detail' && event.key === 'Tab') { event.preventDefault() close(true) return @@ -379,7 +379,7 @@ export function ModelSelect( const onBlur = (event: FocusEvent): void => { // Clicking explanation text can clear focus without leaving its page. - if (pane.kind === 'page' && event.relatedTarget === null) return + if (pane.kind === 'detail' && event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -521,13 +521,13 @@ export function ModelSelect( {pane.kind === 'root' && ( @@ -546,7 +546,7 @@ export function ModelSelect( )} - {renderSlot('conversation.input.model.options', { ...controls, openPage: (page) => { drill({ kind: 'page', page }) } })} + {renderSlot('conversation.input.model.options', { ...controls, openPane: (pane) => { drill({ kind: 'detail', pane }) } })} )} @@ -689,9 +689,9 @@ export function ModelSelect(
)} - {pane.kind === 'page' && ( + {pane.kind === 'detail' && (
- {renderSlot('conversation.input.model.page', controls, { entryKey: pane.page.key })} + {renderSlot('conversation.input.model.pane', controls, { entryKey: pane.pane.key })}
)} , diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index 7a567a4c30..1c37307902 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -175,7 +175,7 @@ export function apply(ctx: ClientContext): void { children: { 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, - 'conversation.input.model.page': { kind: 'keyed', scope: 'session' }, + 'conversation.input.model.pane': { kind: 'keyed', scope: 'session' }, }, inject: (sessionId): ModelSelectInjected => { const directory = models.directoryFor(sessionId) diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 3f1670f236..1aabbd0d54 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,15 +17,15 @@ export interface ModelLabelOwner { selected: boolean } -/** Data identifying a keyed contribution displayed as a second page of the model menu. */ -export interface ModelMenuPageRef { - /** Registration key in conversation.input.model.page; also marks its root button's data-model-menu-page. */ +/** Data identifying a keyed contribution displayed as a detail pane of the model menu. */ +export interface ModelMenuPaneRef { + /** Registration key in conversation.input.model.pane; also marks its root button's data-model-menu-pane. */ key: string - /** Localized accessible name of the detail page. */ + /** Localized accessible name of the detail pane. */ title: string } -/** Selection state and feedback shared by menu option entries and detail pages. */ +/** Selection state and feedback shared by menu option entries and detail panes. */ export interface ModelMenuControls { /** Whether the composer refuses changes, including while a model selection is saving. */ locked: boolean @@ -35,13 +35,13 @@ export interface ModelMenuControls { reportFailure: (message: string) => void } -/** Root-menu controls for opening plugin-owned settings pages. */ +/** Root-menu controls for opening plugin-owned settings panes. */ export type ModelMenuOptions = ModelMenuControls & { /** - * Open page.key in conversation.input.model.page with page.title as its localized accessible name. - * The root button's data-model-menu-page must match page.key for focus return. + * Open pane.key in conversation.input.model.pane with pane.title as its localized accessible name. + * The root button's data-model-menu-pane must match pane.key for focus return. */ - openPage: (page: ModelMenuPageRef) => void + openPane: (pane: ModelMenuPaneRef) => void } declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -53,11 +53,11 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { owner: ModelMenuOptions } /** - * Plugin-owned content displayed as a model-menu detail page. - * The page places its own initial focus, for example with `autoFocus`; without one, + * Plugin-owned content displayed as a model-menu detail pane. + * The pane places its own initial focus, for example with `autoFocus`; without one, * focus stays on the menu surface, where Escape and Shift+Tab still return to the root menu. */ - 'conversation.input.model.page': { + 'conversation.input.model.pane': { kind: 'keyed' scope: 'session' owner: ModelMenuControls diff --git a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx similarity index 94% rename from packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx rename to packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx index c37e850291..b7c0a22c4d 100644 --- a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx @@ -22,11 +22,11 @@ function setup(autoFocus = true) { const renderSlot: ComponentProps['renderSlot'] = (name, owner, options) => { if (name === 'conversation.input.model.options') { const controls = owner as object as OwnerOf<'conversation.input.model.options'> - return + return } - if (name === 'conversation.input.model.page') { - const controls = owner as object as OwnerOf<'conversation.input.model.page'> + if (name === 'conversation.input.model.pane') { + const controls = owner as object as OwnerOf<'conversation.input.model.pane'> expect(options?.entryKey).toBe('fixture') return <>

Fixture explanation

@@ -66,7 +66,7 @@ it('keeps focus on the page surface when the page places none, so Escape still r expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) }) -it('closes a detail page on an outside touch press that dispatches no mousedown', () => { +it('closes a detail pane on an outside touch press that dispatches no mousedown', () => { const { trigger } = setup() fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) fireEvent.blur(screen.getByRole('switch'), { relatedTarget: null }) @@ -76,7 +76,7 @@ it('closes a detail page on an outside touch press that dispatches no mousedown' expect(trigger.getAttribute('aria-expanded')).toBe('false') }) -it.each([false, true])('closes a detail page on Tab without changing its setting (shift: %s)', async (shiftKey) => { +it.each([false, true])('closes a detail pane on Tab without changing its setting (shift: %s)', async (shiftKey) => { const { trigger, change } = setup() fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) fireEvent.keyDown(screen.getByRole('switch'), { key: 'Tab', shiftKey }) 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 f3589becb2..30de620d98 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1648,11 +1648,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', - '/** Root-menu controls for opening plugin-owned settings pages. */\nexport type ModelMenuOptions = ModelMenuControls & {\n /**\n * Open page.key in conversation.input.model.page with page.title as its localized accessible name.\n * The root button\'s data-model-menu-page must match page.key for focus return.\n */\n openPage: (page: ModelMenuPageRef) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail panes. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Root-menu controls for opening plugin-owned settings panes. */\nexport type ModelMenuOptions = ModelMenuControls & {\n /**\n * Open pane.key in conversation.input.model.pane with pane.title as its localized accessible name.\n * The root button\'s data-model-menu-pane must match pane.key for focus return.\n */\n openPane: (pane: ModelMenuPaneRef) => void\n}', ], ownerPropsReferences: [ - 'ModelMenuPageRef', + 'ModelMenuPaneRef', ], standardProps: [ 'useRemoteAccess: (action: RemoteEndpoint) => boolean', @@ -1687,11 +1687,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ source: 'packages/client/ui-model-selection/src/client/slots.ts:50', }, { - key: 'conversation.input.model.page', + key: 'conversation.input.model.pane', kind: 'keyed', scope: 'session', - summary: 'Plugin-owned content displayed as a model-menu detail page.', - doc: 'Plugin-owned content displayed as a model-menu detail page.\nThe page places its own initial focus, for example with `autoFocus`; without one,\nfocus stays on the menu surface, where Escape and Shift+Tab still return to the root menu.', + summary: 'Plugin-owned content displayed as a model-menu detail pane.', + doc: 'Plugin-owned content displayed as a model-menu detail pane.\nThe pane places its own initial focus, for example with `autoFocus`; without one,\nfocus stays on the menu surface, where Escape and Shift+Tab still return to the root menu.', registerOptions: [ { name: 'key', @@ -1701,7 +1701,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Selection state and feedback shared by menu option entries and detail pages. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', + '/** Selection state and feedback shared by menu option entries and detail panes. */\nexport interface ModelMenuControls {\n /** Whether the composer refuses changes, including while a model selection is saving. */\n locked: boolean\n /** Close the menu and focus its trigger synchronously before opening another overlay. */\n dismiss: () => void\n /** Report a failed selection through the menu owner\'s persistent toast. */\n reportFailure: (message: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -1730,10 +1730,10 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'conversation.input.model\' (client-ui-model-selection), so it exists while that entry is mounted', occupants: [ - 'client-ui-agent-team TeamModePage key \'agent-team\'', + 'client-ui-agent-team TeamModePane key \'agent-team\'', ], replaceRisk: 'shadows-shipped-ui', - example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.page\', () => ctx.slots.register(\n { name: \'conversation.input.model.page\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.pane\', () => ctx.slots.register(\n { name: \'conversation.input.model.pane\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-model-selection/src/client/slots.ts:60', }, { diff --git a/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts b/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts index 0834f05cce..9d32c4e59e 100644 --- a/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts +++ b/packages/extensions/cordis-client-runner/tests/providers.client.spec.ts @@ -32,7 +32,7 @@ describe('Client inspect providers', () => { const options = await provider.query('listSubTree', { root: 'conversation.input.model.options' }, {} as never) const menuOwner = (options as typeof selected).selected.catalog.ownerProps.join('\n') expect(menuOwner).toContain('ModelMenuOptions') - expect(menuOwner).toContain('openPage: (page: ModelMenuPageRef) => void') + expect(menuOwner).toContain('openPane: (pane: ModelMenuPaneRef) => void') } finally { await fiber.dispose() } From 95b08637ad62ac1c4be76bca7117f54360faa9d9 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 17:51:07 +0800 Subject: [PATCH 46/68] fix(tool-terminal): reject a disabled background send as ToolArgsError When enableRunInBackground is false the schema does not offer run_in_background, so a model that passes it fails with ToolArgsError INVALID_ARGS naming the configuration, like bash and pwsh, instead of JobError JOB_BACKGROUND_DISABLED. Refs #7869 --- packages/experimental/tool-terminal/README.i18n.yaml | 4 ++-- packages/experimental/tool-terminal/README.md | 2 +- packages/experimental/tool-terminal/README.zh.md | 2 +- packages/experimental/tool-terminal/src/index.ts | 4 ++-- packages/experimental/tool-terminal/tests/tools.spec.ts | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/experimental/tool-terminal/README.i18n.yaml b/packages/experimental/tool-terminal/README.i18n.yaml index 918803c164..02dc0d007f 100644 --- a/packages/experimental/tool-terminal/README.i18n.yaml +++ b/packages/experimental/tool-terminal/README.i18n.yaml @@ -30,8 +30,8 @@ en: 2ad49d4f69deb06d zh: 5f29972b5feec7e3 /deepseek-ai-dsh-tool-terminal/use-this-package/observable-outcomes-and-failures: - en: a4231b8c3bfaedfc - zh: 7955c1d1a842e867 + en: f8549c20403b1d65 + zh: ef98b292e71de6ac /deepseek-ai-dsh-tool-terminal/understand-the-implementation: en: 6302fca8fef89136 zh: 6327d56edb798ab2 diff --git a/packages/experimental/tool-terminal/README.md b/packages/experimental/tool-terminal/README.md index d50fdfe6c0..d14805f522 100644 --- a/packages/experimental/tool-terminal/README.md +++ b/packages/experimental/tool-terminal/README.md @@ -65,7 +65,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Observable outcomes and failures -A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Failed calls carry a structured error identity: an empty `type` or `sessionId` is a `ToolArgsError` (`INVALID_ARGS`), a call without a calling Agent or a background send without the jobs service is a `ToolContextUnavailableError`, a background send with `enableRunInBackground: false` is a `JobError` (`JOB_BACKGROUND_DISABLED`), a cancelled foreground send is an `AbortError`, and terminal service failures keep their `TerminalError` code. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. +A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Failed calls carry a structured error identity: an empty `type` or `sessionId` is a `ToolArgsError` (`INVALID_ARGS`), a call without a calling Agent or a background send without the jobs service is a `ToolContextUnavailableError`, a background send with `enableRunInBackground: false` is a `ToolArgsError` (`INVALID_ARGS`) because the schema does not offer `run_in_background`, a cancelled foreground send is an `AbortError`, and terminal service failures keep their `TerminalError` code. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. ----- diff --git a/packages/experimental/tool-terminal/README.zh.md b/packages/experimental/tool-terminal/README.zh.md index 2b595e88f7..d6bd337a62 100644 --- a/packages/experimental/tool-terminal/README.zh.md +++ b/packages/experimental/tool-terminal/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" ### 可观察结果与失败 -前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。失败的调用带有结构化错误标识:`type` 或 `sessionId` 为空时为 `ToolArgsError`(`INVALID_ARGS`),没有调用方 Agent 或后台发送缺少 jobs 服务时为 `ToolContextUnavailableError`,`enableRunInBackground: false` 时的后台发送为 `JobError`(`JOB_BACKGROUND_DISABLED`),被取消的前台发送为 `AbortError`,终端服务失败保留其 `TerminalError` code。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 +前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。失败的调用带有结构化错误标识:`type` 或 `sessionId` 为空时为 `ToolArgsError`(`INVALID_ARGS`),没有调用方 Agent 或后台发送缺少 jobs 服务时为 `ToolContextUnavailableError`,`enableRunInBackground: false` 时的后台发送为 `ToolArgsError`(`INVALID_ARGS`),因为 schema 不提供 `run_in_background`,被取消的前台发送为 `AbortError`,终端服务失败保留其 `TerminalError` code。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 ----- diff --git a/packages/experimental/tool-terminal/src/index.ts b/packages/experimental/tool-terminal/src/index.ts index 638182ebdb..28d4a8cc00 100644 --- a/packages/experimental/tool-terminal/src/index.ts +++ b/packages/experimental/tool-terminal/src/index.ts @@ -12,7 +12,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@deepseek-ai/dsh-terminal' -import { JobError } from '@deepseek-ai/dsh-jobs' +import type {} from '@deepseek-ai/dsh-jobs' import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import { sendSource } from './background.ts' @@ -258,7 +258,7 @@ export function apply(ctx: Context, config: Config = {}): void { const id = sessionId(args) const request = { text: args.text, submit: args.submit ?? true } if (args.run_in_background === true) { - if (!enableRunInBackground) throw new JobError('background terminal sends are disabled by tool-terminal configuration', 'JOB_BACKGROUND_DISABLED') + if (!enableRunInBackground) throw new ToolArgsError(['run_in_background is disabled by tool-terminal configuration (enableRunInBackground: false)']) const jobs = ctx.get('jobs') if (jobs === undefined) throw new ToolContextUnavailableError('background terminal sends require @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') let cancelRequested = false diff --git a/packages/experimental/tool-terminal/tests/tools.spec.ts b/packages/experimental/tool-terminal/tests/tools.spec.ts index 9447fa564e..0988f8948a 100644 --- a/packages/experimental/tool-terminal/tests/tools.spec.ts +++ b/packages/experimental/tool-terminal/tests/tools.spec.ts @@ -344,7 +344,7 @@ describe('tool-terminal foreground API', () => { await call(disabled.ctx, 'terminal_open', { type: 'stub' }, disabled.agent) expect((await call(disabled.ctx, 'terminal_send', { sessionId: 'pty-1', text: 'work', run_in_background: true, - }, disabled.agent)).error?.info).toEqual({ name: 'JobError', code: 'JOB_BACKGROUND_DISABLED' }) + }, disabled.agent)).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const defaults = await setupBase(false) ToolPty.apply(defaults.ctx) From fa82fe81b76e379ca000a4c5017d044ff9d5759c Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 20:40:29 +0800 Subject: [PATCH 47/68] test(snapshots): refresh cua-native error identities after merging master Refs #7869 --- snapshots/session/cua-native/session.v4.jsonl | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 1eaff28c9f..9676e97cc7 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -19,17 +19,17 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350258,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350258,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1794214350258,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350258,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350289,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350289,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214350289,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350289,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350310,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350310,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794214350310,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350310,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REQUIRED"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350331,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350331,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1794214350331,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350331,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -104,12 +104,12 @@ {"type":"step/start","data":{"turn":1,"step":19}} {"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350810,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350810,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214350810,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350810,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAccessibilityTree"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAccessibilityTree"}],"isError":true,"id":"{{message:41}}"},"error":{"name":"NativeError","code":"STALE_SNAPSHOT"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} {"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350830,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350830,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794214350830,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350830,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"},"error":{"name":"NativeError","code":"STALE_SNAPSHOT"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} {"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350854,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350854,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1794214350854,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350854,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -139,22 +139,22 @@ {"type":"step/start","data":{"turn":1,"step":26}} {"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350980,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350980,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1794214350980,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350980,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} {"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351004,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351004,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1794214351004,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351004,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} {"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351030,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351030,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1794214351030,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351030,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} {"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351059,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351059,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1794214351059,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351059,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"},"error":{"name":"NativeError","code":"WINDOW_CHANGED"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} {"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351085,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351085,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1794214351085,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351085,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -174,7 +174,7 @@ {"type":"step/start","data":{"turn":1,"step":33}} {"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351149,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351149,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214351149,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351149,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"},"error":{"name":"NativeError","code":"CAPTURE_BUSY"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} {"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351177,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351177,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214351177,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351177,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -224,7 +224,7 @@ {"type":"step/start","data":{"turn":1,"step":43}} {"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351431,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351431,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1794214351431,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351431,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-unavailable"},"toolCallId":"cua-hover-unavailable","content":[{"type":"text","text":"Error: HOVER_UNAVAILABLE: No AX alternate UI at this target. No input was sent and the pointer did not move."}],"isError":true,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-unavailable"},"toolCallId":"cua-hover-unavailable","content":[{"type":"text","text":"Error: HOVER_UNAVAILABLE: No AX alternate UI at this target. No input was sent and the pointer did not move."}],"isError":true,"id":"{{message:89}}"},"error":{"name":"NativeError","code":"HOVER_UNAVAILABLE"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} {"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-explicit-pointer-move","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true,\"useSystemPointer\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351455,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351455,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-explicit-pointer-move","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true,\"useSystemPointer\":true}}"}}},{"type":"chunk","time":1794214351455,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351455,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -249,7 +249,7 @@ {"type":"step/start","data":{"turn":1,"step":48}} {"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351537,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351537,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1794214351537,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351537,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:99}}"},"error":{"name":"NativeError","code":"PASTE_NOT_CONSUMED"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} {"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351561,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351561,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214351561,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351561,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -339,12 +339,12 @@ {"type":"step/start","data":{"turn":1,"step":66}} {"type":"assistant/message","data":{"turn":1,"step":66,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:134}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214351994,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214351994,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1794214351994,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214351994,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":66,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":66,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:135}}"}},"sourceEventSeqs":[339],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":66,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:135}}"},"error":{"name":"NativeError","code":"NATIVE_PROTOCOL"}},"sourceEventSeqs":[339],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":66}} {"type":"step/start","data":{"turn":1,"step":67}} {"type":"assistant/message","data":{"turn":1,"step":67,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:136}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214352032,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214352032,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1794214352032,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214352032,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":67,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":67,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:137}}"}},"sourceEventSeqs":[344],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":67,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:137}}"},"error":{"name":"NativeError","code":"APP_ACCESS_DENIED"}},"sourceEventSeqs":[344],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":67}} {"type":"step/start","data":{"turn":1,"step":68}} {"type":"assistant/message","data":{"turn":1,"step":68,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:138}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214352213,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214352213,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1794214352213,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214352213,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -354,7 +354,7 @@ {"type":"step/start","data":{"turn":1,"step":69}} {"type":"assistant/message","data":{"turn":1,"step":69,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:140}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214352404,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214352404,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1794214352404,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214352404,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":69,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":69,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:141}}"}},"sourceEventSeqs":[354],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":69,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:141}}"},"error":{"name":"NativeError","code":"APP_ACCESS_REVOKED"}},"sourceEventSeqs":[354],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":69}} {"type":"step/start","data":{"turn":1,"step":70}} {"type":"assistant/message","data":{"turn":1,"step":70,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:142}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214352423,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794214352423,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1794214352423,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214352423,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} From d0f26fd4fdd47767f2a931b083342c6e7b33b4c1 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 20:48:31 +0800 Subject: [PATCH 48/68] test(snapshots): record NativeError identity on cua-ptc dispatch results Refs #7869 --- snapshots/session/cua-ptc/session.v4.jsonl | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index df13a371cc..1adb2c3b92 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -37,11 +37,11 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"error":{"name":"NativeError","code":"NATIVE_ERROR"},"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"error":{"name":"NativeError","code":"NATIVE_ERROR"},"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":7,"x":100,"y":100,"relative":true,"mouseButton":"left","clickCount":1}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":7,"x":100,"y":100,"relative":true,"mouseButton":"left","clickCount":1}},"isError":true,"content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Window has no observation; read getAccessibilityTree or take a screenshot before coordinate input"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":7,"x":100,"y":100,"relative":true,"mouseButton":"left","clickCount":1}},"isError":true,"error":{"name":"NativeError","code":"STALE_SNAPSHOT"},"content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Window has no observation; read getAccessibilityTree or take a screenshot before coordinate input"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:8","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":7,"x":100,"y":100,"relative":true,"mouseButton":"left","clickCount":1}}}} @@ -61,11 +61,11 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":null,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=unknown selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:4","name":"cua","arguments":{"method":"setValue","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-3","elementId":"1","value":"must not be written"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:4","name":"cua","arguments":{"method":"setValue","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-3","elementId":"1","value":"must not be written"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXValue failed with error -25200"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:4","name":"cua","arguments":{"method":"setValue","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-3","elementId":"1","value":"must not be written"}},"isError":true,"error":{"name":"NativeError","code":"NATIVE_ERROR"},"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXValue failed with error -25200"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":null,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=unknown value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:6","name":"cua","arguments":{"method":"selectText","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-4","elementId":"1","text":"Fixture"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:6","name":"cua","arguments":{"method":"selectText","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-4","elementId":"1","text":"Fixture"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXSelectedTextRange failed with error -25200"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:6","name":"cua","arguments":{"method":"selectText","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-4","elementId":"1","text":"Fixture"}},"isError":true,"error":{"name":"NativeError","code":"NATIVE_ERROR"},"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXSelectedTextRange failed with error -25200"}]}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-writability"},"toolCallId":"cua-ptc-writability","content":[{"type":"text","text":"[\n {\n \"attribute\": \"AXValue\",\n \"unknown\": true,\n \"otherNodesRetained\": true,\n \"writeRefused\": true\n },\n {\n \"attribute\": \"AXSelectedTextRange\",\n \"unknown\": true,\n \"otherNodesRetained\": true,\n \"writeRefused\": true\n }\n]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} From 688caffc8c7aa80b505463375faa3552d4cd2c0b Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 12:47:42 +0800 Subject: [PATCH 49/68] docs(upgrade-guide): move experimental tool error codes guide to v0.2.2-rc.2 The root version is now 0.2.2-rc.2, so the guide belongs in that release directory. Refs #7869 --- .../experimental-tool-error-codes/guide.i18n.yaml | 6 +++--- .../experimental-tool-error-codes/guide.md | 0 .../experimental-tool-error-codes/guide.zh.md | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/experimental-tool-error-codes/guide.i18n.yaml (86%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/experimental-tool-error-codes/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/experimental-tool-error-codes/guide.zh.md (100%) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml similarity index 86% rename from docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml index 13f20ee758..3e90191a9d 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md /: en: 4d6f7a78d1415f20 zh: a5a906f4f1266243 /experimental-plugin-failures-carry-error-codes: - en: 075d975981aa61d4 - zh: 244a36616232b8e1 + en: 13f43192e549438f + zh: ce8c5bf26aefbd4f /experimental-plugin-failures-carry-error-codes/change: en: 98bbff2056476763 zh: 390a61ff8faeeec0 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.md rename to docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/experimental-tool-error-codes/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md From d7603e425a90da93ba08b6a22d0e8cadad362f7a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 14:04:31 +0800 Subject: [PATCH 50/68] test(ptc-runtime): cover PtcRuntimeError where the Python runtime is skipped On Windows the Python runtime tests that construct PtcRuntimeError are skipped, so the class needs its own test in its package to meet the per-file coverage gate. package.json and tsconfig.json again match deepseek-harness#8168 after its merge with master. Refs #7869 --- packages/ptc-runtime/ptc-runtime/package.json | 8 ++++---- .../ptc-runtime/ptc-runtime/tests/service.spec.ts | 12 +++++++++++- packages/ptc-runtime/ptc-runtime/tsconfig.json | 4 ++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/packages/ptc-runtime/ptc-runtime/package.json b/packages/ptc-runtime/ptc-runtime/package.json index 6c5b157b2c..60db26aa1c 100644 --- a/packages/ptc-runtime/ptc-runtime/package.json +++ b/packages/ptc-runtime/ptc-runtime/package.json @@ -32,13 +32,13 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-sandbox": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*", - "@deepseek-ai/dsh-attachment": "workspace:*" + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-sandbox": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*", - "@deepseek-ai/dsh-attachment": "workspace:*" + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts b/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts index 4e0c52f3b1..7be3273220 100644 --- a/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts +++ b/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' /** @@ -95,3 +96,12 @@ describe('PtcRuntime service seam', () => { }) }) + +describe('PtcRuntimeError', () => { + it('carries its routable name and code as a HarnessError', () => { + const cause = new Error('underlying') + const error = new PtcRuntimeError('run() after disposal', 'PTC_RUNTIME_UNAVAILABLE', { cause }) + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE', message: 'run() after disposal', cause }) + }) +}) diff --git a/packages/ptc-runtime/ptc-runtime/tsconfig.json b/packages/ptc-runtime/ptc-runtime/tsconfig.json index 690dfe3bdd..c67dd70cb4 100644 --- a/packages/ptc-runtime/ptc-runtime/tsconfig.json +++ b/packages/ptc-runtime/ptc-runtime/tsconfig.json @@ -18,10 +18,10 @@ "path": "../../sandbox/sandbox" }, { - "path": "../../util/error" + "path": "../../attachment/attachment" }, { - "path": "../../attachment/attachment" + "path": "../../util/error" } ] } From 4ad94b044561dbdc7a0283d0404c0836592eb307 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 14:17:46 +0800 Subject: [PATCH 51/68] fix(cua): name the failing field when no request form matches An argument union that no form matches now lists each form's own issues with their full paths, so a click missing y reports params.y: expected number, received undefined instead of only params: Invalid input. Refs #7869 --- .../cua-macos/tests/provider-lifecycle.spec.ts | 10 ++++++++++ packages/experimental/cua/src/index.ts | 17 ++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 884a910815..942d6e1f28 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -616,6 +616,16 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag } finally { release.resolve(); await closing } }) +it('names the missing field of a request that matches none of its accepted forms', async () => { + const f = await setup() + const result = await f.execute('click', { appHandle: 'app', windowId: '7', x: 20 }) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + const text = JSON.stringify(result.content) + expect(text).toContain('params: matches none of the accepted forms') + expect(text).toContain('params.y: Invalid input: expected number, received undefined') + expect(native.request).not.toHaveBeenCalled() +}) + it('rejects malformed and unowned operations before acquiring a helper', async () => { const f = await setup() const malformed = await f.execute('screenshot', { pid: 9, windowId: '7' }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index ce5ea32bf3..da78cb8c84 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -93,10 +93,25 @@ function executionAgent(execution: Readonly): Agent { return execution.agent } +/** + * Describe one request issue for the model. A union that no accepted form matches lists each form's own + * issues, so the model learns which field to add or remove, such as a missing `params.y`. + * @param issue - one issue from parsing the request. + * @param base - path of the value the issue belongs to. + * @returns a single-line violation naming the field and the reason. + */ +function requestViolation(issue: z.core.$ZodIssue, base: readonly PropertyKey[] = []): string { + const path = [...base, ...issue.path] + const field = path.map(String).join('.') + if (issue.code !== 'invalid_union' || issue.errors.length === 0) return `${field}: ${issue.message}` + const forms = issue.errors.map(form => `(${form.map(nested => requestViolation(nested, path)).join('; ')})`) + return `${field}: matches none of the accepted forms: ${forms.join(' or ')}` +} + /** Parse the tool request; refinements the parameter schema cannot express fail as argument errors. */ function parseRequest(schema: z.ZodType, args: unknown): T { const parsed = schema.safeParse(args) - if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`)) + if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => requestViolation(issue))) return parsed.data } From cfa565e1bbf5aeadd1537e4cfd909d711ae6d50e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 14:23:30 +0800 Subject: [PATCH 52/68] fix(cua): label a top-level request issue as arguments A key outside method and params reported an empty field name; it now reads arguments: Unrecognized key, matching how other issues name their field. Refs #7869 --- .../cua-macos/tests/provider-lifecycle.spec.ts | 9 +++++++++ packages/experimental/cua/src/index.ts | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 942d6e1f28..d5cd4d3fc6 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -626,6 +626,15 @@ it('names the missing field of a request that matches none of its accepted forms expect(native.request).not.toHaveBeenCalled() }) +it('names an unknown top-level request key', async () => { + const f = await setup() + const result = await executeToolFixture(f.ctx, { + agent: f.handle.agent, signal: new AbortController().signal, callId: ToolCallId('extra-key'), name: 'cua', + arguments: { method: 'listApps', params: {}, extra: 1 }, + }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: arguments: Unrecognized key: "extra"' }]) +}) + it('rejects malformed and unowned operations before acquiring a helper', async () => { const f = await setup() const malformed = await f.execute('screenshot', { pid: 9, windowId: '7' }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index da78cb8c84..6992e1b61e 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -102,7 +102,7 @@ function executionAgent(execution: Readonly): Agent { */ function requestViolation(issue: z.core.$ZodIssue, base: readonly PropertyKey[] = []): string { const path = [...base, ...issue.path] - const field = path.map(String).join('.') + const field = path.length > 0 ? path.map(String).join('.') : 'arguments' if (issue.code !== 'invalid_union' || issue.errors.length === 0) return `${field}: ${issue.message}` const forms = issue.errors.map(form => `(${form.map(nested => requestViolation(nested, path)).join('; ')})`) return `${field}: matches none of the accepted forms: ${forms.join(' or ')}` From 0e06389fbe29e22b4c52a72cf2877466e14b9eb1 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 14:55:24 +0800 Subject: [PATCH 53/68] fix(stagehand): read non-object arguments as the MCP bridge does Host-side validation now reads a non-object argument value as {}, the value the MCP bridge passes to the call, so stagehand_screenshot(null) takes a screenshot as before instead of failing as invalid arguments. Refs #7869 --- .../experimental/browser-use-stagehand-native/src/index.ts | 4 +++- .../browser-use-stagehand-native/tests/provider.spec.ts | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/experimental/browser-use-stagehand-native/src/index.ts b/packages/experimental/browser-use-stagehand-native/src/index.ts index 86b2a7c6eb..ad7dc7ba5e 100644 --- a/packages/experimental/browser-use-stagehand-native/src/index.ts +++ b/packages/experimental/browser-use-stagehand-native/src/index.ts @@ -195,7 +195,9 @@ function mountTools(ctx: Context, resources: SessionResources): throw new ToolContextUnavailableError('Stagehand browser tools require an exact live Agent') } // Arguments are checked before the browser is acquired, so an invalid first call launches nothing. - const parsed = browserInputs[exec.name.slice('stagehand_'.length) as BrowserMethod].safeParse(exec.arguments) + // A non-object value is read as `{}`, exactly as the MCP bridge passes it to the call. + const args = typeof exec.arguments === 'object' && exec.arguments !== null ? exec.arguments : {} + const parsed = browserInputs[exec.name.slice('stagehand_'.length) as BrowserMethod].safeParse(args) if (!parsed.success) { throw new ToolArgsError(parsed.error.issues.map(issue => `${['arguments', ...issue.path].join('.')}: ${issue.message}`)) } diff --git a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts index aa35d4ce4b..8a5a806d85 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts @@ -138,6 +138,13 @@ it('rejects invalid arguments before acquiring a browser', async () => { expect(fixture.browsers).toEqual([]) }) +it('reads non-object arguments as an empty request, as the MCP bridge does', async () => { + await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) + const result = await execute(first, 'screenshot', null) + expect(result.isError).toBe(false) + expect(fixture.browsers).toHaveLength(1) +}) + it('uses its independent model for actions, observations, and a caller-selected extraction schema', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) expect((await execute(first, 'act', { instruction: 'Click the fixture button' })).isError).toBe(false) From aa6f6c1a304c5e51ab1ffb1263a4b15c41ddb4ee Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Wed, 11 Nov 2026 15:50:28 +0800 Subject: [PATCH 54/68] test: brand ToolCallId with brandString after merging master master replaced the branded-id constructors with brandString; the wrapper-cancellation and cua-driver cancellation tests this branch adds now use it too. Refs #7869 --- packages/core/tools/tests/tools.spec.ts | 4 ++-- .../computer-use-cua-driver-native/tests/provider.spec.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index d1b6ec6f2a..cf0828f361 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -2212,7 +2212,7 @@ describe('ToolRuntime', () => { return fail(exec.signal) }) - const result = await executeToolFixture(ctx, { signal: controller.signal, callId: ToolCallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + const result = await executeToolFixture(ctx, { signal: controller.signal, callId: brandString('c1'), name: 'echo', arguments: { text: 'hi' } }) expect(result.isError).toBe(true) expect(result.error?.info).toEqual(info) }) @@ -2222,7 +2222,7 @@ describe('ToolRuntime', () => { ctx.tools.register(echoTool) ctx.on('tools/execute', async () => { throw new DOMException('wrapper stopped', 'AbortError') }) - const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: ToolCallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: brandString('c1'), name: 'echo', arguments: { text: 'hi' } }) expect(result.error).toEqual({ message: 'wrapper stopped' }) }) diff --git a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts index ab69ef6c77..94cf8f95bf 100644 --- a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts +++ b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts @@ -117,7 +117,7 @@ describe('Cua Driver native provider', () => { await ctx.plugin(NativeProvider) const controller = new AbortController() const result = executeToolFixture(ctx, { - name: 'cua_driver_native__click', callId: ToolCallId('native-cancel'), arguments: { pid: 9, window_id: 7 }, signal: controller.signal, + name: 'cua_driver_native__click', callId: brandString('native-cancel'), arguments: { pid: 9, window_id: 7 }, signal: controller.signal, }) await called.promise controller.abort(new Error('Stop clicking')) From 49d112aa673f315afae9f54421fdbb9616bdd467 Mon Sep 17 00:00:00 2001 From: audit Date: Thu, 12 Nov 2026 11:51:12 +0800 Subject: [PATCH 55/68] docs: raise the packages/README.md word ceiling to 1,100 The package group table holds 49 rows and has grown to 992 of its 994 words since the 2026-08-25 rebuild, so the next group row cannot fit; the connector group (`packages/connector/`) needs 11 words. The ceiling and the target in docs/AGENTS.md move together to 1,100, which leaves room for several group rows at the current row length. --- docs/AGENTS.md | 2 +- scripts/doc-budgets.manifest.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 818f40b452..70e40c2b68 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -56,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 1,100; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index f301060236..458e86710f 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -5,5 +5,5 @@ "docs/cordis-primer.md": 600, "docs/testing.md": 1350, "packages/AGENTS.md": 810, - "packages/README.md": 994 + "packages/README.md": 1100 } From 037410b5d7e27005d360cdbdf9873409331e005a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 12 Nov 2026 13:16:51 +0800 Subject: [PATCH 56/68] fix(cua-macos): recover readable AX children by range --- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXAccess.swift | 66 +++++++++++++++---- .../CuaNative/AXObservedChildren.swift | 44 +++++++++++++ .../native/Sources/CuaNative/Protocol.swift | 4 +- .../tests/swift/AXObservedChildrenTests.swift | 56 ++++++++++++++++ snapshots/session/cua-native/session.v4.jsonl | 2 +- .../cua-native/workspace/native-helper.mjs | 4 +- 9 files changed, 165 insertions(+), 19 deletions(-) create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift create mode 100644 packages/experimental/cua-macos/native/tests/swift/AXObservedChildrenTests.swift diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index d7f6930b1b..462e939bb1 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 21d92283c084d8bb zh: 7a29731b9f58c709 /dsh-cua-native-helper/observation-and-input: - en: a1de529f35c130d4 - zh: ec19b62804df2264 + en: 70f4d9992b3f052c + zh: 3fec0fbfb8274ca0 /dsh-cua-native-helper/verification: en: 908b13b2732c1bec zh: ac3bbd77ed9a69b8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 738a852b52..4cc793f1a5 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra AX requests across the observation. Missing children are marked in the tree and set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 4bb22baabb..c934601256 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的恢复操作最多额外调用 `maxElements` 次 AX 接口。树会标出未读到的子项,并将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 123127827d..e0210951b3 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -53,9 +53,9 @@ final class AXAccess { let error = AXUIElementSetMessagingTimeout(element, timeout) guard error == .success else { throw failure(error, "set AX messaging timeout") } } - func failure(_ error: AXError, _ operation: String) -> NativeFailure { + func failure(_ error: AXError, _ operation: String, attribute: String? = nil) -> NativeFailure { NativeFailure(code: error == .apiDisabled ? "PERMISSION_DENIED" : "NATIVE_ERROR", - message: "Accessibility \(operation) failed with error \(error.rawValue)", accessibilityError: error.rawValue) + message: "Accessibility \(operation) failed with error \(error.rawValue)", accessibilityError: error.rawValue, attribute: attribute) } private func absent(_ error: AXError) -> Bool { error == .attributeUnsupported || error == .noValue || error == .notImplemented } static func optionalAttributeUnavailable(_ error: AXError, attribute: String) -> Bool { @@ -71,7 +71,7 @@ final class AXAccess { var value: CFTypeRef? let error = AXUIElementCopyAttributeValue(element, name as CFString, &value) if absent(error) || Self.optionalAttributeUnavailable(error, attribute: name) { return nil } - guard error == .success else { throw failure(error, "read \(name)") } + guard error == .success else { throw failure(error, "read \(name)", attribute: name) } guard let value else { throw NativeFailure(code: "NATIVE_ERROR", message: "Accessibility \(name) returned no value after success") } return value } @@ -118,6 +118,26 @@ final class AXAccess { } return try array.map { try elementValue($0, name) } } + private func recoverChildren(_ element: AXUIElement, limit: Int, requests: inout Int) throws -> AXObservedChildren { + guard requests > 0 else { return .unavailable } + requests -= 1 + try prepare(element) + var count = 0 + let error = AXUIElementGetAttributeValueCount(element, kAXChildrenAttribute as CFString, &count) + if absent(error) || error == .failure { return .unavailable } + guard error == .success else { throw failure(error, "count AXChildren") } + return try AXObservedChildren.readRanges(count: count, limit: limit, requests: &requests) { range in + try prepare(element) + var values: CFArray? + let error = AXUIElementCopyAttributeValues(element, kAXChildrenAttribute as CFString, + range.lowerBound, range.count, &values) + if error == .failure { return .unreadable } + if absent(error) || error == .illegalArgument { return .unavailable } + guard error == .success else { throw failure(error, "read AXChildren range") } + guard let values, CFArrayGetCount(values) == range.count else { return .unavailable } + return .values(try childValues(values, attribute: "AXChildren")) + } + } func windowID(_ element: AXUIElement) throws -> UInt32? { try prepare(element) guard let windowFunction else { return nil } @@ -515,7 +535,7 @@ final class AXAccess { if error == .attributeUnsupported || error == .noValue || error == .notImplemented || optionalAttributeUnavailable(error, attribute: name) { return nil } throw NativeFailure(code: error == .apiDisabled ? "PERMISSION_DENIED" : "NATIVE_ERROR", - message: "Accessibility read \(name) failed with error \(error.rawValue)", accessibilityError: error.rawValue) + message: "Accessibility read \(name) failed with error \(error.rawValue)", accessibilityError: error.rawValue, attribute: name) } } return value @@ -545,7 +565,20 @@ final class AXAccess { func project(identity: ProcessIdentity, windowID requested: UInt32?, maxElements: Int, maxDepth: Int, includeMenus: Bool = false, details: Bool = false) throws -> AXProjection { let app = AXUIElementCreateApplication(identity.pid) try enableAX(app, identity: identity) - var roots = try children(app) + var recoveryRequests = maxElements + // Window discovery and traversal can both enumerate the same parent. + var discovery: [AXUIElement: AXObservedChildren] = [:] + func observedChildren(_ parent: AXUIElement, _ value: @autoclosure () throws -> CFTypeRef?, duringDiscovery: Bool = false) throws -> AXObservedChildren { + if let cached = discovery[parent] { return cached } + do { + return try AXObservedChildren(elements: childValues(value(), attribute: "AXChildren"), incomplete: false) + } catch let error as NativeFailure where error.attribute == "AXChildren" && error.accessibilityError == AXError.failure.rawValue { + let children = try recoverChildren(parent, limit: maxElements, requests: &recoveryRequests) + if duringDiscovery { discovery[parent] = children } + return children + } + } + var roots = try observedChildren(app, attribute(app, "AXChildren"), duringDiscovery: true).elements func appendUnique(_ element: AXUIElement) { if !roots.contains(where: { CFEqual($0, element) }) { roots.append(element) } } @@ -558,7 +591,7 @@ final class AXAccess { cursor += 1 let role = try string(root, "AXRole") guard role == "AXWindow" || role == "AXSheet" else { continue } - for child in try children(root) where roots.count < maxElements { + for child in try observedChildren(root, attribute(root, "AXChildren"), duringDiscovery: true).elements where roots.count < maxElements { if try string(child, "AXRole") == "AXSheet" { appendUnique(child) } } } @@ -577,6 +610,7 @@ final class AXAccess { } if matches.isEmpty { _ = try NativePlatform.ownedWindow(identity.pid, requested) + if discovery.values.contains(where: \.incomplete) { throw failure(.failure, "locate window in incomplete AXChildren") } return AXProjection(tree: "", elements: [], indexed: [:], focusedWindowID: focusedID, truncated: false) } let dialog = try matches.contains { root in @@ -592,17 +626,26 @@ final class AXAccess { } if !dialog { roots.append(contentsOf: anonymousSheets) } } + if roots.isEmpty && discovery[app]?.incomplete == true { throw failure(.failure, "read application AXChildren") } var visited: [CFHashCode: [AXUIElement]] = [:] var count = 0 var elementLimitReached = false var depthLimitReached = false + var unreportedParents = Set(discovery.compactMap { $0.value.incomplete ? $0.key : nil }) + var childrenMissing = !unreportedParents.isEmpty var menusCollapsed = false var lines = ["AX scope=\(requested == nil ? "application" : "window") offsets=UTF-16\(details ? " bounds=global-points" : "")"] var elements: [JSONValue] = [] var indexed: [Int: AXUIElement] = [:] var pending = roots.reversed().map { (element: $0, level: 0, depth: 0) } - func enqueueChildren(_ children: [AXUIElement], level: Int, depth: Int) { - for child in children.reversed() { pending.append((child, level, depth)) } + func enqueueChildren(_ parent: AXUIElement, observation: AXNodeObservation, level: Int, depth: Int) throws { + let children = try observedChildren(parent, observation.attribute("AXChildren")) + if children.incomplete { + childrenMissing = true + unreportedParents.remove(parent) + lines.append(String(repeating: " ", count: level) + "[Some children of " + observation.role + " could not be read.]") + } + for child in children.elements.reversed() { pending.append((child, level, depth)) } } while let (element, level, depth) = pending.popLast() { try cancellation.check() @@ -644,7 +687,7 @@ final class AXAccess { identifier: identifier, url: url, focused: focused, expanded: expanded) node.validateSelection() if node.transparent || (!addressable && !node.hasMeaning && role != "AXWindow" && role != "AXSheet") { - enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level, depth: depth + 1) + try enqueueChildren(element, observation: observation, level: level, depth: depth + 1) continue } let index: Int? = addressable ? indexed.count : nil @@ -669,12 +712,13 @@ final class AXAccess { ])) } if role == "AXMenuBarItem" && !includeMenus { menusCollapsed = true; continue } - enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level + 1, depth: depth + 1) + try enqueueChildren(element, observation: observation, level: level + 1, depth: depth + 1) } if menusCollapsed { lines.append("Menu contents omitted; request includeMenus=true to expand.") } let truncated = elementLimitReached || depthLimitReached if truncated { lines.append(AXTextFormatter.truncation(maxElements: elementLimitReached ? maxElements : nil, maxDepth: depthLimitReached ? maxDepth : nil)) } - return AXProjection(tree: lines.joined(separator: "\n"), elements: elements, indexed: indexed, focusedWindowID: focusedID, truncated: truncated) + if !unreportedParents.isEmpty { lines.append("[Some children could not be read during window discovery.]") } + return AXProjection(tree: lines.joined(separator: "\n"), elements: elements, indexed: indexed, focusedWindowID: focusedID, truncated: truncated || childrenMissing) } func enclosingWindow(_ element: AXUIElement) throws -> (element: AXUIElement, id: UInt32) { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift new file mode 100644 index 0000000000..351a0fb940 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift @@ -0,0 +1,44 @@ +// Range reads recover siblings when one child prevents macOS from returning the entire AXChildren array. +import ApplicationServices + +struct AXObservedChildren { + let elements: [AXUIElement] + let incomplete: Bool + + static var unavailable: Self { Self(elements: [], incomplete: true) } + + enum RangeRead { + case values([AXUIElement]) + case unreadable + case unavailable + } + + /// Requests are shared across the observation. A changed range invalidates this parent's accumulated indices. + static func readRanges(count: Int, limit: Int, requests: inout Int, + read: (Range) throws -> RangeRead) rethrows -> Self { + guard count > 0 else { return .unavailable } + let end = min(count, limit) + var pending = [0.. 0 else { incomplete = true; break } + requests -= 1 + switch try read(range) { + case .values(let values): + children.append(contentsOf: values) + case .unavailable: + return .unavailable + case .unreadable: + if range.count == 1 { + incomplete = true + } else { + let middle = range.lowerBound + range.count / 2 + pending.append(middle.. 0) +} + +@Test func recoveryHonorsBothTheRequestAndElementLimits() { + let node = AXUIElementCreateApplication(1) + var requests = 3 + let limited = AXObservedChildren.readRanges(count: Int.max, limit: 4, requests: &requests) { range in + #expect(range.upperBound <= 4) + return range.upperBound > 2 ? .unreadable : .values(Array(repeating: node, count: range.count)) + } + #expect(limited.elements == [node, node]) + #expect(limited.incomplete) + #expect(requests == 0) + + let exhausted = AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { _ in + Issue.record("Recovery called AX after exhausting the observation budget") + return .unreadable + } + #expect(exhausted.elements.isEmpty) + #expect(exhausted.incomplete) +} + +@Test func aChangedRangeDiscardsEarlierChildrenAndOtherErrorsPropagate() { + let node = AXUIElementCreateApplication(1) + var requests = 10 + let changed = AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { range in + if range.count == 2 { return .unreadable } + return range.lowerBound == 0 ? .values([node]) : .unavailable + } + #expect(changed.incomplete) + #expect(changed.elements.isEmpty) + #expect(throws: CancellationError.self) { + try AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { _ in throw CancellationError() } + } +} + +@Test func completeRangeRecoveryPublishesACompleteObservation() { + let node = AXUIElementCreateApplication(1) + var requests = 1 + let recovered = AXObservedChildren.readRanges(count: 1, limit: 1, requests: &requests) { _ in .values([node]) } + #expect(recovered.elements == [node]) + #expect(!recovered.incomplete) +} diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 764a726230..9cceb3c3ab 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -39,7 +39,7 @@ {"type":"step/start","data":{"turn":1,"step":6}} {"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350389,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350389,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1794214350389,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350389,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n [Some children of AXMenuBarItem could not be read.]\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":true}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} {"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350417,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350417,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 17330ed8b0..ff45f6b81b 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -190,10 +190,10 @@ function createApplicationState(socket, record, application, captureBroker, conn tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16\n- [0] AXButton "Increment"\nAccessibility tree truncated (maxElements=1).`, elements: [], windows: windows(), truncated: true } return { appHandle: app.appHandle, windowId: params.windowId ?? null, - snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : 'true'} value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, + snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : 'true'} value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n [Some children of AXMenuBarItem could not be read.]\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, elements: [{ elementId: '0', role: 'AXButton', title: 'Increment', value: null, description: null, identifier: null, bounds: [60, 80, 100, 20], actions: ['AXPress'], enabled: true }], - focusedWindowId: window.windowId, windows: windows(), truncated: false } + focusedWindowId: window.windowId, windows: windows(), truncated: params.includeMenus === true } } if (params.windowId === '9' && ['screenshot', 'mouseMove', 'click', 'scroll', 'drag'].includes(method) && params.elementId === undefined) { refuse('WINDOW_CHANGED', 'Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input') From 3fdea06f54055aa8ae2a91c48d90d446e1e27a11 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 12 Nov 2026 13:21:20 +0800 Subject: [PATCH 57/68] fix(cua-macos): keep unreadable children in sibling order --- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXAccess.swift | 38 +++++++++++++------ .../CuaNative/AXObservedChildren.swift | 27 +++++++------ .../tests/swift/AXObservedChildrenTests.swift | 13 ++++--- snapshots/session/cua-native/session.v4.jsonl | 2 +- .../cua-native/workspace/native-helper.mjs | 2 +- 8 files changed, 55 insertions(+), 35 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 462e939bb1..a5154cc8f8 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 21d92283c084d8bb zh: 7a29731b9f58c709 /dsh-cua-native-helper/observation-and-input: - en: 70f4d9992b3f052c - zh: 3fec0fbfb8274ca0 + en: 91ec2b1cb49041e3 + zh: e7131744a12437c3 /dsh-cua-native-helper/verification: en: 908b13b2732c1bec zh: ac3bbd77ed9a69b8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 4cc793f1a5..ef0d071ec0 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra AX requests across the observation. Missing children are marked in the tree and set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra AX requests across the observation. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index c934601256..ce6cd2c663 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的恢复操作最多额外调用 `maxElements` 次 AX 接口。树会标出未读到的子项,并将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的恢复操作最多额外调用 `maxElements` 次 AX 接口。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都会将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index e0210951b3..13252b77cc 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -134,7 +134,7 @@ final class AXAccess { if error == .failure { return .unreadable } if absent(error) || error == .illegalArgument { return .unavailable } guard error == .success else { throw failure(error, "read AXChildren range") } - guard let values, CFArrayGetCount(values) == range.count else { return .unavailable } + guard let values, CFArrayGetCount(values) <= range.count else { return .unavailable } return .values(try childValues(values, attribute: "AXChildren")) } } @@ -571,14 +571,16 @@ final class AXAccess { func observedChildren(_ parent: AXUIElement, _ value: @autoclosure () throws -> CFTypeRef?, duringDiscovery: Bool = false) throws -> AXObservedChildren { if let cached = discovery[parent] { return cached } do { - return try AXObservedChildren(elements: childValues(value(), attribute: "AXChildren"), incomplete: false) + return try AXObservedChildren(entries: childValues(value(), attribute: "AXChildren")) } catch let error as NativeFailure where error.attribute == "AXChildren" && error.accessibilityError == AXError.failure.rawValue { let children = try recoverChildren(parent, limit: maxElements, requests: &recoveryRequests) if duringDiscovery { discovery[parent] = children } return children } } - var roots = try observedChildren(app, attribute(app, "AXChildren"), duringDiscovery: true).elements + let appChildren = try observedChildren(app, attribute(app, "AXChildren"), duringDiscovery: true) + var roots = appChildren.entries.compactMap { $0 } + let appRootCount = roots.count func appendUnique(_ element: AXUIElement) { if !roots.contains(where: { CFEqual($0, element) }) { roots.append(element) } } @@ -591,7 +593,7 @@ final class AXAccess { cursor += 1 let role = try string(root, "AXRole") guard role == "AXWindow" || role == "AXSheet" else { continue } - for child in try observedChildren(root, attribute(root, "AXChildren"), duringDiscovery: true).elements where roots.count < maxElements { + for case let child? in try observedChildren(root, attribute(root, "AXChildren"), duringDiscovery: true).entries where roots.count < maxElements { if try string(child, "AXRole") == "AXSheet" { appendUnique(child) } } } @@ -610,8 +612,9 @@ final class AXAccess { } if matches.isEmpty { _ = try NativePlatform.ownedWindow(identity.pid, requested) - if discovery.values.contains(where: \.incomplete) { throw failure(.failure, "locate window in incomplete AXChildren") } - return AXProjection(tree: "", elements: [], indexed: [:], focusedWindowID: focusedID, truncated: false) + let incomplete = discovery.values.contains(where: \.incomplete) + let tree = incomplete ? "[Window discovery incomplete. Some children could not be read.]" : "" + return AXProjection(tree: tree, elements: [], indexed: [:], focusedWindowID: focusedID, truncated: incomplete) } let dialog = try matches.contains { root in let role = try string(root, "AXRole") @@ -626,7 +629,6 @@ final class AXAccess { } if !dialog { roots.append(contentsOf: anonymousSheets) } } - if roots.isEmpty && discovery[app]?.incomplete == true { throw failure(.failure, "read application AXChildren") } var visited: [CFHashCode: [AXUIElement]] = [:] var count = 0 var elementLimitReached = false @@ -637,22 +639,36 @@ final class AXAccess { var lines = ["AX scope=\(requested == nil ? "application" : "window") offsets=UTF-16\(details ? " bounds=global-points" : "")"] var elements: [JSONValue] = [] var indexed: [Int: AXUIElement] = [:] - var pending = roots.reversed().map { (element: $0, level: 0, depth: 0) } + let rootEntries: [AXUIElement?] + if requested == nil { + rootEntries = appChildren.entries + roots.dropFirst(appRootCount) + unreportedParents.remove(app) + if appChildren.parentIncomplete { lines.append("[Some children of AXApplication could not be read.]") } + } else { + rootEntries = roots + } + var pending = rootEntries.reversed().map { (element: $0, level: 0, depth: 0) } func enqueueChildren(_ parent: AXUIElement, observation: AXNodeObservation, level: Int, depth: Int) throws { let children = try observedChildren(parent, observation.attribute("AXChildren")) if children.incomplete { childrenMissing = true unreportedParents.remove(parent) + } + if children.parentIncomplete { lines.append(String(repeating: " ", count: level) + "[Some children of " + observation.role + " could not be read.]") } - for child in children.elements.reversed() { pending.append((child, level, depth)) } + for child in children.entries.reversed() { pending.append((child, level, depth)) } } - while let (element, level, depth) = pending.popLast() { + while let (entry, level, depth) = pending.popLast() { try cancellation.check() + guard depth <= maxDepth else { depthLimitReached = true; continue } + guard let element = entry else { + lines.append(String(repeating: " ", count: level) + "[One child could not be read.]") + continue + } let hash = CFHash(element) if visited[hash, default: []].contains(where: { CFEqual($0, element) }) { continue } guard count < maxElements else { elementLimitReached = true; break } - guard depth <= maxDepth else { depthLimitReached = true; continue } visited[hash, default: []].append(element) count += 1 let observation = try nodeObservation(attributes: metadata(element), fallback: { try self.attribute(element, $0) }) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift index 351a0fb940..4cd6807eb0 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift @@ -1,11 +1,12 @@ -// Range reads recover siblings when one child prevents macOS from returning the entire AXChildren array. +// A nil entry preserves the position of an unreadable child without creating an actionable AX reference. import ApplicationServices struct AXObservedChildren { - let elements: [AXUIElement] - let incomplete: Bool + var entries: [AXUIElement?] = [] + var parentIncomplete = false - static var unavailable: Self { Self(elements: [], incomplete: true) } + var incomplete: Bool { parentIncomplete || entries.contains(nil) } + static var unavailable: Self { Self(parentIncomplete: true) } enum RangeRead { case values([AXUIElement]) @@ -13,32 +14,34 @@ struct AXObservedChildren { case unavailable } - /// Requests are shared across the observation. A changed range invalidates this parent's accumulated indices. + /// A single observation shares its extra AX requests across all parents. Changed ranges lose their position guarantee. static func readRanges(count: Int, limit: Int, requests: inout Int, read: (Range) throws -> RangeRead) rethrows -> Self { guard count > 0 else { return .unavailable } let end = min(count, limit) var pending = [0.. 0 else { incomplete = true; break } + guard requests > 0 else { result.parentIncomplete = true; break } requests -= 1 switch try read(range) { case .values(let values): - children.append(contentsOf: values) + result.entries.append(contentsOf: values) + if values.count == range.count { continue } case .unavailable: - return .unavailable + break case .unreadable: if range.count == 1 { - incomplete = true + result.entries.append(nil) } else { let middle = range.lowerBound + range.count / 2 pending.append(middle.. 0) } @@ -21,7 +21,7 @@ import Testing #expect(range.upperBound <= 4) return range.upperBound > 2 ? .unreadable : .values(Array(repeating: node, count: range.count)) } - #expect(limited.elements == [node, node]) + #expect(limited.entries == [node, node]) #expect(limited.incomplete) #expect(requests == 0) @@ -29,11 +29,11 @@ import Testing Issue.record("Recovery called AX after exhausting the observation budget") return .unreadable } - #expect(exhausted.elements.isEmpty) + #expect(exhausted.entries.isEmpty) #expect(exhausted.incomplete) } -@Test func aChangedRangeDiscardsEarlierChildrenAndOtherErrorsPropagate() { +@Test func aChangedRangeRetainsReadableReferencesAndOtherErrorsPropagate() { let node = AXUIElementCreateApplication(1) var requests = 10 let changed = AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { range in @@ -41,7 +41,8 @@ import Testing return range.lowerBound == 0 ? .values([node]) : .unavailable } #expect(changed.incomplete) - #expect(changed.elements.isEmpty) + #expect(changed.entries == [node]) + #expect(changed.parentIncomplete) #expect(throws: CancellationError.self) { try AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { _ in throw CancellationError() } } @@ -51,6 +52,6 @@ import Testing let node = AXUIElementCreateApplication(1) var requests = 1 let recovered = AXObservedChildren.readRanges(count: 1, limit: 1, requests: &requests) { _ in .values([node]) } - #expect(recovered.elements == [node]) + #expect(recovered.entries == [node]) #expect(!recovered.incomplete) } diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 9cceb3c3ab..51306d9004 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -39,7 +39,7 @@ {"type":"step/start","data":{"turn":1,"step":6}} {"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350389,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350389,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1794214350389,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350389,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n [Some children of AXMenuBarItem could not be read.]\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":true}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\\n [One child could not be read.]\\n - [4] AXMenuItem \\\"Close\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":true}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} {"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794214350417,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350417,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index ff45f6b81b..9255f9c9e1 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -190,7 +190,7 @@ function createApplicationState(socket, record, application, captureBroker, conn tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16\n- [0] AXButton "Increment"\nAccessibility tree truncated (maxElements=1).`, elements: [], windows: windows(), truncated: true } return { appHandle: app.appHandle, windowId: params.windowId ?? null, - snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : 'true'} value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n [Some children of AXMenuBarItem could not be read.]\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, + snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : 'true'} value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"\n [One child could not be read.]\n - [4] AXMenuItem "Close"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, elements: [{ elementId: '0', role: 'AXButton', title: 'Increment', value: null, description: null, identifier: null, bounds: [60, 80, 100, 20], actions: ['AXPress'], enabled: true }], focusedWindowId: window.windowId, windows: windows(), truncated: params.includeMenus === true } From 7863218fcdce029023a34a12d8edb39b84ccb6d9 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 12 Nov 2026 13:24:35 +0800 Subject: [PATCH 58/68] fix(cua-macos): apply traversal limits to unreadable entries --- .../experimental/cua-macos/native/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/native/README.md | 2 +- .../experimental/cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXAccess.swift | 14 +++++++------- .../tests/swift/AXObservedChildrenTests.swift | 4 +++- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index a5154cc8f8..273d6fa217 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 21d92283c084d8bb zh: 7a29731b9f58c709 /dsh-cua-native-helper/observation-and-input: - en: 91ec2b1cb49041e3 - zh: e7131744a12437c3 + en: 9a4e178c02195280 + zh: b69303ad6621fe8e /dsh-cua-native-helper/verification: en: 908b13b2732c1bec zh: ac3bbd77ed9a69b8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index ef0d071ec0..04338f300c 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra AX requests across the observation. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra count and range reads across the observation. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index ce6cd2c663..d46383512e 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的恢复操作最多额外调用 `maxElements` 次 AX 接口。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都会将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的额外计数和范围读取合计不超过 `maxElements` 次。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都会将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 13252b77cc..1de0859717 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -124,7 +124,7 @@ final class AXAccess { try prepare(element) var count = 0 let error = AXUIElementGetAttributeValueCount(element, kAXChildrenAttribute as CFString, &count) - if absent(error) || error == .failure { return .unavailable } + if absent(error) || error == .failure || error == .illegalArgument { return .unavailable } guard error == .success else { throw failure(error, "count AXChildren") } return try AXObservedChildren.readRanges(count: count, limit: limit, requests: &requests) { range in try prepare(element) @@ -641,7 +641,7 @@ final class AXAccess { var indexed: [Int: AXUIElement] = [:] let rootEntries: [AXUIElement?] if requested == nil { - rootEntries = appChildren.entries + roots.dropFirst(appRootCount) + rootEntries = appChildren.entries + roots.dropFirst(appRootCount).map(Optional.some) unreportedParents.remove(app) if appChildren.parentIncomplete { lines.append("[Some children of AXApplication could not be read.]") } } else { @@ -661,16 +661,16 @@ final class AXAccess { } while let (entry, level, depth) = pending.popLast() { try cancellation.check() + let hash = entry.map { CFHash($0) } + if let element = entry, let hash, visited[hash, default: []].contains(where: { CFEqual($0, element) }) { continue } + guard count < maxElements else { elementLimitReached = true; break } guard depth <= maxDepth else { depthLimitReached = true; continue } - guard let element = entry else { + count += 1 + guard let element = entry, let hash else { lines.append(String(repeating: " ", count: level) + "[One child could not be read.]") continue } - let hash = CFHash(element) - if visited[hash, default: []].contains(where: { CFEqual($0, element) }) { continue } - guard count < maxElements else { elementLimitReached = true; break } visited[hash, default: []].append(element) - count += 1 let observation = try nodeObservation(attributes: metadata(element), fallback: { try self.attribute(element, $0) }) let role = observation.role let observed = observation.attribute diff --git a/packages/experimental/cua-macos/native/tests/swift/AXObservedChildrenTests.swift b/packages/experimental/cua-macos/native/tests/swift/AXObservedChildrenTests.swift index 8096c64f23..90805b58e9 100644 --- a/packages/experimental/cua-macos/native/tests/swift/AXObservedChildrenTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/AXObservedChildrenTests.swift @@ -10,7 +10,9 @@ import Testing range.contains(17) ? .unreadable : .values(Array(nodes[range])) } #expect(children.incomplete) - #expect(children.entries == Array(nodes[..<17]) + [nil] + Array(nodes[18...])) + var expected = nodes.map(Optional.some) + expected[17] = nil + #expect(children.entries == expected) #expect(requests > 0) } From 394476afec7ba8260608a225c5040ada079f31a2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 12 Nov 2026 13:25:25 +0800 Subject: [PATCH 59/68] fix(cua-macos): read failed ranges of up to five children by index --- .../cua-macos/native/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/native/README.md | 2 +- .../experimental/cua-macos/native/README.zh.md | 2 +- .../Sources/CuaNative/AXObservedChildren.swift | 14 ++++++++++---- .../tests/swift/AXObservedChildrenTests.swift | 16 ++++++++++++++++ 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 273d6fa217..c2c6bf2720 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 21d92283c084d8bb zh: 7a29731b9f58c709 /dsh-cua-native-helper/observation-and-input: - en: 9a4e178c02195280 - zh: b69303ad6621fe8e + en: 2df3a698707a902b + zh: 98b450abe89b200a /dsh-cua-native-helper/verification: en: 908b13b2732c1bec zh: ac3bbd77ed9a69b8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 04338f300c..0d275e8b1f 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra count and range reads across the observation. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When window discovery completes and an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. If reading `AXChildren` returns -25200, the helper reads failed ranges of up to five children individually and halves larger failed ranges. Successful ranges retain their original order. Recovery shares a budget of `maxElements` extra count and range reads across the observation. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `truncated` to true. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index d46383512e..1b0e65d9dc 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的额外计数和范围读取合计不超过 `maxElements` 次。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都会将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 将读取失败且超过 5 项的范围对半拆分,5 项及以下的失败范围按下标逐项读取,成功的范围按原顺序保留。一次观察中的额外计数和范围读取合计不超过 `maxElements` 次。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都会将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift index 4cd6807eb0..d31df23851 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXObservedChildren.swift @@ -14,12 +14,20 @@ struct AXObservedChildren { case unavailable } + private static func smallerRanges(_ failed: Range) -> [Range] { + if failed.count <= 5 { return failed.map { $0..<($0 + 1) } } + let middle = failed.lowerBound + failed.count / 2 + return [failed.lowerBound..) throws -> RangeRead) rethrows -> Self { guard count > 0 else { return .unavailable } let end = min(count, limit) - var pending = [0.. 0 else { result.parentIncomplete = true; break } @@ -34,9 +42,7 @@ struct AXObservedChildren { if range.count == 1 { result.entries.append(nil) } else { - let middle = range.lowerBound + range.count / 2 - pending.append(middle..] = [] + var requests = 20 + let result = AXObservedChildren.readRanges(count: count, limit: count, requests: &requests) { range in + ranges.append(range) + return range.contains(failed) ? .unreadable : .values(Array(repeating: element, count: range.count)) + } + let expected = count <= 5 ? (0.. Date: Thu, 12 Nov 2026 13:35:57 +0800 Subject: [PATCH 60/68] feat(session): add host reading status to SessionStatus (#6858) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com> --- ...sion-history-and-event-transport.i18n.yaml | 4 +- ...-18-session-history-and-event-transport.md | 2 +- ...-session-history-and-event-transport.zh.md | 2 +- ...t-session-conversation-ownership.i18n.yaml | 4 +- ...0-client-session-conversation-ownership.md | 2 +- ...lient-session-conversation-ownership.zh.md | 2 +- ...-09-15-client-session-references.i18n.yaml | 4 +- .../2026-09-15-client-session-references.md | 14 +- ...2026-09-15-client-session-references.zh.md | 14 +- ...026-10-23-session-reading-memory.i18n.yaml | 31 ++ .../2026-10-23-session-reading-memory.md | 58 +++ .../2026-10-23-session-reading-memory.zh.md | 58 +++ apps/web/tests/client-plugin-live.e2e.ts | 2 +- apps/web/tests/context-menus.e2e.ts | 4 +- .../session-actions.expected.md | 1 + .../tests/expected/context-menus/session.txt | 1 + .../menu-material/session-menu.expected.md | 1 + .../session-reading/failed-unread.expected.md | 1 + .../session-reading/unread-menu.expected.md | 11 + .../macos-defaults.expected.md | 3 + .../session-menu.expected.md | 1 + .../expected/shortcuts/en-US.expected.md | 3 + .../expected/shortcuts/zh-CN.expected.md | 3 + .../owner-running.expected.md | 2 +- apps/web/tests/github-ready-review.e2e.ts | 3 + apps/web/tests/plan-review.e2e.ts | 6 +- apps/web/tests/question-composer.e2e.ts | 2 +- apps/web/tests/session-reading.e2e.ts | 179 +++++++++ .../tests/sidebar-subagent-activity.e2e.ts | 2 +- apps/web/tsconfig.json | 1 + docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 5 + docs/capability-seams.zh.md | 5 + docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/subsystems/web-client.i18n.yaml | 20 +- docs/subsystems/web-client.md | 59 ++- docs/subsystems/web-client.zh.md | 59 ++- .../session-status-package/guide.i18n.yaml | 22 +- .../session-status-package/guide.md | 23 +- .../session-status-package/guide.zh.md | 21 +- packages/api/gateway/README.i18n.yaml | 4 +- packages/api/gateway/README.md | 2 +- packages/api/gateway/README.zh.md | 2 +- packages/api/gateway/src/client/index.ts | 3 +- .../api/gateway/src/client/journal-stream.ts | 4 +- .../api/gateway/src/client/remote-stream.ts | 15 +- .../api/gateway/src/client/stream-client.ts | 34 +- .../tests/control-retry.client.spec.ts | 43 +++ packages/api/remotes/package.json | 1 + packages/api/remotes/src/client/index.ts | 5 +- .../src/client/transport.ts | 5 +- .../terminal-controller/src/client/model.ts | 4 +- .../tests/model.client.spec.ts | 9 + .../workspace-controller/src/client/index.ts | 3 +- packages/bundle/web-app/cordis.patch.yml | 3 +- packages/client/AGENTS.md | 4 +- packages/client/README.i18n.yaml | 4 +- packages/client/README.md | 2 +- packages/client/README.zh.md | 2 +- .../tests/collection.client.spec.ts | 2 +- .../tests/apply.client.spec.ts | 4 +- .../ui-conversation/tsconfig.client.json | 2 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../client/ui-primitives/src/icons/artwork.ts | 2 + .../client/ui-primitives/src/icons/index.tsx | 12 + .../client/ui-session-status/README.i18n.yaml | 38 +- packages/client/ui-session-status/README.md | 77 +++- .../client/ui-session-status/README.zh.md | 85 ++++- .../client/ui-session-status/package.json | 36 +- .../src/client/acknowledge.ts | 103 ++++++ .../ui-session-status/src/client/index.ts | 11 +- .../ui-session-status/src/client/model.ts | 73 ++++ .../ui-session-status/src/client/read.ts | 62 ++++ .../ui-session-status/src/client/status.ts | 122 +++++-- packages/client/ui-session-status/src/feed.ts | 58 +++ .../client/ui-session-status/src/index.ts | 148 +++++++- packages/client/ui-session-status/src/spec.ts | 5 + .../client/ui-session-status/src/types.ts | 32 ++ .../tests/access.client.spec.ts | 157 ++++++++ .../tests/acknowledge.client.spec.ts | 291 +++++++++++++++ .../tests/model.client.spec.ts | 87 +++++ .../tests/status-controller.client.spec.ts | 85 ++++- .../tests/status-view.client.spec.ts | 109 ++++++ .../tests/status.client.spec.ts | 159 +++++--- .../tests/status.host.spec.ts | 345 ++++++++++++++++++ .../ui-session-status/tsconfig.client.json | 47 +++ .../ui-session-status/tsconfig.host.json | 34 ++ .../client/ui-session-status/tsconfig.json | 35 +- .../client/ui-session-status/tsdown.config.ts | 2 +- packages/client/ui-sidebar/README.i18n.yaml | 4 +- packages/client/ui-sidebar/README.md | 1 - packages/client/ui-sidebar/README.zh.md | 1 - .../tests/conversation-ui.client.spec.tsx | 2 +- packages/client/ui-subagent/tsconfig.json | 2 +- .../tests/workflow-run.client.spec.tsx | 4 +- packages/client/ui-workflow-run/tsconfig.json | 2 +- packages/client/ui-workspace/README.i18n.yaml | 16 +- packages/client/ui-workspace/README.md | 12 +- packages/client/ui-workspace/README.zh.md | 12 +- .../ui-workspace/src/client/contract/slots.ts | 1 + .../client/ui-workspace/src/client/index.ts | 11 +- .../client/ui-workspace/src/client/locales.ts | 88 ++++- .../ui-workspace/src/client/rows/Rows.tsx | 25 +- .../client/session-actions/context-menus.tsx | 19 +- .../ui-workspace/src/client/shortcuts.ts | 28 ++ .../ui-workspace/src/client/toast/register.ts | 7 + .../client/ui-workspace/src/client/tree.ts | 10 +- .../tests/access-assembly.client.spec.tsx | 5 +- .../ui-workspace/tests/apply.client.spec.ts | 40 +- .../tests/rename-assembly.client.spec.tsx | 2 +- .../ui-workspace/tests/rows.client.spec.tsx | 127 ++++--- .../tests/session-actions.client.spec.tsx | 6 + .../tests/session-menu-actions.client.spec.ts | 42 ++- .../tests/session-status.client.ts | 33 ++ .../tests/shortcuts.client.spec.ts | 64 +++- .../ui-workspace/tests/tree.client.spec.ts | 20 +- .../tests/workspace-browser.client.spec.tsx | 16 +- packages/client/ui-workspace/tsconfig.json | 2 +- .../liveshare/src/endpoint-classification.ts | 2 + .../tests/viewer-access-policy.spec.ts | 11 + .../viewer-shell-artifact.client.spec.tsx | 6 +- .../src/client/api-catalog.ts | 6 +- .../src/client/slot-catalog.ts | 3 +- .../extensions/tool-cordis/src/api-catalog.ts | 32 ++ .../tests/projection.spec.ts | 2 +- .../skills/dsh-doc/references/packages.md | 2 +- .../session-title/tests/projection.spec.ts | 2 +- .../src/assembly/remote-default-responses.ts | 1 + .../test-support/client-runtime/src/index.ts | 13 +- .../test-support/client-runtime/src/remote.ts | 21 +- .../tests/helpers.client.spec.tsx | 4 +- .../test-support/client-runtime/tsconfig.json | 2 +- pnpm-lock.yaml | 31 ++ scripts/gen-cordis-catalog.ts | 4 + scripts/gen-doc-graphs.ts | 8 + scripts/verify-client-packages.spec.ts | 23 +- scripts/verify-client-packages.ts | 18 +- .../verify-package-readme-model-experience.ts | 2 +- tsconfig.base.json | 1 + tsconfig.client.json | 2 +- tsconfig.host.json | 2 + 146 files changed, 3404 insertions(+), 423 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-10-23-session-reading-memory.md create mode 100644 .agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md create mode 100644 apps/web/tests/expected/session-reading/failed-unread.expected.md create mode 100644 apps/web/tests/expected/session-reading/unread-menu.expected.md create mode 100644 apps/web/tests/session-reading.e2e.ts create mode 100644 packages/client/ui-session-status/src/client/acknowledge.ts create mode 100644 packages/client/ui-session-status/src/client/model.ts create mode 100644 packages/client/ui-session-status/src/client/read.ts create mode 100644 packages/client/ui-session-status/src/feed.ts create mode 100644 packages/client/ui-session-status/src/spec.ts create mode 100644 packages/client/ui-session-status/src/types.ts create mode 100644 packages/client/ui-session-status/tests/access.client.spec.ts create mode 100644 packages/client/ui-session-status/tests/acknowledge.client.spec.ts create mode 100644 packages/client/ui-session-status/tests/model.client.spec.ts create mode 100644 packages/client/ui-session-status/tests/status-view.client.spec.ts create mode 100644 packages/client/ui-session-status/tests/status.host.spec.ts create mode 100644 packages/client/ui-session-status/tsconfig.client.json create mode 100644 packages/client/ui-session-status/tsconfig.host.json create mode 100644 packages/client/ui-workspace/tests/session-status.client.ts diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml index 93feec2b95..617d73c1af 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml @@ -18,8 +18,8 @@ en: fb2c7bcde3b1672a zh: a05bd30be07e5413 /agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotestream: - en: d55c2ce88400e448 - zh: 344d510ab946bb9f + en: 867f3ac763f81d8d + zh: a936269f2fc40f8d /agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotesnapshotstream: en: f2c1d2b00d9554fd zh: c3e85cf344f7ef24 diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md index ee43b551eb..c9447a8b1a 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md @@ -101,7 +101,7 @@ Domain Controllers use them through composition or thin adapters; Session and Wo Each item carries a monotonic generation, that generation's `AbortSignal`, and `accept()`. A domain consumer calls `accept()` only after validating the opening cursor or baseline. -Only `RemoteStreamCarrierError` permits retry. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately. +Only a failure whose `code` is `gateway/carrier-lost` permits retry; `RemoteStreamCarrierError` carries that code, and a domain `ended` callback may return a plain `Error` with it. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately. `restart()` replaces only the current physical generation and preserves the logical stream. `dispose()` permanently ends the logical stream, pending retry, and iterator, then waits for quiescence. diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md index 9df5c55701..4347de301c 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md @@ -101,7 +101,7 @@ RemoteStream 每个 item 携带单调 generation、该 generation 的 `AbortSignal` 与 `accept()`。领域 consumer 只有在验证 opening cursor 或 baseline 后才调用 `accept()`。 -只有 `RemoteStreamCarrierError` 可触发重试。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。 +只有 `code` 为 `gateway/carrier-lost` 的失败可触发重试;`RemoteStreamCarrierError` 带有该 code,领域的 `ended` 回调也可以返回带该 code 的普通 `Error`。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。 `restart()` 只淘汰当前物理 generation,保留 logical stream;`dispose()` 永久结束 logical stream、pending retry 与 iterator,并等待 quiescence。 diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml index 802e66d820..7795233f7c 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml @@ -24,8 +24,8 @@ en: b6f585ca87e1fc6f zh: 53fd58c3e93cf17c /agent-note-client-session-conversation-and-ui-ownership-layers/package-ownership: - en: 89f75f7cc2fe0e6c - zh: e50974fad3baf69c + en: f3f1e545f7b15d9a + zh: 80927e6b4e8ed5bc /agent-note-client-session-conversation-and-ui-ownership-layers/overall-data-flow: en: 002d9f406580684b zh: a86742c6c943ac85 diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md index 4ef7434535..b3286623c4 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md @@ -81,7 +81,7 @@ Adding a target does not add a branch to the renderer or Session Controller. The | `api/session-controller/client` | Session objects, catalog, references, source counts, commands, projections, event windows, and Agent Contexts | Navigation, completion reminders, Conversation targets, React, Slots, Workspace | | `api/workspace-controller/client` | Workspace objects, ordering, archive state, commands, and snapshots | React, Session navigation policy, directory UI | | `client/ui-session` | Explicit Session scope, standard sources, `SessionProvider`, and effective pending interactions | Session transport, reference ownership, Conversation assembly, Approval/Question results, unified UI status | -| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders | Pending-interaction registration, Session transport, React | +| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders; Host reading records and their Client copy; main-view reading acknowledgement | Pending-interaction registration, Session transport, React | | `client/ui-workspace` | Workspace hook, browser UI, main-area reference, and cross-Controller navigation policy | Workspace transport, copies of Session data | | `client/ui-conversation` | Conversation core, registries, bindings, shell, input, composer, queue, and View navigation | Session transport, Chat/Trajectory snapshots | | `client/ui-chat` | Chat target, Node definitions, renderers, selection, details, and locale | Session lifecycle, generic View navigation, Trajectory, historical-image cache | diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md index cf3b65492d..6a604e52cb 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md @@ -81,7 +81,7 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把 | `api/session-controller/client` | 会话对象、目录、引用、来源计数、命令、投影、事件窗口与 Agent Context | 导航、完成提醒、Conversation target、React、Slot、Workspace | | `api/workspace-controller/client` | Workspace 对象、顺序、归档、命令和 snapshot | React、Session 导航策略、目录 UI | | `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与有效待处理交互 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果、统一 UI 状态 | -| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒 | 待处理交互登记、会话传输、React | +| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒;宿主阅读记录及其前端副本;主视图阅读确认 | 待处理交互登记、会话传输、React | | `client/ui-workspace` | Workspace 钩子、浏览器 UI、主区域引用与跨控制器导航策略 | Workspace 传输、会话数据副本 | | `client/ui-conversation` | Conversation core、registry、binding、shell、input、composer、queue 和 View 导航 | Session transport、Chat/Trajectory snapshot | | `client/ui-chat` | Chat target、Node definitions、renderer、selection、details 和 locale | Session 生命周期、通用 View 导航、Trajectory、历史图片 cache | diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml index 12ad701c1e..6826d6a497 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml @@ -24,8 +24,8 @@ en: e2de83d10542f93b zh: 3855b38fc8c48ea3 /agent-note-client-session-references-reference-sources-and-ui-status/decision/unified-ui-session-status: - en: 07ea04b9ca50dd8f - zh: e025fcea4c9f0fb9 + en: 45038468e95179f9 + zh: ac8f2f098f5b2427 /agent-note-client-session-references-reference-sources-and-ui-status/decision/explicit-providers-and-consumer-lifetimes: en: 04802baa0147fec1 zh: b86037bf2e4bc936 diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md index ac8eb95cf7..6a7c15ad86 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md @@ -96,22 +96,16 @@ Window-level consumers may inspect source markers. Session business operations s | --- | --- | --- | | `running` | `boolean` or `undefined` | Latest known Session running fact; absence of a baseline is not confirmed idle | | `pendingInteraction` | `SessionPendingInteraction` or `undefined` | Effective domain-owned request, or absence when no request is pending | -| `completionUnread` | `boolean` | UI reminder for an observed stop that has not been acknowledged | +| `completionUnread` | `boolean` | Host reading record carries a manual unread mark or an unacknowledged completed turn | +| `completionFailed` | `boolean` | The Session is unread and its latest completed turn ended with an execution error | Source counts remain authoritative in `SessionListState.byId[id].retainedBy`; UI status reads them for acknowledgement policy without owning another reference registry. Titles, Workspace associations, history, queues, and projection data remain with their existing owners. Pending domains retain `SessionPendingInteractionMap`, request identities, precedence, publication disposers, and teardown delegation in `ui-session`, which publishes each Session's effective request read-only as `ctx.uiSession.pendingInteractions`. The unified status includes the same effective request object; it does not copy requests or create a second pending registry. Workspace status indicators and Conversation composer selection read `useSessionStatus` instead of separate `useSessionPendingInteraction` and `useCompletedSessionIds` hooks. -Completion tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared. The update rules are: +Running tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared, and removing a Session clears its running baseline; pending-request teardown stays with the request's domain. -- An initial idle baseline does not create a completion reminder. -- Observing running clears an earlier reminder and records the running baseline. -- A known running-to-idle transition sets `completionUnread` only when the Session lacks main-view ownership. -- Acquiring main-view ownership clears the reminder; retaining from an unrelated source does not. -- Releasing main-view ownership does not manufacture a reminder for an earlier stop. -- Removing a Session clears its completion reminder and running baseline; pending-request teardown stays with the request's domain. - -The reminder denotes an observed stop, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount. +Completion reminders follow the Host reading records described in [Host-memory Session reading state](../feature/2026-10-23-session-reading-memory.md), which supersedes this note's earlier Client-local reminder rules: running changes and main-view ownership neither set nor clear a reminder, and the visible main view acknowledges a completed turn only after its body arrives. The reminder denotes a completed turn, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount. The Session Controller publishes running and reference-source facts but owns no completion-reminder set, `consumeCompletion` method, or pending-interaction presentation. Reference acquisition does not execute completion-reminder business logic. diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md index 3a4168f4c4..167dbac7b9 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md @@ -96,22 +96,16 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源 | --- | --- | --- | | `running` | `boolean` 或 `undefined` | 最新已知的 Session 运行事实;缺少基线不表示已确认 idle | | `pendingInteraction` | `SessionPendingInteraction` 或 `undefined` | 领域拥有的有效请求;没有待处理请求时缺失 | -| `completionUnread` | `boolean` | 已观察到停止、但尚未确认的 UI 提醒 | +| `completionUnread` | `boolean` | 宿主阅读记录带有手动未读标记或尚未确认的完成轮次 | +| `completionFailed` | `boolean` | Session 未读,且最近完成的轮次以执行错误结束 | 来源计数以 `SessionListState.byId[id].retainedBy` 为准;UI 状态读取它以执行确认策略,不维护另一套引用注册表。标题、Workspace 关联、历史、队列和投影数据保留在各自的既有所有者中。 待处理领域在 `ui-session` 中保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托,`ui-session` 以只读的 `ctx.uiSession.pendingInteractions` 发布每个 Session 的有效请求。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。 -完成跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失。更新规则如下: +运行跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失;移除 Session 时清除其运行基线,待处理请求的清理仍属于请求领域。 -- 初始 idle 基线不产生完成提醒。 -- 观察到 running 时清除旧提醒,并记录运行基线。 -- 从已知 running 变为 idle 时,仅在 Session 没有主视图持有的情况下设置 `completionUnread`。 -- 获得主视图持有时清除提醒;无关来源的 retain 不清除提醒。 -- 释放主视图持有不会为更早的一次停止补造提醒。 -- 移除 Session 时清除其完成提醒与运行基线;待处理请求的清理仍属于请求领域。 - -提醒表示观察到的一次停止,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。 +完成提醒跟随[宿主内存中的会话阅读状态](../feature/2026-10-23-session-reading-memory.zh.md)所述的宿主阅读记录,该记录取代本记录早先的前端本地提醒规则:运行变化和主视图持有都不会设置或清除提醒,可见的主视图只在正文到达后确认完成的轮次。提醒表示完成的一个轮次,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。 Session Controller 发布运行与引用来源事实,但不拥有完成提醒集合、`consumeCompletion` 方法或待处理交互展示。引用获取不执行完成提醒业务逻辑。 diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml new file mode 100644 index 0000000000..b101719d93 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-23-session-reading-memory.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-23-session-reading-memory.md +/agent-note-host-memory-session-reading-state: + en: d0d93ca91b0bfd16 + zh: 55f67f2074612e4d +/agent-note-host-memory-session-reading-state/problem: + en: 61f665a6dc1bc503 + zh: 3421cf192528179e +/agent-note-host-memory-session-reading-state/decision: + en: a15c7c13f167e5ac + zh: 63bcc2ef60c2f344 +/agent-note-host-memory-session-reading-state/decision/package-structure: + en: e22765435a1ab422 + zh: 7ac9fbcea4c15387 +/agent-note-host-memory-session-reading-state/decision/client-dependency-rules: + en: e38746215940a163 + zh: a4e343dac7942aa2 +/agent-note-host-memory-session-reading-state/decision/host-records: + en: ea1b8aa4ed60f04c + zh: 9c979b7b40eacb3e +/agent-note-host-memory-session-reading-state/decision/automatic-acknowledgement: + en: 64f9e14597dbc3d4 + zh: e2d20a5105c9d950 +/agent-note-host-memory-session-reading-state/alternatives-considered: + en: 755d2e5eb626b445 + zh: 898f83b86d2e2209 +/agent-note-host-memory-session-reading-state/consequences: + en: 01f6beaeff1e6c7f + zh: 1fdee75b2c4bf646 diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md new file mode 100644 index 0000000000..52951c5b06 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md @@ -0,0 +1,58 @@ +# Agent Note: Host-memory Session reading state + +Status: implemented + +English | [中文](2026-10-23-session-reading-memory.zh.md) + +## Problem + +Clients connected to the same Host need consistent reading reminders, including completions that end while every Client is offline. Automatic acknowledgements must not clear unseen completions or manual unread marks. Reading activity must not change model history. The reminders appear in the Client Session status table that [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md) owns, so the reading records, their Client follower, and the table that consumes them need one owner whose Client face may follow a Host Remote stream. + +## Decision + +### Package structure + +`@deepseek-ai/dsh-client-ui-session-status` owns the feature on both faces, following the Host-and-Client package precedent of ui-trajectory: + +| Face | Service | Responsibility | +|---|---|---| +| Host (`.`) | `ctx.sessionStatus` (`SessionStatusService`) | Keeps one reading record per Session in an in-memory Map; the `sessionStatus` Remote namespace serves `mark` and `follow`; failures use `session-status/not-found` and `session-status/unavailable` | +| Client (`./client`) | `ctx.uiSession.sessionStatus` (service name `uiSession.sessionStatus`) | Follows the Host reading stream, builds the status table with `completionUnread` and `completionFailed`, exposes `mark` and `readingReady`, and acknowledges main-view reading | + +The Client copy of the reading records is a package-internal module: it exports no value or type and provides no Client service of its own, so consumers such as ui-workspace and ui-conversation depend only on `ctx.uiSession.sessionStatus` and the exported status types. The Web bundle's single `ui-session-status` row loads both faces, api/remotes mounts the package's `/remote` descriptor, and the Web client lists the package among its required boot entries. ui-session, pending-interaction registration, and `ctx.uiSession.pendingInteractions` stay unchanged. + +### Client dependency rules + +Following the Host stream needs the Gateway's `RemoteSnapshotStream` at runtime. `verify-client-packages` lets a `packages/client` feature package request rows under `packages/api/` through `dsh.client.external`, while still rejecting requests for another feature plugin's row; the Remote API group is infrastructure, not a feature plugin. The package requests only `@deepseek-ai/dsh-api-gateway/client`. The stream runs only while `ctx.remoteAccess` allows `sessionStatus/follow`; that endpoint is owner-only for LiveShare, so a viewer page opens no stream, keeps `readingReady` false, and reports no synchronization failure. + +`RemoteStream` decides reconnection by the stable error code `gateway/carrier-lost` rather than by `instanceof RemoteStreamCarrierError`. The class carries that code, so existing callers keep their behavior, and the package's `ended` callback returns a plain `Error` with the code, typed by the exported `RemoteStreamCarrierFailure` type, without importing the class. The code is produced only inside the Client process: a `RemoteError` returned by the Host terminates the stream even when it carries the same code. + +### Host records + +The Host service owns one in-memory record per Session and derives the latest ended turn and its failure flag from `turn/end` events itself. Mutations update the Map synchronously. Read actions carry the Client-observed completed turn; the Host advances the read position monotonically and never beyond its known completion. Automatic acknowledgements leave manual unread unchanged; explicit marks replace it in Host processing order. Only the ordered baseline and whole-record change stream updates the Client, so mutation replies need no record or revision. + +Cold Session marks read metadata without opening history. A Session without a record reads as read, so history neither needs a startup scan nor distinguishes a cold Session from a live zero-turn one. Shutdown closes followers and clears records. A pending metadata lookup rejects its mark after disposal rather than delaying teardown for an in-memory write. + +### Automatic acknowledgement + +Only a visible, focused main view acknowledges reading, after a rendering frame and evidence that the body reached the completed turn. Window focus advances only the natural read position. A main-view switch to a different Session, including the first selection after a page load, clears that Session's existing manual reminder once its body arrives; the check waits for a ready reading baseline. Window focus, a replaced binding for the same Session, and activity in the open Session do not clear it, so a mark made in the open Session stays until the view leaves and returns. Later automatic acknowledgements preserve manual marks, including those received while the body loads. Keeping the rule inside the acknowledgement plugin avoids a cross-package reading event and changes to the Conversation body. While the visible, focused main view retains an open Session, the status table does not show that Session's unacknowledged completion, so its row does not flash unread before the acknowledgement round trip; manual marks stay visible, and the reminder returns when the window loses focus or the view moves away first. Archived rows read as read and offer no reading mark. + +## Alternatives considered + +- **ui-session reads reading state:** the base UI package would depend on a feature package, and every UI above it could not start without the reading plugin. +- **A separate reading package with a Client service:** consumers would see a second reading API beside `ctx.uiSession.sessionStatus`, and the status table would depend on another package's service only to fold its records. +- **An api-group reading package beside the client table:** splits one feature across two packages whose Host contract, Client follower, and table evolve together; the relaxed external rule lets the client package follow the stream itself. +- **Reimplementing the snapshot protocol over `ctx.remote.$stream`:** duplicates Gateway-owned baseline and reconnection logic in a feature package. +- **Importing `RemoteStreamCarrierError` into the client package:** a feature package would depend on a Gateway class identity for one retry decision; a stable code states the decision without class identity across separately bundled modules. +- **Host face in the shared base bundle:** profiles without a Web Client would run a reading service no Client reads, and the Host face would load from a different bundle than its Client face. +- **Frontend memory or local storage:** cannot provide one authority for browsers and Desktop clients, or collect completions while all frontends are offline. +- **Persistent Host records:** preserve reminders across Host restarts but require a separate lifecycle design for Session checkpoints, domain ownership, backend shutdown, and failed writes. This implementation deliberately limits ownership to memory; persistence is a separate change. +- **Reading events in the Session log:** mix viewer intent with model history and require loading cold histories for metadata-only actions. +- **Revision-based conditional writes:** prevent delayed explicit actions from replacing newer manual intent, but require conflict responses, revision bookkeeping and unary-result reconciliation. Session reminders accept Host processing order instead. A read-position cursor still prevents unseen completions from being acknowledged. +- **Message ID cursor:** identifies a message but does not order completed turns, including failures without a new assistant message. The existing completed-turn number directly represents this feature's unit of progress. + +## Consequences + +Browser refresh and temporary disconnect preserve reminders while this Host service runs. Host restart or plugin reload resets every reading record and treats existing history as read; a turn that failed before the restart leaves no outcome, so marking that Session unread shows the ordinary reminder. Profiles without the Web bundle run no reading service. There are no read-state files, storage-domain dependencies, checkpoint writes, or cross-process synchronization guarantees. Reminders remain for detached Sessions until the service stops; reclaiming records requires a Session deletion lifecycle. + +Concurrent explicit actions have last-processed semantics; an entry acknowledgement can clear another manual mark that arrives before it is processed. Verification covers two followers, monotonic read positions and manual-mark preservation during automatic acknowledgements, a first completion after manual marks, access-driven rebaselines, shutdown with a pending metadata lookup, service reload, independence from Session flush, and the failure flag of a completing turn. Client tests cover the reading stream's baseline replacement and terminal failure, delayed body delivery, manual marks during loading, and manual-reminder clearing on main-view switches but not on window focus or a replaced binding. Gateway tests cover reconnection for a plain error carrying the carrier code and termination without it. Persistent restart recovery, crash consistency, storage-provider ordering, and cross-process writers require separate validation before persistence is enabled. The main-view retention signal does not distinguish every settings or auxiliary panel; that visibility refinement remains part of the notification work. diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md new file mode 100644 index 0000000000..e47c4435f4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md @@ -0,0 +1,58 @@ +# Agent Note: 宿主内存中的会话阅读状态 + +Status: implemented + +[English](2026-10-23-session-reading-memory.md) | 中文 + +## 问题 + +连接同一宿主的前端需要一致的阅读提醒,包括所有前端都离线时结束的轮次。自动阅读确认不能清除尚未看到的完成提醒或手动未读标记。阅读行为不能改变模型历史。这些提醒显示在 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md) 拥有的前端会话状态表中,因此阅读记录、它的前端订阅方和使用它的状态表需要同一个归属方,而且其前端面能够订阅宿主 Remote 流。 + +## 决策 + +### 包结构 + +`@deepseek-ai/dsh-client-ui-session-status` 在两个面上拥有该功能,沿用 ui-trajectory 同时提供宿主面和前端面的先例: + +| 面 | 服务 | 职责 | +|---|---|---| +| 宿主(`.`) | `ctx.sessionStatus`(`SessionStatusService`) | 在内存 Map 中为每个会话保存一条阅读记录;Remote 命名空间 `sessionStatus` 提供 `mark` 和 `follow`;失败使用 `session-status/not-found` 和 `session-status/unavailable` | +| 前端(`./client`) | `ctx.uiSession.sessionStatus`(服务名 `uiSession.sessionStatus`) | 订阅宿主阅读流,构建含 `completionUnread` 和 `completionFailed` 的状态表,提供 `mark` 和 `readingReady`,并确认主视图已读 | + +前端的阅读记录副本是包内部模块:它不导出任何值或类型,也不提供自己的前端服务,因此 ui-workspace、ui-conversation 等使用方只依赖 `ctx.uiSession.sessionStatus` 和导出的状态类型。Web bundle 中唯一的 `ui-session-status` 行加载两个面,api/remotes 挂载本包的 `/remote` 描述,Web 前端把本包列为启动必需入口。ui-session、待交互登记和 `ctx.uiSession.pendingInteractions` 保持不变。 + +### 前端依赖规则 + +订阅宿主流在运行时需要 Gateway 的 `RemoteSnapshotStream`。`verify-client-packages` 允许 `packages/client` 下的功能包通过 `dsh.client.external` 请求 `packages/api/` 下的行,但仍拒绝请求另一个功能插件的行;Remote API 组是基础设施,不是功能插件。本包只请求 `@deepseek-ai/dsh-api-gateway/client`。只有 `ctx.remoteAccess` 允许 `sessionStatus/follow` 时才运行该流;该端点在 LiveShare 中仅限所有者,因此查看者页面不打开该流,`readingReady` 保持 false,也不报告同步失败。 + +`RemoteStream` 按稳定的 error code `gateway/carrier-lost` 判断是否重连,而不是按 `instanceof RemoteStreamCarrierError`。该 class 自带这个 code,现有调用方行为不变;本包的 `ended` 回调返回带该 code 的普通 `Error`,用导出的 `RemoteStreamCarrierFailure` 类型描述,而不导入该 class。该 code 只在前端进程内产生:宿主返回的 `RemoteError` 即使带有相同 code 也会终止流。 + +### 宿主记录 + +宿主服务在内存中为每个会话保存一条记录,自己从 `turn/end` 事件取得最近结束的轮次及其失败标记。修改同步更新 Map。已读请求携带前端已看到的完成轮次;宿主单调推进阅读位置,且不越过已知完成位置。自动确认保留手动未读,主动标记按宿主处理顺序替换它。前端只通过有序基线和整条记录的更新流取得状态,修改回复不需要记录或版本。 + +对冷会话的标记只读取元信息,不打开历史。没有记录的会话按已读处理,因此历史既不需要启动扫描,也不需要区分冷会话和零轮次的活跃会话。关闭时结束订阅并清空记录;尚在等待元信息的标记请求会在查询返回后被拒绝,不会为了内存写入延迟卸载。 + +### 自动确认 + +只有可见且聚焦的主视图会确认阅读,并等待一次渲染帧及正文已到达完成轮次的证据。窗口聚焦只推进自然已读位置。主视图切换到另一个会话(包括页面加载后的首次选中)时,会在正文到达后清除该会话已有的手动提醒;检查会等待阅读基线就绪。窗口聚焦、同一会话更换 binding 以及在已打开会话中的操作都不会清除它,因此在已打开会话中做的标记会保留到视图切走再切回。后续自动确认保留手动标记,包括正文加载期间收到的标记。把规则留在确认插件内部,可以避免跨包的阅读事件,也不需要修改 Conversation 正文。可见且聚焦的主视图持有某个已打开的会话时,状态表不显示该会话尚未确认的完成轮次,避免在确认往返完成前闪现未读;手动标记照常显示,窗口失焦或视图先行切走时提醒会重新出现。归档行按已读处理,不提供阅读标记。 + +## 考虑过的替代方案 + +- **ui-session 读取阅读状态:** 基础 UI 包会依赖功能包,阅读插件缺席时其上的所有界面都无法启动。 +- **单独的阅读包并提供前端服务:** 使用方会在 `ctx.uiSession.sessionStatus` 之外看到第二套阅读 API,状态表也只为汇总记录而依赖另一个包的服务。 +- **在前端状态表旁另建 api 组阅读包:** 把一个功能拆到两个包中,而宿主接口、前端订阅方和状态表同步演进;放宽 external 规则后,前端包可以自己订阅该流。 +- **在 `ctx.remote.$stream` 之上重写快照协议:** 会在功能包中复制 Gateway 负责的基线与重连逻辑。 +- **在前端包中导入 `RemoteStreamCarrierError`:** 功能包会为一次重试判断依赖 Gateway 的 class 身份;稳定的 code 能表达这一判断,而不依赖跨独立打包模块的 class 身份。 +- **宿主面放在共享基础 bundle:** 没有 Web 前端的 profile 会运行无人读取的阅读服务,宿主面也会与前端面从不同的 bundle 加载。 +- **前端内存或本地存储:** 无法为浏览器和 Desktop 前端提供共同的权威状态,也无法收集所有前端离线期间的完成提醒。 +- **宿主持久化记录:** 能够让提醒跨宿主重启保留,但需要单独设计会话检查点、存储域归属、后端关闭及写入失败的生命周期。本实现将状态限制在内存,持久化另行实现。 +- **在会话日志中记录阅读事件:** 会把使用者意图混入模型历史,并使只需元信息的操作也要加载冷会话历史。 +- **按版本条件写入:** 可防止延迟的主动操作覆盖较新的手动意图,但需要冲突响应、版本维护和请求响应的状态合并。会话提醒接受宿主处理顺序,仍保留阅读位置以防误读新完成内容。 +- **消息 ID 游标:** 只能定位消息,不能直接排序已完成轮次,也不能覆盖未产生新助手消息的失败。已有完成轮次直接对应本功能的进度单位。 + +## 结果 + +宿主服务运行期间,刷新浏览器或临时断线会保留提醒。宿主重启或插件重载会重置全部阅读记录,并把已有历史视为已读;重启前失败的轮次不留下结果,因此把该会话标为未读时显示普通提醒。不含 Web bundle 的 profile 不运行阅读服务。没有阅读状态文件、存储域依赖、检查点写入或跨进程同步保证。会话从内存卸载后,其提醒保留到服务停止;回收记录需要会话删除生命周期。 + +并发主动操作以宿主最后处理的操作为准;进入视图的确认可能清除处理前到达的另一条手动标记。验证覆盖双订阅、单调阅读位置与自动确认保留手动标记、手动标记后的首次完成、访问权限变化后的新基线、元信息查询期间关闭、服务重载、不依赖会话刷盘,以及结束轮次的失败标记。前端测试覆盖阅读流的基线替换与终态失败、正文延迟、加载期间的手动标记,以及主视图切换时清除手动提醒、窗口聚焦或更换 binding 时不清除。Gateway 测试覆盖带 carrier code 的普通错误会重连、不带 code 时终止。启用持久化前,需单独验证重启恢复、崩溃一致性、存储提供方关闭顺序和跨进程写入。当前主视图保留信号不能区分所有设置或辅助面板;该可见性细化仍属于通知工作的范围。 diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 72a389f9c8..21495dc936 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -196,7 +196,7 @@ it('keeps ordered legacy Session menu rows before Archive and removes them with await row.hover() await trigger.click() await menu.waitFor() - const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Copy Session ID', 'Archive session'] + const remainingNames = ['Pin session', 'Rename', 'Mark as unread', 'Fork session', 'Copy Session ID', 'Archive session'] const remainingItems = menu.getByRole('menuitem') expect(await remainingItems.count()).toBe(remainingNames.length) for (const [index, name] of remainingNames.entries()) { diff --git a/apps/web/tests/context-menus.e2e.ts b/apps/web/tests/context-menus.e2e.ts index 79fe82f2f1..b5035f449a 100644 --- a/apps/web/tests/context-menus.e2e.ts +++ b/apps/web/tests/context-menus.e2e.ts @@ -75,7 +75,9 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s', const menu = page.getByRole('menu') await menu.getByRole('menuitem', { name: /Copy.*[Ii][Dd]/ }).waitFor() const names = await menuLabels(menu) - expect(names.slice(0, 4)).toEqual(['Pin session', 'Rename', 'Fork session', 'Copy Session ID']) + expect(names.slice(0, 5)).toEqual([ + 'Pin session', 'Rename', 'Mark as unread', 'Fork session', 'Copy Session ID', + ]) expect(names).not.toContain('Open in') expect(names.at(-1)).toBe('Archive session') expect(await menu.getByRole('menuitem').evaluateAll(rows => rows.every(row => row.querySelector('svg[data-icon]')))).toBe(true) diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md index 93f241e0fc..19356fc99e 100644 --- a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/context-menus/session.txt b/apps/web/tests/expected/context-menus/session.txt index ac477e2304..7036ac96e9 100644 --- a/apps/web/tests/expected/context-menus/session.txt +++ b/apps/web/tests/expected/context-menus/session.txt @@ -1,5 +1,6 @@ Pin session Rename +Mark as unread Fork session Copy Session ID Archive session diff --git a/apps/web/tests/expected/menu-material/session-menu.expected.md b/apps/web/tests/expected/menu-material/session-menu.expected.md index c7c535b9e4..0bfe2df5d3 100644 --- a/apps/web/tests/expected/menu-material/session-menu.expected.md +++ b/apps/web/tests/expected/menu-material/session-menu.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/session-reading/failed-unread.expected.md b/apps/web/tests/expected/session-reading/failed-unread.expected.md new file mode 100644 index 0000000000..7422403748 --- /dev/null +++ b/apps/web/tests/expected/session-reading/failed-unread.expected.md @@ -0,0 +1 @@ +- treeitem "Unread Untitled {{age}}" diff --git a/apps/web/tests/expected/session-reading/unread-menu.expected.md b/apps/web/tests/expected/session-reading/unread-menu.expected.md new file mode 100644 index 0000000000..14b42ba2d1 --- /dev/null +++ b/apps/web/tests/expected/session-reading/unread-menu.expected.md @@ -0,0 +1,11 @@ +- menu: + - menuitem "Pin session" + - menuitem "Rename" + - menuitem "Mark as read" + - menuitem "Fork session" + - separator + - menuitem "Copy Session ID" + - separator + - menuitem "Archive session" +Row state: done +Title font weight: 400 diff --git a/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md b/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md index 180988c7c7..68be7e2bb6 100644 --- a/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md @@ -54,6 +54,9 @@ - listitem: - button "Edit shortcut for Close current page or window" - text: Close current page or window ⌥ ⌘ W + - listitem: + - button "Edit shortcut for Toggle read/unread" + - text: Toggle read/unread ⇧ ⌘ U - region "Message input": - heading "Message input" [level=3] - list: diff --git a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md index f3836b2d55..7c3e33a81d 100644 --- a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/shortcuts/en-US.expected.md b/apps/web/tests/expected/shortcuts/en-US.expected.md index 9cbb7a0562..2360979af0 100644 --- a/apps/web/tests/expected/shortcuts/en-US.expected.md +++ b/apps/web/tests/expected/shortcuts/en-US.expected.md @@ -54,6 +54,9 @@ - listitem: - button "Edit shortcut for Close current page or window" - text: Close current page or window Ctrl + Alt + W + - listitem: + - button "Edit shortcut for Toggle read/unread" + - text: Toggle read/unread Ctrl + Shift + U - region "Message input": - heading "Message input" [level=3] - list: diff --git a/apps/web/tests/expected/shortcuts/zh-CN.expected.md b/apps/web/tests/expected/shortcuts/zh-CN.expected.md index 157d94b120..149ac1ff0b 100644 --- a/apps/web/tests/expected/shortcuts/zh-CN.expected.md +++ b/apps/web/tests/expected/shortcuts/zh-CN.expected.md @@ -54,6 +54,9 @@ - listitem: - button "修改关闭当前页面/窗口快捷键" - text: 关闭当前页面/窗口 ⌥ ⌘ W + - listitem: + - button "修改切换已读/未读快捷键" + - text: 切换已读/未读 ⇧ ⌘ U - region "消息输入": - heading "消息输入" [level=3] - list: diff --git a/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md b/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md index e17e9cdfa1..bf3bfab624 100644 --- a/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md +++ b/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md @@ -1,4 +1,4 @@ - tree "Sessions": - treeitem "workspace" [expanded] - treeitem "New Session" [selected] - - treeitem "1 subagent running Delegate a background job. now" + - treeitem "1 subagent running Unread Delegate a background job. now" diff --git a/apps/web/tests/github-ready-review.e2e.ts b/apps/web/tests/github-ready-review.e2e.ts index 9c9ae295e9..96bfa66fe8 100644 --- a/apps/web/tests/github-ready-review.e2e.ts +++ b/apps/web/tests/github-ready-review.e2e.ts @@ -195,8 +195,11 @@ describe.skipIf(MODE === 'record')('web e2e: GitHub ready-for-review', () => { const workspaceRow = page.locator('[role="treeitem"]').first() if (await workspaceRow.getAttribute('aria-expanded') !== 'true') await workspaceRow.click() + await page.bringToFront() await page.getByText(TITLE, { exact: true }).click() await page.getByText(REPLY, { exact: true }).waitFor({ state: 'visible', timeout: 30_000 }) + const reviewRow = page.locator('[role="treeitem"]').filter({ has: page.getByText(TITLE, { exact: true }) }) + await expect.poll(() => reviewRow.getByText('Unread', { exact: true }).count()).toBe(0) const tree = await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd) const conversation = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd) await compareOrRefreshGolden(EXPECTED, `${tree}\n\n---\n\n${conversation}`, MODE) diff --git a/apps/web/tests/plan-review.e2e.ts b/apps/web/tests/plan-review.e2e.ts index e59c1239ba..d2a46e5c8a 100644 --- a/apps/web/tests/plan-review.e2e.ts +++ b/apps/web/tests/plan-review.e2e.ts @@ -149,7 +149,7 @@ describe('web e2e: plan review takeover round trip', () => { await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) // Card gone; regular input restored. expect(await page.locator('[data-plan-review-key]').count()).toBe(0) - expect(await selectedRow.locator('[data-state="warning"]').count()).toBe(0) + await expect.poll(() => selectedRow.getByText('Plan awaiting review', { exact: true }).count()).toBe(0) await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true) // Completed plans join the final artifacts after the Turn's closing reply. await planCard.waitFor({ state: 'visible' }) @@ -245,7 +245,7 @@ describe('web e2e: plan review takeover round trip', () => { }) const outcome = asked.then(value => value, (error: unknown) => ({ error })) try { - const row = page.locator('[role="treeitem"]').filter({ has: page.locator('[data-state="warning"]') }).first() + const row = page.locator(`[data-row-key="session:${reviewedSession}"]`) await row.waitFor({ timeout: 10_000 }) await row.click() const card = page.locator('[data-plan-review-key]') @@ -325,7 +325,7 @@ describe.skipIf(MODE === 'record')('web e2e: pending plan review across Sidebar }) const outcome = asked.then(value => value, (error: unknown) => ({ error })) try { - await row(session).locator('[data-state="warning"]').waitFor({ timeout: 10_000 }) + await row(session).getByText('Plan awaiting review', { exact: true }).waitFor({ timeout: 10_000 }) await scenario() } finally { controller.abort() diff --git a/apps/web/tests/question-composer.e2e.ts b/apps/web/tests/question-composer.e2e.ts index afe0f3cb39..8403ce534d 100644 --- a/apps/web/tests/question-composer.e2e.ts +++ b/apps/web/tests/question-composer.e2e.ts @@ -545,7 +545,7 @@ describe('web e2e: resident question composer round trip', () => { await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) // Composer gone; regular input restored. expect(await page.locator('[data-question-key]').count()).toBe(0) - expect(await selectedRow.locator('[data-state="warning"]').count()).toBe(0) + await expect.poll(() => selectedRow.getByText('Waiting for answer', { exact: true }).count()).toBe(0) await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true) const reply = page.locator('[data-question-reply]') await reply.waitFor({ state: 'visible', timeout: 15_000 }) diff --git a/apps/web/tests/session-reading.e2e.ts b/apps/web/tests/session-reading.e2e.ts new file mode 100644 index 0000000000..1edf0c8868 --- /dev/null +++ b/apps/web/tests/session-reading.e2e.ts @@ -0,0 +1,179 @@ +/** Reading marks through the shipped Web profile, real Session history, and two Clients. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, expect, it, onTestFailed } from 'vitest' +import { + acknowledgeReloadConnectionLoss, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) +const EXPECTED = fileURLToPath(new URL('./expected/session-reading/unread-menu.expected.md', import.meta.url)) +const FAILED_EXPECTED = fileURLToPath(new URL('./expected/session-reading/failed-unread.expected.md', import.meta.url)) +let scaffold: WebScaffold +let browser: Browser +let first: Page +let second: Page +let sessionId: string +let failedSessionId: string + +beforeAll(async () => { + scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + const history = await readFile(SEED, 'utf8') + sessionId = await seedSession(scaffold, history, 'session-reading-web') + const failedHistory = `${history.trimEnd()}\n${JSON.stringify({ type: 'turn/start', data: { turn: 2 } })}\n${JSON.stringify({ + type: 'turn/end', data: { turn: 2, reason: { kind: 'error', error: { code: 'UNKNOWN', message: 'Request failed' } } }, + })}\n` + failedSessionId = await seedSession(scaffold, failedHistory, 'session-reading-failed') + browser = await chromium.launch() + first = await newEnglishPage(browser) + second = await newEnglishPage(browser) + for (const [page, platform] of [[first, 'MacIntel'], [second, 'Win32']] as const) { + await page.addInitScript((value) => { Object.defineProperty(navigator, 'platform', { value }) }, platform) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const group = page.getByText('Ungrouped', { exact: true }).locator('xpath=ancestor::*[@role="treeitem"][1]') + await group.waitFor({ timeout: 30_000 }) + if (await group.getAttribute('aria-expanded') !== 'true') await group.click() + await page.locator(`[data-row-key="session:${sessionId}"]`).waitFor({ timeout: 10_000 }) + } +}, 120_000) + +afterAll(async () => { + await browser?.close() + await scaffold?.close() +}) + +async function mark(page: Page, name: 'Mark as read' | 'Mark as unread', id = sessionId): Promise { + await page.bringToFront() + const row = page.locator(`[data-row-key="session:${id}"]`) + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + await page.getByRole('menuitem', { name, exact: true }).click() +} + +async function unread(page: Page): Promise { + return page.locator(`[data-row-key="session:${sessionId}"]`).getByText('Unread', { exact: true }).count() +} + +it('synchronizes manual marks, retains them across reload, and acknowledges only on a new view entry', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading')) + const left = watchConsole(first) + const right = watchConsole(second) + const row = first.locator(`[data-row-key="session:${sessionId}"]`) + const title = row.locator(':scope > span').nth(1) + const initialWeight = await title.evaluate(element => getComputedStyle(element).fontWeight) + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + expect(await row.locator('[data-state="done"]').count()).toBe(1) + expect(await title.evaluate(element => getComputedStyle(element).fontWeight)).toBe(initialWeight) + expect(await first.getByRole('alert').count()).toBe(0) + + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + expect(await first.getByRole('menuitem', { name: 'Mark as read', exact: true }).getAttribute('aria-keyshortcuts')).toBe('Shift+Meta+U') + const menuSnapshot = await captureStableAria(first, '[role="menu"]', scaffold.workspaceCwd) + const rowState = await row.locator('[data-state]').getAttribute('data-state') + const titleWeight = await title.evaluate(element => getComputedStyle(element).fontWeight) + await compareOrRefreshGolden(EXPECTED, `${menuSnapshot}\nRow state: ${rowState}\nTitle font weight: ${titleWeight}`, webSnapshotMode()) + await first.keyboard.press('Escape') + + const warningStart = right.warnings.length + await second.reload({ waitUntil: 'load' }) + await expect.poll(() => unread(second)).toBe(1) + acknowledgeReloadConnectionLoss(right, warningStart) + + await first.bringToFront() + await row.click() + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + await first.bringToFront() + await first.keyboard.press('Meta+Shift+U') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await first.keyboard.press('Meta+Shift+U') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + await second.bringToFront() + await second.locator(`[data-row-key="session:${sessionId}"]`).click() + await second.keyboard.press('Control+Shift+U') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await second.keyboard.press('Control+Shift+U') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + expect(await first.getByRole('alert').count()).toBe(0) + expect(await second.getByRole('alert').count()).toBe(0) + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await mark(second, 'Mark as read') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + expect(left.pageErrors).toEqual([]) + expect(right.pageErrors).toEqual([]) + expect(left.warnings).toEqual([]) + expect(right.warnings).toEqual([]) +}) + +it('shares a manual reminder on restored history without claiming its outcome', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading-restored')) + const row = (page: Page) => page.locator(`[data-row-key="session:${failedSessionId}"]`) + const errors = (page: Page) => row(page).locator('[data-state="error"]').count() + const done = (page: Page) => row(page).locator('[data-state="done"]').count() + await first.bringToFront() + await mark(first, 'Mark as unread', failedSessionId) + await expect.poll(() => done(first)).toBe(1) + await expect.poll(() => done(second)).toBe(1) + expect(await errors(first)).toBe(0) + expect(await row(first).getByText('Unread', { exact: true }).count()).toBe(1) + await compareOrRefreshGolden(FAILED_EXPECTED, await captureStableAria( + first, `[data-row-key="session:${failedSessionId}"]`, scaffold.workspaceCwd, { normalizeAge: true }, + ), webSnapshotMode()) + const consoleState = watchConsole(second) + const warningStart = consoleState.warnings.length + await second.reload({ waitUntil: 'load' }) + await expect.poll(() => done(second)).toBe(1) + acknowledgeReloadConnectionLoss(consoleState, warningStart) + await mark(first, 'Mark as read', failedSessionId) + await expect.poll(() => done(first)).toBe(0) + await expect.poll(() => done(second)).toBe(0) + await mark(first, 'Mark as unread', failedSessionId) + await expect.poll(() => done(second)).toBe(1) + expect(consoleState.pageErrors).toEqual([]) + expect(consoleState.warnings).toEqual([]) +}) + +it('preserves manual unread on window focus and clears it after the main view leaves and returns', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading-entry')) + const row = first.locator(`[data-row-key="session:${sessionId}"]`) + const content = (id: string) => first.locator(`[data-conversation-content][data-conversation-session="${id}"]`) + await first.bringToFront() + await row.click() + await content(sessionId).waitFor() + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + + await second.bringToFront() + await first.bringToFront() + await expect.poll(() => first.evaluate(() => document.hasFocus())).toBe(true) + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + await first.getByRole('menuitem', { name: 'Mark as read', exact: true }).waitFor() + expect(await unread(first)).toBe(1) + expect(await unread(second)).toBe(1) + await first.keyboard.press('Escape') + + await first.locator(`[data-row-key="session:${failedSessionId}"]`).click() + await content(failedSessionId).waitFor() + expect(await unread(first)).toBe(1) + await row.click() + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) +}) diff --git a/apps/web/tests/sidebar-subagent-activity.e2e.ts b/apps/web/tests/sidebar-subagent-activity.e2e.ts index c4a923f1a4..bbe961d7bc 100644 --- a/apps/web/tests/sidebar-subagent-activity.e2e.ts +++ b/apps/web/tests/sidebar-subagent-activity.e2e.ts @@ -136,7 +136,7 @@ describe('web e2e: sidebar subagent activity', () => { it('pins a running descendant on its visible idle owner row', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-subagent-activity')) const sidebar = page.getByRole('tree', { name: 'Sessions' }) - const ownerRow = sidebar.getByRole('treeitem', { name: /1 subagent running Delegate a background job/ }) + const ownerRow = sidebar.getByRole('treeitem', { name: /1 subagent running.*Delegate a background job/ }) await ownerRow.waitFor({ timeout: 10_000 }) expect(parentHandle.agent.status).toBe('idle') await compareOrRefreshGolden( diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 491b459b0d..a652e166b1 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -32,6 +32,7 @@ "tests/additional-locales.e2e.ts", "tests/rich-text-quotes.e2e.ts", "tests/hover-input.e2e.ts", + "tests/session-reading.e2e.ts", "tests/collapse-timing.e2e.ts", "tests/notice-wake-tail.e2e.ts", "tests/fold-blank-matrix.e2e.ts", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index a226a4be68..a7c01f3ef1 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 9f66fbb344cf1074 - zh: 7f985c73b1e6a34e + en: 78778294644e7b42 + zh: 2985cca0ffc69256 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index ee9d7bb82c..943631f1b0 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -105,6 +105,8 @@ flowchart LR pkg_message_feedback["message-feedback"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] svc_speechController["ctx.speechController
Experimental transcription Remote"] + pkg_client_ui_session_status["client-ui-session-status"] + svc_sessionStatus["ctx.sessionStatus
Host Session reading records"] svc_sessionController["ctx.sessionController
Host Session Remote controller"] svc_sessionFileReferences["ctx.sessionFileReferences
Session-addressed file-reference Remote adapter"] svc_sessionSkillCatalog["ctx.sessionSkillCatalog
Session-addressed skill Remote adapter"] @@ -346,6 +348,7 @@ flowchart LR pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe + pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -576,6 +579,7 @@ flowchart LR svc_sessionProjections --> pkg_tool_todo svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query + svc_sessionStatus --> pkg_client_ui_session_status svc_sessions --> pkg_agent svc_sessions --> pkg_agent_loop svc_sessions --> pkg_message_feedback @@ -684,6 +688,7 @@ flowchart LR | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent`](../packages/subagent/subagent), [`message-feedback`](../packages/feedback/message-feedback) | - | Owns append-only Session instances and emits the durable session event feed. | | `ctx.speechController` | `core` | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | - | - | Validates bounded browser audio before provider dispatch. | +| `ctx.sessionStatus` | `core` | [`client-ui-session-status`](../packages/client/ui-session-status) | - | [`client-ui-session-status`](../packages/client/ui-session-status) | - | Stores owner reading acknowledgements and manual unread marks outside Session history; its Client half follows committed changes over Remote, acknowledges loaded completions, and serves the Session status table. | | `ctx.sessionController` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Owns Session commands, cold reads, durable-event following, live control state, model catalogs, workspace opening, and Agent activation policy. | | `ctx.sessionFileReferences` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Delegates file-reference discovery through the Session Controller's established Agent lookup policy. | | `ctx.sessionSkillCatalog` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Lists the Session composition's user-invocable skills without activating a cold Agent. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index f09e02313c..3f33e41e82 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -107,6 +107,8 @@ flowchart LR pkg_message_feedback["message-feedback"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] svc_speechController["ctx.speechController
Experimental transcription Remote"] + pkg_client_ui_session_status["client-ui-session-status"] + svc_sessionStatus["ctx.sessionStatus
Host Session reading records"] svc_sessionController["ctx.sessionController
Host Session Remote controller"] svc_sessionFileReferences["ctx.sessionFileReferences
Session-addressed file-reference Remote adapter"] svc_sessionSkillCatalog["ctx.sessionSkillCatalog
Session-addressed skill Remote adapter"] @@ -348,6 +350,7 @@ flowchart LR pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe + pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -578,6 +581,7 @@ flowchart LR svc_sessionProjections --> pkg_tool_todo svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query + svc_sessionStatus --> pkg_client_ui_session_status svc_sessions --> pkg_agent svc_sessions --> pkg_agent_loop svc_sessions --> pkg_message_feedback @@ -686,6 +690,7 @@ flowchart LR | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 在摘要压缩前,通过可回放的单节点表层替换来改写过大的当前工具结果。 | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent`](../packages/subagent/subagent), [`message-feedback`](../packages/feedback/message-feedback) | - | 拥有仅追加的 Session 实例,并发出持久的会话事件流。 | | `ctx.speechController` | `core` | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | - | - | 在 Provider 调用前校验受限的浏览器音频。 | +| `ctx.sessionStatus` | `core` | [`client-ui-session-status`](../packages/client/ui-session-status) | - | [`client-ui-session-status`](../packages/client/ui-session-status) | - | 在会话历史之外保存使用者的阅读确认和手动未读标记;其前端部分通过 Remote 订阅已保存的更新、确认已加载的完成内容,并提供会话状态表。 | | `ctx.sessionController` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 负责 Session 命令、冷读取、持久事件跟随、实时控制状态、模型目录、workspace 打开与 Agent 激活策略。 | | `ctx.sessionFileReferences` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 通过 Session Controller 的既有 Agent lookup 策略委托文件引用发现。 | | `ctx.sessionSkillCatalog` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 在不激活冷 Agent 的前提下列出 Session 组合中允许用户调用的 skill。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 0125a08ad0..a435e9ecb1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -5089,7 +5089,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-session-status` | — | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5e08abfb15..0fe59c8fad 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -5091,7 +5091,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-session-status` | — | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 95208e20dd..1e32371657 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -74,7 +74,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 2d44561b3f..675cd96348 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -76,7 +76,7 @@ | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/subsystems/web-client.i18n.yaml b/docs/subsystems/web-client.i18n.yaml index 4ff473259e..47748543cf 100644 --- a/docs/subsystems/web-client.i18n.yaml +++ b/docs/subsystems/web-client.i18n.yaml @@ -24,14 +24,26 @@ en: c063711f8247c240 zh: 5e54758bbaf1670c /web-client-architecture/conversation-and-presentation: - en: f37ba948a8838fb0 - zh: df19542d87860221 + en: 1283921eb19b9be3 + zh: bc42b48592d50f3a /web-client-architecture/data-paths: en: a254278432416473 zh: 567c2d3c6a20b304 /web-client-architecture/reconnection: en: 478f461e261b1ca5 zh: 626791d04656faee +/web-client-architecture/reading-reminders: + en: 59427b3b5d8d633c + zh: 864e0ea121534aa3 +/web-client-architecture/reading-reminders/sessionreadstate: + en: 62e6bfae05af614a + zh: cbd33ee7b57ac723 +/web-client-architecture/reading-reminders/sessionreadaction: + en: 7ed7e42b233ee2c0 + zh: fd4e5b67f3358059 +/web-client-architecture/reading-reminders/sessionreadframe: + en: 993e0b409439b15c + zh: f7785bea2e8f5b00 /web-client-architecture/package-boundaries: - en: 3e64e8c28f0c4cb1 - zh: 47aa81c2ace5ba89 + en: 085622c76f4d5b06 + zh: 12ef92771b4d9a4a diff --git a/docs/subsystems/web-client.md b/docs/subsystems/web-client.md index fbdaecf3d5..f9c248b9ad 100644 --- a/docs/subsystems/web-client.md +++ b/docs/subsystems/web-client.md @@ -57,7 +57,7 @@ This pairing is not a second source of business truth. Host controllers decide d Web and desktop share the [Coding Tools preference](../../packages/client/ui-settings/README.md#use-this-package). It controls diagnostic Views, [available preset choices](../../packages/client/ui-agent-preset/README.md), changed-file cards, and the builtin HTML preview policy without changing Session records. -`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionRetainInfo`, `useSessionAccess`, `useSession`, `sessionId`, `useProjection`, and the Session-scope `useAccess` over the [remote-access](../../packages/api/remote-access/README.md) Client service. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. [`ui-session-status`](../../packages/client/ui-session-status/README.md) publishes `useSessionStatus` from the `ctx.uiSession.sessionStatus` table of running state, the effective pending interaction, and completion reminders. Domain adapters add further standard sources without putting React hooks on the model objects. +`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionRetainInfo`, `useSessionAccess`, `useSession`, `sessionId`, `useProjection`, and the Session-scope `useAccess` over the [remote-access](../../packages/api/remote-access/README.md) Client service. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. [`ui-session-status`](../../packages/client/ui-session-status/README.md) publishes `useSessionStatus` from the `ctx.uiSession.sessionStatus` table of running state, the effective pending interaction, and reading reminders that its Host face keeps for every Client of one Host. Domain adapters add further standard sources without putting React hooks on the model objects. `ui-conversation` binds once to each `SessionBinding.eventSource`. Its event registry correlates durable Session events and Client-only `assistant/live-chunk` updates into stable business Contexts, and its view registry materializes target snapshots. Chat Assistant, Trajectory Assistant, and Turn Tail interpret both live chunks and the compact streams embedded in durable settlements, so reconnect and paged history reproduce the same Assistant state without durable token rows. `ui-chat` and `ui-trajectory` register separate Definitions and builders: they may interpret the same event family, but they do not import or share each other's final display model. The shell selects a registered view and passes its snapshot through standard hooks and Slots. [Conversation](conversation.md) defines Context identity, replay, Location data, target builders, and keyed renderers. @@ -86,11 +86,29 @@ Recovery follows the data's semantics: There is no monolithic Client `Runtime`, `HostFrame`, `events.mux`, `events.host`, or universal `resync()` API. The Connection exposes generation state, Gateway owns logical stream supervision, and each Client model defines replacement or resume semantics appropriate to its data. +## Reading reminders + +[Session status](../../packages/client/ui-session-status/README.md) holds read acknowledgements and explicit unread marks in Host memory, outside the conversation log. Its Host Remote service sends complete reconnect baselines and committed changes; its Client plugin folds them into the `ctx.uiSession.sessionStatus` status table and acknowledges loaded completions in the visible, focused main view. Reading state does not change model history. + +### SessionReadState + +A whole reading record names its `sessionId`, latest `completedTurn`, whether that turn `failed` with an execution error this Host observed, acknowledged `readTurn`, and `manualUnread` flag. A Session is unread when the flag is set or its latest ended turn exceeds the acknowledged turn. + +`mark(sessionId, action)` updates one Session in Host processing order. Only the ordered subscription updates Client records. The service records `turn/end` events itself, including whether that turn failed. + +### SessionReadAction + +An `unread` action sets the manual flag. A `read` action clears it and advances the read position through its `throughTurn`; an `acknowledge` action advances that position without changing the flag. Positions never move backwards or beyond the Host's latest completed turn. Mutation replies report success or failure without echoing a record. + +### SessionReadFrame + +A follow generation starts with `type: 'baseline'` and every accessible record in `items`. Each later `type: 'changed'` carries one complete committed `state`. Reconnection replaces the previous generation's records. + ## Package boundaries Feature plugin packages may share declarations through `import type`; they do not runtime-import or re-export another feature plugin's values. Cross-package behavior uses injected Cordis services, and cross-package UI uses Slots. Target-specific Conversation Definitions, projection helpers, and final view data stay with their target package even when Chat and Trajectory intentionally implement parallel logic. -Shared runtime values need a narrow static owner with no feature lifecycle, such as `client/store`, `ui-primitives`, or a browser-safe utility package. Transport and generated API assembly may import runtime contributions because assembling one protocol is their explicit responsibility. A feature package does not add `dsh.client.external` merely to bypass this rule. +Shared runtime values need a narrow static owner with no feature lifecycle, such as `client/store`, `ui-primitives`, or a browser-safe utility package. Transport and generated API assembly may import runtime contributions because assembling one protocol is their explicit responsibility. A feature package may request the runtime values of a row under `packages/api/` through `dsh.client.external`, but never another feature plugin's row. Use the four detailed references according to the extension being added: @@ -98,3 +116,40 @@ Use the four detailed references according to the extension being added: - [API Gateway](../api-gateway.md) for Host methods, generated Remote contributions, streams, and forwarded events. - [Web Client Slots](slots.md) for components, hooks, stores, injection, and placement. - [Conversation](conversation.md) for durable event correlation, target snapshots, and Chat or Trajectory view contributions. + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.sessionStatus` — `SessionStatusService` + +Shared owner reading records; no reading operation changes model history. + +```ts cordis-catalog +/** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ +@Remote async mark(sessionId: SessionId, action: SessionReadAction): Promise + +/** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Types: [SessionId](core.md) + +Source: [`packages/client/ui-session-status/src/index.ts`](../../packages/client/ui-session-status/src/index.ts) + diff --git a/docs/subsystems/web-client.zh.md b/docs/subsystems/web-client.zh.md index 50ef3f9146..7b92946915 100644 --- a/docs/subsystems/web-client.zh.md +++ b/docs/subsystems/web-client.zh.md @@ -57,7 +57,7 @@ Connection 拥有请求 URL 解析、request correlation、`/api` carrier、trus Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settings/README.zh.md#use-this-package)。它控制诊断 View、[可用的预设选项](../../packages/client/ui-agent-preset/README.zh.md)、改动文件卡片和内置 HTML 预览策略,不改变 Session 记录。 -`ui-session` 安装 Session scope adapter,并在 [remote-access](../../packages/api/remote-access/README.zh.md) Client 服务之上提供 `useSessions`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。[`ui-session-status`](../../packages/client/ui-session-status/README.zh.md) 从 `ctx.uiSession.sessionStatus` 状态表提供 `useSessionStatus`,该表汇总运行状态、生效的待交互请求和完成提醒。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 +`ui-session` 安装 Session scope adapter,并在 [remote-access](../../packages/api/remote-access/README.zh.md) Client 服务之上提供 `useSessions`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。[`ui-session-status`](../../packages/client/ui-session-status/README.zh.md) 从 `ctx.uiSession.sessionStatus` 状态表提供 `useSessionStatus`,该表汇总运行状态、生效的待交互请求,以及其宿主面为同一宿主各前端保存的阅读提醒。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 `ui-conversation` 对每个 `SessionBinding.eventSource` 只绑定一次。它的 event registry 把持久 Session event 与 Client-only `assistant/live-chunk` update 关联成稳定的业务 Context,view registry 则 materialize target snapshot。Chat Assistant、Trajectory Assistant 与 Turn Tail 同时解释 live chunk 和持久 settlement 中嵌入的紧凑 stream,因此重连与分页历史无需持久 token 行即可复现相同 Assistant 状态。`ui-chat` 与 `ui-trajectory` 分别注册自己的 Definition 和 builder:它们可以解释同一 event family,但不会导入或共享彼此的最终 display model。Shell 选择一个已注册 view,再通过标准 hook 与 Slot 交付其 snapshot。[Conversation](conversation.zh.md)定义 Context identity、replay、Location data、target builder 与 keyed renderer。 @@ -86,11 +86,29 @@ Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settin 架构中没有统一的 Client `Runtime`、`HostFrame`、`events.mux`、`events.host` 或通用 `resync()` API。Connection 公开 generation state,Gateway 管理 logical stream,Client model 则按自身数据定义 replacement 或 resume 语义。 +## 阅读提醒 + +[会话状态](../../packages/client/ui-session-status/README.zh.md)在宿主内存中保存使用者的阅读确认和手动未读标记。其宿主 Remote 服务发送重连快照和已保存的更新;其前端插件把这些记录汇入 `ctx.uiSession.sessionStatus` 状态表,并在可见且聚焦的主视图中确认已加载的完成内容。阅读状态不改变模型历史。 + +### SessionReadState + +完整阅读记录包含 `sessionId`、最近结束的 `completedTurn`、该轮是否以本宿主观察到的执行错误结束的 `failed`、已确认的 `readTurn` 和 `manualUnread` 标记。设置了手动标记,或最近结束的轮次大于已确认轮次时,会话为未读。 + +`mark(sessionId, action)` 按宿主处理顺序更新会话。前端只通过有序订阅流更新记录。该服务自己记录 `turn/end` 事件,包括该轮是否失败。 + +### SessionReadAction + +`unread` 操作设置手动标记。`read` 操作清除标记,并将阅读位置推进至它的 `throughTurn`;`acknowledge` 操作只推进位置,不改变标记。位置不会回退,也不越过宿主最近完成的轮次。修改回复仅表示成功或失败,不回传记录。 + +### SessionReadFrame + +每次同步先发送 `type: 'baseline'`,在 `items` 中包含所有可访问的记录。后续每个 `type: 'changed'` 都携带一条已保存的完整 `state`。重连会替换上一代同步流的记录。 + ## 包边界 功能插件包可以通过 `import type` 共享声明;不得运行时导入或转发另一个功能插件的值。跨包行为使用注入的 Cordis service,跨包 UI 使用 Slots。特定 target 的 Conversation Definition、projection helper 与最终 view data 留在所属 target 包中,即使 Chat 和 Trajectory 有意实现平行逻辑。 -共享运行时值需要一个职责收窄、没有功能生命周期的静态 owner,例如 `client/store`、`ui-primitives` 或浏览器安全的 util 包。Transport 与生成 API assembly 可以导入运行时 contribution,因为组装同一个 protocol 正是它们的显式职责。功能包不能只为绕过此规则而添加 `dsh.client.external`。 +共享运行时值需要一个职责收窄、没有功能生命周期的静态 owner,例如 `client/store`、`ui-primitives` 或浏览器安全的 util 包。Transport 与生成 API assembly 可以导入运行时 contribution,因为组装同一个 protocol 正是它们的显式职责。功能包可以通过 `dsh.client.external` 请求 `packages/api/` 下某一行的运行时值,但不能请求另一个功能插件的行。 根据所添加的扩展查阅四篇详细参考: @@ -98,3 +116,40 @@ Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settin - [API Gateway](../api-gateway.zh.md):Host method、生成的 Remote contribution、stream 与 forwarded event。 - [Web Client Slots](slots.zh.md):component、hook、store、injection 与 placement。 - [Conversation](conversation.zh.md):持久 event correlation、target snapshot,以及 Chat 或 Trajectory view contribution。 + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.sessionStatus` — `SessionStatusService` + +Shared owner reading records; no reading operation changes model history. + +```ts cordis-catalog +/** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ +@Remote async mark(sessionId: SessionId, action: SessionReadAction): Promise + +/** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Types: [SessionId](core.zh.md) + +Source: [`packages/client/ui-session-status/src/index.ts`](../../packages/client/ui-session-status/src/index.ts) + diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml index b2225275ad..72f725d176 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md /: - en: 34a382f0eacc70b6 - zh: 251d8ba446d1b358 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status: - en: 97c85d1b9ace1ddf - zh: 0c4d30289336b324 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status/change: - en: 62ea699966c0e9d5 - zh: 31afc236690b0cd5 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status/migration: - en: 529f2def0221d26d - zh: 6009726243e1c8a6 + en: 3ac349a835a29b14 + zh: 2c0d4c7e3cfb59ca +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records: + en: fb71a29f84e6d36d + zh: 5f46ad954c473f7e +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records/change: + en: ec4737fe7f5e4839 + zh: e68a22fe18216760 +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records/migration: + en: 20d2b7a2809ffc2d + zh: 9ca5578f94130755 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md index c4fdfe189a..3addbda815 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md @@ -1,28 +1,31 @@ --- kind: upgrade-guide -description: "SessionStatus, SessionStatusSnapshot, UseSessionStatus, and the useSessionStatus hook move from @deepseek-ai/dsh-client-ui-session/client to @deepseek-ai/dsh-client-ui-session-status/client, and ctx.uiSession.sessionStatus becomes the separate uiSession.sessionStatus service that readers inject." +description: "Session status types and the useSessionStatus hook move to @deepseek-ai/dsh-client-ui-session-status/client, ctx.uiSession.sessionStatus becomes an injected service, and completion reminders follow Host reading records." --- -# Session status moves to `@deepseek-ai/dsh-client-ui-session-status` +# Session status moves to `@deepseek-ai/dsh-client-ui-session-status` and completion reminders follow Host reading records English | [中文](guide.zh.md) ## Change -`@deepseek-ai/dsh-client-ui-session/client` no longer exports `SessionStatus`, `SessionStatusSnapshot`, or `UseSessionStatus`, and ui-session no longer declares or provides the `useSessionStatus` root hook. Both now belong to the Client plugin [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md), which the Web bundle loads beside ui-session. The `SessionStatus` fields `running`, `pendingInteraction`, and `completionUnread` and their meaning are unchanged. A Client composition that loads ui-session without ui-session-status has no status table and no `useSessionStatus` hook. +`@deepseek-ai/dsh-client-ui-session/client` no longer exports `SessionStatus`, `SessionStatusSnapshot`, or `UseSessionStatus`, and ui-session no longer declares or provides the `useSessionStatus` root hook. Both now belong to the Client plugin [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md), one Web bundle row with a Host reading service and the Client table. A Client composition that loads ui-session without ui-session-status has no status table and no `useSessionStatus` hook. -`ctx.uiSession.sessionStatus` is now the separate `uiSession.sessionStatus` service. Reading it through `ctx.uiSession.sessionStatus.getSnapshot()` and `subscribe()` keeps its form, but a plugin that reads it without injecting `'uiSession.sessionStatus'` fails with `cannot get property "uiSession.sessionStatus" without inject`. A plugin whose components call `useSessionStatus` without that injection stays active when the status table unloads, and its components then fail with `useSessionStatus is not a function`. `ctx.uiSession` now has the type `UiSessionService`, which extends the unchanged `UiSession` class with members such as `sessionStatus`; a value annotated as `UiSession` does not show `sessionStatus`. +`ctx.uiSession.sessionStatus` is now the separate `uiSession.sessionStatus` service. Reading it through `ctx.uiSession.sessionStatus.getSnapshot()` and `subscribe()` keeps its form, but a plugin that reads it without injecting `'uiSession.sessionStatus'` fails with `cannot get property "uiSession.sessionStatus" without inject`. Components of a plugin without that injection fail with `useSessionStatus is not a function` after the table unloads. `ctx.uiSession` now has the type `UiSessionService`, which extends the unchanged `UiSession` class with members such as `sessionStatus`; a value annotated as `UiSession` does not show `sessionStatus`. -Pending interactions stay in ui-session: `ctx.uiSession.registerPendingInteraction(precedence)`, `SessionPendingInteractionBase`, `SessionPendingInteractionMap`, `SessionPendingInteraction`, and `PendingInteractionPublisher` keep their names, behavior, and `@deepseek-ai/dsh-client-ui-session/client` export. Declarations that extend `SessionPendingInteractionMap` keep targeting that module. ui-session additionally exposes the read-only `ctx.uiSession.pendingInteractions` source. +Pending interactions stay in ui-session: `ctx.uiSession.registerPendingInteraction(precedence)`, `SessionPendingInteractionBase`, `SessionPendingInteractionMap`, `SessionPendingInteraction`, and `PendingInteractionPublisher` keep their names, behavior, and `@deepseek-ai/dsh-client-ui-session/client` export. Extensions of `SessionPendingInteractionMap` keep targeting that module. ui-session additionally exposes the read-only `ctx.uiSession.pendingInteractions` source. -This affects Client plugins and tests that import the three status types, render components that read `useSessionStatus`, or read `ctx.uiSession.sessionStatus`. +`completionUnread` follows Host-memory reading records shared by every Client and changes through Host completions, explicit marks, and visible main-view acknowledgement; only a main-view switch, including a reload, clears a manual mark. The open viewed Session hides its unacknowledged turn; earlier history reads as read. The required `completionFailed` field marks an unread Session whose latest turn failed. The new `mark(sessionId, unread)` rejects until `readingReady` reports the Host baseline. + +This affects Client plugins and tests that import the three status types, construct `SessionStatus` values, render components that read `useSessionStatus`, or read `ctx.uiSession.sessionStatus`. ## Migration 1. Import `SessionStatus`, `SessionStatusSnapshot`, and `UseSessionStatus` from `@deepseek-ai/dsh-client-ui-session-status/client`. A package that only imports these types, for example in tests, declares `@deepseek-ai/dsh-client-ui-session-status` in `devDependencies` and its TypeScript project references. -2. A package whose source components call `useSessionStatus` additionally lists the package in `dsh.client.inject`, adds `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'` when it imports none of the types, and adds `'uiSession.sessionStatus'` to the Cordis `inject` of the plugin that registers those components, so the plugin unloads and reloads with the status table. -3. In each plugin that reads `ctx.uiSession.sessionStatus` in JavaScript, add `'uiSession.sessionStatus'` to `inject`. A plugin that only needs the effective pending request may read and subscribe to `ctx.uiSession.pendingInteractions` instead. +2. A package whose components call `useSessionStatus` also lists the package in `dsh.client.inject`, adds `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'` when it imports none of the types, and adds `'uiSession.sessionStatus'` to the Cordis `inject` of the plugin that registers them. +3. Each plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession.sessionStatus'` to `inject`; one that needs only the effective pending request may subscribe to `ctx.uiSession.pendingInteractions` instead. 4. Where code passes `ctx.uiSession` through a parameter or field annotated as `UiSession` and then reads `sessionStatus`, annotate it as `UiSessionService` from `@deepseek-ai/dsh-client-ui-session/client`. 5. Leave `registerPendingInteraction` calls and `declare module '@deepseek-ai/dsh-client-ui-session/client'` augmentations of `SessionPendingInteractionMap` unchanged. -6. A custom Client composition that loads `@deepseek-ai/dsh-client-ui-session` also loads `@deepseek-ai/dsh-client-ui-session-status`, so `useSessionStatus` remains available. -7. Confirm that the plugin type-checks and that a Session row still shows its running or waiting indicator. +6. Add `completionFailed` to `SessionStatus` values in tests and fixtures, and script Host reading records to drive `completionUnread`. +7. A custom composition that loads `@deepseek-ai/dsh-client-ui-session` also loads `@deepseek-ai/dsh-client-ui-session-status` as a plugin row, so its Host reading service and `useSessionStatus` are available. +8. Confirm that the plugin type-checks, that a Session row still shows its running or waiting indicator, and that a Session finishing outside the main view shows an unread reminder. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md index 8403fc5f48..8fa30ace12 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md @@ -1,28 +1,31 @@ --- kind: upgrade-guide -description: "SessionStatus、SessionStatusSnapshot、UseSessionStatus 和 useSessionStatus hook 从 @deepseek-ai/dsh-client-ui-session/client 移到 @deepseek-ai/dsh-client-ui-session-status/client,ctx.uiSession.sessionStatus 改为读取方需要注入的独立 uiSession.sessionStatus 服务。" +description: "会话状态类型与 useSessionStatus hook 移到 @deepseek-ai/dsh-client-ui-session-status/client,ctx.uiSession.sessionStatus 改为需要注入的服务,完成提醒改为跟随宿主阅读记录。" --- -# 会话状态移到 `@deepseek-ai/dsh-client-ui-session-status` +# 会话状态移到 `@deepseek-ai/dsh-client-ui-session-status`,完成提醒改由宿主阅读记录提供 [English](guide.md) | 中文 ## 变更 -`@deepseek-ai/dsh-client-ui-session/client` 不再导出 `SessionStatus`、`SessionStatusSnapshot` 或 `UseSessionStatus`,ui-session 也不再声明或提供根 hook `useSessionStatus`。它们现在属于 Client 插件 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md),Web bundle 会与 ui-session 一起加载它。`SessionStatus` 的字段 `running`、`pendingInteraction`、`completionUnread` 及其含义不变。只加载 ui-session、不加载 ui-session-status 的 Client 组合没有状态表,也没有 `useSessionStatus` hook。 +`@deepseek-ai/dsh-client-ui-session/client` 不再导出 `SessionStatus`、`SessionStatusSnapshot` 或 `UseSessionStatus`,ui-session 也不再声明或提供根 hook `useSessionStatus`。它们现在属于 Client 插件 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md),即 Web bundle 中同时提供宿主阅读服务和前端状态表的一行。只加载 ui-session、不加载 ui-session-status 的 Client 组合没有状态表,也没有 `useSessionStatus` hook。 -`ctx.uiSession.sessionStatus` 现在是独立的 `uiSession.sessionStatus` 服务。通过 `ctx.uiSession.sessionStatus.getSnapshot()` 和 `subscribe()` 读取的写法不变,但未注入 `'uiSession.sessionStatus'` 就读取它的插件会报错 `cannot get property "uiSession.sessionStatus" without inject`。组件调用 `useSessionStatus`、却未注入该服务的插件,在状态表卸载后仍保持激活,其组件随后报错 `useSessionStatus is not a function`。`ctx.uiSession` 的类型改为 `UiSessionService`,它在不变的 `UiSession` class 之上加入 `sessionStatus` 等成员;标注为 `UiSession` 的值看不到 `sessionStatus`。 +`ctx.uiSession.sessionStatus` 现在是独立的 `uiSession.sessionStatus` 服务。通过 `ctx.uiSession.sessionStatus.getSnapshot()` 和 `subscribe()` 读取的写法不变,但未注入 `'uiSession.sessionStatus'` 就读取它的插件会报错 `cannot get property "uiSession.sessionStatus" without inject`。未注入该服务的插件,其组件会在状态表卸载后报错 `useSessionStatus is not a function`。`ctx.uiSession` 的类型改为 `UiSessionService`,它在不变的 `UiSession` class 之上加入 `sessionStatus` 等成员;标注为 `UiSession` 的值看不到 `sessionStatus`。 待交互仍归 ui-session:`ctx.uiSession.registerPendingInteraction(precedence)`、`SessionPendingInteractionBase`、`SessionPendingInteractionMap`、`SessionPendingInteraction` 和 `PendingInteractionPublisher` 的名称、行为以及从 `@deepseek-ai/dsh-client-ui-session/client` 的导出都不变。扩展 `SessionPendingInteractionMap` 的声明继续指向该模块。ui-session 另外提供只读的 `ctx.uiSession.pendingInteractions` 数据源。 -受影响的是导入这三个状态类型、渲染读取 `useSessionStatus` 的组件,或读取 `ctx.uiSession.sessionStatus` 的 Client 插件和测试。 +`completionUnread` 跟随宿主内存中、由所有前端共享的阅读记录,因宿主完成轮次、主动标记和可见主视图的确认而变化;只有主视图切换到该会话(包括刷新后恢复)会自动清除手动标记。正在查看且已打开的会话不显示尚未确认的轮次;宿主启动前已有的历史按已读处理。新增的必填字段 `completionFailed` 标记最近一轮失败的未读会话。新增的 `mark(sessionId, unread)` 在 `readingReady` 报告取得宿主基线之前会拒绝。 + +受影响的是导入这三个状态类型、构造 `SessionStatus` 值、渲染读取 `useSessionStatus` 的组件,或读取 `ctx.uiSession.sessionStatus` 的 Client 插件和测试。 ## 迁移 1. 从 `@deepseek-ai/dsh-client-ui-session-status/client` 导入 `SessionStatus`、`SessionStatusSnapshot` 和 `UseSessionStatus`。只导入这些类型(例如只在测试中导入)的包,在 `devDependencies` 和 TypeScript 项目引用中声明 `@deepseek-ai/dsh-client-ui-session-status`。 -2. 源码组件调用 `useSessionStatus` 的包,另外在 `dsh.client.inject` 中列出该包;不导入任何上述类型时加入 `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'`;并在注册这些组件的插件的 Cordis `inject` 中加入 `'uiSession.sessionStatus'`,使该插件随状态表一起卸载和重新加载。 -3. 在每个在 JS 中读取 `ctx.uiSession.sessionStatus` 的插件中,把 `'uiSession.sessionStatus'` 加到 `inject`。只需要生效待交互请求的插件,可以改为读取并订阅 `ctx.uiSession.pendingInteractions`。 +2. 组件调用 `useSessionStatus` 的包,另外在 `dsh.client.inject` 中列出该包;不导入任何上述类型时加入 `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'`;并在注册这些组件的插件的 Cordis `inject` 中加入 `'uiSession.sessionStatus'`。 +3. 每个读取 `ctx.uiSession.sessionStatus` 的插件把 `'uiSession.sessionStatus'` 加入 `inject`;只需要生效待交互请求的插件,可以改为订阅 `ctx.uiSession.pendingInteractions`。 4. 代码把 `ctx.uiSession` 传给标注为 `UiSession` 的参数或字段、之后又读取 `sessionStatus` 时,把标注改为 `@deepseek-ai/dsh-client-ui-session/client` 的 `UiSessionService`。 5. `registerPendingInteraction` 调用和对 `SessionPendingInteractionMap` 的 `declare module '@deepseek-ai/dsh-client-ui-session/client'` 扩展保持不变。 -6. 加载 `@deepseek-ai/dsh-client-ui-session` 的自定义 Client 组合同时加载 `@deepseek-ai/dsh-client-ui-session-status`,使 `useSessionStatus` 继续可用。 -7. 确认插件通过类型检查,并且会话行仍显示运行或等待标记。 +6. 在测试和 fixture 的 `SessionStatus` 值中加入 `completionFailed`,并编排宿主阅读记录来驱动 `completionUnread`。 +7. 加载 `@deepseek-ai/dsh-client-ui-session` 的自定义组合同时以插件行加载 `@deepseek-ai/dsh-client-ui-session-status`,使其宿主阅读服务和 `useSessionStatus` 可用。 +8. 确认插件通过类型检查、会话行仍显示运行或等待标记,并且在主视图之外结束的会话显示未读提醒。 diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index eb3352e60d..4caa0e8c59 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -18,8 +18,8 @@ en: 6ee072ffebd2eb38 zh: 6a8723d13f443d51 /deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote: - en: 0916113cdbe794fb - zh: 14893c2cba95bfd6 + en: 610e48ec8d772f85 + zh: 627da164fc8297ba /deepseek-ai-dsh-api-gateway/model-experience: en: 6cb309d3378f035d zh: 998042a02ee32850 diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index fea754c891..20f87506d0 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -63,7 +63,7 @@ Every unary call resolves to `RemoteResult` — `{ ok: true, value }` or `{ o `ctx.remote.$host` reads the fixed Host facts as plain values: `home` (undefined until the first ready frame) and `isLoopback`. It is not a store — no subscription, no generation counter — so a consumer that must react to reconnection listens for `connection/reset` instead of polling it. -`ctx.remote.$stream()` returns a single-consumer `RemoteStream` spanning physical carrier generations. For answering Clients it permits one immediate retry after an isolated stream failure while the carrier remains available; after physical WebSocket loss it waits for Connection to reopen the carrier. If the Host generation is already unavailable, it waits for the next connected generation. Each item carries its physical generation. Passive Clients cannot use `$stream()`; they call generated raw stream methods and handle terminal carrier failure themselves. The domain consumer validates and accepts each generation's opening value; business and protocol failures remain terminal. Every terminal failure leaves this face as a `RemoteError`, including exhausted carrier retries and a generation that ends before its opening value, so a stream consumer discriminates the same way a unary caller does. `RemoteStreamCarrierError` names a retryable physical loss and reaches a domain only as the `carrierFailed` callback argument, never as a terminal outcome. `RemoteSnapshotStream` adds one opening snapshot followed by deltas. `RemoteJournalStream` adds follow-before-page opening, pagination, reconnect catch-up, and gap repair over domain-defined inclusive entry ranges; it removes complete duplicates and rejects gaps, inverted ranges, and partial overlaps. A domain may also carry cursorless notifications: they never advance or repair the durable cursor, and notifications received during gap repair publish only after the replacement page commits. If a newer generation supersedes that repair, held notifications from the superseded generation are discarded with its page. Disposing any stream cancels its requests and resolves after the active iterator is fully stopped. +`ctx.remote.$stream()` returns a single-consumer `RemoteStream` spanning physical carrier generations. For answering Clients it permits one immediate retry after an isolated stream failure while the carrier remains available; after physical WebSocket loss it waits for Connection to reopen the carrier. If the Host generation is already unavailable, it waits for the next connected generation. Each item carries its physical generation. Passive Clients cannot use `$stream()`; they call generated raw stream methods and handle terminal carrier failure themselves. The domain consumer validates and accepts each generation's opening value; business and protocol failures remain terminal. Every terminal failure leaves this face as a `RemoteError`, including exhausted carrier retries and a generation that ends before its opening value, so a stream consumer discriminates the same way a unary caller does. A failure whose `code` is `gateway/carrier-lost` names a retryable physical loss: `RemoteStreamCarrierError` carries that code, the `RemoteStreamCarrierFailure` type describes it, `isRemoteStreamCarrierFailure(error)` applies the same retry test for a domain that classifies its own failures, and a domain `ended` callback may return a plain `Error` with it to request reconnection without importing the class. Retry follows the code, not the class; the code is produced only inside the Client process, so a `RemoteError` from the Host terminates the stream even when it carries that code; such a failure reaches a domain only as the `carrierFailed` callback argument, never as a terminal outcome. `RemoteSnapshotStream` adds one opening snapshot followed by deltas. `RemoteJournalStream` adds follow-before-page opening, pagination, reconnect catch-up, and gap repair over domain-defined inclusive entry ranges; it removes complete duplicates and rejects gaps, inverted ranges, and partial overlaps. A domain may also carry cursorless notifications: they never advance or repair the durable cursor, and notifications received during gap repair publish only after the replacement page commits. If a newer generation supersedes that repair, held notifications from the superseded generation are discarded with its page. Disposing any stream cancels its requests and resolves after the active iterator is fully stopped. `ctx.remote.$on()` subscribes to one forwarded Host event. Its legal keys are exactly the Host assembly's forwarding selection, and the listener type is the owning package's own Cordis `Events` declaration, so no second signature can drift from it. Each subscription belongs to the calling fiber and disappears with it. The Client Remote service registers the `$events` pump as a Connection generation source only when `connection.interactions` is `answer`, whether any `$on` listener exists. With `none`, `$on()` is unavailable and the Client opens only the physical lifecycle socket; unary calls never wait for socket readiness. Browsers use Remote mux, while in-process compositions use `connection.rpc.open`; the opening `ready` item establishes a Connection generation and supplies its Host facts. Carrier failure, Remote stream failure, unexpected normal completion, a non-ready opening item, or a malformed event item ends that generation and lets Connection reopen it under continuous, capped jittered exponential backoff. Ordinary notifications run in registration order and isolate listener failures. Agent-scoped waterfalls let a listener return a result, call `next()`, or reject; Gateway returns that outcome through the existing HTTP unary carrier. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index 1dad623204..008b6af7bb 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -63,7 +63,7 @@ Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source `ctx.remote.$host` 以普通值读取固定的 Host 事实:`home`(首个 ready 帧之前为 undefined)与 `isLoopback`。它不是存储——没有订阅、没有代次计数——所以需要响应重连的消费方去监听 `connection/reset`,而不是轮询它。 -`ctx.remote.$stream()` 返回跨越多个物理载体代次的单消费方 `RemoteStream`。对于回答型 Client,载体仍可用时的独立流故障允许一次立即重试;物理 WebSocket 丢失后等待 Connection 重开载体。如果 Host generation 已不可用,则等待下一代连接。每个流项都带有其物理代次。被动 Client 不使用 `$stream()`,而是调用生成的原始流方法,并自行处理终态载体故障。领域消费方校验并接受各代次的 opening value;业务与协议错误仍然终止流。一切终态失败离开本面时都是 `RemoteError`,包括重试耗尽和在 opening value 之前就结束的代次,因此流消费方与一元调用方用同一种方式判别。`RemoteStreamCarrierError` 命名的是可重试的物理丢失,它只作为 `carrierFailed` 回调参数到达领域,绝不作为终态结果。`RemoteSnapshotStream` 在此之上规定每代由一个初始快照和后续 delta 组成。`RemoteJournalStream` 基于领域提供的 entry 闭区间提供 follow-before-page、分页、重连追赶与缺口修复;它丢弃完整重复项,并拒绝缺口、倒置区间和部分重叠。领域还可以携带无 cursor 的通知:通知绝不推进或修复持久 cursor,在缺口修复期间收到的通知只会在 replacement page 提交后发布。若更新代次取代该修复,旧代次 held notification 会与其 page 一同丢弃。对任一种流执行 dispose(资源释放)时,系统会取消该流的请求,并在活动 iterator 完全停止后完成资源释放。 +`ctx.remote.$stream()` 返回跨越多个物理载体代次的单消费方 `RemoteStream`。对于回答型 Client,载体仍可用时的独立流故障允许一次立即重试;物理 WebSocket 丢失后等待 Connection 重开载体。如果 Host generation 已不可用,则等待下一代连接。每个流项都带有其物理代次。被动 Client 不使用 `$stream()`,而是调用生成的原始流方法,并自行处理终态载体故障。领域消费方校验并接受各代次的 opening value;业务与协议错误仍然终止流。一切终态失败离开本面时都是 `RemoteError`,包括重试耗尽和在 opening value 之前就结束的代次,因此流消费方与一元调用方用同一种方式判别。`code` 为 `gateway/carrier-lost` 的失败表示可重试的物理丢失:`RemoteStreamCarrierError` 带有该 code,`RemoteStreamCarrierFailure` 类型描述它,`isRemoteStreamCarrierFailure(error)` 供自行分类失败的领域复用同一重试判断,领域的 `ended` 回调也可以返回带该 code 的普通 `Error` 来请求重连,而无需导入该 class。是否重试只看 code,不看 class;该 code 只在前端进程内产生,因此宿主返回的 `RemoteError` 即使带有该 code 也会终止流;这类失败只作为 `carrierFailed` 回调参数到达领域,绝不作为终态结果。`RemoteSnapshotStream` 在此之上规定每代由一个初始快照和后续 delta 组成。`RemoteJournalStream` 基于领域提供的 entry 闭区间提供 follow-before-page、分页、重连追赶与缺口修复;它丢弃完整重复项,并拒绝缺口、倒置区间和部分重叠。领域还可以携带无 cursor 的通知:通知绝不推进或修复持久 cursor,在缺口修复期间收到的通知只会在 replacement page 提交后发布。若更新代次取代该修复,旧代次 held notification 会与其 page 一同丢弃。对任一种流执行 dispose(资源释放)时,系统会取消该流的请求,并在活动 iterator 完全停止后完成资源释放。 `ctx.remote.$on()` 订阅一条被转发的 Host 事件。它的合法键恰好等于 Host 装配声明的转发选择,listener 类型就是事件所属包自己的 Cordis `Events` 声明,因此不存在会与之漂移的第二份签名。每个订阅归属调用方 fiber,并随该 fiber 一起消失。Client Remote 服务仅在 `connection.interactions` 为 `answer` 时把 `$events` pump 注册为 Connection generation source,无论当前是否存在 `$on` listener。选择 `none` 时,`$on()` 不可用,Client 只打开物理生命周期连接;unary 调用不等待 socket 就绪。浏览器使用 Remote mux,进程内组合使用 `connection.rpc.open`;opening `ready` 项建立 Connection generation 并提供 Host 信息。物理 carrier 失败、Remote 流故障、意外正常结束、非 ready 首项或畸形事件项都会终止该 generation,由 Connection 按持续且间隔封顶的带抖动指数退避重开。普通通知按注册顺序运行并隔离 listener 失败;Agent-scoped waterfall(瀑布式事件)允许 listener 返回结果、调用 `next()` 或拒绝,Gateway 再通过现有 HTTP 一元载体回送该结果。 diff --git a/packages/api/gateway/src/client/index.ts b/packages/api/gateway/src/client/index.ts index f0d2400dc8..3292afcfcc 100644 --- a/packages/api/gateway/src/client/index.ts +++ b/packages/api/gateway/src/client/index.ts @@ -34,7 +34,8 @@ import { type RemoteStreamOptions, } from './remote-stream.ts' -export { RemoteStreamCarrierError } from './stream-client.ts' +export { isRemoteStreamCarrierFailure, RemoteStreamCarrierError } from './stream-client.ts' +export type { RemoteStreamCarrierFailure } from './stream-client.ts' export { RemoteJournalStream } from './journal-stream.ts' export type { RemoteJournalChange, diff --git a/packages/api/gateway/src/client/journal-stream.ts b/packages/api/gateway/src/client/journal-stream.ts index ab013abdf3..2804feb0aa 100644 --- a/packages/api/gateway/src/client/journal-stream.ts +++ b/packages/api/gateway/src/client/journal-stream.ts @@ -1,7 +1,7 @@ /** Cursor, page, and live-tail coordination over a reconnecting Remote stream. */ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' -import { RemoteStreamCarrierError } from './stream-client.ts' +import { RemoteStreamCarrierError, type RemoteStreamCarrierFailure } from './stream-client.ts' import type { RemoteStream, RemoteStreamItem, @@ -75,7 +75,7 @@ export interface RemoteJournalStreamOptions) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal stream, page, or protocol failure after opening. */ readonly failed: (error: unknown) => void } diff --git a/packages/api/gateway/src/client/remote-stream.ts b/packages/api/gateway/src/client/remote-stream.ts index 00b398afd7..66b0f6544b 100644 --- a/packages/api/gateway/src/client/remote-stream.ts +++ b/packages/api/gateway/src/client/remote-stream.ts @@ -2,7 +2,7 @@ import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' -import { RemoteStreamCarrierError } from './stream-client.ts' +import { isRemoteStreamCarrierFailure, type RemoteStreamCarrierFailure } from './stream-client.ts' /** One item annotated with the physical Remote-stream generation that delivered it. */ export interface RemoteStreamItem { @@ -22,10 +22,13 @@ export interface RemoteStreamOptions { readonly name: string /** Open one physical generation of the logical stream. */ readonly open: (signal: AbortSignal) => AsyncIterable - /** Classify a normal generation end after or before its opening item was accepted. */ + /** + * Classify a normal generation end after or before its opening item was accepted; a returned error whose `code` is + * `gateway/carrier-lost` reconnects, and any other error is terminal. + */ readonly ended: (accepted: boolean) => Error /** Observe a retryable carrier loss before the supervisor waits or reopens. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void } /** @@ -129,7 +132,7 @@ export class RemoteStream implements AsyncIterable> } catch (error) { if (isAborted(this.lifetime.signal)) return if (revision !== this.revision) continue - if (!(error instanceof RemoteStreamCarrierError)) throw terminalStreamFailure(error) + if (!isRemoteStreamCarrierFailure(error)) throw terminalStreamFailure(error) this.options.carrierFailed?.(error) if (revision !== this.revision) continue attempt++ @@ -159,7 +162,7 @@ export class RemoteStream implements AsyncIterable> async function waitForRemoteStreamRetry( connection: Pick, - error: RemoteStreamCarrierError, + error: RemoteStreamCarrierFailure, attempt: number, signal: AbortSignal, ): Promise { @@ -199,7 +202,7 @@ async function waitForRemoteStreamRetry( /** * Mark a terminal escape before it crosses the stream boundary: consumers * discriminate failures by code, so an unmarked throw reads as a local bug. - * Marked failures pass through verbatim. The carrier class never escapes as a + * Marked failures pass through verbatim. A carrier failure never escapes as a * terminal outcome — it stays the retry-internal signal fed to `carrierFailed` * and the `ended(true)` retry trigger. */ diff --git a/packages/api/gateway/src/client/stream-client.ts b/packages/api/gateway/src/client/stream-client.ts index 0ada6c4055..1abe342b94 100644 --- a/packages/api/gateway/src/client/stream-client.ts +++ b/packages/api/gateway/src/client/stream-client.ts @@ -1,5 +1,5 @@ /** Client owner for the Gateway multiplexed Remote stream socket. */ -import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionWebSocket } from '@deepseek-ai/dsh-client-connection/client' import { @@ -11,8 +11,22 @@ import { import { Deque } from '@deepseek-ai/dsh-deque' import { randomUUID } from '@deepseek-ai/dsh-util-crypto' +/** + * Retryable physical Remote stream carrier failure. {@link RemoteStream} reconnects on any error whose `code` is + * `gateway/carrier-lost`, so a domain `ended` callback may return a plain `Error` carrying that code. The code is + * produced only inside this Client process; a `RemoteError` returned by the Host never counts as a carrier loss. + */ +export interface RemoteStreamCarrierFailure extends Error { + /** Stable carrier-loss code; class identity is not part of the retry decision. */ + readonly code: 'gateway/carrier-lost' +} + +const REMOTE_STREAM_CARRIER_CODE: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost' + /** Physical Remote stream socket failure that may be retried by a domain transport. */ -export class RemoteStreamCarrierError extends Error { +export class RemoteStreamCarrierError extends Error implements RemoteStreamCarrierFailure { + readonly code: RemoteStreamCarrierFailure['code'] = REMOTE_STREAM_CARRIER_CODE + /** * @param message - physical carrier failure description. * @param options - optional causal error. @@ -23,6 +37,18 @@ export class RemoteStreamCarrierError extends Error { } } +/** + * Whether a failure is a retryable carrier loss, judged by its `code` rather than its class. {@link RemoteStream} uses + * this test, and domains that classify their own failures, such as a disconnected view, reuse it. + * @param error - thrown or returned failure. + * @returns true for a locally produced `Error` whose `code` is `gateway/carrier-lost`; false for any `RemoteError`, + * which reached this Client from the Host and terminates the stream even when it carries that code. + */ +export function isRemoteStreamCarrierFailure(error: unknown): error is RemoteStreamCarrierFailure { + return error instanceof Error && remoteErrorOf(error) === undefined + && 'code' in error && error.code === REMOTE_STREAM_CARRIER_CODE +} + interface SocketWaiter { readonly revision: number resolve(socket: ConnectionWebSocket): void @@ -59,7 +85,7 @@ export class RemoteStreamMuxClient { private readonly socketClosures = new Set>() private running = false private disposed = false - private failure: RemoteStreamCarrierError | undefined + private failure: RemoteStreamCarrierFailure | undefined /** * @param openSocket - selected authenticated carrier; omission uses the browser socket. @@ -367,7 +393,7 @@ export class RemoteStreamMuxClient { () => undefined, (error: unknown) => { if (!this.running) return - const failure = error instanceof RemoteStreamCarrierError ? error + const failure = isRemoteStreamCarrierFailure(error) ? error : new RemoteStreamCarrierError('api gateway: Remote stream WebSocket failed to open', { cause: error }) if (this.revision === revision) this.failure = failure for (const waiter of [...this.waiters]) { diff --git a/packages/api/gateway/tests/control-retry.client.spec.ts b/packages/api/gateway/tests/control-retry.client.spec.ts index c818d507e7..02524e92dd 100644 --- a/packages/api/gateway/tests/control-retry.client.spec.ts +++ b/packages/api/gateway/tests/control-retry.client.spec.ts @@ -4,6 +4,7 @@ import type { ConnectionHandle } from '@deepseek-ai/dsh-api-remotes/client' import { RemoteStreamCarrierError, RemoteStream, + type RemoteStreamCarrierFailure, } from '../src/client/index.ts' const GENERATION = { id: 1, host: { home: '/home/fixture' } } @@ -118,6 +119,48 @@ describe('RemoteStream', () => { expect(carrierFailed).toHaveBeenNthCalledWith(2, repeated) }) + it('reconnects on a plain Error carrying the carrier code and stops on one without it', async () => { + const carrierLoss = Object.assign(new Error('domain stream ended'), { code: 'gateway/carrier-lost' as const }) + const carrierFailed = vi.fn<(error: RemoteStreamCarrierFailure) => void>() + const reconnecting = new RemoteStream(hostSource(true).connection, { + name: 'fixture stream', + open: scripted([{ values: ['first'] }, { values: ['second'], hold: true }]), + ended: accepted => accepted ? carrierLoss : new Error('generation ended before acceptance'), + carrierFailed, + }) + const iterator = reconnecting[Symbol.asyncIterator]() + const first = await iterator.next() + if (first.done) throw new Error('fixture generation ended early') + first.value.accept() + await expect(iterator.next()).resolves.toMatchObject({ done: false, value: { generation: 2, value: 'second' } }) + expect(carrierFailed).toHaveBeenCalledExactlyOnceWith(carrierLoss) + await reconnecting.dispose() + + const plain = new Error('domain stream ended') + const terminal = new RemoteStream(hostSource(true).connection, { + name: 'fixture stream', + open: scripted([{ values: ['first'] }, { values: ['unreached'] }]), + ended: () => plain, + }) + const stopping = terminal[Symbol.asyncIterator]() + const opened = await stopping.next() + if (opened.done) throw new Error('fixture generation ended early') + opened.value.accept() + await expect(stopping.next()).rejects.toMatchObject({ + isDSHRemoteError: true, code: 'gateway/internal', message: 'domain stream ended', cause: plain, + }) + expect(new RemoteStreamCarrierError('socket lost').code).toBe('gateway/carrier-lost') + }) + + it('terminates on a Host RemoteError even when it carries the carrier code', async () => { + const hostFailure = new RemoteError('gateway/carrier-lost' as never, 'host reused the carrier code', {} as never) + const carrierFailed = vi.fn<(error: RemoteStreamCarrierFailure) => void>() + const stream = supervisor(hostSource(true).connection, [{ terminal: hostFailure }, { values: ['unreached'] }], carrierFailed) + + await expect(stream[Symbol.asyncIterator]().next()).rejects.toBe(hostFailure) + expect(carrierFailed).not.toHaveBeenCalled() + }) + it('folds a non-Error terminal escape into a marked gateway/internal failure', async () => { const stream = new RemoteStream(hostSource(true).connection, { name: 'fixture stream', diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index e26f92ee09..e024d0c8b1 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -102,6 +102,7 @@ "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:*", "@deepseek-ai/dsh-web": "workspace:*" diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 5d91957c0a..5efb7dbeb7 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -27,6 +27,8 @@ import sessionFeedbackRemote from '@deepseek-ai/dsh-command-feedback/remote' import fileUploadsRemote from '@deepseek-ai/dsh-client-file-upload/remote' import sessionReferencesRemote from '@deepseek-ai/dsh-session-reference/remote' import subagentsRemote from '@deepseek-ai/dsh-subagent/remote' +import sessionStatusRemote from '@deepseek-ai/dsh-client-ui-session-status/remote' +export type {} from '@deepseek-ai/dsh-client-ui-session-status/remote' import sessionRemote from '@deepseek-ai/dsh-api-session-controller/remote' import jobRemote from '@deepseek-ai/dsh-api-job-controller/remote' import workspaceRemote from '@deepseek-ai/dsh-api-workspace-controller/remote' @@ -203,7 +205,8 @@ export async function apply(ctx: Context): Promise<() => Promise> { toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, - permissionPresetsRemote, subagentsRemote, sessionRemote, jobRemote, workspaceRemote, workspaceFilesRemote, terminalRemote, + permissionPresetsRemote, subagentsRemote, sessionRemote, sessionStatusRemote, jobRemote, + workspaceRemote, workspaceFilesRemote, terminalRemote, officeKitRemote, userQuestionsRemote, webRemote, ]) { disposers.push(await ctx.remote.$mount(contribution)) diff --git a/packages/api/session-controller/src/client/transport.ts b/packages/api/session-controller/src/client/transport.ts index 554eec515e..cc115f30cc 100644 --- a/packages/api/session-controller/src/client/transport.ts +++ b/packages/api/session-controller/src/client/transport.ts @@ -7,6 +7,7 @@ import { RemoteSnapshotStream, RemoteStreamCarrierError, type ClientRemote, + type RemoteStreamCarrierFailure, type RemoteJournalChange, type RemoteJournalFrame, } from '@deepseek-ai/dsh-api-gateway/client' @@ -91,7 +92,7 @@ export interface SessionControlStreamOptions { /** Apply a complete baseline or one later update. */ readonly accept: (frame: SessionControlFrame) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal business or protocol failure. */ readonly failed: (error: unknown) => void } @@ -101,7 +102,7 @@ export interface SessionEventStreamOptions { /** Apply one complete event-window change. */ readonly publish: (change: SessionJournalChange) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal stream, page, or protocol failure after opening. */ readonly failed: (error: unknown) => void } diff --git a/packages/api/terminal-controller/src/client/model.ts b/packages/api/terminal-controller/src/client/model.ts index b1a87d8ae0..7ff08cb237 100644 --- a/packages/api/terminal-controller/src/client/model.ts +++ b/packages/api/terminal-controller/src/client/model.ts @@ -3,7 +3,7 @@ import { preferredShell, rememberShell } from './shell-preference.ts' import type { TerminalInventory } from './inventory.ts' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import { Deque } from '@deepseek-ai/dsh-deque' -import { RemoteStreamCarrierError, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import { isRemoteStreamCarrierFailure, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' import { RemoteError, remoteErrorOf, type RemoteResult, type RemoteStreamHandle, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -407,7 +407,7 @@ export class TerminalView { const failure = remoteErrorOf(error) const issue = failure?.code === 'terminal/view' ? failure.details.issue : failure?.code === 'terminal/limit-reached' ? 'terminalLimit' : failure?.code === 'terminal/unavailable' ? 'missingTerminal' : undefined if (!this.stopped() && issue === 'missingTerminal') this.inventory.remove(this.id) - this.patch({ phase: error instanceof RemoteStreamCarrierError ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) }) + this.patch({ phase: isRemoteStreamCarrierFailure(error) ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) }) } } diff --git a/packages/api/terminal-controller/tests/model.client.spec.ts b/packages/api/terminal-controller/tests/model.client.spec.ts index 6594514dbf..fb6790a7cf 100644 --- a/packages/api/terminal-controller/tests/model.client.spec.ts +++ b/packages/api/terminal-controller/tests/model.client.spec.ts @@ -287,6 +287,15 @@ it('classifies a discovery carrier failure as disconnected and supports explicit expect(remote.create).toHaveBeenCalledOnce() }) +it('classifies a Host RemoteError carrying the carrier code as failed, not disconnected', async () => { + const { model, remote } = fixture() + vi.mocked(remote.environment).mockRejectedValueOnce( + new RemoteError('gateway/carrier-lost' as never, 'host reused the carrier code', {} as never), + ) + await model.refresh() + expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'host reused the carrier code' }) +}) + it('retains state when disposal overtakes successful allocation or a failed discovery', async () => { for (const operation of ['creation', 'discovery'] as const) { const { model, remote } = fixture() diff --git a/packages/api/workspace-controller/src/client/index.ts b/packages/api/workspace-controller/src/client/index.ts index 3bbf4670a0..7f8246aa66 100644 --- a/packages/api/workspace-controller/src/client/index.ts +++ b/packages/api/workspace-controller/src/client/index.ts @@ -5,6 +5,7 @@ import { RemoteSnapshotStream, RemoteStreamCarrierError, type ClientRemote, + type RemoteStreamCarrierFailure, } from '@deepseek-ai/dsh-api-gateway/client' import type { WorkspaceFollowFrame, WorkspaceFollowIncrement } from '../types.ts' import type { WorkspaceFollowSink } from './model.ts' @@ -64,7 +65,7 @@ export interface WorkspaceStateStreamOptions { /** Destinations for decoded Workspace state operations. */ readonly accept: WorkspaceFollowSink /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal business or protocol failure. */ readonly failed: (error: unknown) => void } diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 47049ce8de..6af70f5ae7 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -276,7 +276,8 @@ - id: ui-session name: '@deepseek-ai/dsh-client-ui-session' - # Session status table behind ctx.uiSession.sessionStatus and useSessionStatus. + # Host reading records (ctx.sessionStatus) and the Session status table behind + # ctx.uiSession.sessionStatus and useSessionStatus. - id: ui-session-status name: '@deepseek-ai/dsh-client-ui-session-status' diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 008dfa67de..41d0bee797 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -37,7 +37,7 @@ The `/client` entrypoint of a UI plugin package is its public browser API, not a 1. **A UI plugin exports no values beyond what cordis loading needs** — `apply` / `inject` (and `Config` where present), plus store factories consumed type-only by components (`ReturnType`). Shared types (owner data, injected values, composed prop aliases) may also be exported. Implementation components, pure helpers, constants, and store handles stay internal. Adding any new value export requires user sign-off, not a matching consumer. 2. **Same-package tests import internals directly** — relative `../src/client/xxx.ts` from package tests, or the `./src/*` subpath where a spec lives outside the package. Never widen the public API to make a test compile. -3. **A feature plugin MUST NOT runtime-import or re-export another feature plugin's values, and MUST NOT declare `dsh.client.external` to obtain them.** Shared declarations use `import type`; behavior crosses packages through injected Cordis services, and UI crosses packages through slots. If neither fits, stop and escalate — do not add an export to unblock yourself. Shared runtime code belongs only in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package; transport and generated API assemblies keep their explicit infrastructure edges. +3. **A feature plugin MUST NOT runtime-import or re-export another feature plugin's values, and MUST NOT declare `dsh.client.external` to obtain them.** Shared declarations use `import type`; behavior crosses packages through injected Cordis services, and UI crosses packages through slots. If neither fits, stop and escalate — do not add an export to unblock yourself. Shared runtime code belongs only in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package; a feature plugin may request a `packages/api/` row's runtime values through `dsh.client.external`, and transport and generated API assemblies keep their explicit infrastructure edges. ## ctx discipline (components never see ctx) @@ -81,7 +81,7 @@ Client business code may statically read `process.env.DSH_CLIENT_*`; every refer A dynamic browser half either carries a module privately or requests the shared module-table identity. The client baseline is centralized in [`web/src/platform.ts`](web/src/platform.ts): `PLATFORM_MODULES` names shell-seeded React, Cordis, selected third-party libraries, and static Client libraries; `PRELOADED_CLIENT_EXTERNALS` is reserved for dynamic rows whose factories must arrive before shell boot and is empty when no such row exists. 1. **Baseline externals are implicit for every dynamic bundle.** Do not repeat entries from `PLATFORM_MODULES` in `dsh.client.external`; npm dependency declarations still follow the dependency rules above. -2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Only infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table. Declare the exact import specifier; only a trailing `/client` aliases the package row. +2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table; a feature plugin may request only rows under `packages/api/`. Declare the exact import specifier; only a trailing `/client` aliases the package row. 3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request. 4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. 5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 0ae9892b80..6d52c7f559 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 292a25cf1a426b56 - zh: ca765789a28289f8 + en: 45c1d8a1e1f44425 + zh: 47a5199bca1e7836 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index c7744a38b3..4efbbb0710 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -39,7 +39,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-renderer/`](ui-renderer/README.md) | Binds slot data to React and mounts the assembled application | `ctx.uiRenderer` | | [`ui-slots/`](ui-slots/README.md) | Defines typed extension Slots and reusable Component Factories | — | | [`ui-session/`](ui-session/README.md) | Adapts Session Controller state into standard Slot sources and hooks | — | -| [`ui-session-status/`](ui-session-status/README.md) | Combines running state, the effective pending interaction, and completion reminders into the Session status table behind `useSessionStatus` | `ctx.uiSession.sessionStatus` | +| [`ui-session-status/`](ui-session-status/README.md) | Keeps reading reminders in Host memory and combines running state, the effective pending interaction, and shared reminders into the Session status table behind `useSessionStatus` | `ctx.sessionStatus` / `ctx.uiSession.sessionStatus` | | [`ui-theme/`](ui-theme/README.md) | Applies the selected color theme | — | | [`ui-primitives/`](ui-primitives/README.md) | Provides shared React controls, icons, and content renderers | — | | [`ui-attachment/`](ui-attachment/README.md) | Registers composer and message-image attachment presentation | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 67fba60515..1bb3677465 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -39,7 +39,7 @@ kind: "package-group" | [`ui-renderer/`](ui-renderer/README.zh.md) | 将 slot 数据绑定到 React,并挂载组装完成的应用 | `ctx.uiRenderer` | | [`ui-slots/`](ui-slots/README.zh.md) | 定义类型化扩展 Slots 与可复用 Component Factory | — | | [`ui-session/`](ui-session/README.zh.md) | 把会话控制器状态适配为标准 Slot source 与钩子 | — | -| [`ui-session-status/`](ui-session-status/README.zh.md) | 把运行状态、生效的待交互请求和完成提醒汇总为会话状态表,并通过 `useSessionStatus` 提供 | `ctx.uiSession.sessionStatus` | +| [`ui-session-status/`](ui-session-status/README.zh.md) | 在宿主内存中保存阅读提醒,并把运行状态、生效的待交互请求和共享提醒汇总为会话状态表,通过 `useSessionStatus` 提供 | `ctx.sessionStatus` / `ctx.uiSession.sessionStatus` | | [`ui-theme/`](ui-theme/README.zh.md) | 应用所选颜色主题 | — | | [`ui-primitives/`](ui-primitives/README.zh.md) | 提供共享 React 控件、图标与内容渲染器 | — | | [`ui-attachment/`](ui-attachment/README.zh.md) | 注册输入框与消息图片的附件呈现 | — | diff --git a/packages/client/product-analytics/tests/collection.client.spec.ts b/packages/client/product-analytics/tests/collection.client.spec.ts index bdf5e7e5c5..b94a60921b 100644 --- a/packages/client/product-analytics/tests/collection.client.spec.ts +++ b/packages/client/product-analytics/tests/collection.client.spec.ts @@ -95,7 +95,7 @@ it('fails closed on stream loss and accepts a fresh policy after reconnection', const b = await setup() b.options().open(new AbortController().signal) expect(b.options().ended(true).message).toContain('policy stream ended') - b.options().carrierFailed?.(new Error('offline')) + b.options().carrierFailed?.(Object.assign(new Error('offline'), { code: 'gateway/carrier-lost' as const })) expect(b.ctx.productAnalytics.enabled).toBe(false) await b.policy(true) await b.fail() diff --git a/packages/client/ui-account-notifications/tests/apply.client.spec.ts b/packages/client/ui-account-notifications/tests/apply.client.spec.ts index ba0b42bfd2..d6c5918e68 100644 --- a/packages/client/ui-account-notifications/tests/apply.client.spec.ts +++ b/packages/client/ui-account-notifications/tests/apply.client.spec.ts @@ -297,7 +297,9 @@ it('clears notifications and stops polling when the account carrier fails', asyn const open = c.ctx.remote.$stream.bind(c.ctx.remote) let fail: (() => void) | undefined vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { - if (options.name === 'account') fail = () => { options.carrierFailed?.(new Error('connection lost')) } + if (options.name === 'account') fail = () => { + options.carrierFailed?.(Object.assign(new Error('connection lost'), { code: 'gateway/carrier-lost' as const })) + } return open(options) }) await c.reload(SELF) diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index fd72dbc593..759d52d183 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -19,7 +19,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../../api/workspace-controller/tsconfig.client.json" diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 662fc787a4..828d2ce4f7 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -21,8 +21,8 @@ en: 54c5085d03bf4c53 zh: 6b5114206ca545f3 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: 8265fa792c6fd9ec - zh: 600d2af4d5a3d183 + en: 69acdb3375548a62 + zh: c392c11faf88938f /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: en: e2649937f077d4e0 zh: 6ad604cb5adfc16b diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 5c817b94b2..5479cd773e 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -97,7 +97,7 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconMailReadOutlineRegular`/`Medium` show an open envelope; `IconMailUnreadOutlineRegular`/`Medium` show a closed envelope with an unread dot. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. It stays hidden until its first fit, prefers the requested side, then tries the opposite and perpendicular sides, sliding along the anchor without covering it when a side fits. Horizontal placements keep a 10px gap; vertical placements use `gap` (8px by default). Width and height stay within a 12px viewport margin; text wraps, and content taller than the viewport scrolls when pinned. If no side fits, a stable viewport-bounded fallback can overlap the anchor. Viewport resize refreshes the anchor coordinates; label-size changes reuse them. Fitting does not synchronously measure the bubble or trigger a React render. Touch presses dismiss unpinned hints and do not trigger hover hints, including compatibility mouse events. Mouse entry opens hints only while `(any-hover: hover)` reports an available hover-capable input, excluding iOS mouse entry caused by a tapped icon changing. Keyboard focus and explicit click-to-open explanations remain available on touch-only devices. Opt-in `openOnClick` lets an informational button pin the bubble by click or tap and associates it with the anchor description. Another click or tap, Escape, Tab, or an outside pointerdown closes it. Ordinary action buttons execute their action directly without a touch tooltip. Opt-in `onlyWhenClipped` shows the bubble only when the anchor or an HTML element inside it overflows horizontally when the bubble is about to show, so a label that repeats ellipsis-cut text appears only while it adds information. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f3e1c1719a..407d9aaec0 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -97,7 +97,7 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconMailReadOutlineRegular`/`Medium` 使用打开的信封,`IconMailUnreadOutlineRegular`/`Medium` 使用带未读圆点的闭合信封。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前保持隐藏,优先使用指定方向,再尝试相反方向和垂直于该方向的两侧;只要某一侧容得下,就沿锚点平移而不遮挡锚点。左右放置保留 10px 间距,上下放置使用 `gap`(默认 8px)。宽高限制在视口内并保留 12px 边距;文本自动换行,超出视口高度的内容在固定气泡后可滚动。若所有方向都放不下,则使用稳定的视口内回退位置,可能遮挡锚点。视口尺寸变化会重新读取锚点坐标,标签尺寸变化则复用坐标;定位不会同步测量气泡,也不会触发 React 渲染。 触摸按下会关闭未固定的提示,且不会触发悬停提示,包括触摸后的兼容鼠标事件。只有 `(any-hover: hover)` 表明存在可悬停的输入设备时,鼠标进入才会打开提示,从而排除 iOS 因已点击图标变化而生成的鼠标进入事件。仅有触摸输入的设备仍可使用键盘聚焦提示和显式点击打开的说明。信息按钮可显式启用 `openOnClick`,通过鼠标或触摸点击固定气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮在触摸点击时直接执行操作,不显示 Tooltip。可选的 `onlyWhenClipped` 只在气泡即将显示时锚点或其内部某个 HTML 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index b5f7a16028..dc438249f4 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -20,6 +20,8 @@ interface IconArtwork { /** Default artwork keyed by glyph name; symbol ids derive from these keys. */ export const ICON_ARTWORK = { + 'mail-unread-outline': { size: 16, svg: strokeWidth => `` }, + 'mail-read-outline': { size: 16, svg: strokeWidth => `` }, 'layers-outline': { size: 16, svg: strokeWidth => `` }, 'save-outline': { size: 16, svg: strokeWidth => `` }, 'new-chat-outline': { size: 16, svg: strokeWidth => `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 4d28b0376a..4bb49d1352 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -90,6 +90,18 @@ export const IconCheckOutlineRegular = productIcon('check-outline', 'regular') /** Medium IconCheckOutline artwork with a 1.3px stroke. */ export const IconCheckOutlineMedium = productIcon('check-outline', 'medium') +/** Closed envelope with an unread dot, using the regular product stroke. */ +export const IconMailUnreadOutlineRegular = productIcon('mail-unread-outline', 'regular') + +/** Closed envelope with an unread dot, using the medium product stroke. */ +export const IconMailUnreadOutlineMedium = productIcon('mail-unread-outline', 'medium') + +/** Open envelope for read content, using the regular product stroke. */ +export const IconMailReadOutlineRegular = productIcon('mail-read-outline', 'regular') + +/** Open envelope for read content, using the medium product stroke. */ +export const IconMailReadOutlineMedium = productIcon('mail-read-outline', 'medium') + /** Regular one-pixel IconBranchOutline artwork. */ export const IconBranchOutlineRegular = productIcon('branch-outline', 'regular') diff --git a/packages/client/ui-session-status/README.i18n.yaml b/packages/client/ui-session-status/README.i18n.yaml index bdce0fb16c..c691b64c26 100644 --- a/packages/client/ui-session-status/README.i18n.yaml +++ b/packages/client/ui-session-status/README.i18n.yaml @@ -3,29 +3,35 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-session-status/README.md /: - en: 11efe93e9b428342 - zh: 56d90a359ee86ad5 + en: dc68a4aaa22727ac + zh: aef571e08a364bf1 /deepseek-ai-dsh-client-ui-session-status: en: d572f680cca905e6 zh: 7c397a1fb746b47f /deepseek-ai-dsh-client-ui-session-status/summary: - en: a3e8fe090a557c9b - zh: 782500fb80b92712 + en: 5fe776aee839b428 + zh: 5c183742a98dded0 /deepseek-ai-dsh-client-ui-session-status/table-of-contents: - en: 3e7914c761a1310c - zh: 82c46d3a4d5e6a55 -/deepseek-ai-dsh-client-ui-session-status/status-table: - en: 4c1c64a9e5aa133d - zh: 9248ed3f64a4ebc9 + en: d152484eb41ac6b4 + zh: 7b30b973a849247d +/deepseek-ai-dsh-client-ui-session-status/use-this-package: + en: fe9e33d12e5df30e + zh: 5037b80cad259f47 +/deepseek-ai-dsh-client-ui-session-status/understand-the-implementation: + en: 64919e36946e9fa8 + zh: e6b2d66e98f2bf38 +/deepseek-ai-dsh-client-ui-session-status/further-exploration: + en: e1bb29cafbeee6ec + zh: 6b9af92c1ef2b0e5 /deepseek-ai-dsh-client-ui-session-status/model-experience: - en: 687076082426c060 - zh: 5888fcd520d0e53e + en: 745f3b288309a4b3 + zh: e4150220b50a0338 /deepseek-ai-dsh-client-ui-session-status/model-experience/kv-cache-effect: - en: 99bd3bc7d244944a - zh: 0021893ed90b2686 + en: a4bc54a4825f89d2 + zh: 1a96ffe54bc0192e /deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work: - en: 52d467a078cc3486 - zh: c373685b879ad6de + en: ac174b1d3bdc68aa + zh: 6ece23133dc7dc87 /deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 - zh: e88aeb617ffb74ea + zh: 6df6019931844fb2 diff --git a/packages/client/ui-session-status/README.md b/packages/client/ui-session-status/README.md index 6973059556..7fe2368342 100644 --- a/packages/client/ui-session-status/README.md +++ b/packages/client/ui-session-status/README.md @@ -1,56 +1,105 @@ --- -description: "Client Session status table and useSessionStatus hook: running state, the effective pending interaction, and completion reminders by Session." +description: "Client Session status table and useSessionStatus hook over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one running Host." kind: "package-reference" --- + # @deepseek-ai/dsh-client-ui-session-status English | [中文](README.zh.md) ## Summary -Use this package to read each Session's running state, highest-precedence pending interaction, and completion reminder from one Client status table. Components read the table through the `useSessionStatus` root hook; Client plugins read it as `ctx.uiSession.sessionStatus`. The package has no configuration fields, Host behavior, or persistent storage. +Show each Session's running state, highest-precedence pending interaction, and read or unread reminder from one Client status table. Reminders come from reading records this package keeps in Host memory: they survive a browser refresh while the Host remains running, and connected clients share manual marks and acknowledgements, including completions that occur while every client is offline. Reading marks do not change conversation history or model requests. ## Table of Contents -- [Status table](#status-table) +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) - [Model Experience](#model-experience) - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - [Dev Note](#dev-note) ----- - -## Status table + +## Use this package -The Web bundle loads this plugin after [`dsh-client-ui-session`](../ui-session/README.md) and requires it at startup; a composition that loads ui-session without this package has no status table and no `useSessionStatus` hook. A plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession.sessionStatus'` to its `inject` list; without it, Cordis rejects the property read. A plugin whose components call `useSessionStatus` injects it as well, so the plugin unloads and reloads with the hook. The member is declared on ui-session's `UiSessionService`, the type of `ctx.uiSession`; a value annotated as the `UiSession` class does not show it. +The Web bundle's single `ui-session-status` row loads both faces: the Host reading service `ctx.sessionStatus` and, after [`dsh-client-ui-session`](../ui-session/README.md), the Client plugin, which the Web client requires at startup. A composition without this package has no status table and no `useSessionStatus` hook, and profiles without the Web bundle run no reading service. The package has no configuration fields or persistent storage. Restarting the Host or reloading this plugin discards every record: history reads as read again, and no earlier turn outcome survives. + +Use the Session row menu to **Mark as read** or **Mark as unread**. All clients connected to that Host share the result; a failed operation leaves the previous reminder visible and reports failure. A completed, failed, or cancelled turn creates an unread reminder. Existing history starts read when first observed. Opening a Session in a visible, focused main view acknowledges its loaded completion after a rendering frame. Switching the main view to a Session, including restoring it after a page reload, clears its existing manual reminder after the content arrives. Window focus and further activity in the open Session preserve manual unread. Unread reminders do not imply task success and remain independent of running and pending-interaction status. + +Components read the status table through the `useSessionStatus` root hook. A Client plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession'` and `'uiSession.sessionStatus'` to its `inject` list; without them, Cordis rejects the property read. A plugin whose components call `useSessionStatus` injects `'uiSession.sessionStatus'` as well, so the plugin unloads and reloads with the hook. The member is declared on ui-session's `UiSessionService`, the type of `ctx.uiSession`; a value annotated as the `UiSession` class does not show it. | Member | Use | |---|---| -| `getSnapshot()` | Status by Session identity; the snapshot keeps its reference until a status fact changes | -| `subscribe(listener)` | Observe published changes; a throwing listener is reported without stopping later listeners | +| `getSnapshot()` / `subscribe(listener)` | Status by Session identity; the snapshot keeps its reference until a status fact changes, and a throwing listener is reported without stopping later listeners | +| `mark(sessionId, unread)` | Mark a Session read or unread; rejects while reading is not synchronized or when the Host rejects the mark | +| `readingReady` | Whether the current Host reading baseline has arrived | -Each `SessionStatus` has three independent fields: +Each `SessionStatus` has four fields: | Field | Source | |---|---| | `running` | Host Session list baselines and `api-session/status` events; absent until either establishes it. Subagent catalog rows and retained subagent fallback rows do not establish it. | -| `pendingInteraction` | The same object `ctx.uiSession.pendingInteractions` publishes for that Session. Domain plugins keep registering requests through `ctx.uiSession.registerPendingInteraction(precedence)`. | -| `completionUnread` | A stop this Client observed while the main view did not retain the Session, including an idle event that arrives before the first list baseline. The reminder clears when the main view retains the Session, the Session runs again, or a ready list no longer contains it. | +| `pendingInteraction` | The same object `ctx.uiSession.pendingInteractions` publishes for that Session. Domain plugins register requests through `ctx.uiSession.registerPendingInteraction(precedence)`. | +| `completionUnread` | The Host reading record carries a manual unread mark, or its latest completed turn is beyond the read turn; that unacknowledged turn is not shown while the visible, focused main view retains the Session and it is open | +| `completionFailed` | The Session is unread and its latest completed turn ended with an execution error this Host observed | + +The Host face serves the `sessionStatus` Remote namespace with `mark` and `follow`; its failures use `session-status/not-found` and `session-status/unavailable`. The Client keeps its copy of the reading records private: no Client service other than `ctx.uiSession.sessionStatus` exposes them. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +Reading records live in the Host service's Map and change only from `turn/end` events and explicit marks. Each record holds `completedTurn`, `failed`, `readTurn`, and `manualUnread`. Marks do not change execution facts or flush the Session log. + +The Client submits the completed turn it has seen. The Host advances `readTurn` monotonically up to that position, bounded by its known completion; automatic acknowledgements preserve `manualUnread`. Explicit read and unread actions clear or set that flag in Host processing order. Cold menu actions check metadata without opening history. + +Only the ordered subscription updates Client records; mutation replies report success or failure. Streams send an accessible baseline followed by whole-record changes. The Client follows them through `ctx.remote.$stream` and the Gateway's `RemoteSnapshotStream` only while `ctx.remoteAccess` allows `sessionStatus/follow`, so a LiveShare viewer opens no stream and keeps `readingReady` false; a normal stream end returns an error with the Gateway's `gateway/carrier-lost` code, so the stream reconnects and the next baseline replaces the records. The existing access stream ends a reading generation when grants change, so reconnecting clients receive a fresh baseline. Disposal closes followers and discards records; pending metadata lookups cannot commit afterward. + +The Client plugin combines Session list baselines, `api-session/status` events, ui-session's pending interactions, and reading records into the status table, provided as `uiSession.sessionStatus` beneath `ctx.uiSession`. It also acknowledges the Session retained by the main view. It waits for a visible, focused window, an open Session, a rendering frame, and a loaded body that reaches the completed turn. Window focus only advances the natural read position. When the main view switches to a different Session, the plugin checks that Session's manual unread mark once the reading baseline is ready and clears an existing mark with the next acknowledgement; a replaced binding for the same Session is not a switch, and later acknowledgements keep manual marks. + +
+ +----- + + +## Further Exploration + +- [Session reading memory decision](../../../.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md) — package structure, Host memory ownership, concurrency, and deferred persistence. +- [Session UI adapter](../ui-session/README.md) — the parent `ctx.uiSession` service and pending-interaction registration. +- [Workspace browser](../ui-workspace/README.md) — row menu and reminders. + +----- ## Model Experience -None, as the status table adds no tools, prompts, or Session events. +None, as reading records and the status table add no tools, prompts, or Session events. #### KV Cache effect -None; the status table does not assemble model requests. +None; reading marks and the status table do not assemble model requests. ## Known Limitations and Deferred Work -- **Completion reminders belong to one Client** — another browser tab or a page reload starts without the reminders this Client recorded. +Reading state has these operational limits: + +- **Concurrent explicit marks** — the last action processed by the Host wins. Delayed explicit read actions can clear a newer manual unread mark; there is no revision comparison. Automatic acknowledgements (`acknowledge`) never clear manual unread or read beyond their submitted position. The only automatic path that clears manual unread is the main-view switch rule above, including restoring the main view after a page reload; it applies only when that page is visible, focused, and showing the Session. +- **One Host process** — separate Host processes or machines do not synchronize with each other. +- **Host restart or plugin reload** — all reading state resets and history reads as read. A turn that failed before the restart keeps no outcome, so marking such a Session unread shows the ordinary unread reminder. Reloading the Host plugin ends every reading stream; if the replacement service is not yet serving when the Client reconnects, the Client receives a terminal error, disables reading commands, and recovers only after a page reload. Persistent reminders require the separately tracked follow-up; this package writes no read-state files. +- **Web profiles only** — the row lives in the Web bundle, so profiles without it run no reading service. +- **Metadata and transport failures** — a failed metadata lookup leaves reading state unchanged. A terminal stream or protocol failure disables reading commands until the page reloads; ordinary carrier loss reconnects automatically. +- **Unloaded and archived Sessions** — records for Sessions unloaded from memory remain until the service stops; reclaiming them requires a Session deletion lifecycle. Archived rows hide their unread styling and status, read as read, and offer no reading mark in the row menu or shortcut. +- **Main-view visibility** — main-view retention does not distinguish every settings or auxiliary panel, so acknowledgement can run, and the status table hides the open Session's unacknowledged completion, while such a panel covers the Conversation; that refinement belongs to the notification work. +- **No message counts or read receipts for other people** — the state belongs to the Host's owner and records Session-level reminders. LiveShare viewers cannot read or change it. ### Dev Note diff --git a/packages/client/ui-session-status/README.zh.md b/packages/client/ui-session-status/README.zh.md index fa79a8c760..f6b767304e 100644 --- a/packages/client/ui-session-status/README.zh.md +++ b/packages/client/ui-session-status/README.zh.md @@ -1,62 +1,111 @@ --- -description: "Client 会话状态表与 useSessionStatus hook:按会话提供运行状态、生效的待交互请求和完成提醒。" +description: "基于宿主阅读记录的 Client 会话状态表与 useSessionStatus hook:运行状态、生效的待交互请求,以及连接同一运行中宿主的前端共享的已读、未读提醒。" kind: "package-reference" --- + # @deepseek-ai/dsh-client-ui-session-status [English](README.md) | 中文 ## 概述 -使用本包可从同一张 Client 状态表读取每个 Session 的运行状态、优先级最高的待交互请求和完成提醒。组件通过根 hook `useSessionStatus` 读取该表;Client 插件以 `ctx.uiSession.sessionStatus` 读取。本包没有配置字段、Host 行为或持久化存储。 +通过同一张前端状态表显示每个会话的运行状态、优先级最高的待交互请求和已读、未读提醒。提醒来自本包保存在宿主内存中的阅读记录:只要宿主仍在运行,刷新浏览器后提醒仍然保留;已连接的前端共享手动标记和阅读确认,也能收到所有前端离线期间完成的会话提醒。阅读标记不改变对话历史或模型请求。 ## 目录 -- [状态表](#status-table) +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步阅读](#further-exploration) - [模型体验](#model-experience) -- [已知限制与暂缓事项](#known-limitations-and-deferred-work) +- [已知限制与后续工作](#known-limitations-and-deferred-work) - [开发备注](#dev-note) ----- - -## 状态表 + +## 使用本包 -Web bundle 在 [`dsh-client-ui-session`](../ui-session/README.zh.md) 之后加载本插件,并把它列为启动必需入口;只加载 ui-session、不加载本包的组合没有状态表,也没有 `useSessionStatus` hook。读取 `ctx.uiSession.sessionStatus` 的插件需要在 `inject` 列表中加入 `'uiSession.sessionStatus'`;否则 Cordis 会拒绝该属性读取。组件调用 `useSessionStatus` 的插件也注入它,使插件随该 hook 一起卸载和重新加载。该成员声明在 ui-session 的 `UiSessionService`(`ctx.uiSession` 的类型)上;标注为 `UiSession` class 的值看不到它。 +Web bundle 中唯一的 `ui-session-status` 行同时加载两个面:宿主阅读服务 `ctx.sessionStatus`,以及在 [`dsh-client-ui-session`](../ui-session/README.zh.md) 之后加载、被 Web 前端列为启动必需入口的前端插件。不加载本包的组合没有状态表,也没有 `useSessionStatus` hook;不含 Web bundle 的 profile 不运行阅读服务。本包没有配置项,也不使用持久化存储。重启宿主或重新加载本插件会丢弃全部记录:历史重新按已读处理,之前的轮次结果不再保留。 + +通过会话行菜单**标为已读**或**标为未读**,连接同一宿主的前端会共享结果;操作失败时保留原有提醒并报告失败。本轮宿主运行期间结束的轮次都会产生未读提醒,无论正常完成、失败还是取消。失败标记只适用于本轮宿主看到失败的轮次;宿主启动前就结束的失败无法得知。已有历史默认为已读。在可见且聚焦的窗口中打开会话后,主视图会在一个渲染帧之后确认已加载的完成内容。主视图切换到某个会话(包括刷新页面后恢复主视图)时,会在内容到达后清除其已有的手动提醒。窗口聚焦和在已打开会话中的其他操作都会保留手动未读。未读提醒不表示任务成功,与运行和待交互状态分别显示。 + +组件通过根 hook `useSessionStatus` 读取状态表。读取 `ctx.uiSession.sessionStatus` 的前端插件需要在 `inject` 列表中加入 `'uiSession'` 和 `'uiSession.sessionStatus'`;否则 Cordis 会拒绝该属性读取。组件调用 `useSessionStatus` 的插件也注入 `'uiSession.sessionStatus'`,使插件随该 hook 一起卸载和重新加载。该成员声明在 ui-session 的 `UiSessionService`(`ctx.uiSession` 的类型)上;标注为 `UiSession` class 的值看不到它。 | 成员 | 用途 | |---|---| -| `getSnapshot()` | 按 Session 身份索引的状态;状态事实变化前快照保持同一引用 | -| `subscribe(listener)` | 观察已发布的变化;抛错的 listener 会被报告,不会阻止后续 listener | +| `getSnapshot()` / `subscribe(listener)` | 按会话身份索引的状态;状态事实变化前快照保持同一引用,抛错的 listener 会被报告,不会阻止后续 listener | +| `mark(sessionId, unread)` | 把会话标为已读或未读;阅读状态未同步或宿主拒绝标记时拒绝 | +| `readingReady` | 是否已取得当前宿主的阅读基线 | -每个 `SessionStatus` 有三个相互独立的字段: +每个 `SessionStatus` 有四个字段: | 字段 | 来源 | |---|---| -| `running` | Host 会话列表基线和 `api-session/status` 事件;两者都未建立之前为缺省。Subagent 目录行和已保留子会话的 fallback 行不会建立它。 | -| `pendingInteraction` | `ctx.uiSession.pendingInteractions` 为该 Session 发布的同一个对象。领域插件仍通过 `ctx.uiSession.registerPendingInteraction(precedence)` 登记请求。 | -| `completionUnread` | 本 Client 在主视图未保留该 Session 时观察到的一次停止,包括首个列表基线之前到达的空闲事件。主视图保留该 Session、该 Session 再次运行,或就绪列表不再包含它时,提醒清除。 | +| `running` | 宿主会话列表基线和 `api-session/status` 事件;两者都未建立之前为缺省。Subagent 目录行和已保留子会话的 fallback 行不会建立它。 | +| `pendingInteraction` | `ctx.uiSession.pendingInteractions` 为该会话发布的同一个对象。领域插件通过 `ctx.uiSession.registerPendingInteraction(precedence)` 登记请求。 | +| `completionUnread` | 宿主阅读记录带有手动未读标记,或其最近完成的轮次超过已读轮次;可见且聚焦的主视图正在显示该会话且其已打开时,不显示尚未确认的该轮次 | +| `completionFailed` | 会话未读,且最近完成的轮次以本宿主观察到的执行错误结束 | + +宿主面通过 `sessionStatus` Remote 命名空间提供 `mark` 和 `follow`;失败使用 `session-status/not-found` 和 `session-status/unavailable`。前端保存的阅读记录副本是私有的:除 `ctx.uiSession.sessionStatus` 外,没有其他前端服务暴露这些记录。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +阅读记录放在宿主服务的 Map 中,只由 `turn/end` 事件和主动标记更新。每条记录包含 `completedTurn`、`failed`、`readTurn` 和 `manualUnread`。标记不会改变执行结果,也不会触发会话日志刷盘。 + +前端提交自己已看到的完成轮次。宿主只向前推进 `readTurn`,上限是提交位置与已知完成位置的较小值;自动确认保留 `manualUnread`。主动标为已读或未读按宿主处理顺序清除或设置该标记。冷会话的菜单操作只检查元数据,不打开历史。 + +只有有序订阅流更新前端记录,修改请求仅回复成功或失败。同步流先发送有权访问的完整快照,再推送完整记录。只有 `ctx.remoteAccess` 允许 `sessionStatus/follow` 时,前端才通过 `ctx.remote.$stream` 和 Gateway 的 `RemoteSnapshotStream` 跟随这些记录,因此 LiveShare 查看者不打开该流,`readingReady` 保持 false;流正常结束时返回带 Gateway `gateway/carrier-lost` code 的错误,因此流会重连,下一个快照替换记录。已有的访问流在授权变化时结束阅读订阅,前端重连后取得新快照。卸载会关闭订阅并清空记录,尚未返回的元数据查询不能再提交标记。 + +前端插件把会话列表基线、`api-session/status` 事件、ui-session 的待交互请求和阅读记录汇总为状态表,并以 `uiSession.sessionStatus` 的名字挂在 `ctx.uiSession` 下。它还确认主视图持有的会话。确认需要窗口可见且聚焦、会话已打开、经过一个渲染帧,且已加载的正文到达完成轮次。窗口聚焦只推进自然已读位置。主视图切换到另一个会话时,插件会在阅读基线就绪后检查该会话的手动未读标记,并在下一次确认时清除已有标记;同一会话只是更换 binding 不算切换,之后的确认保留手动标记。 + +
+ +----- + + +## 进一步阅读 + +- [会话阅读记忆决策](../../../.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md)——包结构、宿主内存归属、并发和暂缓的持久化。 +- [会话 UI 适配层](../ui-session/README.zh.md)——上级服务 `ctx.uiSession` 与待交互登记。 +- [工作区浏览器](../ui-workspace/README.zh.md)——会话菜单与提醒。 + +----- ## 模型体验 -无,因为状态表不添加工具、提示词或 Session 事件。 +无,阅读记录和状态表不添加工具、提示词或会话事件。 #### KV Cache 影响 -无;状态表不会组装模型请求。 +无;阅读标记和状态表不参与模型请求构建。 -## 已知限制与暂缓事项 +## 已知限制与后续工作 -- **完成提醒只属于一个 Client**——另一个浏览器标签页或刷新后的页面不会带上本 Client 记录的提醒。 +阅读状态有以下运行限制: + +- **并发主动标记**——以宿主最后处理的操作为准,不比较版本;延迟的主动已读可能清除较新的手动未读。自动确认(`acknowledge`)不会清除手动未读,也不会越过提交的阅读位置。唯一会自动清除手动未读的是上文的主视图切换规则,包括刷新后恢复主视图;它只在该页面可见、聚焦且正在显示该会话时生效。 +- **单个宿主进程**——不同宿主进程或机器之间不互相同步。 +- **宿主重启或插件重载**——全部阅读状态重置,历史按已读处理。重启前失败的轮次不保留结果,因此把这类会话标为未读时显示普通未读提醒。重载宿主插件会结束所有阅读流;前端重连时如果新服务尚未就绪,会收到终止错误并禁用阅读操作,只有刷新页面后才能恢复。持久化提醒由单独跟踪的后续需求负责;本包不写入阅读状态文件。 +- **仅 Web profile**——本包的行位于 Web bundle,不包含该行的 profile 不运行阅读服务。 +- **元信息和传输失败**——元信息查询失败不改变阅读状态。流或协议的终态失败会禁用阅读操作,直到刷新页面;普通连接中断会自动重连。 +- **已卸载和已归档的会话**——会话从内存卸载后,其记录保留到服务停止;回收记录需要会话删除生命周期。归档行隐藏未读样式和状态,按已读处理,行菜单和快捷键都不提供阅读标记。 +- **主视图可见性**——主视图保留信号不能区分所有设置或辅助面板,因此这类面板遮住对话时仍可能确认阅读,状态表也会隐藏该已打开会话尚未确认的完成轮次;该细化属于通知工作的范围。 +- **不提供消息计数或他人的阅读回执**——状态属于宿主的使用者,只记录会话级提醒。LiveShare 查看者不能读取或修改该状态。 ### 开发备注
-维护者工作上下文——点击展开 +维护者上下文——点击展开 无。 diff --git a/packages/client/ui-session-status/package.json b/packages/client/ui-session-status/package.json index be3bba1317..f6856b6ebc 100644 --- a/packages/client/ui-session-status/package.json +++ b/packages/client/ui-session-status/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-session-status", - "description": "Client Session status table: running state, the effective pending interaction, and completion reminders", + "description": "Client Session status table over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one Host", "version": "0.2.2-rc.2", "publishConfig": { "access": "public" @@ -18,17 +18,33 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts" + }, "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, "./src/*": "./src/*", "./package.json": "./package.json", "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { + "external": [ + "@deepseek-ai/dsh-api-gateway/client" + ], "inject": [ + "@deepseek-ai/dsh-api-gateway", + "@deepseek-ai/dsh-api-remote-access", "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-ui-renderer", @@ -42,20 +58,31 @@ "watch": "tsdown --watch" }, "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-deque": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.6.6" + }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-typert-registry": "workspace:*" }, "files": [ "locale/*.json", @@ -64,6 +91,11 @@ "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", "src" ] } diff --git a/packages/client/ui-session-status/src/client/acknowledge.ts b/packages/client/ui-session-status/src/client/acknowledge.ts new file mode 100644 index 0000000000..5c50563abf --- /dev/null +++ b/packages/client/ui-session-status/src/client/acknowledge.ts @@ -0,0 +1,103 @@ +/** Visible main-view acknowledgements over Host reading state. */ +import type { Context } from '@deepseek-ai/cordis' +import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +// Type-only: declares the `mainView` reference source. +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionReadModel } from './model.ts' + +/** + * Acknowledge loaded content after a rendering frame in the visible, focused main view. + * Switching the main view to a Session, including the first selection after a page load, clears that Session's + * manual reminder once its body arrives; window focus and a replaced binding for the same Session preserve it. + * Without a document there is no view to acknowledge, so nothing is installed. + * @param ctx - owning Client plugin Context. + * @param sessions - Session catalog and binding owner. + * @param reading - shared Host-confirmed reading state. + */ +export function installReadingAcknowledgements(ctx: Context, sessions: Pick, reading: Pick): void { + if (typeof document === 'undefined') return + let selected: SessionId | undefined + let binding: SessionBinding | undefined + let releaseBinding = (): void => {} + // The entered Session whose manual reminder the next acknowledgement clears; settled against a ready baseline. + let entered: SessionId | undefined + let attemptedTurn: number | undefined + let frame: number | undefined + let active = true + let pending: Promise | undefined + const visible = (): boolean => document.visibilityState === 'visible' && document.hasFocus() + const schedule = (): void => { + if (!active || frame !== undefined || !visible()) return + frame = requestAnimationFrame(() => { + frame = undefined + acknowledge() + }) + } + const acknowledge = (): void => { + const snapshot = reading.state.getSnapshot() + const record = selected === undefined ? undefined : snapshot.items[selected] + if (!visible() || !snapshot.ready || binding?.session.getSnapshot().openState !== 'open') return + if (record === undefined || pending !== undefined || attemptedTurn === record.completedTurn) return + const clearing = entered === record.sessionId + if (!clearing && record.completedTurn <= record.readTurn) return + const received = record.completedTurn === 0 || binding.eventSource.getSnapshot().entries.some(({ event }) => + (event.type === 'turn/end' && event.data.turn >= record.completedTurn) + || (event.type === 'turn/start' && event.data.turn > record.completedTurn)) + if (!received) return + attemptedTurn = record.completedTurn + entered = undefined + pending = reading.acknowledge(record.sessionId, record.completedTurn, clearing).catch((error: unknown) => { + console.error('[session-status] Reading acknowledgement could not be confirmed. Reopen the Session to refresh its state:', error) + }).finally(() => { pending = undefined; schedule() }) + } + const settleEntry = (): void => { + const snapshot = reading.state.getSnapshot() + if (snapshot.ready && entered !== undefined && !snapshot.items[entered]?.manualUnread) entered = undefined + } + const update = (): void => { + const list = sessions.list.getSnapshot() + const id = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0)?.id + const next = id === undefined ? undefined : sessions.binding(id) + if (id !== selected || next !== binding) { + releaseBinding() + if (id !== selected) { + entered = id + settleEntry() + } + selected = id + binding = next + attemptedTurn = undefined + const releaseSession = next?.session.subscribe(schedule) + const releaseEvents = next?.eventSource.subscribe(schedule) + releaseBinding = () => { releaseSession?.(); releaseEvents?.() } + } + schedule() + } + const focus = (): void => { + attemptedTurn = undefined + schedule() + } + ctx.effect(() => { + const releaseList = sessions.list.subscribe(update) + const releaseReading = reading.state.subscribe(() => { + settleEntry() + schedule() + }) + document.addEventListener('visibilitychange', focus) + window.addEventListener('focus', focus) + window.addEventListener('blur', focus) + update() + return async () => { + active = false + releaseList() + releaseReading() + releaseBinding() + document.removeEventListener('visibilitychange', focus) + window.removeEventListener('focus', focus) + window.removeEventListener('blur', focus) + if (frame !== undefined) cancelAnimationFrame(frame) + await pending + } + }, 'session-status: visible reading acknowledgement') +} diff --git a/packages/client/ui-session-status/src/client/index.ts b/packages/client/ui-session-status/src/client/index.ts index 588d5a2ba7..3d77cd11b2 100644 --- a/packages/client/ui-session-status/src/client/index.ts +++ b/packages/client/ui-session-status/src/client/index.ts @@ -1,21 +1,24 @@ -/** Client Session status plugin: the `uiSession.sessionStatus` service and the `useSessionStatus` root hook. */ +/** Client Session status plugin: the `uiSession.sessionStatus` service, the `useSessionStatus` root hook, and reading. */ import type { Context } from '@deepseek-ai/cordis' // Type-only: declares the `sessions` Controller service. import type {} from '@deepseek-ai/dsh-api-session-controller/client' // Type-only service merge for ctx.slots. import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { installReading } from './read.ts' import { UiSessionStatus } from './status.ts' export type { SessionStatus, SessionStatusSnapshot, UiSessionStatus, UseSessionStatus } from './status.ts' -/** Required Controller, Remote, renderer, and Session UI services. */ -export const inject = ['remote', 'sessions', 'slots', 'uiSession'] +/** Required Controller, Remote, generated reading namespace, access, renderer, and Session UI services. */ +export const inject = ['remote', 'remote.sessionStatus', 'remoteAccess', 'sessions', 'slots', 'uiSession'] /** - * Install `ctx.uiSession.sessionStatus` and publish it through the `useSessionStatus` root hook. + * Install `ctx.uiSession.sessionStatus`, publish it through the `useSessionStatus` root hook, and follow Host reading + * records into it. * @param ctx - Client root context. */ export function apply(ctx: Context): void { const status = new UiSessionStatus(ctx, ctx.sessions, ctx.uiSession.pendingInteractions) ctx.slots.provideRoot({ hooks: { sessionStatus: status } }) + installReading(ctx, status) } diff --git a/packages/client/ui-session-status/src/client/model.ts b/packages/client/ui-session-status/src/client/model.ts new file mode 100644 index 0000000000..9fe7e7f96e --- /dev/null +++ b/packages/client/ui-session-status/src/client/model.ts @@ -0,0 +1,73 @@ +/** React-free Client copy of the Host reading records; internal to the Session status plugin. */ +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/remote' +import type { SessionReadAction, SessionReadState } from '../types.ts' + +/** Reading records retained during reconnection; mutations require a ready baseline. */ +export interface SessionReadSnapshot { + readonly items: Readonly> + readonly ready: boolean +} + +/** Projects the ordered Host stream; mutation responses never replace reading records. */ +export class SessionReadModel { + /** Current reading records and baseline readiness, published synchronously on every change. */ + readonly state: SnapshotStore = createSnapshotStore( + { items: {}, ready: false }, { flush: 'sync' }, + ) + + /** @param remote - generated `sessionStatus` Remote methods. */ + constructor(private readonly remote: Pick) {} + + /** + * Replace the complete projection for a new connection. + * @param items - complete authoritative baseline for the new stream generation. + */ + replace(items: readonly SessionReadState[]): void { + this.state.set({ items: Object.fromEntries(items.map(item => [item.sessionId, item])), ready: true }) + } + + /** + * Accept the next committed record from the ordered subscription. + * @param item - Committed whole-record change. + */ + accept(item: SessionReadState): void { + const snapshot = this.state.getSnapshot() + this.state.set({ ...snapshot, items: { ...snapshot.items, [item.sessionId]: item } }) + } + + /** Retain the last projection while disabling writes until a new baseline. */ + disconnected(): void { + this.state.set({ ...this.state.getSnapshot(), ready: false }) + } + + /** + * Mark the Session through the latest completion known to this Client, without optimistically changing it. + * @param sessionId - known Session identity. + * @param unread - requested reminder state. + * @throws when no current baseline exists or the Host or carrier rejects; reconnect to refresh an unknown outcome. + */ + async mark(sessionId: SessionId, unread: boolean): Promise { + const throughTurn = this.state.getSnapshot().items[sessionId]?.completedTurn ?? 0 + await this.send(sessionId, unread ? { type: 'unread' } : { type: 'read', throughTurn }) + } + + /** + * Acknowledge content received by the visible Session view. + * @param sessionId - Known Session identity. + * @param throughTurn - Latest completed turn received in the Session body. + * @param clearManual - Clear the manual reminder of a Session the main view switched to. + */ + async acknowledge(sessionId: SessionId, throughTurn: number, clearManual: boolean): Promise { + await this.send(sessionId, { type: clearManual ? 'read' : 'acknowledge', throughTurn }) + } + + private async send(sessionId: SessionId, action: SessionReadAction): Promise { + const snapshot = this.state.getSnapshot() + if (!snapshot.ready) throw new Error('Reading state is unavailable. Reload the page to reconnect.') + const result = await this.remote.mark(sessionId, action) + if (!result.ok) throw result.error + } +} diff --git a/packages/client/ui-session-status/src/client/read.ts b/packages/client/ui-session-status/src/client/read.ts new file mode 100644 index 0000000000..16b21b958c --- /dev/null +++ b/packages/client/ui-session-status/src/client/read.ts @@ -0,0 +1,62 @@ +/** Host reading records installed under the Session status table: the access-gated stream and acknowledgements. */ +import type { Context } from '@deepseek-ai/cordis' +import { RemoteSnapshotStream, type RemoteStreamCarrierFailure } from '@deepseek-ai/dsh-api-gateway/client' +// Type-only: declares the `remoteAccess` Client service. +import type {} from '@deepseek-ai/dsh-api-remote-access/client' +// Type-only: declares the `sessions` Controller service. +import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionReadFrame } from '../types.ts' +import { installReadingAcknowledgements } from './acknowledge.ts' +import type { UiSessionStatus } from './status.ts' + +type SessionReadBaseline = Extract +type SessionReadChange = Extract + +const CARRIER_LOST: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost' + +/** + * Follow Host reading records into the status table's reading model and acknowledge reading in the visible main view. + * The stream runs only while the current Peer may follow it, so a LiveShare viewer opens no stream and keeps + * `readingReady` false; carrier reconnection replaces the complete reading baseline. + * @param ctx - Client root context with `remote`, `remoteAccess`, and `sessions`. + * @param status - status table whose reading model receives the records. + */ +export function installReading(ctx: Context, status: UiSessionStatus): void { + const reading = status.reading + installReadingAcknowledgements(ctx, ctx.sessions, reading) + // Each access grant runs one stream. Disposal stops failure reports and carrier retries at once, but a frame + // already handed to the consumer can still arrive, so a revoked or superseded stream's frames are discarded. + let active: object | undefined + const granted = (): boolean => active !== undefined + ctx.remoteAccess.whenAccess('sessionStatus/follow', function* () { + const token = {} + active = token + const current = (): boolean => active === token + const stream = ctx.remote.$stream({ + name: 'Session reading state', + open: signal => ctx.remote.sessionStatus.follow(signal), + carrierFailed: () => { reading.disconnected() }, + ended: (): RemoteStreamCarrierFailure => Object.assign( + new Error('Session reading state stream ended'), { code: CARRIER_LOST }, + ), + }) + const control = new RemoteSnapshotStream(stream, { + name: 'Session reading state', + isSnapshot: (frame): frame is SessionReadBaseline => frame.type === 'baseline', + replace: (frame) => { if (current()) reading.replace(frame.items) }, + update: (frame) => { if (current()) reading.accept(frame.state) }, + failed: (error) => { + reading.disconnected() + console.error('[session-status] Reminders could not be synchronized. Reload the page to reconnect:', error) + }, + }) + control.start() + yield async () => { + active = undefined + reading.disconnected() + await control.dispose() + // A later grant owns readiness once it starts; otherwise reading stays unavailable. + if (!granted()) reading.disconnected() + } + }) +} diff --git a/packages/client/ui-session-status/src/client/status.ts b/packages/client/ui-session-status/src/client/status.ts index 0e514f9033..80aeaf35cc 100644 --- a/packages/client/ui-session-status/src/client/status.ts +++ b/packages/client/ui-session-status/src/client/status.ts @@ -1,13 +1,16 @@ -/** Client Session status table: running state, the effective pending interaction, and completion reminders. */ +/** Client Session status table: running state, the effective pending interaction, and shared reading reminders. */ import { Service, type Context } from '@deepseek-ai/cordis' -import type { ISessions, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' +import type { ISessions, SessionBinding, SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' import { notifySubscribers } from '@deepseek-ai/dsh-client-store' import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only service merge for ctx.slots. +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' // Retains ui-session's Context and Slot prop declarations for every consumer of this face. export type {} from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { SessionReadModel } from './model.ts' /** Independent UI status facts for one Session identity. */ export interface SessionStatus { @@ -15,8 +18,13 @@ export interface SessionStatus { readonly running: boolean | undefined /** Highest-precedence domain request currently awaiting user interaction. */ readonly pendingInteraction: SessionPendingInteraction | undefined - /** Whether an observed stop outside the main view still needs acknowledgement. */ + /** + * Host-confirmed unread completion or explicit unread mark; an unacknowledged completion of the open Session the + * visible, focused main view retains is not shown until the view leaves it. + */ readonly completionUnread: boolean + /** Latest unread completion ended with an execution error this Host observed. */ + readonly completionFailed: boolean } /** Current UI status indexed by Session identity. */ @@ -39,37 +47,57 @@ declare module '@deepseek-ai/dsh-client-ui-session/client' { /** * Session status table provided as the `uiSession.sessionStatus` service and read as `ctx.uiSession.sessionStatus`. - * Completion reminders live only in this Client; the [status table reference](../../README.md#status-table) states - * when each field is set and cleared. + * Completion reminders come from the Host reading records shared by every Client of one Host; the + * [package reference](../../README.md#use-this-package) states when each field is set and cleared. */ export class UiSessionStatus extends Service implements HostObservable { private readonly running = new Map() - private readonly completionUnread = new Set() private statusSnapshot: SessionStatusSnapshot = new Map() + private viewedBinding: SessionBinding | undefined + private viewedOpenState: string | undefined + private releaseViewed = (): void => {} private readonly statusListeners = new Set<() => void>() + /** + * Package-internal Client copy of the Host reading records, which the reading installer follows into. + * @internal + */ + readonly reading: SessionReadModel + /** Whether reading marks can be sent: the current Host reading baseline has arrived. */ + readonly readingReady: HostObservable /** - * @param ctx - Client root context. - * @param sessions - Controller-owned Session catalog. + * @param ctx - Client root context; its generated `sessionStatus` Remote namespace sends reading marks. + * @param sessions - Controller-owned Session catalog and bindings. * @param pendingInteractions - effective pending request by Session, published by ui-session. */ constructor( ctx: Context, - private readonly sessions: Pick, + private readonly sessions: Pick, private readonly pendingInteractions: HostObservable>, ) { super(ctx, 'uiSession.sessionStatus') + const reading = new SessionReadModel(ctx.remote.sessionStatus) + this.reading = reading + this.readingReady = { + getSnapshot: () => reading.state.getSnapshot().ready, + subscribe: listener => reading.state.subscribe(listener), + } ctx.effect(() => { const disposeStatus = sessions.list.subscribe(() => { this.reconcileStatus() }) const disposeRemoteStatus = ctx.remote.$on('api-session/status', (sessionId, running) => { this.observeRunning(sessionId, running) }) const disposePending = pendingInteractions.subscribe(() => { this.publishStatus() }) + const disposeReading = reading.state.subscribe(() => { this.publishStatus() }) + const disposeView = watchViewVisibility(() => { this.publishStatus() }) this.reconcileStatus() return () => { disposeStatus() disposeRemoteStatus() disposePending() + disposeReading() + disposeView() + this.releaseViewed() } }, 'session-status: Session status table') } @@ -90,13 +118,18 @@ export class UiSessionStatus extends Service implements HostObservable { this.statusListeners.delete(listener) } } + /** + * Mark one Session read or unread through the latest completion known to this Client. + * @param sessionId - known Session identity. + * @param unread - requested reminder state. + * @throws when reading is not synchronized or the Host or carrier rejects; reconnect to refresh an unknown outcome. + */ + async mark(sessionId: SessionId, unread: boolean): Promise { + await this.reading.mark(sessionId, unread) + } + private observeRunning(sessionId: SessionId, running: boolean): void { - const previous = this.running.get(sessionId) - const beforeBaseline = this.sessions.list.getSnapshot().phase === 'pending' this.running.set(sessionId, running) - if (running) this.completionUnread.delete(sessionId) - else if ((previous === true || (previous === undefined && beforeBaseline)) - && !this.isMain(sessionId)) this.completionUnread.add(sessionId) this.publishStatus() } @@ -110,37 +143,55 @@ export class UiSessionStatus extends Service implements HostObservable 0 + /** Follow the main-view Session's binding, whose open state decides whether its natural reminder is hidden. */ + private followMainView(list: SessionListState): void { + const id = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0)?.id + const binding = id === undefined ? undefined : this.sessions.binding(id) + if (binding === this.viewedBinding) return + this.releaseViewed() + this.viewedBinding = binding + this.viewedOpenState = binding?.session.getSnapshot().openState + // Session snapshots change with every streamed event; only the open state affects the table. + this.releaseViewed = binding?.session.subscribe(() => { + const openState = binding.session.getSnapshot().openState + if (openState === this.viewedOpenState) return + this.viewedOpenState = openState + this.publishStatus() + }) ?? (() => {}) } private publishStatus(): void { const pending = this.pendingInteractions.getSnapshot() + const reading = this.reading.state.getSnapshot().items + const list = this.sessions.list.getSnapshot() + // The visible, focused main view acknowledges its open Session's completions; hiding them meanwhile avoids a flash. + const viewing = viewVisible() && this.viewedOpenState === 'open' ? this.viewedBinding?.sessionId : undefined const ids = new Set([ - ...(Object.keys(this.sessions.list.getSnapshot().byId) as SessionId[]), + ...(Object.keys(list.byId) as SessionId[]), ...this.running.keys(), ...pending.keys(), - ...this.completionUnread, + ...(Object.keys(reading) as SessionId[]), ]) const next = new Map() for (const id of ids) { + const record = reading[id] + const unread = record !== undefined + && (record.manualUnread || (id !== viewing && record.completedTurn > record.readTurn)) next.set(id, { running: this.running.get(id), pendingInteraction: pending.get(id), - completionUnread: this.completionUnread.has(id), + completionUnread: unread, + completionFailed: unread && record.failed, }) } if (sameSessionStatus(this.statusSnapshot, next)) return @@ -149,6 +200,28 @@ export class UiSessionStatus extends Service implements HostObservable void): () => void { + if (typeof document === 'undefined') return () => {} + document.addEventListener('visibilitychange', changed) + window.addEventListener('focus', changed) + window.addEventListener('blur', changed) + return () => { + document.removeEventListener('visibilitychange', changed) + window.removeEventListener('focus', changed) + window.removeEventListener('blur', changed) + } +} + function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean { if (left.size !== right.size) return false for (const [id, status] of left) { @@ -156,7 +229,8 @@ function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnap if (candidate === undefined || candidate.running !== status.running || candidate.pendingInteraction !== status.pendingInteraction - || candidate.completionUnread !== status.completionUnread) return false + || candidate.completionUnread !== status.completionUnread + || candidate.completionFailed !== status.completionFailed) return false } return true } diff --git a/packages/client/ui-session-status/src/feed.ts b/packages/client/ui-session-status/src/feed.ts new file mode 100644 index 0000000000..ef66255734 --- /dev/null +++ b/packages/client/ui-session-status/src/feed.ts @@ -0,0 +1,58 @@ +/** Cancellation-owned queue for a reading-state follow generation. */ +import { Deque } from '@deepseek-ai/dsh-deque' +import type { SessionReadFrame } from './types.ts' + +type ChangedFrame = Extract + +/** One follower's ordered committed updates. */ +export class SessionReadFollower { + private readonly frames = new Deque() + private wake: (() => void) | undefined + private readonly lifetime = new AbortController() + private failure: Error | undefined + + /** Aborts when this follower closes, including while its consumer is paused. */ + get signal(): AbortSignal { return this.lifetime.signal } + + /** + * Enqueue one update for an active follower. + * @param frame - committed whole-record replacement. + */ + push(frame: ChangedFrame): void { + if (this.signal.aborted) return + this.frames.pushBack(frame) + this.wake?.() + } + + /** + * Wake the reader and end this generation, preserving the first close reason. + * Queued frames are discarded; the next generation supplies a complete baseline. + * @param failure - terminal stream failure, when present. + */ + close(failure?: Error): void { + if (this.signal.aborted) return + this.failure = failure + this.lifetime.abort() + this.wake?.() + } + + /** + * Consume queued changes until cancellation, teardown, or stream failure. + * @param signal - Remote generation lifetime. + * @returns ordered updates; rejects with the first terminal stream failure. + */ + async *read(signal: AbortSignal): AsyncIterable { + const abort = (): void => { this.close() } + signal.addEventListener('abort', abort, { once: true }) + try { + while (!signal.aborted && !this.signal.aborted) { + const frame = this.frames.popFront() + if (frame !== undefined) yield frame + else await new Promise((resolve) => { this.wake = resolve }) + } + if (this.failure !== undefined) throw this.failure + } finally { + signal.removeEventListener('abort', abort) + } + } +} diff --git a/packages/client/ui-session-status/src/index.ts b/packages/client/ui-session-status/src/index.ts index cb1b451cca..e6f80992f7 100644 --- a/packages/client/ui-session-status/src/index.ts +++ b/packages/client/ui-session-status/src/index.ts @@ -1,4 +1,146 @@ -/** Host loader entry for the browser-only Session status plugin. */ +/** Host-authoritative Session reading records, kept in memory, and their Remote service. */ +import { Context, Service } from '@deepseek-ai/cordis' +import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-api-remote-access' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-persistence' +import { SessionReadFollower } from './feed.ts' +import type { SessionReadRecord } from './spec.ts' +import type { SessionReadAction, SessionReadFrame, SessionReadState } from './types.ts' -/** Provides no Host-side behavior. */ -export function apply(): void {} +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Host owner of the in-memory Session reading records behind the `sessionStatus` Remote namespace. */ + sessionStatus: SessionStatusService + } +} + +const emptyRecord: SessionReadRecord = { + completedTurn: 0, failed: false, readTurn: 0, manualUnread: false, +} + +/** Shared owner reading records; no reading operation changes model history. */ +export class SessionStatusService extends TypertRemoteService { + static inject = ['remoteAccess', 'sessions', 'sessionPersistence', 'typert'] + + private readonly records = new Map() + private closing = false + private readonly followers = new Set() + + /** @param ctx - Host services supplying Session events and metadata. */ + constructor(ctx: Context) { + super(ctx, 'sessionStatus', { namespace: 'sessionStatus' }) + } + + protected [Service.init](): void { + this.ctx.effect(() => () => { + this.closing = true + for (const follower of this.followers) follower.close() + this.followers.clear() + this.records.clear() + }, 'session-status: close followers and discard records') + // History recorded before this service started is read: only a turn that + // ends while it runs can raise a reminder. A `turn/end` replayed from a + // restored or forked log reaches no listener, so it raises none either. + this.ctx.on('session/event', (session, event) => { + if (event.type !== 'turn/end') return + this.complete(session.id, event.data.turn, event.data.reason.kind === 'error') + }) + } + + /** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ + @Remote + async mark(sessionId: SessionId, action: SessionReadAction): Promise { + this.assertOpen() + const sessions = this.ctx.sessions + if (sessions.get(sessionId) === undefined) { + let exists: boolean + try { + exists = await this.ctx.sessionPersistence.stat(sessionId) !== undefined + } catch (cause) { + throw this.unavailable(cause) + } + this.assertOpen() + if (!exists) throw new RemoteError('session-status/not-found', 'Session no longer exists', { sessionId }) + } + const record = this.records.get(sessionId) ?? emptyRecord + const next = { ...record, + manualUnread: action.type === 'acknowledge' ? record.manualUnread : action.type === 'unread', + readTurn: action.type === 'unread' ? record.readTurn + : Math.max(record.readTurn, Math.min(action.throughTurn, record.completedTurn)) } + this.records.set(sessionId, next) + this.publish(sessionId, next) + } + + /** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ + @Remote({ mode: 'stream' }) + async *follow(signal: AbortSignal): AsyncIterable { + this.assertOpen() + signal.throwIfAborted() + const allowed = (id: SessionId): boolean => this.ctx.remoteAccess.allows({ kind: 'session', id }) + const follower = new SessionReadFollower() + const access = this.followAccess(follower, AbortSignal.any([signal, follower.signal])) + this.followers.add(follower) + try { + yield { type: 'baseline', items: [...this.records.entries()] + .filter(([id]) => allowed(id)).map(([id, record]) => this.view(id, record)) } + for await (const frame of follower.read(signal)) { + if (allowed(frame.state.sessionId)) yield frame + } + } finally { + this.followers.delete(follower) + follower.close() + await access + } + } + + private async followAccess(follower: SessionReadFollower, signal: AbortSignal): Promise { + try { + for await (const frame of this.ctx.remoteAccess.follow(signal)) { + if (frame.type !== 'baseline') break + } + } catch (cause) { + follower.close(this.unavailable(cause)) + } finally { + follower.close() + } + } + + private assertOpen(): void { + if (this.closing) throw this.unavailable(new Error('Session status service is closing')) + } + + private complete(sessionId: SessionId, turn: number, failed: boolean): void { + const next: SessionReadRecord = { ...(this.records.get(sessionId) ?? emptyRecord), completedTurn: turn, failed } + this.records.set(sessionId, next) + this.publish(sessionId, next) + } + + private view(sessionId: SessionId, record: SessionReadRecord): SessionReadState { + return { sessionId, completedTurn: record.completedTurn, failed: record.failed, + readTurn: record.readTurn, manualUnread: record.manualUnread } + } + + private publish(sessionId: SessionId, record: SessionReadRecord): void { + const state = this.view(sessionId, record) + for (const follower of this.followers) follower.push({ type: 'changed', state }) + } + + private unavailable(cause: unknown): RemoteError { + return new RemoteError('session-status/unavailable', 'Reading state could not be updated. Try the operation again; reload the page if synchronization is unavailable.', {}, { cause }) + } +} + +export default SessionStatusService diff --git a/packages/client/ui-session-status/src/spec.ts b/packages/client/ui-session-status/src/spec.ts new file mode 100644 index 0000000000..1d9d8e21c6 --- /dev/null +++ b/packages/client/ui-session-status/src/spec.ts @@ -0,0 +1,5 @@ +/** Host-owned reading record, reset when the service is reloaded. */ +import type { SessionReadState } from './types.ts' + +/** Reading fields stored per Session, without the map key. */ +export type SessionReadRecord = Omit diff --git a/packages/client/ui-session-status/src/types.ts b/packages/client/ui-session-status/src/types.ts new file mode 100644 index 0000000000..901322bb58 --- /dev/null +++ b/packages/client/ui-session-status/src/types.ts @@ -0,0 +1,32 @@ +/** Browser-safe Session reading state and Remote requests. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** Host-confirmed reading state for one Session; turn numbers survive log-format migrations. */ +export interface SessionReadState { + readonly sessionId: SessionId + /** Latest turn that ended while this Host served the Session; 0 when none did. */ + readonly completedTurn: number + /** Whether {@link SessionReadState.completedTurn} ended with an execution error; older history reads as success. */ + readonly failed: boolean + readonly readTurn: number + readonly manualUnread: boolean +} + +/** Explicit marks replace the manual reminder; automatic acknowledgements only advance the read position. */ +export type SessionReadAction = + | { readonly type: 'unread' } + | { readonly type: 'read' | 'acknowledge'; readonly throughTurn: number } + +/** Reconnect baseline followed by complete replacement records. */ +export type SessionReadFrame = + | { readonly type: 'baseline'; readonly items: readonly SessionReadState[] } + | { readonly type: 'changed'; readonly state: SessionReadState } + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface RemoteErrorDetailsMap { + /** The requested Session does not exist. */ + 'session-status/not-found': { readonly sessionId: SessionId } + /** Reading state could not be updated; the previous value remains visible. */ + 'session-status/unavailable': {} + } +} diff --git a/packages/client/ui-session-status/tests/access.client.spec.ts b/packages/client/ui-session-status/tests/access.client.spec.ts new file mode 100644 index 0000000000..370c05258d --- /dev/null +++ b/packages/client/ui-session-status/tests/access.client.spec.ts @@ -0,0 +1,157 @@ +/** The reading stream follows the current Peer's access to `sessionStatus/follow`. */ +import { Context } from '@deepseek-ai/cordis' +import type { AccessEffect, RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' +import { whenAllowed } from '@deepseek-ai/dsh-api-remote-access/src/client/when-allowed.ts' +import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import { apply, inject } from '../src/client/index.ts' +import type { UiSessionStatus } from '../src/client/status.ts' +import type { SessionReadFrame, SessionReadState } from '../src/types.ts' + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) + +/** A stream whose frames the test hands to the consumer; disposal does not withdraw a frame already handed over. */ +function drivenStream() { + const queue: (SessionReadFrame | undefined)[] = [] + let wake: (() => void) | undefined + const state = { finished: false } + let generation = 1 + const signal = new AbortController().signal + const stream = { + signal, + restart: () => {}, + dispose: async () => {}, + async* [Symbol.asyncIterator]() { + try { + for (;;) { + while (queue.length === 0) await new Promise((resolve) => { wake = resolve }) + const value = queue.shift() + if (value === undefined) return + yield { generation, value, signal, accept: () => {} } + } + } finally { + state.finished = true + } + }, + } + const push = (value: SessionReadFrame | undefined) => { + queue.push(value) + wake?.() + } + return { stream, push, end: () => { push(undefined) }, reconnect: () => { generation++ }, state } +} + +const record = (id: string): SessionReadState => ({ + sessionId: id as SessionId, completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, +}) + +async function harness(initiallyAllowed: boolean, driven = false) { + const ctx = new Context() + roots.push(ctx) + const opened: AbortSignal[] = [] + const follow = (signal: AbortSignal): AsyncIterable => { + opened.push(signal) + return (async function* () { + yield { type: 'baseline', items: [] } + await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + })() + } + const remote = new TestRemote(ctx, { sessionStatus: { follow, mark: vi.fn() } }) + const streams: ReturnType[] = [] + if (driven) { + Object.assign(remote, { $stream: () => { + const next = drivenStream() + streams.push(next) + return next.stream + } }) + } + const allowed = createSnapshotStore(initiallyAllowed, { flush: 'sync' }) + const requested: RemoteEndpoint[] = [] + ctx.provide('remoteAccess', { + whenAccess: (action: RemoteEndpoint, callback: () => AccessEffect) => { + requested.push(action) + return whenAllowed(ctx, allowed, callback, 'test access') + }, + } as never) + ctx.provide('sessions', { + list: createSnapshotStore({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }), + binding: () => undefined, + } as never) + ctx.provide('slots', { provideRoot: () => () => {} } as never) + ctx.provide('uiSession', { + pendingInteractions: createSnapshotStore>(new Map()), + } as never) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + await ctx.plugin({ inject, apply }).await() + const status = ctx.get('uiSession.sessionStatus') as UiSessionStatus + const ready = () => status.readingReady.getSnapshot() + return { ctx, opened, allowed, requested, report, ready, status, streams } +} + +it('opens no reading stream and reports nothing while the Peer may not follow reading records', async () => { + const b = await harness(false) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.requested).toEqual(['sessionStatus/follow']) + expect(b.opened).toEqual([]) + expect(b.ready()).toBe(false) + await expect(b.status.mark('s1' as SessionId, true)).rejects.toThrow('Reading state is unavailable') + expect(b.report).not.toHaveBeenCalled() +}) + +it('starts the stream when access is granted and stops it when access is revoked', async () => { + const b = await harness(false) + b.allowed.set(true) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + expect(b.opened).toHaveLength(1) + b.allowed.set(false) + expect(b.ready()).toBe(false) + await vi.waitFor(() => { expect(b.opened[0]!.aborted).toBe(true) }) + b.allowed.set(true) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + expect(b.opened).toHaveLength(2) + expect(b.report).not.toHaveBeenCalled() +}) + +it('discards frames a revoked stream still delivers and leaves reading unavailable', async () => { + const b = await harness(true, true) + const first = b.streams[0]! + first.push({ type: 'baseline', items: [] }) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + b.allowed.set(false) + expect(b.ready()).toBe(false) + first.reconnect() + first.push({ type: 'baseline', items: [record('late')] }) + first.push({ type: 'changed', state: record('later') }) + first.end() + await vi.waitFor(() => { expect(first.state.finished).toBe(true) }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.ready()).toBe(false) + expect(b.status.getSnapshot().size).toBe(0) +}) + +it('keeps a quick re-grant\'s records and readiness while the revoked stream drains', async () => { + const b = await harness(true, true) + const first = b.streams[0]! + first.push({ type: 'baseline', items: [] }) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + b.allowed.set(false) + b.allowed.set(true) + const second = b.streams[1]! + second.push({ type: 'baseline', items: [record('granted')] }) + await vi.waitFor(() => { expect(b.status.getSnapshot().get('granted' as SessionId)?.completionUnread).toBe(true) }) + first.push({ type: 'changed', state: record('revoked') }) + first.end() + await vi.waitFor(() => { expect(first.state.finished).toBe(true) }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.ready()).toBe(true) + expect([...b.status.getSnapshot().keys()]).toEqual(['granted']) + second.end() +}) diff --git a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts new file mode 100644 index 0000000000..4475586682 --- /dev/null +++ b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts @@ -0,0 +1,291 @@ +// @vitest-environment jsdom +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { AgentContext, SessionBinding, SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { FixtureSession, type SessionFixtureSnapshot } from '@deepseek-ai/dsh-client-test-runtime' +import { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import { installReadingAcknowledgements } from '../src/client/acknowledge.ts' +import type { SessionReadSnapshot } from '../src/client/model.ts' +import type { SessionReadState } from '../src/types.ts' + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +interface HarnessOptions { + /** Manual reminder of the initial record. */ + readonly manual?: boolean + /** Completed turn of the initial record, also delivered to the body. */ + readonly completedTurn?: number + /** Whether the main view retains the Session at install time. */ + readonly selected?: boolean + /** Whether the reading baseline is ready at install time. */ + readonly ready?: boolean +} + +function harness({ manual = false, completedTurn = 1, selected = true, ready = true }: HarnessOptions = {}) { + const ctx = new Context() + roots.push(ctx) + const id = SessionId('viewed') + const state = createSnapshotStore({ ready, items: { [id]: { + sessionId: id, completedTurn, failed: false, readTurn: 0, manualUnread: manual, + } } }, { flush: 'sync' }) + const lifecycle = createSnapshotStore({ + sessionId: id, pendingSubmissions: [], running: false, subagent: null, removed: false, + openState: 'open', openError: null, hasMore: false, loadingOlder: false, promptError: null, + historyLoadStatus: 'idle', historyWasPartial: false, + blank: false, lastAgentError: null, promptAttempted: false, awaitingFirstTurn: false, + }, { flush: 'sync' }) + const session = new FixtureSession(id, lifecycle, {}) + const body = (turn: number) => { session.eventSource.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(turn), time: 0, data: { turn, reason: { kind: 'completed' } }, + } }) } + if (completedTurn > 0) body(completedTurn) + const row = (mainView: boolean) => ({ + id, displayTitle: 'Viewed', retainedBy: mainView ? { mainView: 1 } : {}, running: false, blank: false, updatedAt: 1, + }) + const list = createSnapshotStore({ + ids: [id], phase: 'ready', projectionsBySession: {}, byId: { [id]: row(selected) }, + }, { flush: 'sync' }) + const bind = (): SessionBinding => ({ sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext }) + let binding = bind() + const mark = vi.fn(async (_id: typeof id, _throughTurn: number, _clearManual: boolean) => {}) + let frame: FrameRequestCallback | undefined + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frame = callback; return 1 }) + vi.stubGlobal('cancelAnimationFrame', () => { frame = undefined }) + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true) + const visible = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') + installReadingAcknowledgements(ctx, { list, binding: () => binding }, { state, acknowledge: mark }) + const paint = async () => { + const callback = frame + frame = undefined + callback?.(0) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + } + /** Replace the record with the given fields over the current one. */ + const record = (patch: Partial) => { + const current = state.getSnapshot() + state.set({ ready: true, items: { [id]: { ...current.items[id]!, ...patch } } }) + } + /** Move the main view to or away from the Session. */ + const select = (on: boolean) => { list.update((draft) => { draft.byId[id] = row(on) }) } + /** Replace the binding of the still-selected Session. */ + const rebind = () => { + binding = bind() + list.set({ ...list.getSnapshot() }) + } + return { ctx, id, state, body, lifecycle, list, mark, paint, focus, visible, session, record, select, rebind } +} + +it('waits for a focused visible main view and an open Session before acknowledging', async () => { + const b = harness() + b.visible.mockReturnValue('hidden') + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.visible.mockReturnValue('visible') + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + document.dispatchEvent(new Event('visibilitychange')) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('clears a manual reminder after the main view switches to its Session and the body arrives', async () => { + const b = harness({ manual: true, selected: false }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.select(true) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('preserves a manual mark made in the open Session until the main view leaves and returns', async () => { + const b = harness() + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + b.record({ readTurn: 1, manualUnread: true }) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.select(false) + b.select(true) + await b.paint() + expect(b.mark).toHaveBeenLastCalledWith(b.id, 1, true) +}) + +it('preserves a manual reminder when the window regains focus or visibility', async () => { + const b = harness() + await b.paint() + b.record({ readTurn: 1, manualUnread: true }) + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + document.dispatchEvent(new Event('visibilitychange')) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('treats the initial selection as an entry and clears its manual reminder once a late baseline arrives', async () => { + const b = harness({ manual: true, ready: false }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.record({ manualUnread: true }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('does not treat a replaced binding for the same Session as an entry', async () => { + const b = harness() + await b.paint() + b.record({ readTurn: 1, manualUnread: true }) + b.rebind() + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('acknowledges an earlier manual mark before any turn has completed', async () => { + const b = harness({ manual: true, completedTurn: 0 }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 0, true) +}) + +it('does not read a new completion before its content arrives, or after disposal', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + await b.ctx.fiber.dispose() + await b.paint() + expect(b.mark).not.toHaveBeenCalled() +}) + +it('acknowledges later body progress without clearing manual unread again', async () => { + const b = harness({ manual: true, completedTurn: 0 }) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.body(1) + b.record({ completedTurn: 1, manualUnread: true }) + await b.paint() + expect(b.mark.mock.calls).toEqual([[b.id, 0, true], [b.id, 1, false]]) +}) + +it('retains unread after acknowledgement failure and retries on a new view entry', async () => { + const b = harness() + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + b.mark.mockRejectedValueOnce(new Error('offline')) + await b.paint() + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + expect(report).toHaveBeenCalled() + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(2) +}) + +it('does not acknowledge an unselected or unknown record and tolerates unrelated list updates', async () => { + const b = harness() + const selected = b.list.getSnapshot() + b.list.set({ ...selected, byId: {} }) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.state.set({ ready: true, items: {} }) + b.list.set(selected) + await b.paint() + b.list.set({ ...selected }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + await b.ctx.fiber.dispose() +}) + +it('waits for the body to reach the completed turn before acknowledging', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.body(2) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 2, false) +}) + +it('preserves a manual mark received while the entered Session is loading', async () => { + const b = harness() + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.record({ manualUnread: true }) + await b.paint() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).not.toHaveBeenCalledWith(b.id, 1, true) +}) + +it('keeps a pending entry across window blur and clears after the body loads', async () => { + const b = harness({ manual: true }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + await b.paint() + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + b.lifecycle.update((draft) => { draft.openState = 'open' }) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('retains an entry while a natural acknowledgement is pending', async () => { + const b = harness() + let resolve!: () => void + b.mark.mockImplementationOnce(() => new Promise((settle) => { resolve = settle })) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + b.record({ manualUnread: true }) + b.select(false) + b.select(true) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + resolve() + await b.paint() + await b.paint() + expect(b.mark).toHaveBeenLastCalledWith(b.id, 1, true) +}) + +it('drops an entry after another client clears the manual reminder', async () => { + const b = harness({ manual: true }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.record({ manualUnread: false }) + b.record({ manualUnread: true }) + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('acknowledges a completed turn only after the body advances to the next turn', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + const start = (turn: number) => { b.session.eventSource.replace([{ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(turn), time: 0, data: { turn }, + } }], true) } + start(2) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + start(3) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 2, false) +}) diff --git a/packages/client/ui-session-status/tests/model.client.spec.ts b/packages/client/ui-session-status/tests/model.client.spec.ts new file mode 100644 index 0000000000..f5db380693 --- /dev/null +++ b/packages/client/ui-session-status/tests/model.client.spec.ts @@ -0,0 +1,87 @@ +import { expect, it, vi } from 'vitest' +import { RemoteError, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SessionReadModel } from '../src/client/model.ts' +import type { SessionReadState } from '../src/types.ts' + +const id = SessionId('reading') +const record = (completedTurn: number, manualUnread = false): SessionReadState => ({ + sessionId: id, completedTurn, failed: false, readTurn: 0, manualUnread, +}) + +it('replaces reconnect baselines and rejects actions without a current baseline', async () => { + const mark = vi.fn() + const model = new SessionReadModel({ mark }) + await expect(model.mark(id, false)).rejects.toThrow('Reload the page') + model.replace([record(1)]) + model.accept(record(2)) + expect(model.state.getSnapshot().items[id]?.completedTurn).toBe(2) + model.disconnected() + expect(model.state.getSnapshot()).toMatchObject({ ready: false }) + model.replace([]) + expect(model.state.getSnapshot()).toEqual({ items: {}, ready: true }) +}) + +it('keeps newer pushed unread marks when an older read response arrives', async () => { + const response = Promise.withResolvers<{ ok: true; value: undefined }>() + const mark = vi.fn(() => response.promise) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + const pending = model.mark(id, false) + model.accept(record(3, true)) + response.resolve({ ok: true, value: undefined }) + await pending + expect(mark).toHaveBeenCalledWith(id, { type: 'read', throughTurn: 1 }) + expect(model.state.getSnapshot().items[id]).toEqual(record(3, true)) +}) + +it('keeps a replaced baseline when an earlier operation completes and preserves records on failure', async () => { + const response = Promise.withResolvers<{ ok: true; value: undefined }>() + const mark = vi.fn(() => response.promise) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + const pending = model.mark(id, true) + model.disconnected() + model.replace([]) + response.resolve({ ok: true, value: undefined }) + await pending + expect(model.state.getSnapshot().items).toEqual({}) + mark.mockRejectedValueOnce(new Error('offline')) + await expect(model.mark(id, true)).rejects.toThrow('offline') + expect(model.state.getSnapshot().items).toEqual({}) +}) + +it('sends explicit marks and body acknowledgements with their observed positions', async () => { + const mark = vi.fn(async () => ({ ok: true, value: undefined })) + const model = new SessionReadModel({ mark }) + model.replace([]) + await model.mark(id, false) + await model.mark(id, true) + await model.acknowledge(id, 2, false) + await model.acknowledge(id, 3, true) + expect(mark.mock.calls).toEqual([ + [id, { type: 'read', throughTurn: 0 }], + [id, { type: 'unread' }], + [id, { type: 'acknowledge', throughTurn: 2 }], + [id, { type: 'read', throughTurn: 3 }], + ]) + expect(model.state.getSnapshot().items).toEqual({}) +}) + +it('reports business rejection and disables writes without losing reminders', async () => { + const error = new RemoteError('session-status/unavailable', 'Storage unavailable', {}) + const mark = vi.fn(async () => ({ ok: false, error })) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + await expect(model.mark(id, false)).rejects.toBe(error) + expect(model.state.getSnapshot().items[id]).toEqual(record(1)) + model.disconnected() + expect(model.state.getSnapshot()).toMatchObject({ ready: false }) +}) + +it('accepts the first pushed record for a newly visible Session', () => { + const model = new SessionReadModel({ mark: vi.fn() }) + model.replace([]) + model.accept(record(1)) + expect(model.state.getSnapshot().items[id]).toEqual(record(1)) +}) diff --git a/packages/client/ui-session-status/tests/status-controller.client.spec.ts b/packages/client/ui-session-status/tests/status-controller.client.spec.ts index 3a7e2543ab..13ce251f13 100644 --- a/packages/client/ui-session-status/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session-status/tests/status-controller.client.spec.ts @@ -1,5 +1,6 @@ /** Session status across the real Controller catalog, ui-session pending interactions, and the status service. */ -import { expect, vi } from 'vitest' +import { expect, onTestFinished, vi } from 'vitest' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { ok } from '@deepseek-ai/dsh-remote-mock' import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import { SESSION_FORMAT_VERSION, type SessionId } from '@deepseek-ai/dsh-session/types' @@ -11,6 +12,39 @@ const it = createClientTest({ roster: webApp.closure(['@deepseek-ai/dsh-client-u const parentId = 'status-parent' as SessionId const childId = 'status-child' as SessionId +it('reports a failed completion as an error reminder until it is read', async ({ mock, start }) => { + const record = (turn: number, readTurn: number, failed = false) => ({ + sessionId: parentId, completedTurn: turn, failed, readTurn, manualUnread: false, + }) + mock.remote.session.list.mockResolvedValue(ok({ items: [{ + sessionId: parentId, updatedAt: 1, running: false, blank: false, agentAvailable: true, + }] })) + mock.stream('sessionStatus/follow', (_request, stream) => { + stream.push({ type: 'baseline', items: [record(1, 0, true)] }) + }) + const client = await start() + const sessions = client.ctx.sessions + const status = () => client.ctx.uiSession.sessionStatus.getSnapshot().get(parentId) + await sessions.refresh() + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: true }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 0) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: false }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 2, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: false, completionFailed: false }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(3, 2, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: true }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(3, 3, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: false, completionFailed: false }) }) +}) + it('preserves unlisted child status through metadata updates and main view acknowledgement', async ({ mock, start }) => { mock.remote.session.list.mockResolvedValue(ok({ items: [{ sessionId: parentId, updatedAt: 1, running: false, blank: false, agentAvailable: true, @@ -53,11 +87,20 @@ it('preserves unlisted child status through metadata updates and main view ackno mock.streams.push('$events', { type: 'emit', event: 'api-session/status', args: [childId, false] }) await mock.streams.drained('$events') await client.flush() + mock.streams.push('sessionStatus/follow', { type: 'changed', state: { + sessionId: childId, completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, + } }) + await mock.streams.drained('sessionStatus/follow') + await client.flush() expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: true }) using reference = sessions.retain(childId, { source: 'mainView' }) await reference.ready expect(sessions.list.getSnapshot().ids).not.toContain(childId) + mock.streams.push('sessionStatus/follow', { type: 'changed', state: { + sessionId: childId, completedTurn: 1, failed: false, readTurn: 1, manualUnread: false, + } }) + await mock.streams.drained('sessionStatus/follow') await vi.waitFor(() => { expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: false }) }) @@ -76,3 +119,43 @@ it('reports the effective ui-session pending interaction as the same request obj remove() expect(status.getSnapshot().get(parentId)?.pendingInteraction).toBeUndefined() }) + +it('applies ordered whole-record reading changes after the baseline', async ({ mock, start }) => { + const record = (completedTurn: number, readTurn: number) => ({ + sessionId: parentId, completedTurn, failed: false, readTurn, manualUnread: false, + }) + mock.stream('sessionStatus/follow', (_request, stream) => { + stream.push({ type: 'baseline', items: [record(1, 0)] }) + }) + const client = await start() + const status = client.ctx.uiSession.sessionStatus + await vi.waitFor(() => { expect(status.getSnapshot().get(parentId)?.completionUnread).toBe(true) }) + expect(status.readingReady.getSnapshot()).toBe(true) + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 2) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status.getSnapshot().get(parentId)?.completionUnread).toBe(false) }) +}) + +it('retains reminders after a stream ends, replaces the reconnect baseline, and reports terminal failure', async ({ mock, start }) => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { report.mockRestore() }) + let generation = 0 + mock.stream('sessionStatus/follow', (_request, stream) => { + generation++ + stream.push({ type: 'baseline', items: [{ + sessionId: parentId, completedTurn: generation, failed: generation === 2, readTurn: 0, + manualUnread: false, + }] }) + if (generation === 1) stream.end() + else stream.fail(new RemoteError('session-status/unavailable', 'Reading storage unavailable', {})) + }) + const client = await start() + const status = client.ctx.uiSession.sessionStatus + await vi.waitFor(() => { + expect(status.getSnapshot().get(parentId)).toMatchObject({ completionUnread: true, completionFailed: true }) + expect(status.readingReady.getSnapshot()).toBe(false) + }) + expect(generation).toBe(2) + await expect(status.mark(parentId, false)).rejects.toThrow('Reload the page') + expect(report).toHaveBeenCalledWith(expect.stringContaining('Reminders could not be synchronized'), expect.any(Error)) +}) diff --git a/packages/client/ui-session-status/tests/status-view.client.spec.ts b/packages/client/ui-session-status/tests/status-view.client.spec.ts new file mode 100644 index 0000000000..ef03c22f15 --- /dev/null +++ b/packages/client/ui-session-status/tests/status-view.client.spec.ts @@ -0,0 +1,109 @@ +// @vitest-environment jsdom +/** Natural reminders of the Session the visible, focused main view retains. */ +import { Context } from '@deepseek-ai/cordis' +import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import type { SessionReadSnapshot } from '../src/client/model.ts' +import { UiSessionStatus } from '../src/client/status.ts' +import type { SessionReadState } from '../src/types.ts' + +const viewed = 'viewed' as SessionId +const other = 'other' as SessionId +const roots: Context[] = [] + +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) + +function bench() { + const ctx = new Context() + roots.push(ctx) + ctx.provide('remote', { $on: () => () => {} } as never) + const row = (id: SessionId, mainView: boolean) => ({ + id, displayTitle: id, running: false, retainedBy: mainView ? { mainView: 1 } : {}, blank: false, updatedAt: 1, + }) + const list = createSnapshotStore({ + ids: [viewed, other], phase: 'ready', projectionsBySession: {}, + byId: { [viewed]: row(viewed, true), [other]: row(other, false) }, + }) + const record = (id: SessionId, value: Partial): SessionReadState => ({ + sessionId: id, completedTurn: 1, failed: true, readTurn: 0, manualUnread: false, ...value, + }) + const opened = (id: SessionId) => ({ + sessionId: id, session: createSnapshotStore<{ readonly openState: string; readonly running?: boolean }>({ openState: 'open' }), + }) + const bindings = new Map([viewed, other].map(id => [id, opened(id)])) + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true) + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') + const service = new UiSessionStatus(ctx, { list, binding: (id: SessionId) => bindings.get(id) as never }, + createSnapshotStore>(new Map())) + const reading: { set(value: SessionReadSnapshot): void } = service.reading.state + reading.set({ ready: true, items: { [viewed]: record(viewed, {}), [other]: record(other, {}) } }) + const status = (id: SessionId) => service.getSnapshot().get(id) + const view = (id: SessionId) => { + list.update((draft) => { + for (const key of [viewed, other]) draft.byId[key] = row(key, key === id) + }) + } + const openState = (id: SessionId, state: string) => { bindings.get(id)!.session.set({ openState: state }) } + const snapshot = (id: SessionId, value: { readonly openState: string; readonly running?: boolean }) => { + bindings.get(id)!.session.set(value) + } + return { ctx, reading, record, focus, visibility, status, view, openState, service, snapshot } +} + +it('hides the natural reminder of the viewed Session until the window loses focus or visibility', () => { + const b = bench() + expect(b.status(viewed)).toMatchObject({ completionUnread: false, completionFailed: false }) + expect(b.status(other)).toMatchObject({ completionUnread: true, completionFailed: true }) + + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + expect(b.status(viewed)?.completionUnread).toBe(false) + + b.visibility.mockReturnValue('hidden') + document.dispatchEvent(new Event('visibilitychange')) + expect(b.status(viewed)?.completionUnread).toBe(true) +}) + +it('keeps a manual reminder of the viewed Session visible', () => { + const b = bench() + b.reading.set({ ready: true, items: { [viewed]: b.record(viewed, { readTurn: 1, manualUnread: true }) } }) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) +}) + +it('shows an unacknowledged completion again after the main view switches to another Session', () => { + const b = bench() + b.view(other) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + expect(b.status(other)).toMatchObject({ completionUnread: false, completionFailed: false }) +}) + +it('shows the natural reminder of the viewed Session until that Session is open', () => { + const b = bench() + b.openState(viewed, 'loading') + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.openState(viewed, 'error') + expect(b.status(viewed)?.completionUnread).toBe(true) + b.openState(viewed, 'open') + expect(b.status(viewed)).toMatchObject({ completionUnread: false, completionFailed: false }) +}) + +it('does not rebuild the table when the viewed Session snapshot changes without an open-state change', () => { + const b = bench() + const before = b.service.getSnapshot() + const changed = vi.fn() + b.service.subscribe(changed) + const rebuild = vi.spyOn(b.service.reading.state, 'getSnapshot') + b.snapshot(viewed, { openState: 'open', running: true }) + expect(rebuild).not.toHaveBeenCalled() + expect(b.service.getSnapshot()).toBe(before) + expect(changed).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-session-status/tests/status.client.spec.ts b/packages/client/ui-session-status/tests/status.client.spec.ts index 9257f7afe7..01abc42679 100644 --- a/packages/client/ui-session-status/tests/status.client.spec.ts +++ b/packages/client/ui-session-status/tests/status.client.spec.ts @@ -4,9 +4,10 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { afterEach, describe, expect, it, vi } from 'vitest' +import type { SessionReadSnapshot } from '../src/client/model.ts' import { apply } from '../src/client/index.ts' import { UiSessionStatus } from '../src/client/status.ts' -import { apply as nodeApply } from '../src/index.ts' +import type { SessionReadState } from '../src/types.ts' const sessionId = (value: string): SessionId => value as SessionId const pendingQuestion = (id: SessionId) => ({ key: 'question:1', kind: 'question', sessionId: id }) as SessionPendingInteraction @@ -21,16 +22,33 @@ function bench() { const ctx = new Context() roots.push(ctx) let statusListener: ((id: SessionId, running: boolean) => void) | undefined + const remoteMark = vi.fn(async () => ({ ok: true as const, value: undefined })) ctx.provide('remote', { $on: (_event: string, listener: (id: SessionId, running: boolean) => void) => { statusListener = listener return () => { if (statusListener === listener) statusListener = undefined } }, + sessionStatus: { mark: remoteMark }, } as never) const list = createSnapshotStore({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }) - const sessions: Pick = { list } + const sessions: Pick = { list, binding: () => undefined } const pending = createSnapshotStore>(new Map()) - const status = () => new UiSessionStatus(ctx, sessions, pending) + // The status table owns its reading model; this facade drives the most recently created one with a ready baseline. + let latest: UiSessionStatus | undefined + const model = () => { + if (latest === undefined) throw new Error('no status table was created') + return latest.reading.state + } + const reading = { + set: (value: SessionReadSnapshot) => { model().set(value) }, + getSnapshot: () => model().getSnapshot(), + } + const create = (scope: Context = ctx, catalog: Pick = sessions) => { + latest = new UiSessionStatus(scope, catalog, pending) + latest.reading.replace([]) + return latest + } + const status = () => create() const row = (id: SessionId) => { list.update((draft) => { if (!draft.ids.includes(id)) draft.ids.push(id) @@ -46,10 +64,16 @@ function bench() { if (statusListener === undefined) throw new Error('api-session/status is not subscribed') statusListener(id, running) } - return { ctx, list, pending, status, row, setMainView, emitStatus, subscribed: () => statusListener !== undefined } + const record = (id: SessionId, value: Partial): SessionReadState => ({ + sessionId: id, completedTurn: 0, failed: false, readTurn: 0, manualUnread: false, ...value, + }) + return { + ctx, list, pending, reading, remoteMark, create, status, row, setMainView, emitStatus, record, + subscribed: () => statusListener !== undefined, + } } -describe('Session running status and completion reminders', () => { +describe('Session running status', () => { it('keeps synthetic-row status unknown until an event or Host baseline establishes it', () => { const b = bench() const id = sessionId('catalog-only') @@ -58,19 +82,17 @@ describe('Session running status and completion reminders', () => { }) const service = b.status() expect(service.getSnapshot().get(id)?.running).toBeUndefined() - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) b.emitStatus(id, true) b.list.update((draft) => { draft.byId[id]!.displayTitle = 'Renamed child' }) expect(service.getSnapshot().get(id)?.running).toBe(true) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) b.list.update((draft) => { draft.ids.push(id) }) expect(service.getSnapshot().get(id)?.running).toBe(false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) }) - it('records non-main completions and lets main-view activity acknowledge them', () => { + it('publishes running changes from list rows and status events, and skips unchanged status', () => { const b = bench() const id = sessionId('s1') b.row(id) @@ -79,41 +101,20 @@ describe('Session running status and completion reminders', () => { const off = service.subscribe(changed) expect(service.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: false, + running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, }) b.list.update((draft) => { draft.byId[id]!.running = true }) expect(service.getSnapshot().get(id)?.running).toBe(true) - b.list.update((draft) => { draft.byId[id]!.running = false }) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - b.setMainView(id, 1) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.setMainView(id, 0) - - b.emitStatus(id, true) b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - - b.setMainView(id, 1) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.emitStatus(id, true) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - - b.setMainView(id, 0) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.emitStatus(id, true) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - b.emitStatus(id, true) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + expect(service.getSnapshot().get(id)?.running).toBe(false) expect(changed).toHaveBeenCalled() + const calls = changed.mock.calls.length + b.emitStatus(id, false) + expect(changed).toHaveBeenCalledTimes(calls) off() }) - it('records an idle event before the initial catalog baseline and retires absent status later', () => { + it('records an event before the initial catalog baseline and retires absent status later', () => { const b = bench() const id = sessionId('early') b.list.update((draft) => { draft.phase = 'pending' }) @@ -121,9 +122,7 @@ describe('Session running status and completion reminders', () => { b.emitStatus(id, false) expect(service.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: true, + running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, }) b.list.update((draft) => { draft.phase = 'ready' }) expect(service.getSnapshot().has(id)).toBe(false) @@ -148,6 +147,69 @@ describe('Session running status and completion reminders', () => { }) }) +describe('Session reading reminders', () => { + it('derives unread and failed reminders from Host reading records', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + b.emitStatus(id, true) + b.emitStatus(id, false) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, failed: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2 }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: false }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2, readTurn: 2, failed: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: false, completionFailed: false }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2, readTurn: 2, manualUnread: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: false }) + }) + + it('preserves a Host reminder through main view selection and running changes', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1 }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.setMainView(id, 1) + b.emitStatus(id, true) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, readTurn: 1, manualUnread: true }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, readTurn: 1 }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + }) + + it('retains a shared reminder for a Session that left the catalog', () => { + const b = bench() + const id = sessionId('evicted') + const service = b.status() + b.emitStatus(id, true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1 }) } }) + b.list.set({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }) + expect(service.getSnapshot().get(id)).toMatchObject({ running: undefined, completionUnread: true }) + }) + + it('reports reading readiness and forwards explicit marks', async () => { + const b = bench() + const service = b.status() + const ready = vi.fn() + const off = service.readingReady.subscribe(ready) + expect(service.readingReady.getSnapshot()).toBe(true) + b.reading.set({ ...b.reading.getSnapshot(), ready: false }) + expect(service.readingReady.getSnapshot()).toBe(false) + expect(ready).toHaveBeenCalled() + off() + b.reading.set({ ...b.reading.getSnapshot(), ready: true }) + const mark = vi.spyOn(service.reading, 'mark') + await service.mark(sessionId('s1'), true) + expect(mark).toHaveBeenCalledExactlyOnceWith(sessionId('s1'), true) + expect(b.remoteMark).toHaveBeenCalledExactlyOnceWith(sessionId('s1'), { type: 'unread' }) + }) +}) + describe('Session status pending interactions', () => { it('carries the exact effective request object and adds Sessions known only by their request', () => { const b = bench() @@ -161,10 +223,12 @@ describe('Session status pending interactions', () => { const question = { key: 'question:1', kind: 'question', sessionId: unlisted } as SessionPendingInteraction b.pending.set(new Map([[listed, approval], [unlisted, question]])) - expect(service.getSnapshot().get(listed)).toEqual({ running: false, pendingInteraction: approval, completionUnread: false }) + expect(service.getSnapshot().get(listed)).toEqual({ + running: false, pendingInteraction: approval, completionUnread: false, completionFailed: false, + }) expect(service.getSnapshot().get(listed)?.pendingInteraction).toBe(approval) expect(service.getSnapshot().get(unlisted)).toEqual({ - running: undefined, pendingInteraction: question, completionUnread: false, + running: undefined, pendingInteraction: question, completionUnread: false, completionFailed: false, }) expect(changed).toHaveBeenCalledOnce() @@ -196,7 +260,7 @@ describe('Session status pending interactions', () => { let service: UiSessionStatus | undefined const fiber = b.ctx.plugin({ apply(scope: Context) { - service = new UiSessionStatus(scope, { list: b.list }, b.pending) + service = b.create(scope) }, }) await fiber.await() @@ -209,6 +273,7 @@ describe('Session status pending interactions', () => { expect(b.subscribed()).toBe(false) b.row(sessionId('later')) b.pending.set(new Map([[sessionId('later'), pendingQuestion(sessionId('later'))]])) + b.reading.set({ ready: true, items: { [sessionId('later')]: b.record(sessionId('later'), { completedTurn: 1 }) } }) expect(service.getSnapshot()).toBe(before) }) }) @@ -217,9 +282,10 @@ describe('session-status apply', () => { it('provides the status service under ctx.uiSession and publishes it as the root useSessionStatus source', () => { const b = bench() const provideRoot = vi.fn() - b.ctx.provide('sessions', { list: b.list } as never) b.ctx.provide('slots', { provideRoot } as never) b.ctx.provide('uiSession', { pendingInteractions: b.pending } as never) + b.ctx.provide('sessions', { list: b.list, binding: () => undefined } as never) + b.ctx.provide('remoteAccess', { whenAccess: () => () => {} } as never) apply(b.ctx) @@ -227,13 +293,8 @@ describe('session-status apply', () => { const root = provideRoot.mock.calls[0]![0] as { hooks: { sessionStatus: UiSessionStatus } } expect(Object.keys(root)).toEqual(['hooks']) expect(Object.keys(root.hooks)).toEqual(['sessionStatus']) - expect(root.hooks.sessionStatus).toBeInstanceOf(UiSessionStatus) const provided: unknown = b.ctx.get('uiSession.sessionStatus') if (!(provided instanceof UiSessionStatus)) throw new Error('uiSession.sessionStatus is not provided') - expect(provided.getSnapshot()).toBe(root.hooks.sessionStatus.getSnapshot()) - }) - - it('keeps the Host loader half inert', () => { - expect(() => { nodeApply() }).not.toThrow() + expect(root.hooks.sessionStatus.getSnapshot()).toBe(provided.getSnapshot()) }) }) diff --git a/packages/client/ui-session-status/tests/status.host.spec.ts b/packages/client/ui-session-status/tests/status.host.spec.ts new file mode 100644 index 0000000000..bcb23c74d4 --- /dev/null +++ b/packages/client/ui-session-status/tests/status.host.spec.ts @@ -0,0 +1,345 @@ +import { Context } from '@deepseek-ai/cordis' +import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import Projections from '@deepseek-ai/dsh-session-projection' +import RemoteAccess from '@deepseek-ai/dsh-api-remote-access' +import Typert from '@deepseek-ai/dsh-typert-registry' +import { Peer } from '@deepseek-ai/dsh-client-connection' +import { afterEach, expect, it, vi } from 'vitest' +import { remoteMethods, type RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' +import SessionStatusService from '../src/index.ts' +import { SessionReadFollower } from '../src/feed.ts' +import type { SessionReadState, SessionReadFrame } from '../src/types.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + 'reading-test': { readonly kind: 'reading-test' } + } +} + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) +}) + +async function harness(before?: (ctx: Context) => void) { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(Projections) + await ctx.plugin(Typert) + await ctx.plugin(RemoteAccess) + const stat = vi.fn(async (_id: SessionId): Promise => undefined) + ctx.provide('sessionPersistence', { stat } as never) + const allows = vi.spyOn(ctx.remoteAccess, 'allows').mockReturnValue(true) + before?.(ctx) + const fiber = ctx.plugin(SessionStatusService) + await fiber + return { ctx, service: ctx.sessionStatus, allows, stat, fiber } +} + +function end(session: Session, turn: number): readonly SessionEvent[] { + return [session.append('turn/start', { turn }), + session.append('turn/end', { turn, reason: { kind: 'completed' } })] +} + +async function nextFrame(iterator: AsyncIterator): Promise { + const result = await iterator.next() + if (result.done) throw new Error('reading stream ended') + return result.value +} + +async function baseline(service: SessionStatusService): Promise { + const abort = new AbortController() + const iterator = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + const frame = await nextFrame(iterator) + if (frame?.type !== 'baseline') throw new Error('missing reading baseline') + return frame.items + } finally { + abort.abort() + await iterator.return?.() + } +} + +it('raises no reminder for history recorded before the service started', async () => { + const { ctx, service } = await harness((context) => { + end(context.sessions.create(SessionId('history')), 7) + }) + expect(await baseline(service)).toEqual([]) + end(ctx.sessions.get(SessionId('history'))!, 8) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 8, readTurn: 0 })]) +}) + +it('raises no reminder for a Session restored from stored history', async () => { + const { ctx, service } = await harness() + ctx.sessions.create(SessionId('restored'), { seed: end(Session.create(SessionId('seed')), 7) }) + expect(await baseline(service)).toEqual([]) +}) + +it('records whether the completing turn failed', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('failed')) + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'boom', code: 'UNKNOWN' } } }) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, failed: true })]) + session.append('turn/start', { turn: 2 }) + session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 2, failed: false })]) +}) + +it('broadcasts explicit marks to both frontends and keeps later completions unread', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('shared')) + end(session, 1) + const abort = new AbortController() + const left = service.follow(abort.signal)[Symbol.asyncIterator]() + const right = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + const opening = await nextFrame(left) + await right.next() + if (opening?.type !== 'baseline') throw new Error('missing baseline') + await service.mark(session.id, { type: 'read', throughTurn: opening.items[0]!.completedTurn }) + const read = { sessionId: session.id, completedTurn: 1, failed: false, readTurn: 1, manualUnread: false } + expect(await left.next()).toMatchObject({ value: { type: 'changed', state: read } }) + expect(await right.next()).toMatchObject({ value: { type: 'changed', state: read } }) + await service.mark(session.id, { type: 'unread' }) + end(session, 2) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 1 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2, manualUnread: true }]) + await service.mark(session.id, { type: 'read', throughTurn: 1 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2 }]) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 9 }) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 0 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2, readTurn: 2 }]) + } finally { + abort.abort() + await Promise.all([left.return?.(), right.return?.()]) + } +}) + +it('filters the baseline and increments by Session access and rejects missing Sessions', async () => { + const { ctx, service, allows } = await harness() + const visible = ctx.sessions.create(SessionId('visible')) + const hidden = ctx.sessions.create(SessionId('hidden')) + end(visible, 1) + end(hidden, 1) + await baseline(service) + allows.mockImplementation(resource => resource.kind !== 'session' || resource.id !== hidden.id) + expect(await baseline(service)).toEqual([expect.objectContaining({ sessionId: visible.id })]) + const marker = remoteMethods(service).find(method => method.method === 'mark') + expect(marker?.resources).toBeUndefined() + const abort = new AbortController() + const iterator = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + await nextFrame(iterator) + const next = nextFrame(iterator) + end(hidden, 2) + end(visible, 2) + expect(await next).toMatchObject({ type: 'changed', state: { sessionId: visible.id, completedTurn: 2 } }) + } finally { + abort.abort() + await iterator.return?.() + } + await expect(service.mark(SessionId('missing'), { type: 'unread' })) + .rejects.toMatchObject({ code: 'session-status/not-found' }) +}) + +it('marks cold history without opening it', async () => { + const { ctx, service, stat } = await harness() + const id = SessionId('cold') + stat.mockResolvedValue({}) + await service.mark(id, { type: 'unread' }) + expect(ctx.sessions.get(id)).toBeUndefined() + expect(await baseline(service)).toEqual([ + { sessionId: id, completedTurn: 0, failed: false, readTurn: 0, manualUnread: true }, + ]) +}) + +it('closes an idle follower when its Host owner is disposed', async () => { + const { ctx, service } = await harness() + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + const pending = iterator.next() + await ctx.fiber.dispose() + expect(await pending).toMatchObject({ done: true }) +}) + +it('cancels its access watcher even when a consumer pauses after the baseline', async () => { + const { ctx, service, fiber } = await harness() + const follow = ctx.remoteAccess.follow.bind(ctx.remoteAccess) + let stopped = false + vi.spyOn(ctx.remoteAccess, 'follow').mockImplementation(async function* (signal) { + try { yield* follow(signal) } finally { stopped = true } + }) + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + await fiber.dispose() + await vi.waitFor(() => { expect(stopped).toBe(true) }) + await iterator.return?.() +}) + +it('ignores late updates after a follower closes and wakes a cancelled reader', async () => { + const follower = new SessionReadFollower() + const abort = new AbortController() + const iterator = follower.read(abort.signal)[Symbol.asyncIterator]() + const pending = iterator.next() + abort.abort() + follower.push({ type: 'changed', state: { + sessionId: SessionId('closed'), completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, + } }) + expect(await pending).toMatchObject({ done: true }) +}) + +it('preserves the first follower failure even when cancellation follows immediately', async () => { + const follower = new SessionReadFollower() + const abort = new AbortController() + const iterator = follower.read(abort.signal)[Symbol.asyncIterator]() + const pending = iterator.next() + const error = new Error('failed') + follower.close(error) + abort.abort() + follower.close() + await expect(pending).rejects.toBe(error) +}) + +it('keeps the first completion unread after a live zero-turn Session is marked unread then read', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('first-turn')) + await service.mark(session.id, { type: 'unread' }) + await service.mark(session.id, { type: 'read', throughTurn: 0 }) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it('restarts filtered followers on access changes so new grants receive a baseline', async () => { + const { ctx, allows } = await harness() + allows.mockRestore() + const session = ctx.sessions.create(SessionId('new-grant')) + end(session, 1) + const principal = { kind: 'reading-test' } as const + let granted = false + ctx.remoteAccess.registerPolicy('reading-test', { bindings: () => granted ? [{ + role: { name: 'reader', resource: 'session', actions: ['sessionStatus/follow'] }, + resource: { kind: 'session', id: session.id }, + }] : [] }) + const abort = new AbortController() + const invocation: RemoteInvocation = { + request: { namespace: 'sessionStatus', method: 'follow', args: {} }, service: 'sessionStatus', + peer: new Peer(ctx, { principal }), signal: abort.signal, + uplink: (): AsyncIterable => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }), + } + const scoped = ctx.extend({ invocation }).sessionStatus + const iterator = scoped.follow(abort.signal)[Symbol.asyncIterator]() + try { + expect(await nextFrame(iterator)).toEqual({ type: 'baseline', items: [] }) + const ended = iterator.next() + granted = true + ctx.remoteAccess.invalidate(principal) + expect(await ended).toMatchObject({ done: true }) + expect(await baseline(scoped)).toEqual([expect.objectContaining({ sessionId: session.id, completedTurn: 1 })]) + } finally { + abort.abort() + await iterator.return?.() + } +}) + +it('reports a failed access stream without leaving its reading follower open', async () => { + const { ctx, service } = await harness() + vi.spyOn(ctx.remoteAccess, 'follow').mockImplementation(async function* () { + yield { type: 'baseline', owner: true } + throw new Error('access stream failed') + }) + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + await expect(iterator.next()).rejects.toMatchObject({ code: 'session-status/unavailable' }) +}) + +it('discards every record when the service reloads', async () => { + const { ctx, service, fiber } = await harness() + const session = ctx.sessions.create(SessionId('restart')) + end(session, 1) + await service.mark(session.id, { type: 'unread' }) + await fiber.dispose() + await ctx.plugin(SessionStatusService) + expect(await baseline(ctx.sessionStatus)).toEqual([]) +}) + +it('records completions without waiting for or triggering a Session flush', async () => { + const { ctx, service } = await harness() + const flush = vi.fn(() => { throw new Error('unavailable disk') }) + ctx.on('session/flush', flush) + const session = ctx.sessions.create(SessionId('memory-only')) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) + expect(flush).not.toHaveBeenCalled() +}) + +it('rechecks a Session opened while its metadata lookup is pending', async () => { + const { ctx, service, stat } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('opening') + const mark = service.mark(id, { type: 'read', throughTurn: 0 }) + const session = ctx.sessions.create(id) + pending.resolve({}) + await expect(mark).resolves.toBeUndefined() + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it('keeps a completion unread when an earlier read position arrives after metadata lookup', async () => { + const { ctx, service, stat } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('opening-completed') + const mark = service.mark(id, { type: 'read', throughTurn: 0 }) + end(ctx.sessions.create(id), 1) + pending.resolve({}) + await expect(mark).resolves.toBeUndefined() + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it.each(['service', 'Host'] as const)('discards pending marks without waiting for metadata during %s teardown', async (owner) => { + const { ctx, service, stat, fiber } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('closing') + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + const closed = iterator.next() + const mark = service.mark(id, { type: 'unread' }) + const rejected = expect(mark).rejects.toMatchObject({ code: 'session-status/unavailable' }) + let disposed = false + const disposal = (owner === 'Host' ? ctx.fiber.dispose() : fiber.dispose()).then(() => { disposed = true }) + try { + expect(await closed).toMatchObject({ done: true }) + await vi.waitFor(() => { expect(disposed).toBe(true) }) + await expect(service.mark(id, { type: 'read', throughTurn: 0 })) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + await expect(service.follow(new AbortController().signal)[Symbol.asyncIterator]().next()) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + } finally { + pending.resolve({}) + await Promise.allSettled([rejected, disposal]) + await iterator.return?.() + } + await rejected + expect(disposed).toBe(true) +}) + +it('keeps other readers available after a metadata failure', async () => { + const { ctx, service, stat } = await harness() + stat.mockRejectedValueOnce(new Error('metadata unavailable')) + await expect(service.mark(SessionId('failed'), { type: 'unread' })) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + const session = ctx.sessions.create(SessionId('healthy')) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ sessionId: session.id, completedTurn: 1 })]) +}) + +it('keeps arbitrary Session ids distinct without filesystem restrictions', async () => { + const { ctx, service } = await harness() + const ids = ['thread.42', 'user/1', '..', 'a'.repeat(200), '\ud800', '\ufffd'].map(SessionId) + for (const id of ids) end(ctx.sessions.create(id), 1) + expect((await baseline(service)).map(record => record.sessionId).sort()).toEqual([...ids].sort()) +}) diff --git a/packages/client/ui-session-status/tsconfig.client.json b/packages/client/ui-session-status/tsconfig.client.json new file mode 100644 index 0000000000..0e04c23729 --- /dev/null +++ b/packages/client/ui-session-status/tsconfig.client.json @@ -0,0 +1,47 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../api/remote-access/tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-session-status/tsconfig.host.json b/packages/client/ui-session-status/tsconfig.host.json new file mode 100644 index 0000000000..4b8c8637f5 --- /dev/null +++ b/packages/client/ui-session-status/tsconfig.host.json @@ -0,0 +1,34 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/spec.ts", + "src/types.ts", + "src/feed.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../api/remote-access/tsconfig.host.json" + }, + { + "path": "../../session/session-persistence" + }, + { + "path": "../../util/deque" + } + ] +} diff --git a/packages/client/ui-session-status/tsconfig.json b/packages/client/ui-session-status/tsconfig.json index 4c10ff072a..2a0b0e33f7 100644 --- a/packages/client/ui-session-status/tsconfig.json +++ b/packages/client/ui-session-status/tsconfig.json @@ -1,36 +1,7 @@ { - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, - { - "path": "../../api/session-controller/tsconfig.client.json" - }, - { - "path": "../../core/session" - }, - { - "path": "../store" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-session" - }, - { - "path": "../ui-slots" - } + { "path": "./tsconfig.host.json" }, + { "path": "./tsconfig.client.json" } ] } diff --git a/packages/client/ui-session-status/tsdown.config.ts b/packages/client/ui-session-status/tsdown.config.ts index 7aa03cebc1..620261533c 100644 --- a/packages/client/ui-session-status/tsdown.config.ts +++ b/packages/client/ui-session-status/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle(import.meta.dirname, ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-sidebar/README.i18n.yaml b/packages/client/ui-sidebar/README.i18n.yaml index 6ce4278621..5847e07229 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -51,8 +51,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-sidebar/known-limitations-and-deferred-work: - en: 9738f4cd887876d0 - zh: 95a646deba4a6489 + en: f31345fa08c77f91 + zh: e2639d597353207f /deepseek-ai-dsh-client-ui-sidebar/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index ea682c7e41..43cfe45193 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -127,7 +127,6 @@ These limits define what the shell owns versus what its occupants own; they are - **Session state-dot rendering is owned by ui-workspace** — no done/error notification sources are available to this shell. - **Workspace browser behavior is composition-owned** — grouping, ordering, search, and row state belong to ui-workspace, not this shell. -- **"New task completed" unread marking is local viewing state** — completion-time > last-seen never reaches the host. - **Copying the local-build version is mouse-only** — keyboard activation of the brand starts a session. - **Only wheel and trackpad input crosses the navigation boundary in one gesture** — touch drags keep native nested scrolling and stop where the viewport reaches its end; browsers without scroll-state container queries scroll the section first. Wheel steps split in JavaScript run on the main thread without smooth-scrolling animation or overscroll bounce. diff --git a/packages/client/ui-sidebar/README.zh.md b/packages/client/ui-sidebar/README.zh.md index 58ccbebef2..2f0c507119 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -127,7 +127,6 @@ root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区 - **Session 状态点渲染由 ui-workspace 持有**:本外壳没有可用的 done/error 通知数据源。 - **Workspace 浏览行为由组合持有**:分组、排序、搜索与行状态都属于 ui-workspace,不属于此外壳。 -- **「New task completed」未读标记是本地查看状态**:完成时间 > 上次查看时间这一事实永远不会到达宿主。 - **复制本地构建版本号仅支持鼠标**:键盘激活品牌会新建会话。 - **只有滚轮和触控板输入能在一次手势中越过导航边界**:触摸拖动保持浏览器原生的嵌套滚动,在视口滚到底时停止;不支持滚动状态容器查询的浏览器会先滚动区块。由 JavaScript 分配的滚轮步进在主线程执行,没有平滑滚动动画,也没有越界回弹。 diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 660db73fd5..7ff86bb02c 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -449,7 +449,7 @@ describe('SubagentHeaderLineage', () => { const input = props(catalog({ entries: [{ id: CHILD, mode: 'continuable', label: 'worker', activity: 'inactive' }] })) const initial = input.useSessions(state => state) const statuses: SessionStatusSnapshot = new Map([[CHILD, { - running: true, completionUnread: false, pendingInteraction: undefined, + running: true, completionUnread: false, completionFailed: false, pendingInteraction: undefined, }]]) render( select({ ...initial, ids: [] })} diff --git a/packages/client/ui-subagent/tsconfig.json b/packages/client/ui-subagent/tsconfig.json index cbf78e252c..1478265add 100644 --- a/packages/client/ui-subagent/tsconfig.json +++ b/packages/client/ui-subagent/tsconfig.json @@ -12,7 +12,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../../../vendor/cordis" diff --git a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx index 84f1d6045d..84255d3e45 100644 --- a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx +++ b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx @@ -885,14 +885,14 @@ describe('WorkflowRunPanel', () => { byId: { ...listState().byId, [CHILD_ID]: { ...listState().byId[CHILD_ID]!, running: false } }, }) const openSession = vi.fn() - let statuses = new Map([[CHILD_ID, { running: true, pendingInteraction: undefined, completionUnread: false }]]) + let statuses = new Map([[CHILD_ID, { running: true, pendingInteraction: undefined, completionUnread: false, completionFailed: false }]]) const props: WorkflowRunPanelProps = { ...panelProps(data, sessions, openSession), useSessionStatus: select => select(statuses), } const view = render() fireEvent.click(screen.getByRole('button', { name: '打开 worker' })) expect(openSession).toHaveBeenCalledWith({ parentSessionId: PARENT_ID, childSessionId: CHILD_ID, mode: 'one-shot' }) - statuses = new Map([[CHILD_ID, { running: false, pendingInteraction: undefined, completionUnread: false }]]) + statuses = new Map([[CHILD_ID, { running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false }]]) view.rerender() expect(screen.queryByRole('button', { name: '打开 worker' })).toBeNull() }) diff --git a/packages/client/ui-workflow-run/tsconfig.json b/packages/client/ui-workflow-run/tsconfig.json index f48fbe28f0..786a9f9b06 100644 --- a/packages/client/ui-workflow-run/tsconfig.json +++ b/packages/client/ui-workflow-run/tsconfig.json @@ -18,7 +18,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../store" diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index e8365eb4c0..7e4bc36aea 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-workspace/use-this-package: - en: 9226c42c2559fbf0 - zh: 5527f59aa379c9fd + en: c24ee36a92dcb08e + zh: 1383bbf4d2579e97 /deepseek-ai-dsh-client-ui-workspace/use-this-package/reordering-and-view-options: en: 55054408b8593c70 zh: 9fdf9861a48abba3 @@ -27,11 +27,11 @@ en: 148f2ab562fecc09 zh: 9ba7c07999705b31 /deepseek-ai-dsh-client-ui-workspace/use-this-package/managing-sessions: - en: 29b6b357fc6be99a - zh: 182996efed35029c + en: 0515aae59aa89cce + zh: 83b150ab0e233d8a /deepseek-ai-dsh-client-ui-workspace/use-this-package/pending-interactions: - en: 9fb88260380bf093 - zh: 3bace2b96ecd4a82 + en: 27089341ac2cbcc4 + zh: 63d818a53a7c20e9 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: en: 249d9552d8bef805 zh: 405b1c636cba8e0b @@ -42,8 +42,8 @@ en: 868904dbfb5713f8 zh: 35d3c285ed770885 /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions: - en: 511408e373ff8c70 - zh: 7ae3b396171821a4 + en: d309a8bc5085616b + zh: 66152a89d58cb7cb /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions/packaged-client-plugin: en: 36934671b80b11ae zh: 8e0aea6162e35e77 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index fb4c55b2d2..00eea4ac7a 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -31,6 +31,8 @@ Use the sidebar to browse Workspaces and their Sessions, reorder them, and start History rows without a stored title use the localized unnamed label (未命名 / Untitled), rather than a directory name. The current blank row remains New Session; other blank rows remain hidden. Rename drafts use the stored title, or start empty when unnamed; unnamed rows do not offer title copying. +**Mark as read / Mark as unread** in each Session menu saves shared reading state on the Host; archived Sessions read as read and offer neither. Unread reminders survive browser reloads while the Host runs, and reset on Host restart or plugin reload, appear alongside live activity, and do not imply successful completion. Window focus confirms natural unread content. Manual unread stays until the main view switches to the Session or an explicit read mark arrives, and automatic confirmation always waits for the content to arrive. See [Session status](../ui-session-status/README.md) for synchronization and lifetime limits. + Without hover, Workspace actions appear only while expanded, Session More buttons stay visible, and search-result actions remain visible. Toolbar tooltips render outside the sidebar so its drawer animation does not crop them. Search and rename inputs use 16px text with a coarse pointer; a fine pointer keeps their compact sizes. ### Reordering and view options @@ -67,11 +69,13 @@ Archive commits without a confirmation dialog for a quiet Session and retains th Session update times use the tertiary label color, including on archived rows. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start. -The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. The navigation drawer allows these commands; other dialogs follow the command’s modal restrictions. Rename requires a nonblank main Conversation with no other modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. +The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, Archive session, and Toggle read/unread. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. The navigation drawer allows these commands; other dialogs follow the command’s modal restrictions. Rename requires a nonblank main Conversation with no other modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. + +Toggle read/unread uses Command+Shift+U on macOS and Control+Shift+U on Windows in both Desktop and Web. Linux leaves it unbound for customization. It targets the nonblank main Conversation, requires synchronized reading state and permission, and does not run behind another main panel or a modal. Menu actions target their own row. Successful and stale reading changes remain silent; only a failed write raises a toast. ### Pending interactions -Session rows render the runtime's live `pendingInteraction` classification: approvals report **Waiting for approval**, plan reviews report **Plan awaiting review**, and ordinary questions report **Waiting for answer**. While an interaction is pending, the row uses the shared warning dot and replaces its trailing update time with **Approval**, **Plan review**, or **Answer**; the full status and relative time remain in hover details. Pending interaction takes precedence over the shared ongoing loader; a finished-but-unviewed Session uses done, while idle remains dot-free in the row and uses the shared idle dot in its hover details. The leading seat renders only while the row's primary status is idle — no pending interaction, no own or descendant activity, and no unviewed completion — so an occupant there never appears beside the row's own status dot. An archived row keeps that cell blank: it shows neither a status dot nor the seat, and its live status appears on the hover card only. +Session rows render the runtime's live `pendingInteraction` classification: approvals report **Waiting for approval**, plan reviews report **Plan awaiting review**, and ordinary questions report **Waiting for answer**. While an interaction is pending, the row uses the shared warning dot and replaces its trailing update time with **Approval**, **Plan review**, or **Answer**; the full status and relative time remain in hover details. Pending interaction takes precedence over the shared ongoing loader, which takes precedence over unread reminders. A failed turn uses a red reminder; other ended turns, including cancellation, use green. Opening the Session or marking it read clears either reminder. Marking a Session unread preserves its title weight and any pending-interaction dot. Idle remains dot-free in the row and uses the shared idle dot in its hover details. The leading seat renders only while the row's primary status is idle — no pending interaction, no own or descendant activity, and no unviewed completion — so an occupant there never appears beside the row's own status dot. An archived row keeps that cell blank: it shows neither a status dot nor the seat, and its live status appears on the hover card only. ### Active Schedule markers @@ -121,9 +125,9 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session row actions -Built-in Session menu actions register structured contributions through `ctx.contextMenus`: pin (100), rename (200), fork (300), copy ID (450), and archive (600). Native directory reveal belongs to ui-open-in-app (500). Rename, fork, and archive associate existing command IDs for live shortcut display; clicks retain their captured Session and invoke the existing business callback. Pin and archive also retain their hover-button Slot entries. +Built-in Session menu actions register structured contributions through `ctx.contextMenus`: pin (100), rename (200), read/unread (250), fork (300), copy ID (450), and archive (600). Native directory reveal belongs to ui-open-in-app (500). Rename, read/unread, fork, and archive associate existing command IDs for live shortcut display; clicks retain their captured Session and invoke the existing business callback. Pin and archive also retain their hover-button Slot entries. -The legacy `sidebar.workspaces.session.menu.item` Slot remains for external React entries. It receives `sessionId`, `displayTitle`, and `useMenuOpenState` for dismissal. Legacy entries retain their own order and render together before Archive; their priority no longer replaces built-in data actions. New contributions use the [menu service](../ui-context-menu/README.md). Built-in visibility tracks permissions and pin/archive membership while open; dialogs and notices remain frame-wide overlays. +The legacy `sidebar.workspaces.session.menu.item` Slot remains for external React entries. It receives `sessionId`, `displayTitle`, and `useMenuOpenState` for dismissal. Legacy entries retain their own order and render together before Archive; their priority no longer replaces built-in data actions. New contributions use the [menu service](../ui-context-menu/README.md). Built-in visibility tracks permissions and pin/archive membership while open; the reading action also tracks reminders and synchronization readiness. Dialogs and notices remain frame-wide overlays. The existing notice overlay dispatches `workspace.toast` by notice kind. Keyed registrations inject localized display mappings and their own actions; only archive notices subscribe to the viewing filter. They render the package-local `workspace.toast.content` Factory, which reuses the Toast primitive once for all presentations. The existing notice state, display sequence, latest-notice replacement, and dismissal remain shared; locale or filter changes do not restart the same notice's timer. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 2037167c1c..0075ba3c0d 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -31,6 +31,8 @@ kind: "package-reference" 未保存标题的历史会话显示本地化名称「未命名 / Untitled」,不使用目录名兜底。当前空会话仍显示「新会话」,其他空会话仍隐藏。重命名草稿使用已保存标题,无标题时留空;无标题行不提供标题复制。 +会话菜单中的**标为已读/标为未读**将阅读状态保存到宿主,并同步给各前端;已归档的会话按已读处理,不提供这两项。宿主运行期间刷新浏览器会保留未读提醒,宿主重启或插件重载则会重置,可与运行状态同时出现,不表示任务成功。窗口聚焦只确认自然未读。手动未读会保留到主视图切换到该会话或主动标为已读,自动确认始终等待正文到达。同步和生命周期的限制见[会话状态](../ui-session-status/README.zh.md)。 + 无 hover 时,工作区操作仅在展开时显示,会话的更多按钮始终显示,搜索结果操作保持可见。工具栏的提示气泡在侧边栏外渲染,避免被抽屉动画裁切。使用粗指针时,搜索和重命名输入框采用 16px 字号;精细指针下保留紧凑字号。 ### 重排序与视图选项 @@ -67,11 +69,13 @@ Session 行内的 Rename 操作打开一个以该行显示标题预填的对话 会话更新时间使用 tertiary 文本色,包括已归档行。标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。 -快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。导航抽屉允许这些命令,其他对话框遵循命令的模态限制。重命名要求主区域正在显示非空会话,且没有其他模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 +快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话、归档会话和切换已读/未读。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。导航抽屉允许这些命令,其他对话框遵循命令的模态限制。重命名要求主区域正在显示非空会话,且没有其他模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 + +切换已读/未读在 macOS 的 Desktop 和 Web 中使用 Command+Shift+U,在 Windows 使用 Control+Shift+U;Linux 默认不绑定,可自行配置。快捷键操作主区域显示的非空会话,要求阅读状态已同步且具有操作权限;切换到其他主面板或打开模态对话框时不可用。菜单操作始终针对所在行。成功修改及并发导致的过期请求都不弹提示,只有保存失败时显示 toast。 ### 待处理交互 -Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**等待审批**,计划审阅显示**计划待审**,普通问题显示**等待回答**。交互待处理期间,该行使用共享 warning 橙点,并以**待批准**、**计划待审**或**待回答**替换尾部更新时间;悬停详情仍保留完整状态和相对时间。待处理交互的优先级高于共享 ongoing loading;已完成但未查看的 Session 使用 done,idle 在行内不显示点,在悬停详情中使用共享 idle 灰点。 行首 seat 仅在该行的主状态为 idle 时渲染——没有待处理交互、没有自身或后代活动、也没有未查看的完成提醒——因此该处的占用方不会与行自身的状态点同时出现。归档行该格整体留空:既不显示状态点也不挂 seat,其活动状态只出现在悬浮卡片上。 +Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**等待审批**,计划审阅显示**计划待审**,普通问题显示**等待回答**。交互待处理期间,该行使用共享 warning 橙点,并以**待批准**、**计划待审**或**待回答**替换尾部更新时间;悬停详情仍保留完整状态和相对时间。待处理交互优先于共享 ongoing loading,后者优先于未读提醒。失败的轮次显示红点,其他结束的轮次(含主动取消)显示绿点。打开会话或标为已读会清除这两种提醒。标为未读不会改变标题字重或已有的待处理交互点。idle 在行内不显示点,在悬停详情中使用共享 idle 灰点。行首 seat 仅在该行的主状态为 idle 时渲染——没有待处理交互、没有自身或后代活动、也没有未查看的完成提醒——因此该处的占用方不会与行自身的状态点同时出现。归档行该格整体留空:既不显示状态点也不挂 seat,其活动状态只出现在悬浮卡片上。 ### 活动 Schedule 标识 @@ -122,9 +126,9 @@ Session 行可通过 Tab 聚焦,使用不带修饰键的 Enter 或空格打开 ### Session 行 action -内置 Session 菜单动作通过 `ctx.contextMenus` 注册结构化贡献:置顶(100)、重命名(200)、分支(300)、复制 ID(450)和归档(600)。本机目录定位由 ui-open-in-app 提供(500)。重命名、分支和归档关联已有命令 ID,以显示实时快捷键;点击仍针对捕获的 Session 调用现有业务回调。置顶和归档同时保留悬停按钮 Slot 条目。 +内置 Session 菜单动作通过 `ctx.contextMenus` 注册结构化贡献:置顶(100)、重命名(200)、已读/未读(250)、分支(300)、复制 ID(450)和归档(600)。本机目录定位由 ui-open-in-app 提供(500)。重命名、已读/未读、分支和归档关联已有命令 ID,以显示实时快捷键;点击仍针对捕获的 Session 调用现有业务回调。置顶和归档同时保留悬停按钮 Slot 条目。 -旧 `sidebar.workspaces.session.menu.item` Slot 保留给外部 React 条目,提供 `sessionId`、`displayTitle` 和用于关闭菜单的 `useMenuOpenState`。旧条目保持彼此顺序,集中显示在归档之前;其 priority 不再替换内置数据动作。新贡献使用[菜单服务](../ui-context-menu/README.zh.md)。内置动作在菜单打开时持续响应权限和置顶/归档状态;对话框与提示仍为应用级浮层。 +旧 `sidebar.workspaces.session.menu.item` Slot 保留给外部 React 条目,提供 `sessionId`、`displayTitle` 和用于关闭菜单的 `useMenuOpenState`。旧条目保持彼此顺序,集中显示在归档之前;其 priority 不再替换内置数据动作。新贡献使用[菜单服务](../ui-context-menu/README.zh.md)。内置动作在菜单打开时持续响应权限和置顶/归档状态;阅读动作还会响应未读提醒和同步就绪状态。对话框与提示仍为应用级浮层。 现有通知浮层按通知 kind 分派 `workspace.toast`。各 keyed 注册注入本地化展示映射与自己的操作,只有归档通知订阅查看筛选状态。它们渲染包内的 `workspace.toast.content` Factory,所有展示共用一处 Toast primitive。现有通知状态、显示序号、最新提示替换及关闭逻辑仍共享;语言或筛选变化不会重新启动同一条提示的计时。 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 7e53a43400..ffa5850cb8 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -320,6 +320,7 @@ export type SessionRowActionProps = export type RowToast = | { kind: 'archived'; sessionId: SessionId; message?: string; tone?: 'success' | 'warning' } | { kind: 'stoppedAndArchived'; sessionId: SessionId; message?: string; tone?: 'success' | 'warning' } + | { kind: 'readingFailed' } | { kind: 'sessionIdCopied' } | { kind: 'sessionIdCopyFailed' } | { kind: 'pinFailed' } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 425fcbf712..5d95282a59 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -1,4 +1,4 @@ -import { IconEditOutlineRegular, IconTrashOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconUnarchiveOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, IconCopyOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconEditOutlineRegular, IconTrashOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconUnarchiveOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, IconCopyOutlineRegular, IconMailReadOutlineRegular, IconMailUnreadOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { SessionMenu } from './session-actions/SessionMenu.tsx' import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** @@ -137,7 +137,7 @@ const NS = 'workspace' */ export const inject = ['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', - 'uiSession.sessionStatus', + 'uiSession', 'uiSession.sessionStatus', ] /** @@ -196,6 +196,9 @@ export function apply(ctx: Context): void { // Registry-global sets as Sets, rebuilt only when the Workspace snapshot changes. const pinnedSet = derive(workspaces.list, snapshot => new Set(snapshot.pinnedSessionIds)) const archivedSet = derive(workspaces.list, snapshot => new Set(snapshot.archivedSessionIds)) + const markSession = (sessionId: SessionId, unread: boolean): void => { + ctx.uiSession.sessionStatus.mark(sessionId, unread).catch(() => { notify({ kind: 'readingFailed' }) }) + } // Plugin-private facts the row actions and their overlay surfaces share: // the pending rename request and the notice on display. Each business // writes through its own injected callback and the surface reads through @@ -262,7 +265,7 @@ export function apply(ctx: Context): void { unarchiveSession, }) installWorkspaceShortcuts(ctx, uiWorkspace, shortcutControls, archiveInjected().archiveSession, - (reason) => { notify({ kind: 'shortcutForkFailed', reason }) }) + (reason) => { notify({ kind: 'shortcutForkFailed', reason }) }, markSession) const archiveConfirmInjected = (): SessionArchiveConfirmInjected => ({ hooks: { archiveRequest }, settleSessionArchive: () => { archiveRequest.set(null) }, @@ -323,6 +326,7 @@ export function apply(ctx: Context): void { 'workspace.pin': IconPinOutlineRegular, 'workspace.unpin': IconPinFillRegular, 'workspace.archive': IconArchiveOutlineRegular, 'workspace.unarchive': IconUnarchiveOutlineRegular, 'workspace.fork': IconBranchOutlineRegular, 'workspace.copy': IconCopyOutlineRegular, + 'workspace.markRead': IconMailReadOutlineRegular, 'workspace.markUnread': IconMailUnreadOutlineRegular, })) yield ctx.slots.register({ name: 'contextMenu.icon', key }, Icon) }) ctx.effect(() => ctx.contextMenus.register({ @@ -390,6 +394,7 @@ export function apply(ctx: Context): void { }, SessionMenu)) registerSessionMenus(ctx, { ...pinInjected(), ...archiveInjected(), ...renameInjected(), ...forkInjected(), ...sessionIdInjected(), + markSession, }) ctx.slots.inject('sidebar.workspaces.session.row.action', function* () { yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'archive', order: 100, locale: NS, inject: archiveInjected }, ArchiveSessionRowButton) diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index 7420f4547b..bcdb692951 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -13,6 +13,11 @@ export const zh = { 'session.new': '新会话', 'session.untitled': '未命名', 'shortcut.noSession': '请先选择一个会话', + 'shortcut.closeDialog': '请先关闭打开的对话框', + 'shortcut.closePanel': '请先关闭打开的面板,返回会话', + 'shortcut.archivedReading': '已归档的会话没有未读提醒', + 'shortcut.toggleRead': '切换已读/未读', + 'shortcut.readingUnavailable': '当前无法修改阅读状态,请刷新页面以重新连接', 'shortcut.noPicker': '目录选择器不可用', 'shortcut.directoryBusy': '正在选择或添加工作区', 'shortcut.noCompletedTurn': '当前会话没有已结束的轮次', @@ -114,7 +119,11 @@ export const zh = { 'status.compact.approval': '待审批', 'status.compact.planReview': '计划待审', 'status.compact.answer': '待回答', - 'status.completed': '已完成', + 'status.unread': '未读', + 'status.failed': '运行出错', + 'menu.markRead': '标为已读', + 'menu.markUnread': '标为未读', + 'toast.readingFailed': '未能确认阅读状态,请重试', 'hover.created': '创建于 {time}', 'hover.copied': '已复制', 'date.ymd': '{y}年{m}月{d}日', @@ -139,6 +148,11 @@ export const en = { 'session.new': 'New Session', 'session.untitled': 'Untitled', 'shortcut.noSession': 'Select a session first', + 'shortcut.closeDialog': 'Close the open dialog first', + 'shortcut.closePanel': 'Close the open panel to return to the session', + 'shortcut.archivedReading': 'Archived sessions have no unread reminders', + 'shortcut.toggleRead': 'Toggle read/unread', + 'shortcut.readingUnavailable': 'Reading state is unavailable. Reload the page to reconnect.', 'shortcut.noPicker': 'Directory picker unavailable', 'shortcut.directoryBusy': 'Selecting or adding a workspace', 'shortcut.noCompletedTurn': 'This session has no completed turn', @@ -240,7 +254,11 @@ export const en = { 'status.compact.approval': 'Approval', 'status.compact.planReview': 'Plan review', 'status.compact.answer': 'Answer', - 'status.completed': 'Completed', + 'status.unread': 'Unread', + 'status.failed': 'Run failed', + 'menu.markRead': 'Mark as read', + 'menu.markUnread': 'Mark as unread', + 'toast.readingFailed': 'Could not confirm reading state. Try again.', 'hover.created': 'Created {time}', 'hover.copied': 'Copied', 'date.ymd': '{y}-{m}-{d}', @@ -262,6 +280,11 @@ export const ja = { 'session.new': '新しいセッション', 'session.untitled': '無題', 'shortcut.noSession': '先にセッションを選択してください', + 'shortcut.closeDialog': '先に開いているダイアログを閉じてください', + 'shortcut.closePanel': '開いているパネルを閉じてセッションに戻ってください', + 'shortcut.archivedReading': 'アーカイブ済みのセッションには未読の通知がありません', + 'shortcut.toggleRead': '既読・未読を切り替え', + 'shortcut.readingUnavailable': '現在、既読状態を変更できません。ページを再読み込みして接続し直してください。', 'shortcut.noPicker': 'ディレクトリピッカーを利用できません', 'shortcut.directoryBusy': 'ワークスペースを選択または追加しています', 'shortcut.noCompletedTurn': 'このセッションには完了したターンがありません', @@ -363,7 +386,11 @@ export const ja = { 'status.compact.approval': '承認', 'status.compact.planReview': '計画レビュー', 'status.compact.answer': '回答', - 'status.completed': '完了', + 'status.unread': '未読', + 'status.failed': '実行エラー', + 'menu.markRead': '既読にする', + 'menu.markUnread': '未読にする', + 'toast.readingFailed': '既読状態を確認できませんでした。再試行してください。', 'hover.created': '作成日時 {time}', 'hover.copied': 'コピーしました', 'date.ymd': '{y}-{m}-{d}', @@ -385,6 +412,11 @@ export const es = { 'session.new': 'Nueva sesión', 'session.untitled': 'Sin título', 'shortcut.noSession': 'Seleccione una sesión primero', + 'shortcut.closeDialog': 'Cierre primero el cuadro de diálogo abierto', + 'shortcut.closePanel': 'Cierre el panel abierto para volver a la sesión', + 'shortcut.archivedReading': 'Las sesiones archivadas no tienen avisos de no leído', + 'shortcut.toggleRead': 'Alternar leído/no leído', + 'shortcut.readingUnavailable': 'El estado de lectura no está disponible. Recarga la página para volver a conectarte.', 'shortcut.noPicker': 'Selector de directorio no disponible', 'shortcut.directoryBusy': 'Seleccionar o agregar un espacio de trabajo', 'shortcut.noCompletedTurn': 'Esta sesión no tiene turno completo', @@ -486,7 +518,11 @@ export const es = { 'status.compact.approval': 'Aprobación', 'status.compact.planReview': 'Revisión del plan', 'status.compact.answer': 'respuesta', - 'status.completed': 'Completado', + 'status.unread': 'No leído', + 'status.failed': 'La ejecución ha fallado', + 'menu.markRead': 'Marcar como leído', + 'menu.markUnread': 'Marcar como no leído', + 'toast.readingFailed': 'No se pudo confirmar el estado de lectura. Inténtalo de nuevo.', 'hover.created': 'Creado {time}', 'hover.copied': 'Copiado', 'date.ymd': '{y}-{m}-{d}', @@ -508,6 +544,11 @@ export const fr = { 'session.new': 'Nouvelle séance', 'session.untitled': 'Sans titre', 'shortcut.noSession': "Sélectionnez d'abord une session", + 'shortcut.closeDialog': "Fermez d'abord la boîte de dialogue ouverte", + 'shortcut.closePanel': 'Fermez le panneau ouvert pour revenir à la session', + 'shortcut.archivedReading': "Les sessions archivées n'ont pas de rappel non lu", + 'shortcut.toggleRead': 'Basculer lu/non lu', + 'shortcut.readingUnavailable': 'Le statut de lecture est indisponible. Rechargez la page pour vous reconnecter.', 'shortcut.noPicker': 'Sélecteur de répertoire indisponible', 'shortcut.directoryBusy': "Sélection ou ajout d'un espace de travail", 'shortcut.noCompletedTurn': "Cette session n'a pas de tour terminé", @@ -609,7 +650,11 @@ export const fr = { 'status.compact.approval': 'Approbation', 'status.compact.planReview': 'Révision des plans', 'status.compact.answer': 'Réponse', - 'status.completed': 'Terminé', + 'status.unread': 'Non lu', + 'status.failed': 'Échec de l’exécution', + 'menu.markRead': 'Marquer comme lu', + 'menu.markUnread': 'Marquer comme non lu', + 'toast.readingFailed': 'Impossible de confirmer le statut de lecture. Réessayez.', 'hover.created': 'Créé {time}', 'hover.copied': 'Copié', 'date.ymd': '{y}-{m}-{d}', @@ -631,6 +676,11 @@ export const de = { 'session.new': 'Neue Sitzung', 'session.untitled': 'Ohne Titel', 'shortcut.noSession': 'Wählen Sie zunächst eine Sitzung aus', + 'shortcut.closeDialog': 'Schließen Sie zuerst den geöffneten Dialog', + 'shortcut.closePanel': 'Schließen Sie das geöffnete Panel, um zur Sitzung zurückzukehren', + 'shortcut.archivedReading': 'Archivierte Sitzungen haben keine Ungelesen-Hinweise', + 'shortcut.toggleRead': 'Gelesen/ungelesen umschalten', + 'shortcut.readingUnavailable': 'Der Lesestatus ist nicht verfügbar. Lade die Seite neu, um die Verbindung wiederherzustellen.', 'shortcut.noPicker': 'Verzeichnisauswahl nicht verfügbar', 'shortcut.directoryBusy': 'Auswählen oder Hinzufügen eines Arbeitsbereichs', 'shortcut.noCompletedTurn': 'Diese Sitzung hat keine abgeschlossene Runde', @@ -732,7 +782,11 @@ export const de = { 'status.compact.approval': 'Zustimmung', 'status.compact.planReview': 'Planüberprüfung', 'status.compact.answer': 'Antwort', - 'status.completed': 'Abgeschlossen', + 'status.unread': 'Ungelesen', + 'status.failed': 'Ausführung fehlgeschlagen', + 'menu.markRead': 'Als gelesen markieren', + 'menu.markUnread': 'Als ungelesen markieren', + 'toast.readingFailed': 'Der Lesestatus konnte nicht bestätigt werden. Versuche es erneut.', 'hover.created': 'Erstellt {time}', 'hover.copied': 'Kopiert', 'date.ymd': '{y}-{m}-{d}', @@ -754,6 +808,11 @@ export const ru = { 'session.new': 'Новая сессия', 'session.untitled': 'Без названия', 'shortcut.noSession': 'Сначала выберите сеанс', + 'shortcut.closeDialog': 'Сначала закройте открытое диалоговое окно', + 'shortcut.closePanel': 'Закройте открытую панель, чтобы вернуться к сеансу', + 'shortcut.archivedReading': 'У архивных сеансов нет напоминаний о непрочитанном', + 'shortcut.toggleRead': 'Переключить прочитано/не прочитано', + 'shortcut.readingUnavailable': 'Статус прочтения недоступен. Перезагрузите страницу для повторного подключения.', 'shortcut.noPicker': 'Выбор каталога недоступен.', 'shortcut.directoryBusy': 'Выбор или добавление рабочего пространства', 'shortcut.noCompletedTurn': 'В этой сессии нет завершенных ходов', @@ -855,7 +914,11 @@ export const ru = { 'status.compact.approval': 'Одобрение', 'status.compact.planReview': 'Обзор плана', 'status.compact.answer': 'Ответ', - 'status.completed': 'Завершено', + 'status.unread': 'Не прочитано', + 'status.failed': 'Ошибка выполнения', + 'menu.markRead': 'Отметить как прочитанное', + 'menu.markUnread': 'Отметить как непрочитанное', + 'toast.readingFailed': 'Не удалось подтвердить статус прочтения. Повторите попытку.', 'hover.created': 'Создано {time}', 'hover.copied': 'Скопировано', 'date.ymd': '{y}-{m}-{d}', @@ -877,6 +940,11 @@ export const pt = { 'session.new': 'Nova sessão', 'session.untitled': 'Sem título', 'shortcut.noSession': 'Selecione uma sessão primeiro', + 'shortcut.closeDialog': 'Feche primeiro a caixa de diálogo aberta', + 'shortcut.closePanel': 'Feche o painel aberto para voltar à sessão', + 'shortcut.archivedReading': 'Sessões arquivadas não têm avisos de não lido', + 'shortcut.toggleRead': 'Alternar lido/não lido', + 'shortcut.readingUnavailable': 'O estado de leitura está indisponível. Recarregue a página para voltar a conectar.', 'shortcut.noPicker': 'Seletor de diretório indisponível', 'shortcut.directoryBusy': 'Selecionando ou adicionando um espaço de trabalho', 'shortcut.noCompletedTurn': 'Esta sessão não tem turno concluído', @@ -978,7 +1046,11 @@ export const pt = { 'status.compact.approval': 'Aprovação', 'status.compact.planReview': 'Revisão do plano', 'status.compact.answer': 'Resposta', - 'status.completed': 'Concluído', + 'status.unread': 'Não lido', + 'status.failed': 'Falha na execução', + 'menu.markRead': 'Marcar como lido', + 'menu.markUnread': 'Marcar como não lido', + 'toast.readingFailed': 'Não foi possível confirmar o estado de leitura. Tente novamente.', 'hover.created': 'Criado {time}', 'hover.copied': 'Copiado', 'date.ymd': '{y}-{m}-{d}', diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx index 04b56cb10c..e2094eeabf 100644 --- a/packages/client/ui-workspace/src/client/rows/Rows.tsx +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -382,7 +382,7 @@ interface SessionStatus { * outranks completion reminders. */ function sessionStatuses( - node: Pick, + node: Pick, t: RowTranslate, ): readonly [SessionStatus, ...SessionStatus[]] { const subagents: SessionStatus | undefined = node.runningSubagentCount === 0 @@ -423,13 +423,17 @@ function sessionStatuses( /* v8 ignore next -- closed PendingInteractionStatus union */ default: return assertNever(node.pendingInteraction) } - if (pending !== undefined) return subagents === undefined ? [pending] : [pending, subagents] + const completion: SessionStatus = node.failed + ? { state: 'error', label: t('status.failed') } + : { state: 'done', label: t('status.unread') } + const unread: SessionStatus[] = node.completed ? [completion] : [] + if (pending !== undefined) return subagents === undefined ? [pending, ...unread] : [pending, subagents, ...unread] if (node.running) { const primary: SessionStatus = { state: 'ongoing', label: t('status.running') } - return subagents === undefined ? [primary] : [primary, subagents] + return subagents === undefined ? [primary, ...unread] : [primary, subagents, ...unread] } - if (subagents !== undefined) return [subagents] - if (node.completed) return [{ state: 'done', label: t('status.completed') }] + if (subagents !== undefined) return [subagents, ...unread] + if (node.completed) return [completion] return [{ state: 'idle', label: t('status.idle') }] } @@ -468,10 +472,9 @@ function SessionHoverContent({ node, cwd, now, renderSlot, t }: { renderSlot: RowRenderSlots t: RowTranslate }) { - // On archived rows the archived line already says the session is inactive, - // so resting statuses (idle/completed) drop; live activity still shows. - const statuses = sessionStatuses(node, t) - .filter(status => !(node.archived && (status.state === 'done' || status.state === 'idle'))) + // Archived rows show live activity but suppress idle and unread reminders. + const statuses = sessionStatuses(node.archived ? { ...node, completed: false } : node, t) + .filter(status => !(node.archived && status.state === 'idle')) return (
{displayTitle(node, t)}
@@ -701,8 +704,8 @@ export function SessionNodeItem({ }} > {/* Pending interaction and own or descendant activity outrank the - finished-but-unviewed reminder, which returns after activity stops - and is cleared by opening the session. Archived rows keep the slot + unread reminder, which returns after activity stops + and clears after the visible content is acknowledged. Archived rows keep the slot blank — the grayed row carries the archived look — and their live status stays on the hover card only. */} diff --git a/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx b/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx index f312e0233f..a1b94ce8ac 100644 --- a/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx @@ -2,13 +2,17 @@ import type { Context } from '@deepseek-ai/cordis' import type { RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { MenuContribution, ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { ArchiveSessionInjected, ForkSessionInjected, PinSessionInjected, RenameSessionInjected, SessionIdInjected, } from '../contract/slots.ts' type Actions = Omit & ForkSessionInjected & RenameSessionInjected & SessionIdInjected + & { readonly markSession: (sessionId: SessionId, unread: boolean) => void } /** * Register built-in actions while retaining the legacy Slot for external components. @@ -22,11 +26,12 @@ export function registerSessionMenus(ctx: Context, actions: Actions): void { order: number, endpoints: readonly RemoteEndpoint[], resolve: MenuContribution<'session'>['resolve'], + sources: readonly ObservableSnapshot[] = [], ): void => { ctx.effect(() => ctx.contextMenus.register({ id: `session.${id}`, target: 'session', order, observe: ({ sessionId }) => [ - ctx.workspaces.list, ctx.locale, + ctx.workspaces.list, ctx.locale, ...sources, ...endpoints.map(action => ctx.remoteAccess.source('session', sessionId, action)), ], resolve, @@ -48,6 +53,18 @@ export function registerSessionMenus(ctx: Context, actions: Actions): void { id: 'rename', label: t('rename'), icon: { key: 'workspace.rename' }, commandId: 'session.rename' as ShortcutCommandId, run: () => { actions.requestSessionRename(target.sessionId, target.displayTitle) }, }] : []) + register('read-state', 250, ['sessionStatus/mark'], (target) => { + // Archived rows hide reminders and read as read, so they offer no reading mark. + if (archived(target) || !allowed(target, 'sessionStatus/mark')) return [] + const status = ctx.uiSession.sessionStatus + const unread = status.getSnapshot().get(target.sessionId)?.completionUnread === true + return [{ + id: 'mark', label: t(unread ? 'menu.markRead' : 'menu.markUnread'), + icon: { key: unread ? 'workspace.markRead' : 'workspace.markUnread' }, + commandId: 'session.toggleRead' as ShortcutCommandId, disabled: !status.readingReady.getSnapshot(), + run: () => { actions.markSession(target.sessionId, !unread) }, + }] + }, [ctx.uiSession.sessionStatus, ctx.uiSession.sessionStatus.readingReady]) register('fork', 300, ['session/fork'], target => allowed(target, 'session/fork') ? [{ id: 'fork', label: t('menu.fork'), icon: { key: 'workspace.fork' }, commandId: 'session.fork' as ShortcutCommandId, run: () => { actions.forkSession(target.sessionId) }, diff --git a/packages/client/ui-workspace/src/client/shortcuts.ts b/packages/client/ui-workspace/src/client/shortcuts.ts index 180c13fbcb..5fe67dd8c8 100644 --- a/packages/client/ui-workspace/src/client/shortcuts.ts +++ b/packages/client/ui-workspace/src/client/shortcuts.ts @@ -54,6 +54,7 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { * @param controls - browser-owned opening requests. * @param archiveSession - shared archive action, including running-work confirmation and notices. * @param reportForkFailure - publish a classified failure through the frame-wide notice channel. + * @param markSession - shared reading action; only failed writes raise a notice. */ export function installWorkspaceShortcuts( ctx: Context, @@ -61,6 +62,7 @@ export function installWorkspaceShortcuts( controls: ReturnType, archiveSession: (sessionId: SessionId) => void, reportForkFailure: (reason: 'unavailable' | 'failed') => void, + markSession: (sessionId: SessionId, unread: boolean) => void, ): void { const t = ctx.locale.bind('workspace') const current = () => Object.values(ctx.sessions.list.getSnapshot().byId) @@ -115,4 +117,30 @@ export function installWorkspaceShortcuts( archiveSession(target.id) } } }) + ctx.effect(() => ctx.shortcuts.register({ + id: 'session.toggleRead' as ShortcutCommandId, + label: () => t('shortcut.toggleRead'), aliases: ['mark as read', 'mark as unread', 'toggle unread'], + defaults: { + 'desktop:macos': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'desktop:windows': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'web:macos': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'web:windows': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + }, + regions: ['page', 'editable'], modals: [], + resolve: (context) => { + const target = current() + if (target === undefined || target.blank) return { status: 'blocked', reason: t('shortcut.noSession') } + // Like the row menu, a Peer that may not mark reading has no reading command. + if (!ctx.remoteAccess.source('session', target.id, 'sessionStatus/mark').getSnapshot()) return { status: 'pass' } + if (context.modal !== null) return { status: 'blocked', reason: t('shortcut.closeDialog') } + if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return { status: 'blocked', reason: t('shortcut.closePanel') } + if (ctx.workspaces.list.getSnapshot().archivedSessionIds.includes(target.id)) { + return { status: 'blocked', reason: t('shortcut.archivedReading') } + } + const status = ctx.uiSession.sessionStatus + if (!status.readingReady.getSnapshot()) return { status: 'blocked', reason: t('shortcut.readingUnavailable') } + const unread = status.getSnapshot().get(target.id)?.completionUnread === true + return { status: 'handled', run: () => { markSession(target.id, !unread) } } + }, + }), 'ui-workspace: session.toggleRead') } diff --git a/packages/client/ui-workspace/src/client/toast/register.ts b/packages/client/ui-workspace/src/client/toast/register.ts index 51a3a6ca09..3ba0eb141b 100644 --- a/packages/client/ui-workspace/src/client/toast/register.ts +++ b/packages/client/ui-workspace/src/client/toast/register.ts @@ -21,6 +21,13 @@ export function registerToasts( }) ctx.slots.registerFactory({ name: 'workspace.toast.content', scope: 'root' }, WorkspaceToast) ctx.slots.inject('workspace.toast', function* () { + yield ctx.slots.register({ + name: 'workspace.toast', key: 'readingFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'readingFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.readingFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ name: 'workspace.toast', key: 'sessionIdCopied', locale: 'workspace', inject: (): ToastDisplayInjected<'sessionIdCopied'> => ({ diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 993c00dbf6..8684ee4238 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -52,8 +52,10 @@ export interface SessionNode { running: boolean /** Running direct children in the loaded subagent catalog. */ runningSubagentCount: number - /** Finished running while not selected and not yet opened (the green "done" reminder dot). */ + /** Host-confirmed unread completion or explicit unread mark. */ completed: boolean + /** Latest unread completion ended with an execution error. */ + failed: boolean /** In the registry-global pin set: leads its section, reorderable only among pinned rows. */ pinned: boolean /** In the registry-global archive set: shown grayed in place and not openable. */ @@ -95,8 +97,10 @@ export interface SearchResultNode { running: boolean /** Running direct children in the loaded subagent catalog. */ runningSubagentCount: number - /** Finished running while not selected and not yet opened (the green "done" reminder dot). */ + /** Host-confirmed unread completion or explicit unread mark. */ completed: boolean + /** Latest unread completion ended with an execution error. */ + failed: boolean /** In the registry-global archive set: shown grayed and not openable. */ archived: boolean snippet?: string @@ -401,6 +405,7 @@ function sessionNode( running: status?.running ?? s.running, runningSubagentCount: runningChildCount(list, s.id, statuses), completed: status?.completionUnread === true, + failed: status?.completionFailed === true, pinned: !archived.has(s.id) && pinned.has(s.id), archived: archived.has(s.id), updatedAt: s.updatedAt, @@ -605,6 +610,7 @@ export function deriveSearchResults( ? {} : { pendingInteraction }), completed: status?.completionUnread === true, + failed: status?.completionFailed === true, archived: archived.has(summary.id), ...match === undefined ? {} : { snippet: match.snippet }, } diff --git a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx index 51ce69fdfb..1adc908ff6 100644 --- a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx @@ -9,8 +9,9 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, screen } from '@testing-library/react' -import type { TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' +import type { AccessEffect, RemoteEndpoint, TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' import { ClientAccessState } from '@deepseek-ai/dsh-api-remote-access/src/client/state.ts' +import { whenAllowed } from '@deepseek-ai/dsh-api-remote-access/src/client/when-allowed.ts' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -48,6 +49,8 @@ async function bench(access: ClientAccessState, options: { ungroupedSession?: Se apply(ctx) { ctx.provide('remoteAccess', { source: (kind: TypertResourceKind, id: string, action: string) => access.resource(kind, id, action), + whenAccess: (action: RemoteEndpoint, callback: () => AccessEffect) => + whenAllowed(ctx, access.global(action), callback, `access-assembly: ${action}`), }) ctx.slots.provideRoot({ keyedHooks: { remoteAccess: action => access.global(action) } }) }, diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index efe3751dc6..c5828af449 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -31,6 +31,7 @@ import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' import { apply as hostApply } from '../src/index.ts' import { SECTION_HOOK_CONTEXT, SECTION_INJECT } from './section-scroller.client.ts' +import { provideSessionStatus } from './session-status.client.ts' const sid = (id: string) => id as SessionId const summary = (id: string, updatedAt: number): SessionSummary => ({ @@ -70,7 +71,7 @@ async function bench(access: 'fake' | 'static' = 'fake') { onTestFinished(() => { menuRegistry.dispose() }) ctx.provide('contextMenus', { register: menuRegistry.register.bind(menuRegistry), resolve: menuRegistry.resolve.bind(menuRegistry), active: createSnapshotStore(null), open: vi.fn(), close: vi.fn() } as never) ctx.provide('uiConversation', {}) - ctx.provide('uiSession.sessionStatus', createSnapshotStore(new Map()) as never) + const status = provideSessionStatus(ctx) await ctx.plugin(SlotRegistry).await() const accessSource = vi.fn((_kind: string, _id: string, _action: string): HostObservable => ALLOWED) const stopGuard = vi.fn() @@ -169,7 +170,8 @@ async function bench(access: 'fake' | 'static' = 'fake') { locale.setLocale('zh') ctx.provide('locale', locale) return { - ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, accessSource, whenResourceAccess, stopGuard, + ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, accessSource, + whenResourceAccess, stopGuard, status, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, workspacesSubscribe, initializeDefault, history, scope, sessionOf, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, @@ -222,6 +224,7 @@ function sessionMenuActions(ctx: Context) { forkSession: (sessionId: SessionId) => { select('session.fork/fork', sessionId) }, requestSessionRename: (sessionId: SessionId, title: string) => { select('session.rename/rename', sessionId, title) }, copySessionId: async (sessionId: SessionId) => { select('session.id/copy', sessionId); await settled() }, + toggleRead: (sessionId: SessionId) => { select('session.read-state/mark', sessionId) }, } } @@ -243,7 +246,7 @@ describe('ui-workspace apply', () => { it('declares the services it drives', () => { expect(inject).toEqual(['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', - 'uiSession.sessionStatus', + 'uiSession', 'uiSession.sessionStatus', ]) }) @@ -345,6 +348,7 @@ describe('ui-workspace apply', () => { const rowToastEntry = entry(b.slots, 'shell.overlay', 'workspace.row-toast') expect(rowToastEntry.store).toBeUndefined() expect(b.slots.entries('workspace.toast').map(row => row.options.key)).toEqual([ + 'readingFailed', 'sessionIdCopied', 'sessionIdCopyFailed', 'pinFailed', 'unpinFailed', 'archivedNotOpenable', 'defaultWorkspaceFailed', 'shortcutForkFailed', 'createFailed', 'forkRequiresOpen', 'archived', 'stoppedAndArchived', ]) @@ -362,6 +366,36 @@ describe('ui-workspace apply', () => { } }) + it('marks cold Sessions silently and reports only failed writes', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const action = sessionMenuActions(b.ctx) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const menu = b.ctx.contextMenus.resolve({ kind: 'session', value: { sessionId: sid('cold'), displayTitle: 'Cold' } }) + const readAction = () => menu.source.getSnapshot().find(item => item.id === 'session.read-state/mark') + expect(readAction()?.disabled).toBe(false) + b.status.readingReady.set(false) + expect(readAction()?.disabled).toBe(true) + menu.dispose() + b.status.readingReady.set(true) + for (const unread of [true, false]) { + b.status.setUnread(sid('cold'), !unread) + b.status.mark.mockResolvedValueOnce(undefined) + action.toggleRead(sid('cold')) + await Promise.resolve() + expect(b.status.mark).toHaveBeenLastCalledWith(sid('cold'), unread) + expect(toast.hooks.toast.getSnapshot()).toBeNull() + } + b.status.table.set(new Map()) + action.toggleRead(sid('cold')) + await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'readingFailed' }) }) + expect(b.status.mark).toHaveBeenLastCalledWith(sid('cold'), true) + expect(b.retain).not.toHaveBeenCalled() + expect(b.binding).not.toHaveBeenCalled() + }) + it.each([true, false])('copies an ID directly without loading its Session (clipboard accepted: %s)', async (accepted) => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 8e747090c6..fedc107546 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -123,7 +123,7 @@ describe('session rename through the assembled browser', () => { fireEvent.click(trigger) await view.findByRole('menuitem', { name: '置顶会话' }) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '置顶会话', '重命名', '分叉会话', '复制 Session ID', 'Export action', 'Last action', '归档会话', + '置顶会话', '重命名', '标为未读', '分叉会话', '复制 Session ID', 'Export action', 'Last action', '归档会话', ]) expect(view.getAllByRole('separator')).toHaveLength(3) const last = view.getByRole('menuitem', { name: 'Last action' }) diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 0cc4cac028..ad2e5f248d 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -112,7 +112,7 @@ describe('Workspace and Session hover handoff', () => { }) const session: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -175,7 +175,7 @@ describe('native row drag previews', () => { }} onToggle={vi.fn()} onCreate={vi.fn()} drag={drag} t={t} /> : ) const row = screen.getByRole('treeitem') stubRect(row) @@ -238,7 +238,7 @@ describe('native row drag previews', () => { const image = start() rerender() expect(row.getAttribute('draggable')).toBe('false') fireEvent.dragEnd(row) @@ -265,7 +265,7 @@ describe('workspace browser rows', () => { it('keeps the leading status cell in the hierarchy-free flat list', () => { const idle: SessionNode = { id: sid('flat'), title: 'Flat Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const view = render() // The cell is the row's first element and holds nothing while the row is @@ -288,7 +288,7 @@ describe('workspace browser rows', () => { workspace: 'Workspace context', running: true, runningSubagentCount: 0, - completed: false, + completed: false, failed: false, archived: false, snippet: 'matching message excerpt', } @@ -308,7 +308,7 @@ describe('workspace browser rows', () => { it('withholds the search-result restore control while the Session access excludes unarchiving', () => { const result: SearchResultNode = { id: sid('archived-result'), title: 'Archived', workspace: 'Project', - running: false, runningSubagentCount: 0, completed: false, archived: true, + running: false, runningSubagentCount: 0, completed: false, failed: false, archived: true, } const denied = vi.fn(() => false) const view = render( { ] as const)('shows %s ahead of running in search results', (pendingInteraction, label) => { const result: SearchResultNode = { id: sid(pendingInteraction), title: 'Needs input', workspace: 'Project', - pendingInteraction, running: true, runningSubagentCount: 0, completed: false, archived: false, + pendingInteraction, running: true, runningSubagentCount: 0, completed: false, failed: false, archived: false, } render() @@ -364,7 +364,7 @@ describe('workspace browser rows', () => { it('renders and opens a selected running Session row', () => { const node: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: true, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const onOpen = vi.fn() render( @@ -382,7 +382,7 @@ describe('workspace browser rows', () => { it('keeps a row.action entry click in the strip, so a plain button does not open the row', () => { const node: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const onOpen = vi.fn() const pluginAction = vi.fn() @@ -404,7 +404,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('clipped'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -476,7 +476,7 @@ describe('workspace browser rows', () => { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false }))) try { const node: SessionNode = { id: sid('context-crawl'), title: 'A long Session title', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false } + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false } const props = { node, currentId: undefined, now: 0, onOpen: vi.fn(), t } const view = render() const row = screen.getByRole('treeitem') @@ -501,7 +501,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('reduced-motion'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -530,7 +530,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('instant-return'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -559,12 +559,12 @@ describe('workspace browser rows', () => { } }) - it('shows the green done dot only on a finished, unviewed session (live activity wins the slot)', () => { + it('shows the green unread dot only on an unread session (live activity wins the slot)', () => { const renderRow = (over: Partial) => render( , @@ -575,27 +575,51 @@ describe('workspace browser rows', () => { const plain = renderRow({}) expect(stateDot(plain)).toBeNull() plain.unmount() - // Completed while unviewed: the green done dot. const done = renderRow({ completed: true }) expect(done.container.querySelector('[data-state="done"]')).not.toBeNull() done.unmount() - // Running wins the slot: the animated ongoing dot, no done dot. - const running = renderRow({ completed: true, running: true }) + // Running wins the slot: the ongoing dot takes precedence over the unread dot. + const running = renderRow({ completed: true, failed: false, running: true }) expect(running.container.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(running.container.querySelector('[data-state="done"]')).toBeNull() running.unmount() // Descendant activity also wins until the last running descendant stops. - const delegated = renderRow({ completed: true, runningSubagentCount: 1 }) + const delegated = renderRow({ completed: true, failed: false, runningSubagentCount: 1 }) expect(delegated.container.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(delegated.container.querySelector('[data-state="done"]')).toBeNull() }) + it('shows a red unread failure and removes it after the Session is read', () => { + const node = { + id: sid('failed'), title: 'Failed', blank: false, running: false, + runningSubagentCount: 0, completed: true, failed: true, updatedAt: 0, pinned: false, archived: false, + } + const view = render() + expect(view.container.querySelector('[data-state="error"]')).not.toBeNull() + expect(view.container.querySelector('[data-state="done"]')).toBeNull() + expect(screen.getByText('运行出错')).toBeTruthy() + view.rerender() + expect(view.container.querySelector('[data-state]')).toBeNull() + }) + + it.each(['approval', 'plan-review', 'question'] as const)( + 'keeps the yellow %s dot when the session is unread', (pendingInteraction) => { + render() + const row = screen.getByRole('treeitem') + expect(row.querySelector('[data-state="warning"]')).not.toBeNull() + expect(row.querySelector('[data-state="done"]')).toBeNull() + }, + ) + it('shows descendant activity without describing an idle parent as running', () => { vi.useFakeTimers() try { const node: SessionNode = { id: sid('owner'), title: 'Delegating', blank: false, running: false, - runningSubagentCount: 2, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 2, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -616,7 +640,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('owner'), title: 'Delegating', blank: false, running: true, - runningSubagentCount: 1, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 1, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -636,7 +660,7 @@ describe('workspace browser rows', () => { it('keeps child activity as a secondary status while user attention is primary', () => { const node: SessionNode = { id: sid('owner'), title: 'Needs input', blank: false, pendingInteraction: 'question', - running: false, runningSubagentCount: 1, completed: false, updatedAt: 0, pinned: false, archived: false, + running: false, runningSubagentCount: 1, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -646,11 +670,11 @@ describe('workspace browser rows', () => { expect(screen.getByText('1 个子智能体运行中')).toBeTruthy() }) - it('shows the green done dot on a finished search result row', () => { + it('shows the green unread dot on an unread search result row', () => { render( { it('session row drags and renames from its title only while its access snapshot allows each', () => { const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const drag: RowDragProps = { active: false, marker: null, start: vi.fn(), end: vi.fn(), hover: vi.fn(), drop: vi.fn(), @@ -901,7 +925,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('s-blank'), title: 'ignored', blank: true, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const rendered = vi.fn() const renderSlot: RowRenderSlot = (name: RowSlotName) => { rendered(name); return null } @@ -927,7 +951,7 @@ describe('workspace browser rows', () => { describe('Session hover-card working directory', () => { const located: SessionNode = { id: sid('s-cwd'), title: 'Located', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, cwd: '/home/u/project', } function hoverCard(node: SessionNode): void { @@ -962,7 +986,7 @@ describe('workspace browser rows', () => { const renderFactorySlot = vi.fn(renderMenuButton) const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const target = { kind: 'session', value: { sessionId: node.id, displayTitle: 'One' } } render( { : null const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const trigger = screen.getByRole('button', { name: '会话“One”的操作' }) @@ -1012,7 +1036,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('more-hover'), title: 'More hover', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -1037,7 +1061,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('action-hover'), title: 'Action hover', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const renderSlot: RowRenderSlot = (name: RowSlotName) => name === 'sidebar.workspaces.session.row.action' ?