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 001/396] 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 2718245916266aa27156d011ebc3690dd73fd4fc Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:42:06 +0800 Subject: [PATCH 002/396] fix(sidebar-right): drop the left divider in fullscreen The first dock column draws a left border that separates the sidebar from the conversation. Fullscreen has no conversation beside it, so the border showed as a stray line at the window's left edge. Fixes #7927 Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 6 ++++++ .../tests/sidebar-right-styles.client.spec.ts | 7 ++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 09119e640a..d4092a566b 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,6 +83,12 @@ --dsh-dockkit-dock-layer: 40; } +/* Fullscreen has no conversation beside the first column, so dockkit's + column-0 rule separating the two would only edge the window. */ +.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left: none; +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index d59a3c843f..6a90c738c1 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide and reveal-flash style contracts. */ +/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,6 +18,11 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) + it('drops the first column\'s conversation divider in fullscreen', () => { + expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` + + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + }) + it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From e5e7944ff3b0c9ebddbb4df73d4a5cbfd9a14bab Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:49:20 +0800 Subject: [PATCH 003/396] docs(sidebar-right): state the fullscreen divider reason for every platform Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index d4092a566b..c76b0f6e5f 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,7 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 rule separating the two would only edge the window. */ + column-0 divider has nothing to separate. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } From 8f00cc7f678d4e34bedc661372c0f81aa7330168 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:25:15 +0800 Subject: [PATCH 004/396] docs(sidebar-right): note why the fullscreen divider selector is longer Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index c76b0f6e5f..36314b48e0 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,8 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. */ + column-0 divider has nothing to separate. The host attribute and child + combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } 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 005/396] 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 d1da247213f9bdf4a5f4a25ba2ce834ad7b65511 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:50:37 +0800 Subject: [PATCH 006/396] fix(sidebar-right): keep the fullscreen divider during the slide The open and close slides move the fullscreen panel across the conversation, so the first column keeps its divider until an opening slide ends and as soon as a closing slide starts. Only the border color changes, so the pane keeps its width. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 19 +++++++++++++------ .../tests/sidebar-right-styles.client.spec.ts | 11 ++++++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 36314b48e0..6caf305fa3 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,11 +83,17 @@ --dsh-dockkit-dock-layer: 40; } -/* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. The host attribute and child - combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ -.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left: none; +/* Once open, fullscreen has no conversation beside the first column, so + dockkit's column-0 divider has nothing to separate. While the panel slides + in or out across the conversation the divider stays: an opening keeps it + for the slide's duration, and a closing panel no longer matches. Only the + color changes, so the pane keeps its width. */ +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: transparent; +} + +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + transition: border-left-color 0s linear var(--ds-transition-duration-slow); } /* No whole-box subtraction here: Electron drag regions are window geometry, @@ -132,7 +138,8 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]), + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 6a90c738c1..7187986b63 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -18,9 +18,14 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('drops the first column\'s conversation divider in fullscreen', () => { - expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` - + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { + const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` + const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { From 261a86a1087c94aab090e87861443a605263c0b1 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 16:17:02 +0800 Subject: [PATCH 007/396] fix(sidebar-right): end the opening only with a docked item's slide A short transition inside the panel ended the opening early, which cancelled the delayed divider change mid-slide. A pane mounted by the opening also starts with the divider now. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 7 +++++++ .../src/client/shell/SidebarRight.tsx | 14 ++++++++++---- .../ui-sidebar-right/tests/seat.client.spec.tsx | 6 +++++- .../tests/sidebar-right-styles.client.spec.ts | 2 ++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 6caf305fa3..4bda4ee3e6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -96,6 +96,13 @@ transition: border-left-color 0s linear var(--ds-transition-duration-slow); } +/* A pane mounted by the opening starts with the divider, like one already mounted. */ +@starting-style { + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: var(--dsw-alias-border-l4); + } +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index e0182a611b..86117bb069 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject } from 'react' +import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,6 +305,12 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } +/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ +function slideEnded(event: TransitionEvent): boolean { + return event.propertyName === 'transform' + && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") +} + /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -324,8 +330,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { setOpening(false) } : undefined} + onTransitionEnd={opening ? (event) => { if (slideEnded(event)) setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index c6ae78c2e8..106b3b6bf7 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,7 +626,11 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host) + // Short transitions inside an item, or other properties, do not end the slide. + fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) + fireEvent.transitionEnd(host, { propertyName: 'opacity' }) + expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) + fireEvent.transitionEnd(host, { propertyName: 'transform' }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 7187986b63..19cbfb270f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -24,6 +24,8 @@ describe('SidebarRight.module.css', () => { expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) From 3e6916a2d3d62318185fffb8dfc6088bcc9d4928 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:24:15 +0800 Subject: [PATCH 008/396] refactor(desktop): isolate publisher workspace for lightweight rollout --- .github/workflows/desktop-publish.yml | 8 ++-- .github/workflows/desktop-publisher-check.yml | 35 +++++++++++++++++ .github/workflows/desktop-rollout.yml | 37 +++++++++--------- apps/desktop-publisher/package.json | 19 ++++++++++ .../src}/cos-operation.ts | 0 .../desktop-auto-update-environment.d.mts | 0 .../src}/desktop-auto-update-environment.mjs | 0 .../src}/desktop-cos.ts | 2 +- .../src}/desktop-publication-failure.ts | 0 .../src}/desktop-publish-config.ts | 0 .../src}/desktop-publish-cos.ts | 5 ++- .../src}/desktop-publish-qualification.d.mts | 0 .../src}/desktop-publish-qualification.mjs | 0 .../src}/desktop-publish-record.ts | 2 +- .../src}/desktop-publish-route.ts | 0 .../src}/desktop-publish-targets.ts | 0 .../src}/desktop-publish.ts | 7 ++-- .../src}/desktop-purge-recovery.ts | 10 ++--- .../src/desktop-purge-types.ts | 7 ++++ .../src}/desktop-release-store.ts | 2 +- .../src/desktop-releases-root.ts | 15 ++++++++ .../src}/desktop-rollout.ts | 17 +++++---- .../src/desktop-upload-types.ts | 38 +++++++++++++++++++ .../src}/desktop-website-installer.ts | 8 ++-- .../src}/publish-desktop-rollout-ci.ts | 4 +- .../src}/publish-website-ci.ts | 6 +-- .../src}/resolve-desktop-publish-ci.ts | 6 +-- .../resolve-retained-desktop-publish-ci.ts | 6 +-- .../tests/cos-loopback.ts | 0 .../tests/cos-operation.spec.ts | 4 +- .../desktop-auto-update-environment.spec.ts | 2 +- .../tests/desktop-package-selection.spec.ts | 6 +-- .../tests/desktop-publication-failure.spec.ts | 10 ++--- .../tests/desktop-publish-config.spec.ts | 2 +- .../tests/desktop-publish-cos.spec.ts | 10 ++--- .../tests/desktop-publish-record.spec.ts | 4 +- .../tests/desktop-publish-route.spec.ts | 2 +- .../tests/desktop-publish.spec.ts | 4 +- .../tests/desktop-purge-recovery.spec.ts | 4 +- .../tests/desktop-release-store.spec.ts | 2 +- .../tests/desktop-website-installer.spec.ts | 10 ++--- .../tests/expected/cos-GetObject-denied.json | 0 .../tests/expected/cos-PutObject-denied.json | 0 .../tests/expected/website-purge-accepted.md | 0 .../expected/website-purge-unconfirmed.md | 0 .../tests/isolated-install.mjs | 18 +++++++++ .../tests/publish-website-ci.spec.ts | 4 +- apps/desktop-publisher/tests/workflow.spec.ts | 31 +++++++++++++++ apps/desktop/package.json | 3 +- apps/desktop/scripts/archive-desktop-ci.ts | 4 +- .../desktop/scripts/desktop-build-paths.d.mts | 2 +- .../desktop-build-version-discovery.ts | 4 +- apps/desktop/scripts/desktop-edgeone.ts | 11 ++---- .../scripts/desktop-package-environment.mjs | 2 +- .../scripts/desktop-policy-environment.mjs | 2 +- .../scripts/desktop-publication-summary.ts | 4 +- apps/desktop/scripts/desktop-rollback.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 33 ++-------------- apps/desktop/scripts/desktop-upload-run.ts | 6 ++- apps/desktop/scripts/development-project.ts | 2 +- .../scripts/electron-builder-config.mjs | 2 +- apps/desktop/scripts/installed-update-cos.ts | 4 +- .../scripts/macos-app-update-config.mjs | 2 +- apps/desktop/scripts/package-macos.ts | 2 +- apps/desktop/scripts/package-target.ts | 2 +- .../scripts/preflight-desktop-publish.mjs | 2 +- apps/desktop/scripts/publish-desktop-ci.ts | 16 ++++---- apps/desktop/scripts/retain-desktop-ci.ts | 23 ++++------- .../scripts/rollback-desktop-channel.ts | 8 ++-- apps/desktop/scripts/upload-target.ts | 4 +- .../scripts/verify-retained-desktop.ts | 4 +- .../tests/desktop-publication-summary.spec.ts | 2 +- .../tests/desktop-publish-templates.spec.ts | 2 +- apps/desktop/tests/desktop-rollback.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 22 +++++------ .../desktop/tests/desktop-upload-plan.spec.ts | 6 +-- apps/desktop/tests/desktop-upload-run.spec.ts | 6 +-- .../tests/installed-update-cos.spec.ts | 6 +-- apps/desktop/tests/purge-command.spec.ts | 4 +- apps/desktop/tests/retain-desktop-ci.spec.ts | 2 +- apps/desktop/tests/upload-target.spec.ts | 2 +- pnpm-lock.yaml | 24 ++++++++++++ scripts/check-workspace-constraints.spec.ts | 3 +- scripts/check-workspace-constraints.ts | 6 ++- scripts/desktop-publish-workflow.spec.ts | 4 +- tsconfig.base.json | 1 + tsconfig.host.json | 2 + 87 files changed, 372 insertions(+), 213 deletions(-) create mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/package.json rename apps/{desktop/scripts => desktop-publisher/src}/cos-operation.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-cos.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publication-failure.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-config.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-cos.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-record.ts (99%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-route.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-targets.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish.ts (96%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-purge-recovery.ts (94%) create mode 100644 apps/desktop-publisher/src/desktop-purge-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-release-store.ts (98%) create mode 100644 apps/desktop-publisher/src/desktop-releases-root.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-rollout.ts (92%) create mode 100644 apps/desktop-publisher/src/desktop-upload-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-website-installer.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-desktop-rollout-ci.ts (98%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-website-ci.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-desktop-publish-ci.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-retained-desktop-publish-ci.ts (95%) rename apps/{desktop => desktop-publisher}/tests/cos-loopback.ts (100%) rename apps/{desktop => desktop-publisher}/tests/cos-operation.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-auto-update-environment.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-package-selection.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publication-failure.spec.ts (89%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-config.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-cos.spec.ts (91%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-record.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-route.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-purge-recovery.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-release-store.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-website-installer.spec.ts (94%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-GetObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-PutObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-accepted.md (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-unconfirmed.md (100%) create mode 100644 apps/desktop-publisher/tests/isolated-install.mjs rename apps/{desktop => desktop-publisher}/tests/publish-website-ci.spec.ts (97%) create mode 100644 apps/desktop-publisher/tests/workflow.spec.ts diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 32efedf65c..8a1fa4d79d 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -57,7 +57,7 @@ jobs: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -99,7 +99,7 @@ jobs: working-directory: desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts - name: Verify local package without upload credentials id: check working-directory: desktop-publisher @@ -210,7 +210,7 @@ jobs: - name: Upload website installer id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts upload + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true @@ -255,7 +255,7 @@ jobs: - name: Recover and observe website cache purge id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts purge + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml new file mode 100644 index 0000000000..37ad3220d2 --- /dev/null +++ b/.github/workflows/desktop-publisher-check.yml @@ -0,0 +1,35 @@ +name: Verify Desktop Publisher +on: + pull_request: + paths: + - 'apps/desktop-publisher/**' + - 'apps/desktop/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + - '.github/workflows/desktop-publisher-check.yml' + - '.github/workflows/desktop-rollout.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + isolated-install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@v5.0.0 + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Install only publisher production dependencies + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without the Desktop or root development dependencies + working-directory: apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 13549da6b4..80932b63f2 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -50,14 +50,15 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - name: Resolve original package and machine id: route env: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + working-directory: apps/desktop-publisher + run: node --import tsx src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -92,20 +93,20 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts route + run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + run: node --import tsx src/publish-desktop-rollout-ci.ts check publish: name: Approve ${{ needs.prepare.outputs.label }} @@ -139,16 +140,16 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts apply + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true if: always() && steps.publish.outputs.record != '' @@ -191,12 +192,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Upload website installer id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-upload + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' continue-on-error: true @@ -246,12 +247,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Recover and observe website cache purge id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-purge + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/apps/desktop-publisher/package.json b/apps/desktop-publisher/package.json new file mode 100644 index 0000000000..c8aaf573f7 --- /dev/null +++ b/apps/desktop-publisher/package.json @@ -0,0 +1,19 @@ +{ + "name": "@deepseek-ai/dsh-desktop-publisher", + "version": "0.2.2-rc.1", + "description": "Private Desktop release metadata, rollout and website publisher", + "private": true, + "type": "module", + "license": "MIT", + "exports": { + "./*": "./src/*" + }, + "dependencies": { + "zod": "4.6.6", + "js-yaml": "^4.3.2", + "semver": "^7.8.5", + "cos-nodejs-sdk-v5": "3.0.0", + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "tsx": "^4.23.13" + } +} diff --git a/apps/desktop/scripts/cos-operation.ts b/apps/desktop-publisher/src/cos-operation.ts similarity index 100% rename from apps/desktop/scripts/cos-operation.ts rename to apps/desktop-publisher/src/cos-operation.ts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.d.mts b/apps/desktop-publisher/src/desktop-auto-update-environment.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.d.mts rename to apps/desktop-publisher/src/desktop-auto-update-environment.d.mts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.mjs b/apps/desktop-publisher/src/desktop-auto-update-environment.mjs similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.mjs rename to apps/desktop-publisher/src/desktop-auto-update-environment.mjs diff --git a/apps/desktop/scripts/desktop-cos.ts b/apps/desktop-publisher/src/desktop-cos.ts similarity index 97% rename from apps/desktop/scripts/desktop-cos.ts rename to apps/desktop-publisher/src/desktop-cos.ts index 6074d84a05..a117cec4ff 100644 --- a/apps/desktop/scripts/desktop-cos.ts +++ b/apps/desktop-publisher/src/desktop-cos.ts @@ -47,7 +47,7 @@ export function createDesktopCos(credentials: DesktopCosCredentials, timeoutMs: }) cos.on('before-send', (options: CosRequestOptions) => { for (const name of Object.keys(options.headers)) { - if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') delete options.headers[name] + if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') Reflect.deleteProperty(options.headers, name) } }) return cos diff --git a/apps/desktop/scripts/desktop-publication-failure.ts b/apps/desktop-publisher/src/desktop-publication-failure.ts similarity index 100% rename from apps/desktop/scripts/desktop-publication-failure.ts rename to apps/desktop-publisher/src/desktop-publication-failure.ts diff --git a/apps/desktop/scripts/desktop-publish-config.ts b/apps/desktop-publisher/src/desktop-publish-config.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-config.ts rename to apps/desktop-publisher/src/desktop-publish-config.ts diff --git a/apps/desktop/scripts/desktop-publish-cos.ts b/apps/desktop-publisher/src/desktop-publish-cos.ts similarity index 95% rename from apps/desktop/scripts/desktop-publish-cos.ts rename to apps/desktop-publisher/src/desktop-publish-cos.ts index 086303238e..cb89baada6 100644 --- a/apps/desktop/scripts/desktop-publish-cos.ts +++ b/apps/desktop-publisher/src/desktop-publish-cos.ts @@ -5,7 +5,7 @@ import { Readable, Writable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts' import { cosOperation } from './cos-operation.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' @@ -66,7 +66,8 @@ export function desktopPublishCos( if (actual.size !== digest.size || actual.sha512 !== digest.sha512) throw new Error('desktop publish: local input changed') const cos = client() const md5 = createHash('md5') - const bytes = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const bytes = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const chunk of bytes) md5.update(chunk) const body = artifact.contents === undefined ? createReadStream(artifact.path) : Readable.from([Buffer.from(artifact.contents)]) try { diff --git a/apps/desktop/scripts/desktop-publish-qualification.d.mts b/apps/desktop-publisher/src/desktop-publish-qualification.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.d.mts rename to apps/desktop-publisher/src/desktop-publish-qualification.d.mts diff --git a/apps/desktop/scripts/desktop-publish-qualification.mjs b/apps/desktop-publisher/src/desktop-publish-qualification.mjs similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.mjs rename to apps/desktop-publisher/src/desktop-publish-qualification.mjs diff --git a/apps/desktop/scripts/desktop-publish-record.ts b/apps/desktop-publisher/src/desktop-publish-record.ts similarity index 99% rename from apps/desktop/scripts/desktop-publish-record.ts rename to apps/desktop-publisher/src/desktop-publish-record.ts index 718146b86b..6e1fdd554b 100644 --- a/apps/desktop/scripts/desktop-publish-record.ts +++ b/apps/desktop-publisher/src/desktop-publish-record.ts @@ -108,7 +108,7 @@ export async function findDesktopPublication(root: string, expected: { for (const entry of entries) { if (!entry.isDirectory() || !entry.name.startsWith('publish-')) continue const directory = join(root, entry.name) - let operation + let operation: unknown try { operation = JSON.parse(await readFile(join(directory, 'operation.json'), 'utf8')) } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue throw error diff --git a/apps/desktop/scripts/desktop-publish-route.ts b/apps/desktop-publisher/src/desktop-publish-route.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-route.ts rename to apps/desktop-publisher/src/desktop-publish-route.ts diff --git a/apps/desktop/scripts/desktop-publish-targets.ts b/apps/desktop-publisher/src/desktop-publish-targets.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-targets.ts rename to apps/desktop-publisher/src/desktop-publish-targets.ts diff --git a/apps/desktop/scripts/desktop-publish.ts b/apps/desktop-publisher/src/desktop-publish.ts similarity index 96% rename from apps/desktop/scripts/desktop-publish.ts rename to apps/desktop-publisher/src/desktop-publish.ts index d11e2bd098..eb0f2a4ab6 100644 --- a/apps/desktop/scripts/desktop-publish.ts +++ b/apps/desktop-publisher/src/desktop-publish.ts @@ -4,7 +4,7 @@ import { createReadStream } from 'node:fs' import { load } from 'js-yaml' import { gt, valid } from 'semver' import { z } from 'zod' -import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-types.ts' /** File identity computed from bytes, never inferred from COS ETags. */ export interface DesktopObjectDigest { readonly size: number; readonly sha512: string } @@ -51,7 +51,8 @@ export class DesktopPublishError extends Error { export async function desktopArtifactDigest(artifact: DesktopUploadArtifact): Promise { const hash = createHash('sha512') let size = 0 - const stream = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const stream = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const bytes of stream) { hash.update(bytes); size += bytes.length } return { size, sha512: hash.digest('base64') } } @@ -64,7 +65,7 @@ function version(contents: string, remote = false): string { try { const parsed = z.object({ version: z.string() }).parse(load(contents)) if (valid(parsed.version) !== null) return parsed.version - } catch (error) { /* Discard parser error details, which may include raw remote YAML. */ } + } catch (_error) { /* Discard parser error details, which may include raw remote YAML. */ } throw new DesktopPublishError(remote ? 'verification-failed' : 'invalid-plan', `desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`) } diff --git a/apps/desktop/scripts/desktop-purge-recovery.ts b/apps/desktop-publisher/src/desktop-purge-recovery.ts similarity index 94% rename from apps/desktop/scripts/desktop-purge-recovery.ts rename to apps/desktop-publisher/src/desktop-purge-recovery.ts index 890ea003ba..c23cac9ecf 100644 --- a/apps/desktop/scripts/desktop-purge-recovery.ts +++ b/apps/desktop-publisher/src/desktop-purge-recovery.ts @@ -1,6 +1,6 @@ /** Resume a fixed-URL purge without repeating ambiguous submissions. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' -import type { DesktopPurgeConfig } from './desktop-edgeone.ts' +import type { DesktopPurgeConfig } from './desktop-purge-types.ts' /** Non-secret evidence saved before submission and after every observation. */ export interface DesktopPurgeRecord { @@ -65,12 +65,12 @@ async function observe(record: DesktopPurgeRecord, client: DesktopPurgeRecoveryC if (offset >= response.TotalCount) break if (response.Tasks.length === 0 || offset >= 10_000) return unknown('task history could not be fully inspected') } while (true) - } catch (error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } + } catch (_error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } if (matches.length === 0) return unknown(record.jobId ? 'accepted task not found in query history; execution result unconfirmed' : 'no matching submission found; purge may not have been submitted; inspect EdgeOne history before manual recovery') - if (matches.length !== 1) return unknown('multiple matching submissions found; cannot identify this submission') - const task = matches[0]! + const task = matches[0] + if (matches.length !== 1 || !task) return unknown('multiple matching submissions found; cannot identify this submission') if (!task.JobId || !/^[\w.-]{1,128}$/u.test(task.JobId) || task.JobId.includes(config.secretId) || task.JobId.includes(config.secretKey)) return unknown('query returned no usable task ID') const status = task.Status @@ -115,7 +115,7 @@ export async function recoverDesktopPurge(config: DesktopPurgeConfig, previous: await options.save(record) let response: Awaited> | undefined try { response = await client.CreatePurgeTask({ ZoneId: config.zoneId, Type: 'purge_url', Targets: [config.publicUrl] }) } - catch (error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } + catch (_error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } const jobId = response?.JobId if (response?.FailedList?.length) { record = { ...record, status: 'failed' } diff --git a/apps/desktop-publisher/src/desktop-purge-types.ts b/apps/desktop-publisher/src/desktop-purge-types.ts new file mode 100644 index 0000000000..c55ec465ab --- /dev/null +++ b/apps/desktop-publisher/src/desktop-purge-types.ts @@ -0,0 +1,7 @@ +/** Validated production destination and credentials; never serialize this value. */ +export interface DesktopPurgeConfig { + readonly zoneId: string + readonly publicUrl: string + readonly secretId: string + readonly secretKey: string +} diff --git a/apps/desktop/scripts/desktop-release-store.ts b/apps/desktop-publisher/src/desktop-release-store.ts similarity index 98% rename from apps/desktop/scripts/desktop-release-store.ts rename to apps/desktop-publisher/src/desktop-release-store.ts index eb9d5457ff..ae7915443c 100644 --- a/apps/desktop/scripts/desktop-release-store.ts +++ b/apps/desktop-publisher/src/desktop-release-store.ts @@ -44,7 +44,7 @@ async function fingerprint(path: string) { if (!info.isFile() || info.isSymbolicLink()) throw new Error('desktop release store: expected a regular file') const hash = createHash('sha512') let size = 0 - for await (const bytes of createReadStream(path)) { size += bytes.length; hash.update(bytes) } + for await (const bytes of createReadStream(path) as AsyncIterable) { size += bytes.length; hash.update(bytes) } if (size === 0) throw new Error('desktop release store: empty artifact') return { size, sha512: hash.digest('base64') } } diff --git a/apps/desktop-publisher/src/desktop-releases-root.ts b/apps/desktop-publisher/src/desktop-releases-root.ts new file mode 100644 index 0000000000..3d7e11c141 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-releases-root.ts @@ -0,0 +1,15 @@ +/** Resolve retained Desktop storage independently of packaging and signing. */ +import { dirname, isAbsolute, join } from 'node:path' + +/** + * Resolve the persistent release root without assuming a particular user's home directory. + * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. + * @returns Absolute directory outside the disposable checkout. + */ +export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { + const configured = env.DSH_PACKAGING_CONFIG_DIR + if (!configured) throw new Error('desktop retention: DSH_PACKAGING_CONFIG_DIR is required') + const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') + if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') + return root +} diff --git a/apps/desktop/scripts/desktop-rollout.ts b/apps/desktop-publisher/src/desktop-rollout.ts similarity index 92% rename from apps/desktop/scripts/desktop-rollout.ts rename to apps/desktop-publisher/src/desktop-rollout.ts index 50750ef1e8..257830b1a3 100644 --- a/apps/desktop/scripts/desktop-rollout.ts +++ b/apps/desktop-publisher/src/desktop-rollout.ts @@ -7,15 +7,15 @@ import { dump, load } from 'js-yaml' import { z } from 'zod' import { desktopUpdateMetadataFilename, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' const percentage = z.number().int().min(0).max(100) const metadataSchema = z.object({ version: z.string(), - files: z.array(z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).passthrough()).length(1), + files: z.tuple([z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).loose()]), path: z.string().optional(), sha512: z.string().optional(), stagingPercentage: percentage.optional(), -}).passthrough() +}).loose() function metadata(contents: string) { if (Buffer.byteLength(contents) > 1024 * 1024) throw new Error('desktop rollout: metadata exceeds 1 MiB') @@ -26,7 +26,7 @@ function metadata(contents: string) { /** Validated immutable update identity; no installer bytes are read. */ export interface DesktopRolloutPlan { - readonly upload: DesktopUploadPlan + readonly upload: DesktopSingleUploadPlan readonly expected: string } @@ -56,7 +56,7 @@ export async function prepareDesktopRollout(directory: string, manifest: Desktop const parsed = metadata(contents) const payload = `deepseek-harness-${source.version}-${source.target}.${windows ? 'exe' : 'zip'}` const file = manifest.files.find(entry => entry.name === payload) - const entry = parsed.files[0]! + const entry = parsed.files[0] if (parsed.version !== source.version || entry.url !== payload || !file || entry.size !== file.size || entry.sha512 !== file.sha512 || (parsed.path !== undefined && parsed.path !== payload) @@ -103,8 +103,9 @@ export function verifyDesktopRolloutFeed(plan: DesktopRolloutPlan, remote: Deskt export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: number | undefined, operations: Pick) { if (target !== undefined) percentage.parse(target) - const artifact = plan.upload.artifacts[0]! + const artifact = plan.upload.artifacts[0] const before = await operations.transport.read(artifact.key, true) + if (!before?.contents) throw new Error('desktop rollout: published update feed is missing') const current = verifyDesktopRolloutFeed(plan, before) const next = target ?? current.percentage if (next < current.percentage) throw new Error('desktop rollout: percentage cannot decrease; inspect the current rollout') @@ -115,8 +116,8 @@ export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: nu const updated = { ...artifact, contents: dump({ ...current.metadata, stagingPercentage: next }) } const digest = await desktopArtifactDigest(updated) const confirmed = await operations.transport.read(artifact.key, true) - if (confirmed?.contents !== before?.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') - await operations.record({ type: 'put-intent', key: artifact.key, before: before!.contents!, after: updated.contents }) + if (confirmed?.contents !== before.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') + await operations.record({ type: 'put-intent', key: artifact.key, before: before.contents, after: updated.contents }) await operations.transport.put(updated, digest, false) const actual = await operations.transport.read(artifact.key, true) if (actual?.size !== digest.size || actual.sha512 !== digest.sha512) { diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts new file mode 100644 index 0000000000..4faa48b399 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -0,0 +1,38 @@ +/** Shared upload contracts for Desktop packaging and publication. */ +import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' + +/** One local file and its final object metadata. */ +export interface DesktopUploadArtifact { + readonly path: string + readonly filename: string + readonly key: string + readonly contentType: string + /** Browser save name for fixed website downloads, preserving the validated installer basename. */ + readonly contentDisposition?: string + readonly channelMetadata: boolean + /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ + readonly contents?: string +} + +/** A validated installer or update upload, with any channel metadata ordered last. */ +export interface DesktopUploadPlan { + readonly environment: 'test' | 'production' + readonly target: DesktopAutoUpdateTarget + readonly version: string + /** Update feed directory URL, or the single installer URL for a fixed download. */ + readonly publicUrl: string + readonly bucket: string + readonly secretIdEnvName: string + readonly secretKeyEnvName: string + readonly artifacts: readonly DesktopUploadArtifact[] + /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ + readonly commit?: string + /** Whether that checkout carried uncommitted changes. */ + readonly dirty?: boolean +} + + +/** A publication operation targeting exactly one metadata object or installer. */ +export type DesktopSingleUploadPlan = Omit & { + readonly artifacts: readonly [DesktopUploadArtifact] +} diff --git a/apps/desktop/scripts/desktop-website-installer.ts b/apps/desktop-publisher/src/desktop-website-installer.ts similarity index 97% rename from apps/desktop/scripts/desktop-website-installer.ts rename to apps/desktop-publisher/src/desktop-website-installer.ts index 8e3838481f..f98cb20252 100644 --- a/apps/desktop/scripts/desktop-website-installer.ts +++ b/apps/desktop-publisher/src/desktop-website-installer.ts @@ -9,11 +9,11 @@ import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from import { cosOperation } from './cos-operation.ts' import type { DesktopObjectDigest, DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' /** Verified file and destination; the caller closes the handle after publication. */ export interface DesktopWebsiteInstaller { - readonly plan: DesktopUploadPlan + readonly plan: DesktopSingleUploadPlan readonly digest: DesktopObjectDigest readonly md5: string readonly contentDisposition: string @@ -52,7 +52,7 @@ export async function prepareWebsiteInstaller(directory: string, manifest: Deskt const sha512 = createHash('sha512') const md5 = createHash('md5') let size = 0 - for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 })) { + for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 }) as AsyncIterable) { size += bytes.length sha512.update(bytes) md5.update(bytes) @@ -89,7 +89,7 @@ export async function uploadWebsiteInstaller(installer: DesktopWebsiteInstaller, record: (event: 'upload-intent' | 'uploaded') => Promise, options: { createClient?: typeof createDesktopCos; previouslyUploaded?: boolean } = {}, ): Promise<'uploaded' | 'present'> { - const artifact = installer.plan.artifacts[0]! + const artifact = installer.plan.artifacts[0] const matches = (remote: DesktopObjectDigest | null) => remote?.size === installer.digest.size && remote.sha512 === installer.digest.sha512 const remote = await transport.read(artifact.key, false) diff --git a/apps/desktop/scripts/publish-desktop-rollout-ci.ts b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts similarity index 98% rename from apps/desktop/scripts/publish-desktop-rollout-ci.ts rename to apps/desktop-publisher/src/publish-desktop-rollout-ci.ts index 4ab553b3c3..9a915049f3 100644 --- a/apps/desktop/scripts/publish-desktop-rollout-ci.ts +++ b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts @@ -4,7 +4,7 @@ import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { resolveRetainedDesktopPublication, retainedDesktopPublishApi } from './resolve-retained-desktop-publish-ci.ts' import { createDesktopPublicationRecord, findDesktopPublication, withDesktopChannelLock } from './desktop-publish-record.ts' @@ -49,7 +49,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) { || source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) { throw new Error('desktop rollout: repository or release qualification mismatch') } - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, source.preset) + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), source.preset) const environment = source.preset === 'test' ? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin, DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket } diff --git a/apps/desktop/scripts/publish-website-ci.ts b/apps/desktop-publisher/src/publish-website-ci.ts similarity index 97% rename from apps/desktop/scripts/publish-website-ci.ts rename to apps/desktop-publisher/src/publish-website-ci.ts index bd3c32f517..00b0ab96c3 100644 --- a/apps/desktop/scripts/publish-website-ci.ts +++ b/apps/desktop-publisher/src/publish-website-ci.ts @@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts' import { desktopPublishCos } from './desktop-publish-cos.ts' @@ -45,7 +45,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro || !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ATTEMPT || '')) throw new Error('website publication: invalid Actions identity or original machine') const root = desktopReleasesRoot(env) const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt) - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, 'production') + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), 'production') const approval = websiteApproval(manifest, config.bucket) if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed') const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID @@ -68,7 +68,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro const installer = await prepareWebsiteInstaller(retainedDesktopPath(root, route.runId, route.attempt), manifest, route, env.GITHUB_REPOSITORY || '', config.bucket) try { - const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0]!.key}`, async () => { + const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0].key}`, async () => { const previouslyUploaded = state.uploadConfirmed === true || state.upload === 'uploaded' return uploadWebsiteInstaller(installer, credentials, desktopPublishCos(installer.plan, credentials), async (event) => { state = event === 'upload-intent' diff --git a/apps/desktop/scripts/resolve-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-desktop-publish-ci.ts index d1ad2264d4..1f7dfce063 100644 --- a/apps/desktop/scripts/resolve-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts @@ -53,12 +53,12 @@ export function selectDesktopPackage(repository: string, inputsValue: unknown, r } packages = packages.filter(job => job.run_attempt === run.run_attempt && job.conclusion === 'success' && job.runner_name) if (packages.length !== 1) throw new Error('desktop publish: expected one successful package job') - const runnerName = packages[0]!.runner_name! + const runnerName = z.string().parse(packages[0]?.runner_name) const routes = desktopPublishRunnersSchema.parse(routesValue) const route = routes[runnerName] const target = (Object.keys(desktopPackageWorkflows) as Array) - .find(name => desktopPackageWorkflows[name] === run.path)! - if (!route || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') + .find(name => desktopPackageWorkflows[name] === run.path) + if (!route || target === undefined || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') if (new Set(Object.values(routes).map(value => value.label)).size !== Object.keys(routes).length) { throw new Error('desktop publish: each configured machine needs its own unique runner label') } diff --git a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts index 1f2526e78a..99c50b26fc 100644 --- a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts @@ -2,7 +2,7 @@ import { appendFile } from 'node:fs/promises' import { resolve } from 'node:path' import { z } from 'zod' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { verifyRetainedDesktopRelease } from './desktop-release-store.ts' import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' @@ -15,7 +15,7 @@ import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' */ export async function resolveRetainedDesktopPublication(env: NodeJS.ProcessEnv, api: (path: string) => unknown, readManifest = verifyRetainedDesktopRelease) { - const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).passthrough(), + const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).loose(), jobs: z.array(z.unknown()), routes: z.unknown(), runnerName: z.string() }).parse(JSON.parse(env.DESKTOP_PACKAGE_SELECTION || '{}')) if (!env.GITHUB_REPOSITORY || env.RUNNER_NAME !== selection.runnerName) throw new Error('desktop publish: task was dispatched to a different machine') const manifest = await readManifest(desktopReleasesRoot(env), String(selection.run.id), String(selection.run.run_attempt)) @@ -52,7 +52,7 @@ export function retainedDesktopPublishApi(env: NodeJS.ProcessEnv): (path: string signal: AbortSignal.timeout(60_000), }) if (!response.ok) throw new Error(`desktop publish: GitHub verification request failed (HTTP ${response.status})`) - return response.json() + return response.json() as Promise } } diff --git a/apps/desktop/tests/cos-loopback.ts b/apps/desktop-publisher/tests/cos-loopback.ts similarity index 100% rename from apps/desktop/tests/cos-loopback.ts rename to apps/desktop-publisher/tests/cos-loopback.ts diff --git a/apps/desktop/tests/cos-operation.spec.ts b/apps/desktop-publisher/tests/cos-operation.spec.ts similarity index 96% rename from apps/desktop/tests/cos-operation.spec.ts rename to apps/desktop-publisher/tests/cos-operation.spec.ts index 0a065363a0..d653d2e751 100644 --- a/apps/desktop/tests/cos-operation.spec.ts +++ b/apps/desktop-publisher/tests/cos-operation.spec.ts @@ -1,8 +1,8 @@ import { Readable, Writable } from 'node:stream' import type { ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import { cosOperation } from '../scripts/cos-operation.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback, type CosLoopback } from './cos-loopback.ts' const loopbacks: CosLoopback[] = [] diff --git a/apps/desktop/tests/desktop-auto-update-environment.spec.ts b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-auto-update-environment.spec.ts rename to apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts index 74fabee903..8b49573531 100644 --- a/apps/desktop/tests/desktop-auto-update-environment.spec.ts +++ b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts @@ -7,7 +7,7 @@ import { resolveDesktopAutoUpdateEnvironment, resolveDesktopAutoUpdateTarget, resolveDesktopUploadConfig, -} from '../scripts/desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' const RELEASE_ID = '0123456789abcdef0123456789abcdef' diff --git a/apps/desktop/tests/desktop-package-selection.spec.ts b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-package-selection.spec.ts rename to apps/desktop-publisher/tests/desktop-package-selection.spec.ts index 54d2aaec13..0d5342b2be 100644 --- a/apps/desktop/tests/desktop-package-selection.spec.ts +++ b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts @@ -2,9 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { selectDesktopPackage } from '../scripts/resolve-desktop-publish-ci.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import { retainDesktopRelease, verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { selectDesktopPackage } from '../src/resolve-desktop-publish-ci.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import { retainDesktopRelease, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success', diff --git a/apps/desktop/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts similarity index 89% rename from apps/desktop/tests/desktop-publication-failure.spec.ts rename to apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index 721b839ba8..f8ced04f73 100644 --- a/apps/desktop/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -2,8 +2,8 @@ import { spawnSync } from 'node:child_process' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' import { z } from 'zod' -import { DesktopCosOperationError, desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { DesktopPublishError } from '../scripts/desktop-publish.ts' +import { DesktopCosOperationError, desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { DesktopPublishError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' it('preserves actionable validation and filesystem diagnostics', () => { expect(desktopPublicationFailure(new DesktopPublishError('conflict', 'desktop publish: object differs: bin/app.exe'), 'upload')) @@ -26,7 +26,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) + fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) expect(result.error).toBeUndefined() expect(result.signal).toBeNull() expect(result.status).toBe(1) @@ -47,7 +47,7 @@ it('omits malformed provider receipt fields and never copies raw errors into COS it('prints structured archival failure through the real CLI', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/archive-desktop-ci.ts', import.meta.url))], { + fileURLToPath(new URL('../../desktop/scripts/archive-desktop-ci.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, DESKTOP_ARCHIVE_NAME: '', GITHUB_OUTPUT: '' }, }) expect(result.error).toBeUndefined() @@ -66,7 +66,7 @@ it.each(['percentage cannot decrease; inspect the current rollout', 'feed change it.each([['check', 'extra'], ['route']])('prints actionable rollout CLI failures for %s', (...args) => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { + fileURLToPath(new URL('../src/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, GITHUB_OUTPUT: '', GH_TOKEN: '' }, }) expect(result.error).toBeUndefined() diff --git a/apps/desktop/tests/desktop-publish-config.spec.ts b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish-config.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-config.spec.ts index 9577581d82..eaf0dd722f 100644 --- a/apps/desktop/tests/desktop-publish-config.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' it('reads public settings without opening the absent credential file and requires production App settings', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-config-')) diff --git a/apps/desktop/tests/desktop-publish-cos.spec.ts b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts similarity index 91% rename from apps/desktop/tests/desktop-publish-cos.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-cos.spec.ts index 4b42562d40..3b00ae23e7 100644 --- a/apps/desktop/tests/desktop-publish-cos.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts @@ -1,10 +1,10 @@ import { expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' -import { desktopArtifactDigest } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { desktopArtifactDigest } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' it.each([true, false])('preserves download headers and verified bytes with overwrite prevention %s', async (forbidOverwrite) => { const objects = new Map() diff --git a/apps/desktop/tests/desktop-publish-record.spec.ts b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts similarity index 96% rename from apps/desktop/tests/desktop-publish-record.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-record.spec.ts index 287af3e4a2..530e9ae3bf 100644 --- a/apps/desktop/tests/desktop-publish-record.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { expect, it } from 'vitest' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '../scripts/desktop-publish-record.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' it('excludes another process while a channel lock is held and admits it after release', async () => { const root = await mkdtemp(join(tmpdir(), 'desktop-process-lock-')) @@ -18,7 +18,7 @@ it('excludes another process while a channel lock is held and admits it after re } ` const contender = () => promisify(execFile)(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script, - new URL('../scripts/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) + new URL('../src/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) try { await withDesktopChannelLock(root, 'bucket/mac', async () => { expect((await contender()).stdout).toBe('locked') diff --git a/apps/desktop/tests/desktop-publish-route.spec.ts b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-publish-route.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-route.spec.ts index a4e1acb8a1..049863932e 100644 --- a/apps/desktop/tests/desktop-publish-route.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { resolveDesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { resolveDesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), path: '.github/workflows/macos-package.yml', diff --git a/apps/desktop/tests/desktop-publish.spec.ts b/apps/desktop-publisher/tests/desktop-publish.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish.spec.ts rename to apps/desktop-publisher/tests/desktop-publish.spec.ts index cf88751230..408129a913 100644 --- a/apps/desktop/tests/desktop-publish.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' -import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' function observed(contents: string): DesktopRemoteObject { return { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') } diff --git a/apps/desktop/tests/desktop-purge-recovery.spec.ts b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-purge-recovery.spec.ts rename to apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts index 2b4781fcce..19b78bd29e 100644 --- a/apps/desktop/tests/desktop-purge-recovery.spec.ts +++ b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '../scripts/desktop-purge-recovery.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-recovery.ts' const config = { zoneId: 'zone-test', publicUrl: 'https://download.deepseek.com/desktop/test.dmg', secretId: 'secret-id', secretKey: 'secret-key' } const submittedAt = '2026-10-30T00:00:00.000Z' diff --git a/apps/desktop/tests/desktop-release-store.spec.ts b/apps/desktop-publisher/tests/desktop-release-store.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-release-store.spec.ts rename to apps/desktop-publisher/tests/desktop-release-store.spec.ts index 899b38b8cf..0f0b427a02 100644 --- a/apps/desktop/tests/desktop-release-store.spec.ts +++ b/apps/desktop-publisher/tests/desktop-release-store.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/desktop-website-installer.spec.ts b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts similarity index 94% rename from apps/desktop/tests/desktop-website-installer.spec.ts rename to apps/desktop-publisher/tests/desktop-website-installer.spec.ts index d3c2a2a623..56a717f2a3 100644 --- a/apps/desktop/tests/desktop-website-installer.spec.ts +++ b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts @@ -3,12 +3,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '../scripts/desktop-website-installer.ts' -import type { DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import type { DesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '@deepseek-ai/dsh-desktop-publisher/desktop-website-installer.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/expected/cos-GetObject-denied.json b/apps/desktop-publisher/tests/expected/cos-GetObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-GetObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-GetObject-denied.json diff --git a/apps/desktop/tests/expected/cos-PutObject-denied.json b/apps/desktop-publisher/tests/expected/cos-PutObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-PutObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-PutObject-denied.json diff --git a/apps/desktop/tests/expected/website-purge-accepted.md b/apps/desktop-publisher/tests/expected/website-purge-accepted.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-accepted.md rename to apps/desktop-publisher/tests/expected/website-purge-accepted.md diff --git a/apps/desktop/tests/expected/website-purge-unconfirmed.md b/apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-unconfirmed.md rename to apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs new file mode 100644 index 0000000000..049c56522f --- /dev/null +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -0,0 +1,18 @@ +/** Run only in a clean checkout after installing this workspace's production dependencies. */ +import '../src/resolve-desktop-publish-ci.ts' +import assert from 'node:assert/strict' +import { existsSync } from 'node:fs' +import { createRequire } from 'node:module' +import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' +import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' +import { teo } from 'tencentcloud-sdk-nodejs-teo' + +const require = createRequire(import.meta.url) +for (const dependency of ['electron', 'electron-builder', 'app-builder-lib', 'react', 'vite', 'typescript']) { + assert.throws(() => require.resolve(dependency), { code: 'MODULE_NOT_FOUND' }, `${dependency} must not be installed`) +} +assert.equal(existsSync(new URL('../../desktop/node_modules', import.meta.url)), false) +assert.equal(typeof teo.v20220901.Client, 'function') +assert.throws(() => desktopReleasesRoot({}), /DSH_PACKAGING_CONFIG_DIR is required/) +await assert.rejects(prepareDesktopRolloutCi({}), /runId/) +console.log('Desktop publisher isolated install: OK (no package build, credentials or remote operations)') diff --git a/apps/desktop/tests/publish-website-ci.spec.ts b/apps/desktop-publisher/tests/publish-website-ci.spec.ts similarity index 97% rename from apps/desktop/tests/publish-website-ci.spec.ts rename to apps/desktop-publisher/tests/publish-website-ci.spec.ts index 2c75150bc4..cdac810fb6 100644 --- a/apps/desktop/tests/publish-website-ci.spec.ts +++ b/apps/desktop-publisher/tests/publish-website-ci.spec.ts @@ -3,10 +3,10 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import * as desktopCos from '../scripts/desktop-cos.ts' +import * as desktopCos from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' -import { publishWebsiteCi, websiteApproval } from '../scripts/publish-website-ci.ts' +import { publishWebsiteCi, websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} })) afterEach(() => vi.restoreAllMocks()) diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts new file mode 100644 index 0000000000..738412c54a --- /dev/null +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -0,0 +1,31 @@ +import { existsSync, readFileSync } from 'node:fs' +import { resolve, relative } from 'node:path' +import { load } from 'js-yaml' +import { z } from 'zod' +import { expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '../../..') +const step = z.object({ + uses: z.string().optional(), run: z.string().optional(), + 'working-directory': z.string().optional(), + with: z.object({ path: z.string().optional() }).loose().optional(), +}).loose() +const workflowSchema = z.object({ jobs: z.record(z.string(), z.object({ steps: z.array(step) }).loose()) }) + +it('loads every rollout entry from its own installed package and the correct job checkout', () => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows/desktop-rollout.yml'), 'utf8'))) + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + const install = job.steps.find(entry => entry.run?.includes(' install ')) + expect(install?.run).toContain('--filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts') + for (const entry of job.steps) { + if (!entry.run?.startsWith('node --import tsx ')) continue + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('apps/desktop-publisher') + const script = entry.run.split(' ')[3]! + expect(existsSync(resolve(root, directory, script))).toBe(true) + } + expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) + } +}) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c3cf87bfa4..1642eeecd9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -90,6 +90,7 @@ "zod": "4.6.6", "@deepseek-ai/dsh-util-file-drag": "workspace:*", "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", - "tencentcloud-sdk-nodejs-teo": "4.1.330" + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "@deepseek-ai/dsh-desktop-publisher": "workspace:*" } } diff --git a/apps/desktop/scripts/archive-desktop-ci.ts b/apps/desktop/scripts/archive-desktop-ci.ts index 1517d20dd4..3d36b4fcc6 100644 --- a/apps/desktop/scripts/archive-desktop-ci.ts +++ b/apps/desktop/scripts/archive-desktop-ci.ts @@ -2,9 +2,9 @@ import { execFileSync } from 'node:child_process' import { appendFile, mkdtemp } from 'node:fs/promises' import { join, resolve } from 'node:path' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' /** * Verify an original build without interpreting the archive job's attempt as a new build. diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index 910f3032ee..aaf7159d44 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -1,4 +1,4 @@ -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' /** Mutable target directories plus shared download and package caches. */ export interface DesktopTargetBuildPaths { diff --git a/apps/desktop/scripts/desktop-build-version-discovery.ts b/apps/desktop/scripts/desktop-build-version-discovery.ts index 68291ca3b8..d9e87b6965 100644 --- a/apps/desktop/scripts/desktop-build-version-discovery.ts +++ b/apps/desktop/scripts/desktop-build-version-discovery.ts @@ -20,8 +20,8 @@ import { readdir } from 'node:fs/promises' import { parse } from 'semver' import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import type { DesktopPackageTargetName } from './package-target.ts' /** How long the whole bucket listing may take before the suggestion falls back to local artifacts. */ diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index e2faf122a0..dedbd8ad1d 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,16 +1,11 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' -import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -/** Validated production destination and credentials; never serialize this value. */ -export interface DesktopPurgeConfig { - readonly zoneId: string - readonly publicUrl: string - readonly secretId: string - readonly secretKey: string -} +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' +export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ export type DesktopPurgeClient = Pick, 'CreatePurgeTask'> diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 83e9dbbc0f..d301ac4b31 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -5,7 +5,7 @@ import { dirname, isAbsolute, join } from 'node:path' import { fileURLToPath } from 'node:url' import { readDesktopPackageSettings as readSettings } from './desktop-file-settings.mjs' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' import { validateMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' diff --git a/apps/desktop/scripts/desktop-policy-environment.mjs b/apps/desktop/scripts/desktop-policy-environment.mjs index 591147578b..dafaa417ea 100644 --- a/apps/desktop/scripts/desktop-policy-environment.mjs +++ b/apps/desktop/scripts/desktop-policy-environment.mjs @@ -1,5 +1,5 @@ /** Resolve the required policy service from the same deployment as updater publication. */ -import { resolveDesktopAutoUpdateEnvironment } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateEnvironment } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function origin(value, name) { let url diff --git a/apps/desktop/scripts/desktop-publication-summary.ts b/apps/desktop/scripts/desktop-publication-summary.ts index a9e86575fd..13dfd0ae51 100644 --- a/apps/desktop/scripts/desktop-publication-summary.ts +++ b/apps/desktop/scripts/desktop-publication-summary.ts @@ -3,8 +3,8 @@ import { load } from 'js-yaml' import { z } from 'zod' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' -import { desktopWebsiteInstallerUrl } from './desktop-auto-update-environment.mjs' -import type { DesktopRetainedSource } from './desktop-release-store.ts' +import { desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' function text(value: string): string { diff --git a/apps/desktop/scripts/desktop-rollback.ts b/apps/desktop/scripts/desktop-rollback.ts index a96e5d652b..10eacbe555 100644 --- a/apps/desktop/scripts/desktop-rollback.ts +++ b/apps/desktop/scripts/desktop-rollback.ts @@ -2,7 +2,7 @@ import { load } from 'js-yaml' import { z } from 'zod' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' +import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' /** Outcome of an explicitly requested channel restoration. */ export interface DesktopRollbackResult { diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 39ff954bf5..9c8d9c47e7 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -11,7 +11,7 @@ import { desktopLatestInstallerFilename, desktopUpdateMetadataFilename, resolveDesktopUploadConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' @@ -27,35 +27,8 @@ const TARGETS = { readonly os: string }> -/** One local file and its final object metadata. */ -export interface DesktopUploadArtifact { - readonly path: string - readonly filename: string - readonly key: string - readonly contentType: string - /** Browser save name for fixed website downloads, preserving the validated installer basename. */ - readonly contentDisposition?: string - readonly channelMetadata: boolean - /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ - readonly contents?: string -} - -/** A validated installer or update upload, with any channel metadata ordered last. */ -export interface DesktopUploadPlan { - readonly environment: 'test' | 'production' - readonly target: DesktopPackageTargetName - readonly version: string - /** Update feed directory URL, or the single installer URL for a fixed download. */ - readonly publicUrl: string - readonly bucket: string - readonly secretIdEnvName: string - readonly secretKeyEnvName: string - readonly artifacts: readonly DesktopUploadArtifact[] - /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ - readonly commit?: string - /** Whether that checkout carried uncommitted changes. */ - readonly dirty?: boolean -} +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index 3bb305afde..ccf528b1f6 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { Readable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' -import { DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { recordPackagingEvent } from './packaging-run.mjs' const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'BadDigest', 'SignatureDoesNotMatch', @@ -84,7 +84,9 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re } const sourceSha256: Record = {} for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(join(import.meta.dirname, filename))).digest('hex') + sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' + ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) + : join(import.meta.dirname, filename))).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/development-project.ts b/apps/desktop/scripts/development-project.ts index d544ce6d36..becb8e79a4 100644 --- a/apps/desktop/scripts/development-project.ts +++ b/apps/desktop/scripts/development-project.ts @@ -16,7 +16,7 @@ import { dirname, join } from 'node:path' import { createDevelopmentProjectMetadata } from '../src/project-manager.ts' import type { DesktopRelease } from '../src/release.ts' import { DESKTOP_RUNTIME_FILE, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' interface PackageManifest { diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index d5522e3da9..36b0d4e3ba 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -20,7 +20,7 @@ import { resolveWindowsUpdatePublisher, scrubWindowsSigningEnvironment, } from './windows-sign.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { resolveDesktopBuildCommit } from './desktop-build-commit.mjs' import { resolveDesktopBuildVersion } from './desktop-build-version.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' diff --git a/apps/desktop/scripts/installed-update-cos.ts b/apps/desktop/scripts/installed-update-cos.ts index 7dcff940b4..dbc4220aa4 100644 --- a/apps/desktop/scripts/installed-update-cos.ts +++ b/apps/desktop/scripts/installed-update-cos.ts @@ -2,8 +2,8 @@ import { createReadStream } from 'node:fs' import { createHash } from 'node:crypto' import { Readable, Writable } from 'node:stream' -import { cosOperation } from './cos-operation.ts' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import type { InstalledUpdatePublicationStore, InstalledUpdateRemoteObject } from './installed-update-publication.ts' diff --git a/apps/desktop/scripts/macos-app-update-config.mjs b/apps/desktop/scripts/macos-app-update-config.mjs index bdb400bcde..40addd5bf3 100644 --- a/apps/desktop/scripts/macos-app-update-config.mjs +++ b/apps/desktop/scripts/macos-app-update-config.mjs @@ -5,7 +5,7 @@ import { join } from 'node:path' import { dump, load } from 'js-yaml' const CONFIG_FILENAME = 'app-update.yml' -import { resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function object(value, label) { if (typeof value !== 'object' || value === null || Array.isArray(value)) { diff --git a/apps/desktop/scripts/package-macos.ts b/apps/desktop/scripts/package-macos.ts index 4ba0fd12ca..23087c72e6 100644 --- a/apps/desktop/scripts/package-macos.ts +++ b/apps/desktop/scripts/package-macos.ts @@ -13,7 +13,7 @@ import { import { desktopUpdateMetadataFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { verifyMacOSAppUpdateConfig } from './macos-app-update-config.mjs' import { verifyMacOSNotarizedApplication, verifyMacOSSignature } from './verify-macos-signature.mjs' diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index b6bc6efb63..ea244526d5 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -7,7 +7,7 @@ import { join, resolve } from 'node:path' import { desktopBuildRecordFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopArtifactOutput, desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts' import { loadDesktopPackageEnvironment, localMacOSPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop/scripts/preflight-desktop-publish.mjs index fbe6947398..536f3eefa7 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop/scripts/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop/scripts/publish-desktop-ci.ts b/apps/desktop/scripts/publish-desktop-ci.ts index e3d14abbff..cd60886f2e 100644 --- a/apps/desktop/scripts/publish-desktop-ci.ts +++ b/apps/desktop/scripts/publish-desktop-ci.ts @@ -3,19 +3,19 @@ import { createHash } from 'node:crypto' import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyRetainedDesktopSignatures } from './verify-retained-desktop.ts' import { createDesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from './desktop-publish-record.ts' -import { publishDesktopRelease } from './desktop-publish.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { publishDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopPublicationSummary } from './desktop-publication-summary.ts' import { publishDesktopTag } from './desktop-publish-tag.ts' -import { websiteApproval } from './publish-website-ci.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' const routeSchema = z.object({ runId: z.string(), attempt: z.string(), commit: z.string(), runnerName: z.string(), sourceRef: z.string(), channel: z.enum(['nightly', 'stable']), diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index e672274992..fb53e9c065 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,13 +1,15 @@ +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' -import { dirname, isAbsolute, join, resolve } from 'node:path' +import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' -import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' -import { retainDesktopRelease, type DesktopRetainedSource } from './desktop-release-store.ts' +import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { desktopPublishRunnersSchema } from './desktop-publish-targets.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] @@ -15,17 +17,6 @@ function required(env: NodeJS.ProcessEnv, name: string): string { return value } -/** - * Resolve the persistent release root without assuming a particular user's home directory. - * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. - * @returns Absolute directory outside the disposable checkout. - */ -export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { - const configured = required(env, 'DSH_PACKAGING_CONFIG_DIR') - const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') - if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') - return root -} /** * Resolve the original machine's unique label before expensive packaging work. diff --git a/apps/desktop/scripts/rollback-desktop-channel.ts b/apps/desktop/scripts/rollback-desktop-channel.ts index fbefbe4f8b..d799d075a3 100644 --- a/apps/desktop/scripts/rollback-desktop-channel.ts +++ b/apps/desktop/scripts/rollback-desktop-channel.ts @@ -4,11 +4,11 @@ import { dirname, join, resolve } from 'node:path' import { parseArgs } from 'node:util' import { z } from 'zod' import { prepareDesktopPublication } from './publish-desktop-ci.ts' -import { readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, withDesktopChannelLock } from './desktop-publish-record.ts' +import { readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' import { rollbackDesktopChannel } from './desktop-rollback.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { let phase = 'rollback arguments and local publication verification' diff --git a/apps/desktop/scripts/upload-target.ts b/apps/desktop/scripts/upload-target.ts index a1afdb3241..831d8096f0 100644 --- a/apps/desktop/scripts/upload-target.ts +++ b/apps/desktop/scripts/upload-target.ts @@ -3,8 +3,8 @@ import { resolve } from 'node:path' import { parseArgs } from 'node:util' import type { DesktopPackageTargetName } from './package-target.ts' -import { createDesktopCos } from './desktop-cos.ts' -import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { createDesktopUploadPlan, type DesktopUploadPlan } from './desktop-upload-plan.ts' diff --git a/apps/desktop/scripts/verify-retained-desktop.ts b/apps/desktop/scripts/verify-retained-desktop.ts index 613580da9a..fca85421ad 100644 --- a/apps/desktop/scripts/verify-retained-desktop.ts +++ b/apps/desktop/scripts/verify-retained-desktop.ts @@ -3,8 +3,8 @@ import { execFileSync } from 'node:child_process' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopPublishConfig } from './desktop-publish-config.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { verifyMacOSDiskImage, verifyMacOSNotarizedApplication } from './verify-macos-signature.mjs' /** diff --git a/apps/desktop/tests/desktop-publication-summary.spec.ts b/apps/desktop/tests/desktop-publication-summary.spec.ts index 11ca2d064e..c23273f7b5 100644 --- a/apps/desktop/tests/desktop-publication-summary.spec.ts +++ b/apps/desktop/tests/desktop-publication-summary.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { desktopPublicationSummary } from '../scripts/desktop-publication-summary.ts' -import type { DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' const source: DesktopRetainedSource = { diff --git a/apps/desktop/tests/desktop-publish-templates.spec.ts b/apps/desktop/tests/desktop-publish-templates.spec.ts index 0ead9a11ab..34c2a67d20 100644 --- a/apps/desktop/tests/desktop-publish-templates.spec.ts +++ b/apps/desktop/tests/desktop-publish-templates.spec.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join, posix, win32 } from 'node:path' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, type DesktopPublishConfig } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, type DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' for (const platform of ['macos', 'windows'] as const) { for (const preset of ['test', 'production'] as const) { diff --git a/apps/desktop/tests/desktop-rollback.spec.ts b/apps/desktop/tests/desktop-rollback.spec.ts index f7912ea09b..4c858bf613 100644 --- a/apps/desktop/tests/desktop-rollback.spec.ts +++ b/apps/desktop/tests/desktop-rollback.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { rollbackDesktopChannel } from '../scripts/desktop-rollback.ts' -import type { DesktopPublishOperations } from '../scripts/desktop-publish.ts' +import type { DesktopPublishOperations } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' function fixture() { diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 8109327090..4637982916 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -7,17 +7,17 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { teo } from 'tencentcloud-sdk-nodejs-teo' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { dump, load } from 'js-yaml' import { expect, it, vi } from 'vitest' -import { prepareDesktopRollout, rolloutDesktopRelease } from '../scripts/desktop-rollout.ts' -import * as cosTransport from '../scripts/desktop-publish-cos.ts' -import * as websitePublisher from '../scripts/publish-website-ci.ts' -import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '../scripts/publish-desktop-rollout-ci.ts' -import { createDesktopPublicationRecord } from '../scripts/desktop-publish-record.ts' -import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '../scripts/desktop-publish.ts' +import { prepareDesktopRollout, rolloutDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-rollout.ts' +import * as cosTransport from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import * as websitePublisher from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '@deepseek-ai/dsh-desktop-publisher/publish-desktop-rollout-ci.ts' +import { createDesktopPublicationRecord } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' const digest = (contents: string) => ({ size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64'), @@ -284,7 +284,7 @@ it('runs the real route CLI without gh and emits the selected route and preset', routes: { runner: { label: 'dsh-runner', target: 'mac-arm64' } }, } const result = await promisify(execFile)(process.execPath, - ['--import', 'tsx/esm', 'apps/desktop/scripts/publish-desktop-rollout-ci.ts', 'route'], { + ['--import', 'tsx/esm', 'apps/desktop-publisher/src/publish-desktop-rollout-ci.ts', 'route'], { timeout: 30_000, env: { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toLowerCase() !== 'path')), PATH: '', GH_TOKEN: 'fixture-token', GITHUB_API_URL: `http://127.0.0.1:${address.port}`, GITHUB_OUTPUT: output, @@ -403,6 +403,6 @@ it('executes the master guard and keeps all rollout preflights ahead of dependen if (name === 'route') continue const local = job.steps.findIndex(step => step.run?.includes('preflight-desktop-publish-local.mjs')) expect(local).toBeGreaterThanOrEqual(0) - expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) + expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts')) } }) diff --git a/apps/desktop/tests/desktop-upload-plan.spec.ts b/apps/desktop/tests/desktop-upload-plan.spec.ts index 0d9e90f00d..144b249fb4 100644 --- a/apps/desktop/tests/desktop-upload-plan.spec.ts +++ b/apps/desktop/tests/desktop-upload-plan.spec.ts @@ -6,11 +6,11 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { load } from 'js-yaml' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopUpdateMetadataFilename } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopUpdateMetadataFilename } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import type { DesktopPackageTargetName } from '../scripts/package-target.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' -import { startCosLoopback } from './cos-loopback.ts' +import { startCosLoopback } from '../../desktop-publisher/tests/cos-loopback.ts' const temporaryDirectories: string[] = [] const TEST_ORIGIN = 'https://desktop-updates.example.com' diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index 2bbe2a66ab..d3e26bf25b 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -4,10 +4,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it } from 'vitest' -import { createDesktopCos, DESKTOP_COS_REGION } from '../scripts/desktop-cos.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] const loopbacks: CosLoopback[] = [] @@ -107,7 +107,7 @@ describe('release upload audit with the real COS SDK and an isolated loopback or expect(plan.sourceSha256['upload-target.ts']).toBe(createHash('sha256') .update(await readFile(join(import.meta.dirname, '../scripts/upload-target.ts'))).digest('hex')) expect(plan.sourceSha256['desktop-cos.ts']).toBe(createHash('sha256') - .update(await readFile(join(import.meta.dirname, '../scripts/desktop-cos.ts'))).digest('hex')) + .update(await readFile(join(import.meta.dirname, '../../desktop-publisher/src/desktop-cos.ts'))).digest('hex')) const result = await json(join(directory, 'result.json')) expect(result).toMatchObject({ success: true, stage: 'complete', confirmedPuts: 2, publicReadback: 'not-performed' }) const events = await journal(join(directory, 'events.jsonl')) diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index ca8dd93ec0..81f9006c4f 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ settings: 'test', @@ -18,8 +18,8 @@ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackag DOWNLOAD_TEST_COS_SECRET_KEY: 'fixture-key', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin-not-for-sdk', }) })) -vi.mock('../scripts/desktop-cos.ts', async (original) => { - const actual = await original() +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', async (original) => { + const actual = await original() return { ...actual, createDesktopCos: (credentials: Parameters[0]) => { const cos = actual.createDesktopCos(credentials) state.redirect?.(cos) diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index a690db7a35..9b826b0830 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -30,8 +30,10 @@ it('forwards the documented pnpm purge command through both package scripts to t for (const dependency of ['.bin', 'pnpm', 'tsx', 'semver']) { await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } + await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) + await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) - for (const filename of ['desktop-auto-update-environment.mjs', 'desktop-build-paths.mjs']) { + for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) } // Only command forwarding and parsing are under test; all external work fails closed. diff --git a/apps/desktop/tests/retain-desktop-ci.spec.ts b/apps/desktop/tests/retain-desktop-ci.spec.ts index fdddcdf451..48d204e522 100644 --- a/apps/desktop/tests/retain-desktop-ci.spec.ts +++ b/apps/desktop/tests/retain-desktop-ci.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { unzipSync } from 'fflate' import { afterEach, expect, it } from 'vitest' import { desktopReleasesRoot, retainDesktopCi, resolveDesktopRetentionRunner } from '../scripts/retain-desktop-ci.ts' -import { verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyDesktopArchive } from '../scripts/archive-desktop-ci.ts' import { prepareDesktopPublication } from '../scripts/publish-desktop-ci.ts' diff --git a/apps/desktop/tests/upload-target.spec.ts b/apps/desktop/tests/upload-target.spec.ts index 94e9aa5b4f..fa62fbf9d2 100644 --- a/apps/desktop/tests/upload-target.spec.ts +++ b/apps/desktop/tests/upload-target.spec.ts @@ -13,7 +13,7 @@ vi.mock('../scripts/desktop-edgeone.ts', async importOriginal => ({ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackageEnvironment: vi.fn() })) vi.mock('../scripts/desktop-upload-plan.ts', () => ({ createDesktopUploadPlan: vi.fn() })) -vi.mock('../scripts/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) vi.mock('../scripts/desktop-upload-run.ts', () => ({ uploadDesktopRelease: vi.fn() })) vi.mock('../scripts/desktop-release-tag.ts', async importOriginal => ({ ...await importOriginal(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 718a239832..8057f54080 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,6 +734,9 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -843,6 +846,27 @@ importers: specifier: 4.6.6 version: 4.6.6 + apps/desktop-publisher: + dependencies: + zod: + specifier: 4.6.6 + version: 4.6.6 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + apps/desktop-host: dependencies: '@deepseek-ai/cordis': diff --git a/scripts/check-workspace-constraints.spec.ts b/scripts/check-workspace-constraints.spec.ts index a06ff702c2..eb03f5fe29 100644 --- a/scripts/check-workspace-constraints.spec.ts +++ b/scripts/check-workspace-constraints.spec.ts @@ -436,8 +436,7 @@ describe('package payload constraints', () => { }, ) - it('exempts the private plugin market generator from release rules in its own directory only', () => { - const dir = 'apps/plugin-market-generator' + it.each(['apps/plugin-market-generator', 'apps/desktop-publisher'])('exempts private tool %s from release rules in its own directory only', (dir) => { const manifest = JSON.parse(readFileSync(new URL(`../${dir}/package.json`, import.meta.url), 'utf8')) as WorkspaceManifest['manifest'] expect(checkWorkspaceManifest({ dir, manifest })).toEqual([]) expect(checkWorkspaceManifest({ dir: 'apps/other-tool', manifest })).not.toEqual([]) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 5356dba419..d13b0324e0 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -63,12 +63,14 @@ const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harn const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/ /** Private reference tool run from the repository; it publishes no files. */ const pluginMarketGeneratorDirectory = 'apps/plugin-market-generator' +/** Source-only private release tool, sharing the Desktop version. */ +const desktopPublisherDirectory = 'apps/desktop-publisher' /** * Ordinary directories whose packages this repository publishes: one release member each. The reference plugin * market generator is a private repository tool, not a published application. */ const standardReleaseMemberDirectory = new RegExp( - `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, + `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$|${desktopPublisherDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, 'u', ) /** Installable application assembled by electron-builder rather than published to npm. */ @@ -558,7 +560,7 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st return errors } - if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && manifest.name?.startsWith('@deepseek-ai/')) { + if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && dir !== desktopPublisherDirectory && manifest.name?.startsWith('@deepseek-ai/')) { const expectedFiles = appPackageFiles[manifest.name] if (expectedFiles === undefined) { errors.push(`${label}: app package has no publication files policy`) diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index f6dfa1c4f4..26df0d6b73 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -97,7 +97,7 @@ it('defaults to production website upload and separates cache-only recovery', () expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') } - expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload') - expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge') + expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload') + expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge') expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false) }) diff --git a/tsconfig.base.json b/tsconfig.base.json index 1429e8389a..7208c7f37e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -28,6 +28,7 @@ // not declaration path aliases, keep each package/vendor source compiled // under its own tsconfig boundary. "paths": { + "@deepseek-ai/dsh-desktop-publisher/*": ["./apps/desktop-publisher/src/*"], "@deepseek-ai/dsh-client-ui-file-actions": ["./packages/client/ui-file-actions/src/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/client": ["./packages/client/ui-file-actions/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/types": ["./packages/client/ui-file-actions/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 51393074e9..3465ad1e16 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -245,6 +245,8 @@ "apps/cli/tests/**/*.ts", "apps/plugin-market-generator/tests/**/*.ts", "apps/desktop/scripts/**/*.ts", + "apps/desktop-publisher/src/**/*.ts", + "apps/desktop-publisher/tests/**/*.ts", "apps/desktop/tests/**/*.ts", "apps/desktop-host/tests/**/*.ts", "benchmarks/**/*.ts", From 939d83ab9c4be2f2c3c0fbb3dd8f9734d292ba5b Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:45:31 +0800 Subject: [PATCH 009/396] fix(desktop): validate isolated publisher entrypoints and checkout boundaries --- .github/AGENTS.md | 2 +- .github/workflows/ci-windows.yml | 35 +++++++++++- .github/workflows/ci.yml | 37 ++++++++++++- .github/workflows/desktop-publish.yml | 10 ++-- .github/workflows/desktop-publisher-check.yml | 35 ------------ .github/workflows/desktop-rollout.yml | 54 +++++++++---------- THIRD_PARTY_NOTICES.md | 4 +- apps/desktop-publisher/README.i18n.yaml | 28 ++++++++++ apps/desktop-publisher/README.md | 49 +++++++++++++++++ apps/desktop-publisher/README.zh.md | 49 +++++++++++++++++ .../src/desktop-upload-types.ts | 1 - .../preflight-desktop-publish-local.d.mts | 0 .../src}/preflight-desktop-publish-local.mjs | 0 .../src}/preflight-desktop-publish.d.mts | 0 .../src}/preflight-desktop-publish.mjs | 2 +- .../tests/desktop-publication-failure.spec.ts | 2 +- .../tests/isolated-install.mjs | 2 +- apps/desktop-publisher/tests/preinstall.mjs | 32 +++++++++++ apps/desktop-publisher/tests/workflow.spec.ts | 29 +++++++++- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 1 + apps/desktop/README.zh.md | 1 + apps/desktop/scripts/desktop-edgeone.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 8 +-- apps/desktop/scripts/desktop-upload-run.ts | 13 +++-- apps/desktop/scripts/retain-desktop-ci.ts | 6 +-- .../desktop-publish-local-preflight.spec.ts | 6 +-- .../tests/desktop-publish-preflight.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 2 +- apps/desktop/tests/desktop-upload-run.spec.ts | 1 + .../tests/installed-update-cos.spec.ts | 1 + apps/desktop/tests/purge-command.spec.ts | 7 ++- pnpm-lock.yaml | 48 ++++++++--------- scripts/desktop-publish-workflow.spec.ts | 4 +- 34 files changed, 351 insertions(+), 126 deletions(-) delete mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/README.i18n.yaml create mode 100644 apps/desktop-publisher/README.md create mode 100644 apps/desktop-publisher/README.zh.md rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.mjs (96%) create mode 100644 apps/desktop-publisher/tests/preinstall.mjs diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 733b45dac2..ffef007a51 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -8,4 +8,4 @@ The merge checks run from three workflows named `Policy`, which run on `pull_req The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. -`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. +`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`. diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 47ba28681e..142f4dfbd9 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -23,6 +23,39 @@ concurrency: cancel-in-progress: true jobs: + windows-publisher: + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-2vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + defaults: + run: + shell: pwsh + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Native builds and process tests block pull requests independently of coverage. # Observational checks reuse the successful build and remain non-blocking. # Dependabot PRs are excluded from the self-hosted pool and stay queued for @@ -258,7 +291,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [windows-build, windows-native-tests] + needs: [windows-publisher, windows-build, windows-native-tests] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 916971cfa4..d74e2355e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,41 @@ concurrency: cancel-in-progress: true jobs: + publisher-isolated: + strategy: + fail-fast: false + matrix: + os: [linux, macos] + runs-on: >- + ${{ matrix.os == 'macos' && 'macos-latest' + || vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-latest' }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Three enterprise jobs isolate coverage, static analysis, and the # build-backed consumer tail. The consumer job owns the only Linux build so @@ -572,7 +607,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 8a1fa4d79d..030a4cb63b 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -91,7 +91,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Resolve retained package and approval environment @@ -136,7 +136,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Verify local package without upload credentials @@ -204,7 +204,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Upload website installer @@ -249,7 +249,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Recover and observe website cache purge diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml deleted file mode 100644 index 37ad3220d2..0000000000 --- a/.github/workflows/desktop-publisher-check.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Verify Desktop Publisher -on: - pull_request: - paths: - - 'apps/desktop-publisher/**' - - 'apps/desktop/**' - - 'package.json' - - 'pnpm-lock.yaml' - - 'pnpm-workspace.yaml' - - '.github/workflows/desktop-publisher-check.yml' - - '.github/workflows/desktop-rollout.yml' - workflow_dispatch: -permissions: - contents: read -jobs: - isolated-install: - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - - uses: pnpm/action-setup@v5.0.0 - - uses: actions/setup-node@v7.0.0 - with: - node-version: '24' - - name: Install only publisher production dependencies - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - - name: Load publisher without the Desktop or root development dependencies - working-directory: apps/desktop-publisher - run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 80932b63f2..f2e6bec6d8 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -82,28 +82,28 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} run: node --import tsx src/publish-desktop-rollout-ci.ts check @@ -129,26 +129,26 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true @@ -181,22 +181,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Upload website installer id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' @@ -236,22 +236,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Recover and observe website cache purge id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c38e1a3cea..b932fe3827 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -87,6 +87,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`clsx`](https://github.com/lukeed/clsx) | MIT | | [`commander`](https://github.com/tj/commander.js) | MIT | | [`compression`](https://github.com/expressjs/compression) | MIT | +| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cross-spawn`](https://github.com/moxystudio/node-cross-spawn) | MIT | | [`diff`](https://github.com/kpdecker/jsdiff) | BSD-3-Clause | | [`dompurify`](https://github.com/cure53/DOMPurify) | (MPL-2.0 OR Apache-2.0) | @@ -144,6 +145,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`string_decoder`](https://github.com/nodejs/string_decoder) | MIT | | [`supports-color`](https://github.com/chalk/supports-color) | MIT | | [`tar`](https://github.com/isaacs/node-tar) | BlueOak-1.0.0 | +| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsx`](https://github.com/privatenumber/tsx) | MIT | | [`turndown`](https://github.com/mixmark-io/turndown) | MIT | | [`typescript`](https://github.com/microsoft/TypeScript) | Apache-2.0 | @@ -247,7 +249,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`@yao-pkg/pkg`](https://github.com/yao-pkg/pkg) | MIT | | [`@yarnpkg/cli-dist`](https://github.com/yarnpkg/berry) | BSD-2-Clause | | [`app-builder-lib`](https://github.com/electron-userland/electron-builder) | MIT | -| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cytoscape`](https://github.com/cytoscape/cytoscape.js) | MIT | | [`cytoscape-cose-bilkent`](https://github.com/cytoscape/cytoscape.js-cose-bilkent) | MIT | | [`dayjs`](https://github.com/iamkun/dayjs) | MIT | @@ -274,7 +275,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`selfsigned`](https://github.com/jfromaniello/selfsigned) | MIT | | [`smol-toml`](https://github.com/squirrelchat/smol-toml) | BSD-3-Clause | | [`spdx-expression-parse`](https://github.com/jslicense/spdx-expression-parse.js) | MIT | -| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsdown`](https://github.com/rolldown/tsdown) | MIT | | [`typescript-language-server`](https://github.com/typescript-language-server/typescript-language-server) | Apache-2.0 | | [`vite`](https://github.com/vitejs/vite) | MIT | diff --git a/apps/desktop-publisher/README.i18n.yaml b/apps/desktop-publisher/README.i18n.yaml new file mode 100644 index 0000000000..c95af89587 --- /dev/null +++ b/apps/desktop-publisher/README.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for README.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 apps/desktop-publisher/README.md +/: + en: b6cea27035a6acd8 + zh: c8484ea772e48b76 +/desktop-publisher: + en: 2f3214a4c5f468bd + zh: 0344414f601ce5da +/desktop-publisher/summary: + en: 96e01061bb58ef81 + zh: 34e3e9da3adbdfef +/desktop-publisher/table-of-contents: + en: c910eb62c99ebaae + zh: a39d3e1344eb1b3d +/desktop-publisher/use-this-package: + en: 9678d489d32b9e7b + zh: 6d0ddae4cf96db94 +/desktop-publisher/implementation: + en: 62a7d718a25d4ea4 + zh: 10c8e93749810a15 +/desktop-publisher/limitations: + en: cc71e293492ce240 + zh: 1b9388bf9b108274 +/desktop-publisher/limitations/dev-note: + en: 0a1253c6f7b5e8b9 + zh: 9f56528562c7c914 diff --git a/apps/desktop-publisher/README.md b/apps/desktop-publisher/README.md new file mode 100644 index 0000000000..e4724165b7 --- /dev/null +++ b/apps/desktop-publisher/README.md @@ -0,0 +1,49 @@ +--- +description: "Run Desktop publication and staged rollout from retained packages without installing Desktop build dependencies." +kind: "package-library" +--- +# Desktop publisher + +English | [中文](README.zh.md) + +## Summary + +Publish retained Desktop packages, change an existing release's rollout percentage, and refresh website installers. The manual GitHub workflows select the original packaging machine and require the configured environment approvals. This private workspace shares the repository lockfile and runs TypeScript source directly with Node 24 and tsx. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Implementation](#implementation) +- [Limitations](#limitations) + +## Use this package + +Use [Publish Desktop](../../.github/workflows/desktop-publish.yml) for initial publication and [Rollout & Website](../../.github/workflows/desktop-rollout.yml) for an already published version. The workflows own operator inputs, runner routing, credentials, and approval steps. Rollout installs only this workspace's production dependencies with lifecycle scripts disabled; invoke its entrypoints with Node from this package directory to avoid pnpm's automatic dependency repair. + +The dependency-free preflights run before installation. Their executable regression check is: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## Implementation + +
+Maintainer details + +Desktop build and signing scripts stay in `apps/desktop`; publishing code imports no Desktop implementation. Desktop consumes publisher helpers through the workspace package exports. Runtime dependencies belong in this package's `dependencies`; tests and type checking use repository development tools. The root host TypeScript project checks this source, so there is no separate emitted package or package-local tsconfig. + +Full-install publication and filtered-install rollout use different checkout directories. Changing install modes in one checkout removes development dependency links and can retain stale Desktop directories. Release records live outside these checkouts and remain owned by the existing retained-release configuration. + +Tests under `apps/desktop` may reuse the publisher's loopback COS fixture. Publisher failure tests also exercise the Desktop rollback and archival CLIs as repository integration tests; these test-only paths are not runtime dependencies. The isolated-install CI checks load publisher source without Desktop or root development dependencies on Linux, macOS, and Windows, and contribute to required CI verdicts. + +
+ +## Limitations + +- This private tool is not published to npm and does not generate a standalone artifact. Workflow checkouts must contain the shared lockfile and workspace metadata. +- Isolated-install and preflight tests do not authorize a production write or prove that an installer upgrades a real client. + +### Dev Note + +None. diff --git a/apps/desktop-publisher/README.zh.md b/apps/desktop-publisher/README.zh.md new file mode 100644 index 0000000000..62fcc3dcbf --- /dev/null +++ b/apps/desktop-publisher/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "从保留的安装包执行 Desktop 发布和灰度放量,无需安装 Desktop 构建依赖。" +kind: "package-library" +--- +# Desktop 发布工具 + +[English](README.md) | 中文 + +## 概述 + +发布保留的 Desktop 安装包、调整已发布版本的放量比例,以及刷新官网安装包。手动 GitHub 工作流选择原始打包机器,并要求通过配置的环境审批。此私有 workspace 共用仓库锁文件,通过 Node 24 和 tsx 直接执行 TypeScript 源码。 + +## 目录 + +- [使用此包](#use-this-package) +- [实现](#implementation) +- [限制](#limitations) + +## 使用此包 + +首次发布使用 [Publish Desktop](../../.github/workflows/desktop-publish.yml),已发布版本使用 [Rollout & Website](../../.github/workflows/desktop-rollout.yml)。工作流负责操作输入、运行器路由、凭据和审批步骤。放量仅安装此 workspace 的生产依赖,并禁用生命周期脚本;从此包目录使用 Node 调用入口,避免 pnpm 自动修复依赖。 + +无依赖预检在安装之前运行,其可执行回归检查为: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## 实现 + +
+维护者说明 + +Desktop 构建和签名脚本保留在 `apps/desktop`;发布代码不导入 Desktop 实现。Desktop 通过 workspace 包导出使用发布辅助函数。运行时依赖归此包的 `dependencies` 所有;测试和类型检查使用仓库开发工具。根目录的 host TypeScript 项目检查这些源码,因此没有独立的编译产物或包级 tsconfig。 + +完整安装的发布与筛选安装的放量使用不同 checkout 目录。在同一 checkout 切换安装模式会移除开发依赖链接,也可能保留旧 Desktop 目录。发布记录位于这些 checkout 之外,仍由现有保留版本配置管理。 + +`apps/desktop` 下的测试可以复用发布工具的 loopback COS fixture。发布失败测试还将 Desktop 回滚和归档 CLI 作为仓库集成测试执行;这些测试路径不是运行时依赖。隔离安装 CI 在 Linux、macOS 和 Windows 上验证发布源码无需 Desktop 或根目录开发依赖即可加载,结果纳入必需的 CI 汇总检查。 + +
+ +## 限制 + +- 此私有工具不发布到 npm,也不生成独立产物。工作流 checkout 必须包含共用锁文件和 workspace 元数据。 +- 隔离安装和预检测试不授权生产写入,也不能证明安装包能升级真实客户端。 + +### 开发备注 + +无。 diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts index 4faa48b399..48a3982e3a 100644 --- a/apps/desktop-publisher/src/desktop-upload-types.ts +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -31,7 +31,6 @@ export interface DesktopUploadPlan { readonly dirty?: boolean } - /** A publication operation targeting exactly one metadata object or installer. */ export type DesktopSingleUploadPlan = Omit & { readonly artifacts: readonly [DesktopUploadArtifact] diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.mjs b/apps/desktop-publisher/src/preflight-desktop-publish-local.mjs similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish-local.mjs diff --git a/apps/desktop/scripts/preflight-desktop-publish.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop-publisher/src/preflight-desktop-publish.mjs similarity index 96% rename from apps/desktop/scripts/preflight-desktop-publish.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish.mjs index 536f3eefa7..fbe6947398 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop-publisher/src/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index f8ced04f73..b2ab402e2a 100644 --- a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -24,6 +24,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie expect(desktopPublicationFailure({ code: 'AccessDenied', statusCode: 403 }, 'upload').message).toContain('HTTP 403') }) +// These repository integration tests execute Desktop CLIs; the publisher runtime never imports them. it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) @@ -57,7 +58,6 @@ it('prints structured archival failure through the real CLI', () => { message: 'desktop archival: invalid ZIP output settings' }) }) - it.each(['percentage cannot decrease; inspect the current rollout', 'feed changed before write; inspect and retry', 'written feed is unconfirmed; inspect before retrying'])('retains rollout recovery instructions: %s', (message) => { expect(desktopPublicationFailure(new Error(`desktop rollout: ${message}`), 'desktop rollout')) diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs index 049c56522f..dc4d844c9f 100644 --- a/apps/desktop-publisher/tests/isolated-install.mjs +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -1,8 +1,8 @@ /** Run only in a clean checkout after installing this workspace's production dependencies. */ -import '../src/resolve-desktop-publish-ci.ts' import assert from 'node:assert/strict' import { existsSync } from 'node:fs' import { createRequire } from 'node:module' +import '../src/resolve-desktop-publish-ci.ts' import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' diff --git a/apps/desktop-publisher/tests/preinstall.mjs b/apps/desktop-publisher/tests/preinstall.mjs new file mode 100644 index 0000000000..17647a5192 --- /dev/null +++ b/apps/desktop-publisher/tests/preinstall.mjs @@ -0,0 +1,32 @@ +/** Exercise the pre-install entrypoints in a fixture with no workspace dependency links. */ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { copyFile, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const directory = await realpath(await mkdtemp(join(tmpdir(), 'publisher-preinstall-'))) +try { + for (const filename of ['preflight-desktop-publish.mjs', 'preflight-desktop-publish-local.mjs', 'desktop-publish-qualification.mjs']) { + await copyFile(new URL(`../src/${filename}`, import.meta.url), join(directory, filename)) + } + const { preflightDesktopPublish } = await import(pathToFileURL(join(directory, 'preflight-desktop-publish.mjs')).href) + assert.equal(preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [] }]), '2') + assert.throws(() => preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [{ name: 'windows-x64-unsigned-123-2' }] }]), /unsigned/) + const env = { ...process.env } + for (const key of ['GITHUB_EVENT_PATH', 'GITHUB_REPOSITORY', 'GITHUB_OUTPUT', 'DSH_PACKAGING_CONFIG_DIR', 'NODE_OPTIONS']) Reflect.deleteProperty(env, key) + for (const [filename, diagnostic] of [ + ['preflight-desktop-publish.mjs', 'Actions context required'], + ['preflight-desktop-publish-local.mjs', 'set DSH_PACKAGING_CONFIG_DIR'], + ]) { + const result = spawnSync(process.execPath, [join(directory, filename)], { env, encoding: 'utf8', timeout: 10_000 }) + assert.equal(result.error, undefined) + assert.equal(result.status, 1) + assert.ok(result.stderr.includes(diagnostic), result.stderr) + assert.ok(!result.stderr.includes('ERR_MODULE_NOT_FOUND'), result.stderr) + } + console.log('Desktop publisher pre-install entrypoints: OK') +} finally { + await rm(directory, { recursive: true, force: true }) +} diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts index 738412c54a..0950cfec84 100644 --- a/apps/desktop-publisher/tests/workflow.spec.ts +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' -import { resolve, relative } from 'node:path' +import { join, resolve, relative } from 'node:path' import { load } from 'js-yaml' import { z } from 'zod' import { expect, it } from 'vitest' @@ -22,10 +22,35 @@ it('loads every rollout entry from its own installed package and the correct job for (const entry of job.steps) { if (!entry.run?.startsWith('node --import tsx ')) continue const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) - expect(directory).toBe('apps/desktop-publisher') + expect(directory).toBe(join('apps', 'desktop-publisher')) const script = entry.run.split(' ')[3]! expect(existsSync(resolve(root, directory, script))).toBe(true) } expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) } }) + +it.each(['desktop-rollout.yml', 'desktop-publish.yml'])('keeps %s preflights executable before install', (filename) => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + let preflights = 0 + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + for (const [index, entry] of job.steps.entries()) { + if (!entry.run?.startsWith('node apps/desktop-publisher/src/preflight-')) continue + preflights++ + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('') + expect(existsSync(resolve(root, entry.run.split(' ')[1]!))).toBe(true) + expect(index).toBeLessThan(job.steps.findIndex(candidate => candidate.run?.includes(' install '))) + } + } + expect(preflights).toBe(5) +}) + +it('separates rollout checkouts from full-workspace publication checkouts', () => { + const read = (filename: string) => workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + const paths = (filename: string) => Object.values(read(filename).jobs).flatMap(job => job.steps.flatMap(entry => entry.uses?.startsWith('actions/checkout@') && entry.with?.path ? [entry.with.path] : [])) + const full = new Set(paths('desktop-publish.yml')) + for (const path of paths('desktop-rollout.yml')) expect(full.has(path)).toBe(false) +}) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dc6cb5f9e0..2216019fba 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -51,8 +51,8 @@ en: 617a89aeb28131b9 zh: 4d84bd5d86501c86 /deepseek-harness-desktop/package: - en: ac31ebdd9de54f34 - zh: 921e534d5c4b3a16 + en: 7200a35dbed997c3 + zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: en: f1302ed4a3ab58bb zh: cb53b9b349815028 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 68596d719f..e531d2c303 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -243,6 +243,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner - [Desktop packaging](packaging/README.md): local and Actions builds, versions, deployment settings, artifacts, logs and verification. - [Windows signing and runner operations](windows-signing/README.md): machine setup, accepted isolation risks, signing credentials, token failures and cache maintenance. - [Desktop publication](publishing/README.md): upload credentials, release identity, fixed downloads, update feeds and upload recovery. +- [Publisher workspace](../desktop-publisher/README.md): dependency ownership and isolated rollout installation. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 13661f0590..239a59e34e 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -243,6 +243,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否 - [Desktop 打包](packaging/README.zh.md):本地与 Actions 构建、版本、部署配置、产物、日志和验收。 - [Windows 签名与 runner 运维](windows-signing/README.zh.md):机器部署、已接受的隔离风险、签名凭据、Token 失败与缓存维护。 - [Desktop 发布](publishing/README.zh.md):上传凭据、发布标识、固定下载、更新清单和上传恢复。 +- [发布工具 workspace](../desktop-publisher/README.zh.md):依赖归属与放量隔离安装。 diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index dedbd8ad1d..f1f1875f4a 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,10 +1,10 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 9c8d9c47e7..2e57bdb4c2 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -1,11 +1,12 @@ /** Validate packaged Desktop update artifacts before any network upload begins. */ +import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' import { readFile, stat } from 'node:fs/promises' import { basename, join, resolve } from 'node:path' import { dump, load } from 'js-yaml' -import type { DesktopPackageTargetName } from './package-target.ts' import { desktopBuildRecordFilename, desktopLatestInstallerFilename, @@ -15,6 +16,8 @@ import { import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' + const APP_ROOT = resolve(import.meta.dirname, '..') const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..') const TARGETS = { @@ -27,9 +30,6 @@ const TARGETS = { readonly os: string }> -import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' -export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' - /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { /** Publish only the installer at its fixed download URL, replacing the previous object. */ diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index ccf528b1f6..584892e684 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -13,7 +13,12 @@ const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'RequestTimeout', 'TimeoutError', 'AbortError', 'ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ENOSPC', 'EACCES', 'EPERM', 'ENOENT']) /** Object keys fingerprinted into every upload record to bind evidence to this uploader. */ -const UPLOADER_SOURCES = ['desktop-upload-run.ts', 'upload-target.ts', 'desktop-upload-plan.ts', 'desktop-cos.ts'] +const UPLOADER_SOURCES = { + 'desktop-upload-run.ts': new URL('./desktop-upload-run.ts', import.meta.url), + 'upload-target.ts': new URL('./upload-target.ts', import.meta.url), + 'desktop-upload-plan.ts': new URL('./desktop-upload-plan.ts', import.meta.url), + 'desktop-cos.ts': new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')), +} async function fingerprint(artifact: DesktopUploadArtifact) { const sha512 = createHash('sha512') @@ -83,10 +88,8 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re artifacts.push({ ...artifact, ...await fingerprint(artifact) }) } const sourceSha256: Record = {} - for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' - ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) - : join(import.meta.dirname, filename))).digest('hex') + for (const [filename, source] of Object.entries(UPLOADER_SOURCES)) { + sourceSha256[filename] = createHash('sha256').update(await readFile(source)).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index fb53e9c065..d26e6a068c 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,9 +1,8 @@ -import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' -export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' @@ -11,13 +10,14 @@ import { validateDesktopBuildVersion } from './desktop-build-version.mjs' import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' + function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] if (!value) throw new Error(`desktop retention: ${name} is required`) return value } - /** * Resolve the original machine's unique label before expensive packaging work. * @param env Machine identity, target and administrator-owned runner mapping. diff --git a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts index 9f5dccd580..56aa918b92 100644 --- a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { preflightDesktopPublishLocal } from '../scripts/preflight-desktop-publish-local.mjs' +import { preflightDesktopPublishLocal } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish-local.mjs' it('checks the retained preset before approval and the approved preset before upload without opening credentials', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-preflight-')) @@ -39,8 +39,8 @@ it('runs the local preflight before dependency installation in both self-hosted const workflow = await readFile('.github/workflows/desktop-publish.yml', 'utf8') for (const job of ['prepare', 'publish']) { const section = workflow.split(`\n ${job}:`)[1]!.split(/\n \w+:/u)[0]! - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) } }) diff --git a/apps/desktop/tests/desktop-publish-preflight.spec.ts b/apps/desktop/tests/desktop-publish-preflight.spec.ts index 755a0ce8a6..0398d58b81 100644 --- a/apps/desktop/tests/desktop-publish-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-preflight.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { preflightDesktopPublish } from '../scripts/preflight-desktop-publish.mjs' +import { preflightDesktopPublish } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish.mjs' it.each([ ['macos-x64-unnotarized-debug-1.0.0-42-2', '跳过了公证'], diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 4637982916..c7457ea7bc 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -82,7 +82,7 @@ it.each([ expect(await rolloutDesktopRelease(f.plan, 100, operations)).toEqual({ before: 100, after: 100 }) expect(await rolloutDesktopRelease(f.plan, undefined, operations)).toEqual({ before: 100, after: 100 }) expect(mock.writes).toHaveLength(2) - expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0]!.key])) + expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0].key])) for (const [index, value] of mock.writes.entries()) { expect(load(value)).toEqual({ ...original, stagingPercentage: index === 0 ? 30 : 100 }) } diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index d3e26bf25b..775bc8e9b8 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index 81f9006c4f..f84c77c7a3 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index 9b826b0830..8bfcb69a3a 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -31,7 +31,11 @@ it('forwards the documented pnpm purge command through both package scripts to t await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) - await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') + const publisher = join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher') + await mkdir(publisher) + await writeFile(join(publisher, 'package.json'), JSON.stringify({ type: 'module', exports: { './*': './*' } })) + await copyFile(join(root, 'apps/desktop-publisher/src/desktop-auto-update-environment.mjs'), join(publisher, 'desktop-auto-update-environment.mjs')) + await writeFile(join(publisher, 'desktop-cos.ts'), "export const createDesktopCos = () => { throw new Error('unexpected COS') }") await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) @@ -39,7 +43,6 @@ it('forwards the documented pnpm purge command through both package scripts to t // Only command forwarding and parsing are under test; all external work fails closed. const stubs = { 'desktop-package-environment.mjs': "export const loadDesktopPackageEnvironment = () => ({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production' })", - 'desktop-cos.ts': "export const createDesktopCos = () => { throw new Error('unexpected COS') }", 'desktop-upload-plan.ts': "export const createDesktopUploadPlan = () => { throw new Error('unexpected installer read') }", 'desktop-upload-run.ts': "export const uploadDesktopRelease = () => { throw new Error('unexpected upload') }", 'desktop-release-tag.ts': "export const desktopReleaseTag = () => { throw new Error('unexpected tag') }; export const tagDesktopRelease = desktopReleaseTag", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8057f54080..e8468e91e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,9 +734,6 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: - '@deepseek-ai/dsh-desktop-publisher': - specifier: workspace:* - version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -767,6 +764,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths @@ -846,27 +846,6 @@ importers: specifier: 4.6.6 version: 4.6.6 - apps/desktop-publisher: - dependencies: - zod: - specifier: 4.6.6 - version: 4.6.6 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 - semver: - specifier: ^7.8.5 - version: 7.8.5 - cos-nodejs-sdk-v5: - specifier: 3.0.0 - version: 3.0.0 - tencentcloud-sdk-nodejs-teo: - specifier: 4.1.330 - version: 4.1.330(supports-color@9.4.0) - tsx: - specifier: ^4.23.13 - version: 4.23.13 - apps/desktop-host: dependencies: '@deepseek-ai/cordis': @@ -928,6 +907,27 @@ importers: specifier: workspace:* version: link:../../packages/util/workspace-path + apps/desktop-publisher: + dependencies: + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + zod: + specifier: 4.6.6 + version: 4.6.6 + apps/plugin-market-generator: dependencies: '@deepseek-ai/dsh-plugin-market-index': diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index 26df0d6b73..e6093fe599 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -24,7 +24,7 @@ it('rejects debugging packages before dependency setup and pins the checked atte const preflight = steps.findIndex(step => step.id === 'preflight') expect(preflight).toBeGreaterThan(0) expect(preflight).toBeLessThan(steps.findIndex(step => step.uses?.startsWith('pnpm/'))) - expect(steps[preflight]?.run).toBe('node apps/desktop/scripts/preflight-desktop-publish.mjs') + expect(steps[preflight]?.run).toBe('node apps/desktop-publisher/src/preflight-desktop-publish.mjs') expect(steps.find(step => step.id === 'route')?.env?.DESKTOP_PACKAGE_ATTEMPT).toBe('${{ steps.preflight.outputs.attempt }}') }) @@ -92,7 +92,7 @@ it('defaults to production website upload and separates cache-only recovery', () for (const job of [upload, purge]) { expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'") expect(job.environment).toBe('desktop-production') - const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs') + const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs') expect(preflight).toBeGreaterThan(-1) expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') From fe91df778bbdfe3453b24c5f2b6c75af0c6ff3c6 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:49:30 +0800 Subject: [PATCH 010/396] test(ci): preserve worker limits with required publisher smoke --- .github/workflows/ci-windows.yml | 3 ++- .github/workflows/ci.yml | 4 +++- scripts/ci-workflow.spec.ts | 19 ++++++++++++------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 142f4dfbd9..c3ea5c58fc 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -48,7 +48,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -63,6 +63,7 @@ jobs: # Blacksmith uses 2 vCPU for file-serial native tests and 16 for coverage # and the shared build/observational workspace. windows-build: + needs: windows-publisher if: github.event_name == 'pull_request' runs-on: >- ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d74e2355e0..fc83d5c7f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ concurrency: jobs: publisher-isolated: strategy: + max-parallel: 1 fail-fast: false matrix: os: [linux, macos] @@ -46,7 +47,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -494,6 +495,7 @@ jobs: node-compat: + needs: publisher-isolated if: github.event_name == 'pull_request' # Under the selfhosted leg this job admits only repository-owned PR code # to the persistent shared VM; the blacksmith branch targets ephemeral diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index ed7a360894..56bb3f9303 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -41,12 +41,17 @@ describe('CI workflow', () => { }) expect(workflowJob(ci, 'all-checks-passed').needs).toContain('node-compat') const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') expect(job).not.toHaveProperty('uses') } + // Publisher smoke reuses the compatibility/build concurrency slots before those jobs start. + expect(compatibility.needs).toBe('publisher-isolated') + expect(workflowJob(ci, 'publisher-isolated').strategy).toMatchObject({ 'max-parallel': 1, matrix: { os: ['linux', 'macos'] } }) + expect(workflowJob(ciWindows, 'windows-build').needs).toBe('windows-publisher') + expect(workflowJob(ciWindows, 'windows-publisher').defaults).toEqual({ run: { shell: 'pwsh' } }) // Python reports its own required verdict, so neither its jobs nor a // reusable workflow caller remain in the Linux or Windows workflow. expect(Object.keys(ci.jobs).filter(name => name.startsWith('python'))).toEqual([]) @@ -60,7 +65,7 @@ describe('CI workflow', () => { expect(runtime.with).toMatchObject({ targets: 'node24-linux-x64,node24-win-x64' }) expect(runtime.uses).toBe('./.github/workflows/build-exe-for-python-sdk.yml') const windowsJobs = Object.entries(ciWindows.jobs) - .filter(([name]) => name !== 'windows-checks-passed') + .filter(([name]) => !['windows-checks-passed', 'windows-publisher'].includes(name)) for (const [name, job] of windowsJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -95,7 +100,7 @@ describe('CI workflow', () => { expect(afterSdk).toBeLessThanOrEqual(11) }) - it('keeps the union of required PR verdicts equal to the pre-split blocking set', () => { + it('keeps required PR verdicts covering runtime and publisher jobs', () => { const verdicts = [ ['ci.yml', 'all-checks-passed'], ['ci-windows.yml', 'windows-checks-passed'], @@ -112,9 +117,7 @@ describe('CI workflow', () => { expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true) blocking.push(...(verdict.needs as string[])) } - // Splitting the workflows only moves jobs between verdicts; the blocking - // set itself must stay identical, or branch protection would accept a - // failure it rejected before the split. + // Every blocking lane must contribute to a branch-protection verdict. expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', @@ -122,10 +125,12 @@ describe('CI workflow', () => { 'node-24-coverage', 'node-24-lint', 'node-compat', + 'publisher-isolated', 'python-runtime', 'python-sdk', 'windows-build', 'windows-native-tests', + 'windows-publisher', ]) }) @@ -547,7 +552,7 @@ describe('CI workflow', () => { expect(aggregate.needs).not.toContain('windows') // windows-coverage is temporarily non-blocking while Windows ACP // half-close tests are stabilized; observational stays out too. - expect(windowsAggregate.needs).toEqual(['windows-build', 'windows-native-tests']) + expect(windowsAggregate.needs).toEqual(['windows-publisher', 'windows-build', 'windows-native-tests']) expect(windowsAggregate.name).toBe('windows checks passed') expect(windowsAggregate['runs-on']).toBe(aggregate['runs-on']) expect(windowsAggregate.if).toBe(aggregate.if) From eea6dfef87de9dfce21359b847d49d9cfa6f15f2 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:55:24 +0800 Subject: [PATCH 011/396] test(snapshots): refresh terminal runtime context reminder --- snapshots/session/terminal-panel-tools/session.v4.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapshots/session/terminal-panel-tools/session.v4.jsonl b/snapshots/session/terminal-panel-tools/session.v4.jsonl index 01574413c3..290e17f9f6 100644 --- a/snapshots/session/terminal-panel-tools/session.v4.jsonl +++ b/snapshots/session/terminal-panel-tools/session.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"My tests fail in my terminal. What does it say?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"session/title","data":{"title":"My tests fail in my","messageSeqs":[8],"source":{"kind":"fallback"}}} From e9591154b4919682faf539e5ea48951d189b3eae Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 17:57:11 +0800 Subject: [PATCH 012/396] fix(sidebar-right): clip the fullscreen divider past the window edge Make the fullscreen panel 1px wider than the viewport instead of hiding the first column's divider with state-dependent rules. At rest the divider sits past the left edge, where the frame clips it, and the pane's content box matches the viewport; during the open and close slides the divider moves with the panel and stays visible. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 23 +------------------ .../src/client/shell/SidebarRight.tsx | 21 ++++++++--------- .../tests/seat.client.spec.tsx | 9 +++----- .../tests/sidebar-right-styles.client.spec.ts | 14 +---------- 4 files changed, 14 insertions(+), 53 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 454acbcd26..94d08c4f24 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,26 +83,6 @@ --dsh-dockkit-dock-layer: 40; } -/* Once open, fullscreen has no conversation beside the first column, so - dockkit's column-0 divider has nothing to separate. While the panel slides - in or out across the conversation the divider stays: an opening keeps it - for the slide's duration, and a closing panel no longer matches. Only the - color changes, so the pane keeps its width. */ -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: transparent; -} - -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - transition: border-left-color 0s linear var(--ds-transition-duration-slow); -} - -/* A pane mounted by the opening starts with the divider, like one already mounted. */ -@starting-style { - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: var(--dsw-alias-border-l4); - } -} - /* Dockkit owns its pane exclusions and marked strip rows. Electron composes their boxes in DOM order: a pane subtracts its box, then a marked strip adds its row back. ui-web excludes controls within that row and body portals; @@ -144,8 +124,7 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]), - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index 86117bb069..2659481ab6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' +import type { CSSProperties, ReactNode, RefObject } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,12 +305,6 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } -/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ -function slideEnded(event: TransitionEvent): boolean { - return event.propertyName === 'transform' - && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") -} - /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -330,8 +324,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { if (slideEnded(event)) setOpening(false) } : undefined} + onTransitionEnd={opening ? () => { setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 106b3b6bf7..3d1f634711 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,11 +626,7 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - // Short transitions inside an item, or other properties, do not end the slide. - fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) - fireEvent.transitionEnd(host, { propertyName: 'opacity' }) - expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host, { propertyName: 'transform' }) + fireEvent.transitionEnd(host) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) @@ -657,7 +653,8 @@ describe('RightbarSeat presentation', () => { expect(panel.style.width).toBe('420px') fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) expect(h.layout().mode).toBe('fullscreen') - expect(panel.style.width).toBe('100vw') + expect(panel.style.width).toBe('calc(1px + 100vw)') + expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)') expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 19cbfb270f..d59a3c843f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ +/** Right sidebar slide and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,18 +18,6 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { - const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` - const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` - + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) - }) - it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From fa0b1522cb5ddc120b2135c503a8cbc4e9e5c5ac Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 18:41:39 +0800 Subject: [PATCH 013/396] test(web): expect the fullscreen sidebar 1px past the left edge Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- apps/web/tests/details-session-lifecycle.e2e.ts | 14 +++++++------- apps/web/tests/sidebar-right.e2e.ts | 12 ++++++------ apps/web/tests/support.ts | 10 ++++++++++ .../details-session-lifecycle/sidebar.expected.md | 12 ++++++------ 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index e73eaa5d0b..05da4a6afa 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -10,7 +10,7 @@ import { fixtureUserPrompts, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' +import { connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/details-session-lifecycle', import.meta.url)) const HANDLES_EXPECTED = join(SNAPSHOT_DIR, 'handles.expected.md') @@ -110,8 +110,8 @@ async function sidebarSnapshot(page: Page) { mode: panel.getAttribute('data-sidebar-right-panel'), panelContentWidth: expanded ? Math.round(Number.parseFloat(style.width)) : 0, panelOuterWidth: expanded ? Math.round(rect.width) : 0, - coversViewport: expanded && rect.x === 0 && rect.y === 0 - && Math.round(rect.width) === window.innerWidth && Math.round(rect.height) === window.innerHeight, + coversViewport: expanded && rect.x === -1 && rect.y === 0 + && Math.round(rect.width) === window.innerWidth + 1 && Math.round(rect.height) === window.innerHeight, resizeHandleWidth: handle === null ? 0 : Math.round(handle.getBoundingClientRect().width), expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] button[aria-expanded="true"]')] .map(button => button.textContent?.trim()), @@ -195,7 +195,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await expect.poll(() => blankColumn.locator('[data-dockkit-host="dock"]:not([hidden])').evaluate(element => getComputedStyle(element).transform)) .toBe('none') await expect.poll(() => blankColumn.locator('[data-sidebar-right-panel]').boundingBox()) - .toEqual({ x: 0, y: 0, width: 767, height: blankViewport.height }) + .toEqual(fullscreenBox({ width: 767, height: blankViewport.height })) // A preview the files page opened starts with its tree hidden; shown, the tree fills the viewport. const treeToggle = blankColumn.locator('[data-files-navigator-toggle]') await expect.poll(() => treeToggle.getAttribute('aria-expanded')).toBe('false') @@ -360,7 +360,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await checkpoint('A normal: two panes') await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await columns(page)).toEqual(normalColumns) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) expect(await paneSnapshot(page)).toEqual(retainedA) @@ -395,7 +395,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') expect(await paneSnapshot(page)).toEqual(retainedA) await open() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await paneSnapshot(page)).toEqual(retainedA) await checkpoint('A restored: manual fullscreen, tabs, and panes') await column.locator('[data-sidebar-right-mode="push"]').click() @@ -433,7 +433,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await page.locator('[data-sidebar-right-expand]').click() await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420 - normalWidth, normalWidth]) await page.setViewportSize({ width: 767, height: viewport.height }) - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, width: 767, height: viewport.height }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox({ width: 767, height: viewport.height })) await expect.poll(() => columns(page)).toEqual([0, 767, 0]) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) await checkpoint('A automatic fullscreen at 767px') diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 461947ed21..c66eba54db 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -26,7 +26,7 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { acknowledgeReloadConnectionLoss, launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' import { - connectFreshWorkspace, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, + connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, } from './support.ts' /** The produced file the seeded turn writes, and what the preview should show. */ @@ -524,7 +524,7 @@ describe('web e2e: shipped right Sidebar', () => { expect(await width(column)).toBe(trackWidth) const viewport = page.viewportSize() if (viewport === null) throw new Error('expected a fixed viewport') - await expect.poll(async () => await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(async () => await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) await shot(page, '03-fullscreen-panel') @@ -558,7 +558,7 @@ describe('web e2e: shipped right Sidebar', () => { await frame.evaluate(async (node) => { await Promise.allSettled(node.getAnimations().map(animation => animation.finished)) }) const normalColumns = (await geometry()).columns await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) await column.locator('[data-sidebar-right-toggle]').click() await Promise.all([ panel.evaluate(async (node) => { @@ -586,7 +586,7 @@ describe('web e2e: shipped right Sidebar', () => { await held.evaluate((state) => { (state.animation as Animation).finish() }) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await geometry()).toEqual({ columns: normalColumns, transition: 'none', handles: ['none'], animatingGrid: false }) const exit = await holdPanelSlide(panel) @@ -621,7 +621,7 @@ describe('web e2e: shipped right Sidebar', () => { await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBeNull() await expandOf(page).click() await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect((await geometry()).columns).toBe(normalColumns) expect((await geometry()).animatingGrid).toBe(false) } finally { @@ -733,7 +733,7 @@ describe('web e2e: shipped right Sidebar', () => { await page.setViewportSize({ width: 767, height: viewport.height }) await expect.poll(async () => await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') - await expect.poll(async () => await width(panel)).toBe(767) + await expect.poll(async () => await width(panel)).toBe(768) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index cda15bafaf..ec7b5b1404 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -468,3 +468,13 @@ export async function openSettings(page: Page, locale: 'en' | 'zh' | 'ja'): Prom await trigger.click() await page.getByRole('menuitem', { name: labels[locale][1], exact: true }).click() } + +/** + * The right Sidebar's fullscreen panel box: 1px wider than the viewport, so the + * first column's divider sits past the window's left edge where the frame clips it. + * @param viewport - the page viewport size. + * @returns the panel's expected bounding box. + */ +export function fullscreenBox(viewport: { width: number; height: number }): { x: number; y: number; width: number; height: number } { + return { x: -1, y: 0, width: viewport.width + 1, height: viewport.height } +} diff --git a/snapshots/web/details-session-lifecycle/sidebar.expected.md b/snapshots/web/details-session-lifecycle/sidebar.expected.md index f205ed9765..4607cf35ed 100644 --- a/snapshots/web/details-session-lifecycle/sidebar.expected.md +++ b/snapshots/web/details-session-lifecycle/sidebar.expected.md @@ -64,8 +64,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -197,8 +197,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -424,8 +424,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 767, - "panelOuterWidth": 767, + "panelContentWidth": 768, + "panelOuterWidth": 768, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], From ac96c518fb2de7f4700db38531533f1815147164 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:31:24 +0800 Subject: [PATCH 014/396] ci(preview): publish a snapshot diff page with each PR preview Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .../workflows/build-preview-cloudflare.yml | 32 ++- scripts/preview-workflow.spec.ts | 14 +- scripts/snapshot-diff-page.spec.ts | 76 ++++++ scripts/snapshot-diff-page.ts | 223 ++++++++++++++++++ 4 files changed, 333 insertions(+), 12 deletions(-) create mode 100644 scripts/snapshot-diff-page.spec.ts create mode 100644 scripts/snapshot-diff-page.ts diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index 5625d75a9c..c8cb718234 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -43,9 +43,12 @@ jobs: || 'ubuntu-24.04' }} name: cloudflare pages preview steps: + # The pull_request checkout is the merge commit; depth 2 brings its first + # parent, the base branch tip, for the snapshot diff page. - uses: actions/checkout@v7.0.1 with: persist-credentials: false + fetch-depth: 2 - uses: pnpm/action-setup@v5.0.0 with: @@ -98,6 +101,11 @@ jobs: find apps/web/dist -name '*.map' -delete cp apps/web/dist/preview.html apps/web/dist/index.html + # Reviewers read snapshot changes at /snapshot-diff/, which opens on the + # SDK blank-Session catalog (system prompt and tool schemas). + - name: Render the snapshot diff page + run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + - name: Upload to Cloudflare Pages id: upload continue-on-error: true @@ -164,7 +172,8 @@ jobs: # The alias URL follows from the pull request number, so it is stable # across redeploys and worth stating once. The marker makes the comment # idempotent: a pull request opened before this workflow existed never - # sees an `opened` event, and every later push must not restate the URL. + # sees an `opened` event, and every later push must not restate the URL; + # an existing comment with older text is edited in place. - name: Comment the preview URL id: comment continue-on-error: true @@ -173,18 +182,21 @@ jobs: PR: ${{ github.event.pull_request.number }} run: | marker='' - existing=$(gh pr view "$PR" --json comments \ - --jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty") - if [ -n "$existing" ]; then - echo "preview URL already commented: $existing" - exit 0 - fi + url="https://pr-$PR.${CF_PROJECT}.pages.dev" # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - printf '%s\n\n%s\n' \ + body=$(printf '%s\n\n%s\n' \ "$marker" \ - "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \ - | gh pr comment "$PR" --body-file - + "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ + --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + if [ -z "$existing" ]; then + printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null + else + echo "preview URL already commented" + fi # Publishing stays outside the required verdict: a Cloudflare, Access, or # comment failure warns, while a build failure still fails this check. diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index e38f18b776..bd21bc2c0a 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -25,12 +25,12 @@ describe('PR preview workflow', () => { expect(preview['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') expect(workflow.on).toEqual({ pull_request: { types: ['opened', 'synchronize', 'reopened'] } }) expect(workflow.permissions).toEqual({ contents: 'read', 'pull-requests': 'write' }) - expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false }) + expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false, 'fetch-depth': 2 }) }) it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { @@ -79,5 +79,15 @@ describe('PR preview workflow', () => { const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.run).toContain('gh api -X PATCH') + }) + + it('renders the snapshot diff page into the upload against the base branch tip', () => { + const steps = preview.steps.map(step => step.name) + const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) + expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts new file mode 100644 index 0000000000..5147ec6dd0 --- /dev/null +++ b/scripts/snapshot-diff-page.spec.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' + +const limits = { fileLines: 100, totalChars: 10_000 } + +const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md +index 1111111..2222222 100644 +--- a/snapshots/sdk/text-turn/system-prompt.expected.md ++++ b/snapshots/sdk/text-turn/system-prompt.expected.md +@@ -1,2 +1,2 @@ + You are an agent. +-Old rule. ++New rule. +diff --git a/snapshots/web/ptc-round/session.jsonl b/snapshots/web/ptc-round/session.jsonl +deleted file mode 100644 +index 3333333..0000000 +--- a/snapshots/web/ptc-round/session.jsonl ++++ /dev/null +@@ -1 +0,0 @@ +-{"type":"header"} +diff --git a/snapshots/web/ptc-round/image.png b/snapshots/web/ptc-round/image.png +new file mode 100644 +index 0000000..4444444 +Binary files /dev/null and b/snapshots/web/ptc-round/image.png differ +diff --git a/snapshots/web/present/workspace.expected/a b/说明.txt b/snapshots/web/present/workspace.expected/a b/说明.txt +old mode 100644 +new mode 100755 +` + +const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + +describe('snapshot diff page', () => { + it('splits git diff output into files with their hunks', () => { + expect(parseUnifiedDiff(diff, limits)).toEqual([ + { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, + { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + ]) + expect(parseUnifiedDiff('', limits)).toEqual([]) + }) + + it('rejects paths git still quotes', () => { + expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + }) + + it('truncates long files and drops hunks once the total budget is spent', () => { + const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` + const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) + expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) + expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) + expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + }) + + it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { + const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) + expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ + ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + ]) + }) + + it('lists a path once when a type change splits it into two sections', () => { + const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } + const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } + expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + }) + + it('embeds the data so diff text cannot close the script element', () => { + const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + expect(page).not.toContain('') + const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + }) +}) diff --git a/scripts/snapshot-diff-page.ts b/scripts/snapshot-diff-page.ts new file mode 100644 index 0000000000..e4f6bbdc96 --- /dev/null +++ b/scripts/snapshot-diff-page.ts @@ -0,0 +1,223 @@ +/** + * Renders the PR preview's snapshot diff page: one self-contained HTML file + * listing every changed file under `snapshots/` between two revisions, grouped + * by scenario directory. The page opens on the SDK blank-Session catalog, the + * system prompt and tool schemas the `sdk/text-turn` scenario's first request + * carries, and shows "No change" when neither file changed. + * + * Usage: `tsx scripts/snapshot-diff-page.ts --base --head --out ` + */ +import { execFileSync } from 'node:child_process' +import { mkdirSync, writeFileSync } from 'node:fs' +import { dirname } from 'node:path' +import { parseArgs } from 'node:util' +import * as yaml from 'js-yaml' + +/** Scenario whose first request represents a blank SDK Session. */ +const CATALOG_SCENARIO = 'snapshots/sdk/text-turn' + +/** Per-file and total limits on embedded diff text; the page notes what it omits. */ +export interface DiffLimits { + readonly fileLines: number + readonly totalChars: number +} + +/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit and responsive in a browser. */ +const LIMITS: DiffLimits = { fileLines: 2000, totalChars: 8_000_000 } + +/** One `diff --git` section: a changed file and its unified diff text. */ +export interface FileDiff { + /** Repository-relative path. */ + readonly path: string + /** Unified diff lines from the first `@@` hunk header, empty for binary or mode-only changes. */ + readonly hunks: string + /** True when git reports a binary change. */ + readonly binary: boolean + /** Hunk lines left out of `hunks` by the limits. */ + readonly omitted: number +} + +/** A selectable group of file diffs on the page. */ +export interface DiffGroup { + readonly title: string + /** Distinct paths the group covers, including unchanged ones. */ + readonly paths: readonly string[] + readonly files: readonly FileDiff[] +} + +/** + * Splits git diff output into per-file sections. + * @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames`; + * a path git still quotes (one with `"`, `\\`, or a control character) is rejected. + * @param limits - Lines kept per file and characters kept across all files. + * @returns One entry per `diff --git` section, in output order. A path that + * changes between symlink and regular file has two sections. + */ +export function parseUnifiedDiff(text: string, limits: DiffLimits = LIMITS): FileDiff[] { + const files: FileDiff[] = [] + let budget = limits.totalChars + for (const section of text.split(/^(?=diff --git )/m)) { + if (!section.startsWith('diff --git ')) continue + const lines = section.split('\n') + // Without renames the header is `diff --git a/ b/` with both paths equal. + const header = section.slice('diff --git '.length, section.indexOf('\n') === -1 ? undefined : section.indexOf('\n')) + if (header.startsWith('"')) throw new Error(`unsupported quoted path in git diff header: ${header}`) + const path = header.slice('a/'.length, (header.length - ' '.length) / 2) + const hunkStart = lines.findIndex(line => line.startsWith('@@')) + const all = hunkStart === -1 ? [] : lines.slice(hunkStart, lines.at(-1) === '' ? -1 : undefined) + let kept = all.slice(0, limits.fileLines) + let hunks = kept.join('\n') + if (hunks.length > budget) { + kept = [] + hunks = '' + } + budget -= hunks.length + files.push({ path, hunks, binary: lines.some(line => line.startsWith('Binary files ')), omitted: all.length - kept.length }) + } + return files +} + +/** + * Groups changed files for the page: the catalog first, then one group per + * scenario directory (`snapshots//`) in path order. + * @param files - Changed files under `snapshots/`. + * @param catalogPaths - Files that make up the SDK blank-Session catalog. + * @returns The catalog group followed by the scenario groups. + */ +export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly string[]): DiffGroup[] { + const scenarios = new Map() + for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { + const key = file.path.split('/').slice(0, 3).join('/') + scenarios.set(key, [...scenarios.get(key) ?? [], file]) + } + return [ + { title: 'SDK blank Session catalog', paths: catalogPaths, files: files.filter(file => catalogPaths.includes(file.path)) }, + ...[...scenarios].map(([key, group]) => ({ title: key.replace(/^snapshots\//, ''), paths: [...new Set(group.map(file => file.path))], files: group })), + ] +} + +/** + * Renders the self-contained page. + * @param groups - Groups from {@link groupDiffs}; the first one opens by default. + * @param heading - Revision description shown under the title. + * @returns HTML text. + */ +export function renderSnapshotDiffPage(groups: readonly DiffGroup[], heading: string): string { + const data = JSON.stringify({ groups, heading }).replace(/ + + + + +Snapshot changes + + + + +
+ + + + +` +} + +/** + * Reads the catalog files from the catalog scenario's `snapshot.yml`. + * @param rev - Revision to read. + * @returns The system prompt sidecar and the tool schema sidecar, which lives + * in the scenario named by `header.toolSchemasSource` when present. + */ +function catalogPaths(rev: string): string[] { + const spec = yaml.load(git('show', `${rev}:${CATALOG_SCENARIO}/snapshot.yml`), { schema: yaml.JSON_SCHEMA }) as { header?: { toolSchemasSource?: unknown } } + const source = spec.header?.toolSchemasSource + if (source !== undefined && typeof source !== 'string') throw new Error(`${CATALOG_SCENARIO}/snapshot.yml: header.toolSchemasSource must be a string`) + const paths = [`${CATALOG_SCENARIO}/system-prompt.expected.md`, `${source === undefined ? CATALOG_SCENARIO : `snapshots/${source}`}/tool-schemas.expected.json`] + for (const path of paths) { + try { + git('cat-file', '-e', `${rev}:${path}`) + } catch (error) { + throw new Error(`catalog file ${path} is missing at ${rev}`, { cause: error }) + } + } + return paths +} + +function git(...args: string[]): string { + return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 30 }) +} + +if (import.meta.main) { + const { values } = parseArgs({ options: { base: { type: 'string' }, head: { type: 'string' }, out: { type: 'string' } } }) + if (!values.base || !values.head || !values.out) throw new Error('usage: snapshot-diff-page.ts --base --head --out ') + const short = (rev: string) => git('rev-parse', '--short', rev).trim() + const files = parseUnifiedDiff(git('-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--unified=5', values.base, values.head, '--', 'snapshots/')) + // A PR that moves the tool schema source shows both the old and the new file. + const catalog = [...new Set([...catalogPaths(values.base), ...catalogPaths(values.head)])] + const page = renderSnapshotDiffPage(groupDiffs(files, catalog), `${short(values.base)} → ${short(values.head)}`) + mkdirSync(dirname(values.out), { recursive: true }) + writeFileSync(values.out, page) +} From aa90f0be5679c97e03d3f86817b53eaf0a037c34 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:10:50 +0800 Subject: [PATCH 015/396] feat(subagent): attach SubagentError codes to delegation tool failures Delegation, discovery, and control tools threw plain Errors for missing caller context, invalid selections, depth limits, and corrupt or unavailable child state, so tool/result records carried no error.code. SubagentDepthError now extends SubagentError with DEPTH_EXCEEDED; new SubagentError codes cover disabled or disallowed preset and model selection, invalid depth and cwd, a missing working-directory service, a failed join of the parent preset revision, and structured output submitted with pending input. Missing callers and services use ToolContextUnavailableError, and hand-checked route fields use ToolArgsError. A corrupt cold-restore descriptor becomes NOT_RESUMABLE, and the schedule tools read the delegation depth inside their error mapping. Refs #7869 --- packages/schedule/tool-schedule/src/index.ts | 6 ++--- .../tool-schedule/tests/tool-schedule.spec.ts | 15 +++++++++++ .../tests/subagent-spawn-in-process.spec.ts | 5 +++- packages/subagent/subagent/README.i18n.yaml | 4 +-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 25 ++++++++++++----- packages/subagent/subagent/src/depth.ts | 5 ++-- packages/subagent/subagent/src/manager.ts | 15 +++++++++-- .../subagent/subagent/src/out-of-process.ts | 6 +++-- packages/subagent/subagent/src/structured.ts | 5 +++- .../subagent/tests/child-agent.spec.ts | 8 ++++-- .../tests/continuation-presets.spec.ts | 17 +++++++++++- .../subagent/tests/continuation.spec.ts | 27 ++++++++++++++++++- .../subagent/tests/out-of-process.spec.ts | 8 +++--- .../subagent/tests/structured.spec.ts | 2 ++ .../subagent/tests/working-directory.spec.ts | 6 ++++- .../tool-subagent-control/src/index.ts | 6 ++--- .../tool-subagent-control/src/list-agents.ts | 4 +-- .../tests/list-agents.spec.ts | 1 + .../tests/tool-subagent-control.spec.ts | 2 ++ .../subagent/tool-subagent/README.i18n.yaml | 4 +-- packages/subagent/tool-subagent/README.md | 2 +- packages/subagent/tool-subagent/README.zh.md | 2 +- packages/subagent/tool-subagent/src/index.ts | 12 ++++++--- .../subagent/tool-subagent/src/list-models.ts | 22 +++++++-------- .../tool-subagent/src/model-selection.ts | 20 +++++++++----- .../tool-subagent/src/preset-selection.ts | 9 +++++-- .../tool-subagent/tests/list-models.spec.ts | 20 ++++++++++---- .../tests/model-selection-settings.spec.ts | 1 + .../tests/model-selection.spec.ts | 16 ++++++++++- .../tests/preset-selection.spec.ts | 10 +++++-- .../tool-subagent/tests/tool-subagent.spec.ts | 2 ++ .../session.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- 36 files changed, 223 insertions(+), 74 deletions(-) diff --git a/packages/schedule/tool-schedule/src/index.ts b/packages/schedule/tool-schedule/src/index.ts index ab1ed612dc..65040e4c93 100644 --- a/packages/schedule/tool-schedule/src/index.ts +++ b/packages/schedule/tool-schedule/src/index.ts @@ -303,10 +303,10 @@ async function runForCaller( ): Promise | SubagentSessionError | InternalScheduleError> { const agent = exec.agent if (agent === undefined) return internalError() - if (delegationDepthOf(agent) > 0) { - return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } - } try { + if (delegationDepthOf(agent) > 0) { + return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } + } return await operation(agent) } catch (error: unknown) { if (error instanceof ScheduleInputError) { diff --git a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts index 6d3d189d95..983f8a5daf 100644 --- a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts +++ b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts @@ -229,6 +229,21 @@ describe('Schedule model tools', () => { expect((await test.service.list({})).total).toBe(0) }) + it('answers internal_error when the caller carries an invalid runtime delegation depth', async () => { + const test = await harness(); tests.push(test) + const caller = { ...agentFor(test.ctx, 'invalid-depth'), options: { subagentDepth: -1 } } + await test.ctx.agents.register(caller) + await mountToolSchedule(test.ctx, caller) + for (const [name, args] of CALLS) { + const result = await executeToolFixture(test.ctx, { + callId: ToolCallId('invalid-depth-call'), signal: new AbortController().signal, name, arguments: args, agent: caller, + }) + expect(result.isError).toBe(false) + expect(result.value).toEqual(INTERNAL_ERROR) + } + expect((await test.service.list({})).total).toBe(0) + }) + it('describes the create parameters for the model', async () => { const test = await setup() const schema = test.ctx.tools.schemas(test.agent).find(candidate => candidate.name === 'schedule_create') diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index c254b67c8c..3ffd937d4d 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -131,7 +131,10 @@ describe('dsh-subagent-spawn-in-process', () => { const { ctx, parent } = await setup([]) // parent is depth 0, child would be depth 1 — cap at 0 forbids any child. await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 })) - .rejects.toThrow('subagent depth 1 exceeds maxDepth 0') + .rejects.toMatchObject({ + name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: 'subagent depth 1 exceeds maxDepth 0', + attemptedDepth: 1, maxDepth: 0, + }) }) it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => { diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4ff564cb25..ceaac3229a 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: 0dc416ded19e304e - zh: 4726e5fe5f188709 + en: f5393c65bf8ee460 + zh: d037d42bc967f17b /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index b8fd869989..dcad891799 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e0f8f35bda..dfe7d1f835 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 98ebfc9d5d..9f4626641c 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -28,10 +28,10 @@ import type {} from '@deepseek-ai/dsh-agent-preset-registry' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' -/** Thrown when starting a child would exceed the requested depth cap. */ -export class SubagentDepthError extends Error { +/** Thrown when starting a child would exceed the requested depth cap; `code` is `DEPTH_EXCEEDED`. */ +export class SubagentDepthError extends SubagentError { constructor(public readonly attemptedDepth: number, public readonly maxDepth: number) { - super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`) + super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`, 'DEPTH_EXCEEDED') this.name = 'SubagentDepthError' } } @@ -44,12 +44,12 @@ export class SubagentDepthError extends Error { * @param maxDepth - optional absolute cap the resolved depth must not exceed. * @returns the child's non-negative safe-integer depth. * @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`. - * @throws {RangeError} when the resolved depth leaves the safe-integer range. + * @throws {SubagentError} `DEPTH_EXCEEDED` when the resolved depth leaves the safe-integer range. */ export function resolveChildDepth(parent: Agent, maxDepth: number | undefined): number { const childDepth = delegationDepthOf(parent) + 1 if (!Number.isSafeInteger(childDepth)) { - throw new RangeError('subagent child depth exceeds the safe-integer range') + throw new SubagentError('subagent child depth exceeds the safe-integer range', 'DEPTH_EXCEEDED') } if (maxDepth !== undefined && childDepth > maxDepth) { throw new SubagentDepthError(childDepth, maxDepth) @@ -183,6 +183,8 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. */ export function applyChildComposition( childCtx: Context, @@ -198,7 +200,18 @@ export function applyChildComposition( applyChildOverrides(childCtx, composition) }) } - if (parent !== undefined) childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + if (parent !== undefined) { + try { + childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + } catch (error: unknown) { + // The registry cannot import this package, so its plain join failures are classified here. + throw new SubagentError( + 'the child cannot join the parent agent\'s current preset revision', + 'PRESET_UNAVAILABLE', + { cause: error }, + ) + } + } applyChildOverrides(childCtx, composition) } diff --git a/packages/subagent/subagent/src/depth.ts b/packages/subagent/subagent/src/depth.ts index d9fabab860..033e953bf5 100644 --- a/packages/subagent/subagent/src/depth.ts +++ b/packages/subagent/subagent/src/depth.ts @@ -7,6 +7,7 @@ */ import type { Agent } from '@deepseek-ai/dsh-agent' +import { SubagentError } from './error.ts' declare module '@deepseek-ai/dsh-agent' { interface AgentOptions { @@ -23,12 +24,12 @@ declare module '@deepseek-ai/dsh-agent' { * let it delegate as if it were top-level. * @param agent - the agent whose header and options carry the depth. * @returns its non-negative safe-integer depth. - * @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. + * @throws {SubagentError} `INVALID_DEPTH` if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. */ export function delegationDepthOf(agent: Agent): number { const runtime = agent.options.subagentDepth if (runtime !== undefined && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) { - throw new TypeError('agent subagentDepth must be a non-negative safe integer') + throw new SubagentError('agent subagentDepth must be a non-negative safe integer', 'INVALID_DEPTH') } // The header value was validated at the session boundary (creation and // persistence load both construct through the store). diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index db6f04b019..fa97141c76 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -830,7 +830,9 @@ export class SubagentManager { child.session.append('subagent/descriptor', create.descriptor) appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies) const workingDirectory = childCtx.get('workingDirectory') - if (workingDirectory === undefined) throw new Error('local subagents require the working-directory service') + if (workingDirectory === undefined) { + throw new SubagentError('local subagents require the working-directory service', 'WORKING_DIRECTORY_UNAVAILABLE') + } await workingDirectory.set(child, create.cwd, inputs.signal) } if (inputs.composition.agentPreset === undefined) await applyChildComposition(childCtx, create?.parent, inputs.composition) @@ -1205,7 +1207,16 @@ export class SubagentManager { using source = await this.observeContinuation(childId, signal) this.assertAdmitting(root) const ownEvents = source.events.slice(source.inheritedEventCount) - const descriptor = foldSubagentDescriptor(ownEvents) + let descriptor: ReturnType + try { + descriptor = foldSubagentDescriptor(ownEvents) + } catch (error: unknown) { + throw new SubagentError( + `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + 'NOT_RESUMABLE', + { cause: error }, + ) + } if (descriptor === undefined || descriptor.mode !== 'continuable') { throw new SubagentError( `subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index d8a5519c96..84f46ae387 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -13,6 +13,7 @@ import { accessSync, constants, statSync } from 'node:fs' import { isAbsolute } from 'node:path' import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { SubagentError } from './error.ts' import type { SubagentCapabilities, SubagentResult, SubagentRun, SubagentStopReason } from './types.ts' /** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */ @@ -100,13 +101,14 @@ function isEnterableDirectory(path: string): boolean { * @param label - which source supplied the value, for the diagnostic. * @param cwd - the candidate working directory. * @returns `cwd`, validated. + * @throws {SubagentError} `INVALID_CWD` when `cwd` is relative or not an enterable directory. */ export function assertUsableCwd(prefix: string, label: string, cwd: string): string { if (!isAbsolute(cwd)) { - throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} must be an absolute path: ${cwd}`, 'INVALID_CWD') } if (!isEnterableDirectory(cwd)) { - throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} is not an accessible directory: ${cwd}`, 'INVALID_CWD') } return cwd } diff --git a/packages/subagent/subagent/src/structured.ts b/packages/subagent/subagent/src/structured.ts index eeb8c1e86b..81f0952d09 100644 --- a/packages/subagent/subagent/src/structured.ts +++ b/packages/subagent/subagent/src/structured.ts @@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import type { ToolExecution, ToolRunContext } from '@deepseek-ai/dsh-tools' import { ToolArgsError, validateJsonSchemaValue, type ObjectJsonSchema } from '@deepseek-ai/dsh-tools' +import { SubagentError } from './error.ts' /** The model-facing tool name a structured child must call to finish. */ export const STRUCTURED_OUTPUT_TOOL = 'structured_output' @@ -96,7 +97,9 @@ export function attachStructuredRuntime( // ToolArgsError → isError result with INVALID_ARGS: the model retries // within the same turn, exactly like a schema-validated defineTool call. if (violations.length > 0) throw new ToolArgsError(violations) - if (!canComplete()) throw new Error('Process pending messages before submitting structured output.') + if (!canComplete()) { + throw new SubagentError('Process pending messages before submitting structured output.', 'STRUCTURED_OUTPUT_PENDING_INPUT') + } // Two-phase commit, keyed by THIS execution: later transformable // waterfalls may still turn the success into an error. ToolRuntime has // already frozen model-bound arguments at the actual input boundary. diff --git a/packages/subagent/subagent/tests/child-agent.spec.ts b/packages/subagent/subagent/tests/child-agent.spec.ts index 0b661cd21d..ad47b8f6d4 100644 --- a/packages/subagent/subagent/tests/child-agent.spec.ts +++ b/packages/subagent/subagent/tests/child-agent.spec.ts @@ -92,12 +92,16 @@ describe('delegation depth limits', () => { it.each([-1, -0, 0.5, Number.NaN, Number.POSITIVE_INFINITY])('rejects an invalid runtime depth %s', (depth) => { const parent = parentAgent() parent.options.subagentDepth = depth - expect(() => resolveChildDepth(parent, undefined)).toThrow('agent subagentDepth must be a non-negative safe integer') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'INVALID_DEPTH', message: 'agent subagentDepth must be a non-negative safe integer', + })) }) it('rejects a child depth beyond the exact integer range', () => { const parent = parentAgent() parent.options.subagentDepth = Number.MAX_SAFE_INTEGER - expect(() => resolveChildDepth(parent, undefined)).toThrow('subagent child depth exceeds the safe-integer range') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'DEPTH_EXCEEDED', message: 'subagent child depth exceeds the safe-integer range', + })) }) }) diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 941d7faf16..594be164ac 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -1,7 +1,7 @@ /** Independent spawn presets and compatibility of persisted child compositions. */ import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -124,6 +124,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies a failed join of the parent preset revision as PRESET_UNAVAILABLE', async () => { + const { ctx, parent, adapter } = await setup() + const failure = new Error('Parent preset revision is unavailable') + vi.spyOn(ctx.agentPresets, 'composeFrom').mockImplementation(() => { throw failure }) + + await expect(ctx.subagents.startActivation(startSpec(parent))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'the child cannot join the parent agent\'s current preset revision', + cause: failure, + }) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..3948cde2f0 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -766,7 +766,7 @@ describe('SubagentRuntime.startActivation', () => { delivery: 'parent', ...startSpec(parent), prompt: message('deep'), parent, maxDepth: 0, - })).rejects.toThrow(/exceeds maxDepth 0/) + })).rejects.toMatchObject({ name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: expect.stringMatching(/exceeds maxDepth 0/) as string }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([SessionId('parent')]) }) @@ -1160,6 +1160,31 @@ describe('target-only Queue residency routing', () => { .rejects.toMatchObject({ code: 'NOT_RESUMABLE' }) }) + it('rejects a cold target whose persisted descriptor is corrupt as not resumable', async () => { + const { ctx, parent } = await setup([]) + const childId = SessionId('child-with-corrupt-descriptor') + const child = await ctx.agents.create({ + sessionId: childId, + meta: { origin: 'subagent', parentSession: parent.id }, + agentOptions: { provider: 'mock', model: 'mock' }, + setup: (_childCtx, agent) => { + agent.session.append('subagent/descriptor', { + version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'spawn', label: 7, + } as never) + }, + }) + await ctx.sessions.flush(child.agent.session) + await child.dispose() + + await expect(ctx.subagents.sendMessage(parent, childId, message('continue'), { signal: testSignal })) + .rejects.toMatchObject({ + name: 'SubagentError', + code: 'NOT_RESUMABLE', + message: `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + cause: expect.objectContaining({ message: 'persisted subagent descriptor label must be a string' }) as Error, + }) + }) + it('reports an unknown child id as unavailable', async () => { const { ctx } = await setup([]) await expect(queuePrompt(ctx, SessionId('missing'), message('hello'))) diff --git a/packages/subagent/subagent/tests/out-of-process.spec.ts b/packages/subagent/subagent/tests/out-of-process.spec.ts index f4db734e96..79c44ccf4b 100644 --- a/packages/subagent/subagent/tests/out-of-process.spec.ts +++ b/packages/subagent/subagent/tests/out-of-process.spec.ts @@ -42,8 +42,8 @@ describe('assertPositiveFinite', () => { describe('child cwd resolution', () => { it('accepts an absolute enterable directory and rejects relative or missing paths', () => { expect(assertUsableCwd('p', 'config cwd', tmpdir())).toBe(tmpdir()) - expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow('must be an absolute path') - expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('must be an absolute path') as string })) + expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) }) it('rejects an existing path that is a file, not a directory', () => { @@ -51,7 +51,7 @@ describe('child cwd resolution', () => { const file = join(tmp, 'plain.txt') try { writeFileSync(file, 'not a dir\n') - expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { rmSync(tmp, { recursive: true, force: true }) } @@ -64,7 +64,7 @@ describe('child cwd resolution', () => { const tmp = mkdtempSync(join(tmpdir(), 'oop-noexec-')) chmodSync(tmp, 0o600) try { - expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { chmodSync(tmp, 0o700) rmSync(tmp, { recursive: true, force: true }) diff --git a/packages/subagent/subagent/tests/structured.spec.ts b/packages/subagent/subagent/tests/structured.spec.ts index 60f5f8b19e..ea0f4e5109 100644 --- a/packages/subagent/subagent/tests/structured.spec.ts +++ b/packages/subagent/subagent/tests/structured.spec.ts @@ -138,6 +138,8 @@ describe('in-process structured output', () => { const events = run.localAgent.session.snapshotEvents() const first = events.find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'before-input') expect(first?.type === 'tool/result' && first.data.message.isError).toBe(true) + expect(first?.type === 'tool/result' && first.data.error) + .toEqual({ name: 'SubagentError', code: 'STRUCTURED_OUTPUT_PENDING_INPUT' }) expect(events.some(event => event.type === 'user/message' && event.data.id === messageId)).toBe(true) expect(JSON.stringify(adapter.requests.at(-1)?.messages)).toContain('Correction: submit answer 42 instead.') } finally { diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index f3cb6aa47d..befe01a1da 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -101,7 +101,11 @@ describe('subagent working directories', () => { provider: 'spawn', label: 'unavailable directory service', childId, parent, cwd: second, prompt: [{ type: 'text', text: 'child' }], signal: new AbortController().signal, - })).rejects.toThrow(/subagents require the working-directory service/) + })).rejects.toMatchObject({ + name: 'SubagentError', + code: 'WORKING_DIRECTORY_UNAVAILABLE', + message: expect.stringMatching(/subagents require the working-directory service/) as string, + }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(parent.session.snapshotEvents().filter(event => event.type === 'subagent/catalog')).toEqual([]) diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index b6b89603ac..8f9ecc95ba 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { ROOT_AGENT_NAME } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -73,7 +73,7 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const sender = exec.agent if (!sender) { - throw new Error('send_message requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('send_message requires a calling agent (exec.agent was undefined)') } const message: ContentBlock[] = [{ type: 'text', text: args.message }] const targetId = await ctx.subagents.resolveName(sender, args.agent, exec.signal) @@ -146,7 +146,7 @@ export function apply(ctx: Context, config: Config = {}): void { const caller = exec.agent if (!caller) { // Ancestor authority requires an exact live calling agent. - throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('interrupt_agent requires a calling agent (exec.agent was undefined)') } const targetId = await ctx.subagents.resolveName(caller, args.agent, exec.signal) // The service authorizes the exact live caller against the target's diff --git a/packages/subagent/tool-subagent-control/src/list-agents.ts b/packages/subagent/tool-subagent-control/src/list-agents.ts index 50780cf91d..555b16181e 100644 --- a/packages/subagent/tool-subagent-control/src/list-agents.ts +++ b/packages/subagent/tool-subagent-control/src/list-agents.ts @@ -1,7 +1,7 @@ /** Discover the caller's entire subagent tree; the control plugin owns registration. */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { SessionId } from '@deepseek-ai/dsh-session' @@ -78,7 +78,7 @@ export function registerListAgents(ctx: Context): ToolDefinition { const parent = exec.agent if (!parent) { // Non-agent callers have no session whose children could be listed. - throw new Error('list_agents requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('list_agents requires a calling agent (exec.agent was undefined)') } const root = ctx.subagents.rootOf(parent) const entries = await ctx.subagents.listDescendants(root.id, exec.signal) diff --git a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts index a1d0adf382..c927784c70 100644 --- a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts @@ -271,6 +271,7 @@ describe('list_agents', () => { const result = await callTool(ctx, 'list_agents', {}) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('unregisters with its plugin fiber (HMR safety)', async () => { diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index 5ea4866a1c..c12f685212 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -463,6 +463,7 @@ describe('dsh-tool-subagent-control', () => { const result = await callTool(ctx, 'send_message', { agent: 'x', message: 'y' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it.each([{}, { interrupt: true }, { interrupt: false }])('unregisters and reloads with config %j (HMR safety)', async (config) => { @@ -692,5 +693,6 @@ describe('dsh-tool-subagent-control interrupt_agent', () => { const result = await callTool(ctx, 'interrupt_agent', { agent: 'x' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) }) diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 35252c76ab..eb73b24381 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -36,8 +36,8 @@ en: 373abf7c7aa3e4f1 zh: be0b4d4a7371d360 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/activation-ownership: - en: ef692c4d17290920 - zh: b1d0d3dab011e2cd + en: a72ddd82ad7810a1 + zh: 738f8fb157e51c59 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/result-acknowledgement: en: 3c2d70d479be8e38 zh: 9aebdb72223a086e diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index e41c2161b6..f4d29d8b26 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -94,7 +94,7 @@ One instance is one provider plus one tool name. The plugin registers its defini ### Activation ownership -The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result; failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. +The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result. Rejections before startup are coded: a missing calling Agent, `llm` service, or effective parent route throws `ToolContextUnavailableError`; an empty or unpaired route field throws `ToolArgsError`; and `SubagentError` reports a disabled selection (`MODEL_SELECTION_DISABLED`, `PRESET_SELECTION_DISABLED`), a preset outside the allowlist (`PRESET_NOT_ALLOWED`), an unauthorized route (`UNAUTHORIZED`), an unregistered discovery provider (`NO_PROVIDER`), or a provider replaced during route preflight (`PROVIDER_CHANGED`). Failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. ### Result acknowledgement diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 2093ff093a..5760c7f02c 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -94,7 +94,7 @@ kind: "package-reference" ### Activation 所有权 -工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果;发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 +工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果。启动前的拒绝都带 code:缺少调用方 Agent、`llm` 服务或有效的父级路由时抛出 `ToolContextUnavailableError`;路由字段为空或未成对提供时抛出 `ToolArgsError`;`SubagentError` 报告选择被禁用(`MODEL_SELECTION_DISABLED`、`PRESET_SELECTION_DISABLED`)、preset 不在允许列表中(`PRESET_NOT_ALLOWED`)、路由未授权(`UNAUTHORIZED`)、发现查询的提供方未注册(`NO_PROVIDER`),或路由预检期间提供方被替换(`PROVIDER_CHANGED`)。发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 ### 结果确认 diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index 5f2f089363..4cce53ec87 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { AgentOptions } from '@deepseek-ai/dsh-agent' import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' @@ -18,6 +18,7 @@ import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation, + SubagentError, } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' import { @@ -275,7 +276,7 @@ export async function apply(ctx: Context, config: Config): Promise { const parent = exec.agent if (!parent) { // Non-agent callers provide no parent for delegation ownership. - throw new Error('subagent tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('subagent tool requires a calling agent (exec.agent was undefined)') } const routes = subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, parent.session) @@ -298,7 +299,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (requiresRoutePreflight) { const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot resolve the selected child LLM route because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot resolve the selected child LLM route because the `llm` service is unavailable') } const inheritParentReasoningEffort = providerRouteDefaults === undefined && !hasDelegationModelRequest(modelRequest) await preflightChildLlmRoute( @@ -309,7 +310,10 @@ export async function apply(ctx: Context, config: Config): Promise { inheritParentReasoningEffort, ) if (ctx.subagents.getProvider(config.provider) !== subagentProvider) { - throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`) + throw new SubagentError( + `subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`, + 'PROVIDER_CHANGED', + ) } } exec.signal.throwIfAborted() diff --git a/packages/subagent/tool-subagent/src/list-models.ts b/packages/subagent/tool-subagent/src/list-models.ts index 966680a669..4c0ae9b94e 100644 --- a/packages/subagent/tool-subagent/src/list-models.ts +++ b/packages/subagent/tool-subagent/src/list-models.ts @@ -3,8 +3,8 @@ import type { Context } from '@deepseek-ai/cordis' import type LlmRuntime from '@deepseek-ai/dsh-llm' import type { LlmProviderInfo } from '@deepseek-ai/dsh-llm' -import { defineTool } from '@deepseek-ai/dsh-tools' -import { parentAgentOptionsForDelegation } from '@deepseek-ai/dsh-subagent' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { parentAgentOptionsForDelegation, SubagentError } from '@deepseek-ai/dsh-subagent' import type { ToolRunContext } from '@deepseek-ai/dsh-tools' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { AllowedModelRoute, ModelSelectionPolicy } from './model-selection.ts' @@ -28,7 +28,7 @@ function registeredProvider( .filter(candidate => policy.routes.some(route => route.provider === candidate.id)) .map(candidate => candidate.id) .join(', ') || '(none)' - throw new Error(`LLM provider "${providerId}" is not registered; available providers: ${available}`) + throw new SubagentError(`LLM provider "${providerId}" is not registered; available providers: ${available}`, 'NO_PROVIDER') } /** Render one advertised or resolved model. */ @@ -43,24 +43,24 @@ async function listSubagentModels( request: ListSubagentModelsRequest, exec: ToolRunContext, ): Promise { - if (exec.agent === undefined) throw new Error('list_subagent_models requires a calling agent') + if (exec.agent === undefined) throw new ToolContextUnavailableError('list_subagent_models requires a calling agent') const routes = subagentModelSelectionPolicy(policyHandle, exec.agent.session) let policy = routes === undefined ? undefined : { routes } const selectionEnabled = policy !== undefined if (policy === undefined) { const { provider, model } = parentAgentOptionsForDelegation(exec.agent) if (provider === undefined || model === undefined) { - throw new Error('cannot discover child LLM routes without a parent provider and model') + throw new ToolContextUnavailableError('cannot discover child LLM routes without a parent provider and model') } policy = { routes: [{ provider, model }] } } const { signal } = exec const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot discover child LLM routes because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot discover child LLM routes because the `llm` service is unavailable') } if (request.model !== undefined && request.provider === undefined) { - throw new Error('`model` requires `provider`') + throw new ToolArgsError(['`model` requires `provider`']) } if (request.provider === undefined) { const providers = llm.listProviders() @@ -69,11 +69,11 @@ async function listSubagentModels( ? '(no LLM providers)' : providers.map(provider => `${provider.id} — ${provider.name}`).join('\n') } - if (request.provider.length === 0) throw new Error('`provider` must be non-empty') + if (request.provider.length === 0) throw new ToolArgsError(['`provider` must be non-empty']) const allowedRoutes = policy.routes.filter(route => route.provider === request.provider) const [firstRoute] = allowedRoutes if (firstRoute === undefined) { - throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`) + throw new SubagentError(`LLM provider "${request.provider}" is not allowed for this Session`, 'UNAUTHORIZED') } const provider = registeredProvider(llm, policy, request.provider) if (request.model === undefined) { @@ -85,9 +85,9 @@ async function listSubagentModels( ? `(no advertised models for ${provider.id})` : models.map(model => modelLine(provider.id, model)).join('\n') } - if (request.model.length === 0) throw new Error('`model` must be non-empty') + if (request.model.length === 0) throw new ToolArgsError(['`model` must be non-empty']) if (!allowedRoutes.some(route => route.model === request.model)) { - throw new Error(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`) + throw new SubagentError(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`, 'UNAUTHORIZED') } const model = await llm.resolveModelInfo(provider.id, request.model, signal) const efforts = model.reasoning?.efforts.map(effort => ( diff --git a/packages/subagent/tool-subagent/src/model-selection.ts b/packages/subagent/tool-subagent/src/model-selection.ts index cadeff0efe..7fa0da4c15 100644 --- a/packages/subagent/tool-subagent/src/model-selection.ts +++ b/packages/subagent/tool-subagent/src/model-selection.ts @@ -3,6 +3,8 @@ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { LlmRuntime } from '@deepseek-ai/dsh-llm' import type { AgentOptions } from '@deepseek-ai/dsh-agent' +import { SubagentError } from '@deepseek-ai/dsh-subagent' +import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import z from '@deepseek-ai/schemastery' /** One exact child LLM route authorized by a user setting. */ @@ -82,7 +84,7 @@ export function hasDelegationModelRequest(request: DelegationModelRequest): bool /** Reject an empty model-facing route value at the tool JSON boundary. */ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelRequest): void { if (value !== undefined && value.length === 0) { - throw new Error(`child LLM \`${field}\` must be non-empty`) + throw new ToolArgsError([`child LLM \`${field}\` must be non-empty`]) } } @@ -96,6 +98,9 @@ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelR * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @returns Child Agent options, preserving omission when no layer contributes one. + * @throws {SubagentError} `MODEL_SELECTION_DISABLED` when this tool instance + * forbids selection, or `UNAUTHORIZED` when the Session does not allow the route. + * @throws {ToolArgsError} when a field is empty or `provider` and `model` are not supplied together. */ export function requestedAgentOptions( configured: AgentOptions | undefined, @@ -106,15 +111,15 @@ export function requestedAgentOptions( ): AgentOptions | undefined { if (!hasDelegationModelRequest(request)) return configured if (!enabled) { - throw new Error('child model selection is disabled for this tool instance') + throw new SubagentError('child model selection is disabled for this tool instance', 'MODEL_SELECTION_DISABLED') } assertNonEmpty(request.provider, 'provider') assertNonEmpty(request.model, 'model') assertNonEmpty(request.reasoning_effort, 'reasoning_effort') if (request.provider === undefined || request.model === undefined) { - throw new Error(request.reasoning_effort === undefined + throw new ToolArgsError([request.reasoning_effort === undefined ? 'child LLM `provider` and `model` must be supplied together' - : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields') + : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields']) } assertAllowedModelSelection(policy, parentOptions, { provider: request.provider, model: request.model }) @@ -132,6 +137,7 @@ export function requestedAgentOptions( * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @param route - Validated provider/model pair from the tool call. + * @throws {SubagentError} `UNAUTHORIZED` when the Session does not allow the route. */ export function assertAllowedModelSelection( policy: ModelSelectionPolicy | undefined, @@ -143,10 +149,10 @@ export function assertAllowedModelSelection( ? provider === parentOptions.provider && model === parentOptions.model : policy.routes.some(route => route.provider === provider && route.model === model) if (allowed) return - throw new Error(`child LLM route "${provider}/${model}" is not allowed for this Session` + throw new SubagentError(`child LLM route "${provider}/${model}" is not allowed for this Session` + (policy === undefined ? '; without a recorded model-selection policy, explicit selection is limited to the parent route' - : '')) + : ''), 'UNAUTHORIZED') } /** @@ -180,7 +186,7 @@ export async function preflightChildLlmRoute( const provider = requested?.provider ?? parentOptions.provider const model = requested?.model ?? parentOptions.model if (provider === undefined || model === undefined) { - throw new Error('cannot select child LLM values without an effective provider and model') + throw new ToolContextUnavailableError('cannot select child LLM values without an effective provider and model') } const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model const reasoningEffort = requested?.reasoningEffort diff --git a/packages/subagent/tool-subagent/src/preset-selection.ts b/packages/subagent/tool-subagent/src/preset-selection.ts index 0bbb33f712..58da4a00e4 100644 --- a/packages/subagent/tool-subagent/src/preset-selection.ts +++ b/packages/subagent/tool-subagent/src/preset-selection.ts @@ -1,4 +1,5 @@ /** Deployment-owned preset choices for one delegation tool. */ +import { SubagentError } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' /** Optional default and model-selectable preset ids for a spawn tool. */ @@ -59,13 +60,17 @@ export class SubagentPresetSelection { * Validate model input and apply the deployment default. * @param request - Model-supplied tool arguments. * @returns Selected preset id, or omission to inherit the parent. + * @throws {SubagentError} `PRESET_SELECTION_DISABLED` when this tool exposes no + * preset choice, or `PRESET_NOT_ALLOWED` when the id is outside the allowlist. */ resolve(request: PresetSelectionRequest): string | undefined { const id = request.agent_preset if (id === undefined) return this.config.agentPreset - if (this.choices === undefined) throw new Error('agent_preset selection is disabled for this tool instance') + if (this.choices === undefined) { + throw new SubagentError('agent_preset selection is disabled for this tool instance', 'PRESET_SELECTION_DISABLED') + } if (typeof id !== 'string' || !this.choices.includes(id)) { - throw new Error(`agent_preset must be one of: ${this.choices.join(', ')}`) + throw new SubagentError(`agent_preset must be one of: ${this.choices.join(', ')}`, 'PRESET_NOT_ALLOWED') } return id } diff --git a/packages/subagent/tool-subagent/tests/list-models.spec.ts b/packages/subagent/tool-subagent/tests/list-models.spec.ts index 654ab2f1b2..1bb3f053ba 100644 --- a/packages/subagent/tool-subagent/tests/list-models.spec.ts +++ b/packages/subagent/tool-subagent/tests/list-models.spec.ts @@ -177,7 +177,9 @@ describe('list_subagent_models', () => { await mountWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(tool, { provider: 'unused', modelDiscovery: true }) - expect(text(await call(ctx, {}))).toContain('requires a calling agent') + const agentless = await call(ctx, {}) + expect(text(agentless)).toContain('requires a calling agent') + expect(agentless.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) await ctx.fiber.dispose() const parentContext = await setup({ provider: 'mock', withModelSelection: true, hostSelectionEnabled: false }) @@ -188,6 +190,7 @@ describe('list_subagent_models', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('without a parent provider and model') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('reads the recorded Session allowlist through the delegation plugin', async () => { @@ -217,6 +220,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, {}) expect(result.isError).toBe(true) expect(text(result)).toContain('`llm` service is unavailable') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('lists registered providers and follows live registration changes', async () => { @@ -259,6 +263,7 @@ describe('list_subagent_models', () => { const denied = await call(ctx, { provider: 'alpha', model: 'plain' }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('rejects an unauthorized provider before calling its adapter catalog', async () => { @@ -271,6 +276,7 @@ describe('list_subagent_models', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('provider "secret" is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) expect(listModels).not.toHaveBeenCalled() }) @@ -376,14 +382,15 @@ describe('list_subagent_models', () => { }) it.each([ - { args: { model: 'fast' }, expected: '`model` requires `provider`' }, - { args: { provider: '' }, expected: '`provider` must be non-empty' }, - { args: { provider: 'missing' }, expected: 'is not allowed for this Session' }, - ])('rejects incomplete or unavailable provider requests', async ({ args, expected }) => { + { args: { model: 'fast' }, expected: '`model` requires `provider`', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: '' }, expected: '`provider` must be non-empty', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: 'missing' }, expected: 'is not allowed for this Session', info: { name: 'SubagentError', code: 'UNAUTHORIZED' } }, + ])('rejects incomplete or unavailable provider requests', async ({ args, expected, info }) => { const ctx = await setupListTool() const result = await call(ctx, args) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual(info) }) it('rejects an empty exact model after resolving the provider', async () => { @@ -392,6 +399,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'alpha', model: '' }) expect(result.isError).toBe(true) expect(text(result)).toContain('`model` must be non-empty') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('reports registered alternatives for an unavailable provider', async () => { @@ -403,6 +411,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: alpha') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) expect(text(result)).not.toContain('secret') }) @@ -411,5 +420,6 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: (none)') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) }) }) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index 5d26f6eb67..599fde1e79 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -285,6 +285,7 @@ describe('SubagentModelSelectionConfig', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) await ctx.fiber.dispose() }) diff --git a/packages/subagent/tool-subagent/tests/model-selection.spec.ts b/packages/subagent/tool-subagent/tests/model-selection.spec.ts index 014acf6d5b..9d8253ca80 100644 --- a/packages/subagent/tool-subagent/tests/model-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection.spec.ts @@ -119,6 +119,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) }) it('hides and rejects route fields without modelSelection', async () => { @@ -136,6 +137,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'forced route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('child model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } }) @@ -173,6 +175,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(start).not.toHaveBeenCalled() }) @@ -199,6 +202,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('discovers only the parent route without a Session policy and permits its explicit route and effort', async () => { @@ -403,12 +407,17 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects preflight without an effective provider and model', async () => { const ctx = await setup({ provider: 'mock' }) await expect(preflightChildLlmRoute(ctx.llm, {}, undefined, AbortSignal.abort())) - .rejects.toThrow('without an effective provider and model') + .rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: 'cannot select child LLM values without an effective provider and model', + }) }) it.each([ @@ -420,6 +429,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'partial route', prompt: 'do it', ...route }) expect(result.isError).toBe(true) expect(text(result)).toContain('`provider` and `model` must be supplied together') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(starts).toBe(0) }) @@ -432,6 +442,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'empty route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('uses the LLM runtime for provider and reasoning-effort validation before child creation', async () => { @@ -524,6 +535,7 @@ describe('dsh-tool-subagent model selection', () => { const configured = await callSubagent(ctx, { description: 'configured effort', prompt: 'do it' }, { agent: parentWithRoute() }) expect(configured.isError).toBe(true) expect(text(configured)).toContain('`llm` service is unavailable') + expect(configured.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) @@ -566,6 +578,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) const invalidEffort = await callSubagent(ctx, { description: 'unsupported effort', prompt: 'do it', provider: 'alpha', model: 'fast-model', reasoning_effort: 'invalid', @@ -599,6 +612,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'fork work', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } expect(started).not.toHaveBeenCalled() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 636c88805e..9bfa7e9e85 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -98,6 +98,7 @@ describe('spawn preset selection', () => { const forced = await callSubagent(ctx, { ...args, agent_preset: 'writer' }) expect(forced.isError).toBe(true) expect(text(forced)).toContain('selection is disabled') + expect(forced.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_SELECTION_DISABLED' }) expect(onStart).toHaveBeenCalledTimes(1) }) @@ -134,8 +135,13 @@ describe('spawn preset selection', () => { it('rejects forced selection at the model JSON resolver', () => { const selection = new SubagentPresetSelection({ allowedAgentPresets: ['writer'] }) - expect(() => selection.resolve({ agent_preset: 'unlisted' })).toThrow(/must be one of/) - expect(() => selection.resolve({ agent_preset: 1 })).toThrow(/must be one of/) + for (const agent_preset of ['unlisted', 1]) { + expect(() => selection.resolve({ agent_preset })).toThrow(expect.objectContaining({ + name: 'SubagentError', + code: 'PRESET_NOT_ALLOWED', + message: 'agent_preset must be one of: writer', + })) + } }) it('requires the preset service when selection is configured', async () => { diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 095d1de42c..6fcf375ad3 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -242,6 +242,7 @@ describe('dsh-tool-subagent', () => { const result = await pending expect(result.isError).toBe(true) expect(text(result)).toContain('changed while resolving the child LLM route') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PROVIDER_CHANGED' }) expect(oldStart).not.toHaveBeenCalled() expect(replacementStart).not.toHaveBeenCalled() }) @@ -342,6 +343,7 @@ describe('dsh-tool-subagent', () => { const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('registers when the provider appears LATER — no load-order requirement (Loader starts siblings concurrently)', async () => { diff --git a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl index 725da9a4cd..a85b1ef583 100644 --- a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl +++ b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_one_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"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_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"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":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl index a8dbd992e8..dfa91ecadc 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -15,7 +15,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_three_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[15],"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":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 5062e09793..9f3180e9f2 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Correction: submit answer 42 instead."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"SubagentError","code":"STRUCTURED_OUTPUT_PENDING_INPUT"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} From fdd2dcc7e87eb3a0da7c83f7144b8b740dd30d60 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:14 +0800 Subject: [PATCH 016/396] feat(plan-mode): add PlanModeError for exit_plan_mode failures exit_plan_mode threw plain Errors, so its most common failure, the user choosing to keep planning, reached tool/result without an error.code. PlanModeError carries PLAN_NOT_ACTIVE, PLAN_REVIEW_INTERRUPTED, and PLAN_REVISION_REQUESTED. A plan without a leading heading is a ToolArgsError, and a missing caller, user-questions channel, or projection reader is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/plan.i18n.yaml | 4 +- docs/subsystems/plan.md | 2 +- docs/subsystems/plan.zh.md | 2 +- packages/plan/plan-mode/README.i18n.yaml | 12 +++--- packages/plan/plan-mode/README.md | 5 ++- packages/plan/plan-mode/README.zh.md | 5 ++- packages/plan/plan-mode/src/error.ts | 38 +++++++++++++++++++ packages/plan/plan-mode/src/index.ts | 28 +++++++++----- .../plan/plan-mode/tests/plan-mode.spec.ts | 23 +++++++++-- snapshots/sdk/plan-review/session.v4.jsonl | 2 +- 10 files changed, 94 insertions(+), 27 deletions(-) create mode 100644 packages/plan/plan-mode/src/error.ts diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index 5e92dac5a5..f172403181 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -15,8 +15,8 @@ en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: 32ecfb7086dd1578 - zh: 0aaeaa69bb63f255 + en: c9e86f6312dab80f + zh: 41b763216d6b1a54 /plan-mode/the-service: en: f3e6d5a7fe0b67f0 zh: 774cc97e493991fa diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index a37207d868..05dbdc50a9 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -30,7 +30,7 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`. In plan mode it requires a complete markdown plan starting with a `#` heading, rejecting any other plan with `ToolArgsError`, and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call with `PlanModeError` `PLAN_REVISION_REQUESTED` carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel (`ToolContextUnavailableError`) and a service reload during review (`PLAN_REVIEW_INTERRUPTED`) also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index 8f45d70c5b..de51ac0569 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -30,7 +30,7 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,其他计划以 `ToolArgsError` 拒绝,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次以 `PlanModeError` `PLAN_REVISION_REQUESTED` 失败并携带用户反馈的调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。交互通道缺失(`ToolContextUnavailableError`)或评审期间服务重载(`PLAN_REVIEW_INTERRUPTED`)同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 96b7f724c7..31f4436eec 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -45,14 +45,14 @@ en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: 7736aea9e4934fa8 - zh: a595e477f54a199e + en: d14383e9c8c404dc + zh: 056ec01db0f9d63e /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 396d66816890f715 zh: fab5d67c027b33f5 /deepseek-ai-dsh-plan-mode/understand-the-implementation/source-map: - en: fa97e858495a8105 - zh: 8be1fbd7e420ff8a + en: 5c25e9fd2b7104b8 + zh: 00af162e5a9d080a /deepseek-ai-dsh-plan-mode/further-exploration: en: 5008d6d632002f49 zh: 65184d489ecdcec0 @@ -90,8 +90,8 @@ en: 9622e96bdc01276d zh: 53801e68a49f3d1d /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/what-the-model-sees: - en: 1b978a7b6eecdffe - zh: 338000d1bf8dd4a9 + en: 7f132783f06161cf + zh: 571852401060940f /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/token-effect: en: 5ef9db72f91e4a8c zh: 6e96335cc3eb5976 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 0ea3a4b33c..38971a5c94 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`, and a plan without a leading `#` heading fails with `ToolArgsError` before review. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel (`ToolContextUnavailableError`), or after a service reload while the review is pending (`PLAN_REVIEW_INTERRUPTED`), the call fails closed and `/plan off` remains the manual escape. [`src/error.ts`](src/error.ts) lists the `PlanModeError` codes. ### Session projection unit @@ -104,6 +104,7 @@ The unit turns logged `/plan` command runs into a candidate target, commits the |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, the `ctx.planMode` service, `plan:policy` section, `/plan` command, `exit_plan_mode` tool | | [`src/types.ts`](src/types.ts) | The `plan` projection-key declaration and `PlanProjection` wire value | +| [`src/error.ts`](src/error.ts) | `PlanModeError` and its closed code list | | [`src/client.ts`](src/client.ts) | Client-namespace re-export of the types outlet | The review intent carries the originating tool-call id, so the Web client can reopen the same submitted plan after the review closes. The complete Markdown remains in the existing native call or PTC dispatch log. @@ -166,7 +167,7 @@ The user block is append-only conversation growth. Entering or leaving plan mode #### What the model sees -The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. +The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call with `PLAN_REVISION_REQUESTED` carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. #### Token effect diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 90ee3c97e5..76d43e43ec 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用会失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 +`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败,没有前导 `#` 标题的计划在评审前以 `ToolArgsError` 失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道(`ToolContextUnavailableError`),或评审等待期间服务重载(`PLAN_REVIEW_INTERRUPTED`),调用都会以拒绝方式失败,`/plan off` 仍是手动退路。[`src/error.ts`](src/error.ts) 列出 `PlanModeError` 的 code。 ### 会话投影单元 @@ -104,6 +104,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、`ctx.planMode` 服务、`plan:policy` 段落、`/plan` 命令、`exit_plan_mode` 工具 | | [`src/types.ts`](src/types.ts) | `plan` 投影 key 声明与 `PlanProjection` 协议值 | +| [`src/error.ts`](src/error.ts) | `PlanModeError` 及其封闭 code 列表 | | [`src/client.ts`](src/client.ts) | types 出口的客户端命名空间再导出 | 审批意图携带发起工具调用的标识,让 Web 客户端在审批关闭后重新打开同一份计划。完整 Markdown 保留在已有的原生调用或 PTC dispatch 日志中。 @@ -166,7 +167,7 @@ You are in plan mode. Explore and design before presenting the complete plan thr #### 模型看到什么 -[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 +[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是以 `PLAN_REVISION_REQUESTED` 失败并携带评审反馈的调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 #### Token 影响 diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts new file mode 100644 index 0000000000..e0227893bb --- /dev/null +++ b/packages/plan/plan-mode/src/error.ts @@ -0,0 +1,38 @@ +/** + * Typed `exit_plan_mode` failures. + * + * @module @deepseek-ai/dsh-plan-mode/error + */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every machine-routable plan-mode failure: + * - `PLAN_NOT_ACTIVE`: the caller's committed state is not plan mode; work without the exit tool. + * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. + * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. + */ +export const PLAN_MODE_ERROR_CODES = [ + 'PLAN_NOT_ACTIVE', + 'PLAN_REVIEW_INTERRUPTED', + 'PLAN_REVISION_REQUESTED', +] as const + +/** One plan-mode failure code. */ +export type PlanModeErrorCode = typeof PLAN_MODE_ERROR_CODES[number] + +/** Typed plan-mode failure; `code` is one of {@link PLAN_MODE_ERROR_CODES}. */ +export class PlanModeError extends HarnessError { + override readonly code: PlanModeErrorCode + + /** + * @param message - model-facing reason and next step. + * @param code - failure class from {@link PLAN_MODE_ERROR_CODES}. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: PlanModeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'PlanModeError' + this.code = code + } +} diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 06af5c2828..636165c5e3 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -30,18 +30,20 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import { UserQuestionError, type AskUserQuestionAnswer } from '@deepseek-ai/dsh-user-questions' import type { CommandDefinitionId, CommandId } from '@deepseek-ai/dsh-commands' import type {} from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { PlanProjection, PlanUnitState } from './types.ts' +import { PlanModeError } from './error.ts' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { 'plan-mode': { kind: 'plan-mode' } & ContextFormed } } export type * from './types.ts' +export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { @@ -301,15 +303,20 @@ export class PlanModeController extends Service { execute: async (args, exec) => { const agent = exec.agent // Admission outlives plan mode and follows the selected state, so check the committed state. - if (agent === undefined || !this.loggedActive(agent.session)) { - throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) + if (agent === undefined) { + throw new ToolContextUnavailableError(`${EXIT_PLAN_MODE} requires a calling agent`) + } + if (!this.loggedActive(agent.session)) { + throw new PlanModeError(`${EXIT_PLAN_MODE} is only available in plan mode`, 'PLAN_NOT_ACTIVE') } if (!/^#\s+\S/.test(args.plan.trim())) { - throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`) + throw new ToolArgsError([`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`]) } const interaction = ctx.get('userQuestions') if (interaction === undefined) { - throw new Error('no user-questions channel is available to review the plan; ask the user to switch the session mode instead') + throw new ToolContextUnavailableError( + 'no user-questions channel is available to review the plan; ask the user to switch the session mode instead', + ) } let answer: AskUserQuestionAnswer try { @@ -345,15 +352,18 @@ export class PlanModeController extends Service { // A review may outlive this plugin fiber. Without its pre-step listener, // an approved selection could never be appended, so fail and keep planning. if (disposed) { - throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again') + throw new PlanModeError( + 'the plan-mode service was reloaded while the plan was under review; present the plan again', + 'PLAN_REVIEW_INTERRUPTED', + ) } const reviewItems = answer.answers.filter(entry => entry.id === REVIEW_ID) const item = reviewItems.length === 1 ? reviewItems[0] : undefined if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) { const feedback = item?.custom ?? '' - throw new Error(feedback === '' + throw new PlanModeError(feedback === '' ? 'The user chose to keep planning; revise the plan and present it again.' - : `The user chose to keep planning; their feedback: ${feedback}`) + : `The user chose to keep planning; their feedback: ${feedback}`, 'PLAN_REVISION_REQUESTED') } // Keep plan guidance for the rest of this assistant tool batch. The // silent selection is appended at the next accepted in-turn pre-step, @@ -394,7 +404,7 @@ export class PlanModeController extends Service { private planState(session: Session): PlanUnitState { if (this.planProjectionHandle === undefined) { - throw new Error('plan mode is not ready; await plugin activation before running an agent') + throw new ToolContextUnavailableError('plan mode is not ready; await plugin activation before running an agent') } return this.planProjectionHandle.stateOf(session) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 99d72afd1d..0ebe17cb31 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -844,7 +844,11 @@ describe('exit_plan_mode', () => { arguments: { plan: '# P' }, token: Symbol('direct-exit') as ToolExecutionToken, signal: testToolSignal, deferContext() {}, concludeTurn() {}, } - await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toThrow(`${EXIT_PLAN_MODE} is only available in plan mode`) + await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: `${EXIT_PLAN_MODE} requires a calling agent`, + }) }) it('keeps the exit tool after leaving plan mode and rejects a call outside it', async () => { @@ -855,6 +859,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('admits the exit tool for a selected entry but rejects a call before the entry is logged', async () => { @@ -866,6 +871,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('rejects an empty or heading-less plan before asking the reviewer', async () => { @@ -873,7 +879,8 @@ describe('exit_plan_mode', () => { for (const plan of ['', 'do things']) { const result = await callExit(ctx, agent, plan) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) } expect(asked).toHaveLength(0) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) @@ -885,6 +892,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: no user-questions channel is available to review the plan; ask the user to switch the session mode instead' }]) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1022,6 +1030,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: consider the resume path' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1030,6 +1039,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('a custom-text-only answer is feedback, never consent', async () => { @@ -1037,6 +1047,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: add tests first' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1045,6 +1056,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1053,6 +1065,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: change the tests' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1067,6 +1080,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1076,6 +1090,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('declares the plan-review presentation intent naming its approve option', async () => { @@ -1153,6 +1168,7 @@ describe('exit_plan_mode', () => { const result = await pending expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: the plan-mode service was reloaded while the plan was under review; present the plan again' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVIEW_INTERRUPTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1161,7 +1177,8 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) diff --git a/snapshots/sdk/plan-review/session.v4.jsonl b/snapshots/sdk/plan-review/session.v4.jsonl index 5911c994ea..5113b1bcc2 100644 --- a/snapshots/sdk/plan-review/session.v4.jsonl +++ b/snapshots/sdk/plan-review/session.v4.jsonl @@ -34,7 +34,7 @@ {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":31}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:11}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"},"error":{"name":"PlanModeError","code":"PLAN_REVISION_REQUESTED"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":37}} From 551e5ce51a88b92c400f54bcd1e7c243f26045fc Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:15 +0800 Subject: [PATCH 017/396] feat(workflow): code workflow runs that end cancelled or failed The workflow tool threw a plain Error when a foreground run settled as cancelled or error, the most frequent uncoded workflow failure. It now throws WorkflowError CANCELLED or the new RUN_FAILED code, and rethrows the caller's abort reason when the calling step was aborted so the registry records AbortError ABORTED. A disabled run_in_background is UNSUPPORTED_OPTION, and a missing caller or jobs service is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/workflow.i18n.yaml | 4 +-- docs/subsystems/workflow.md | 2 +- docs/subsystems/workflow.zh.md | 2 +- .../workflow/tool-workflow/README.i18n.yaml | 12 ++++----- packages/workflow/tool-workflow/README.md | 6 ++--- packages/workflow/tool-workflow/README.zh.md | 6 ++--- packages/workflow/tool-workflow/src/index.ts | 27 ++++++++++--------- .../tool-workflow/tests/tool-workflow.spec.ts | 10 +++++-- packages/workflow/workflow/README.i18n.yaml | 4 +-- packages/workflow/workflow/README.md | 2 +- packages/workflow/workflow/README.zh.md | 2 +- packages/workflow/workflow/src/index.ts | 7 +++-- 12 files changed, 48 insertions(+), 36 deletions(-) diff --git a/docs/subsystems/workflow.i18n.yaml b/docs/subsystems/workflow.i18n.yaml index f3b906de0d..fdd069e032 100644 --- a/docs/subsystems/workflow.i18n.yaml +++ b/docs/subsystems/workflow.i18n.yaml @@ -18,8 +18,8 @@ en: a86b204323005042 zh: 82b691e28ed4dcd3 /workflow/failure-discipline-workflowerror-fatal: - en: 4d390801bb07374c - zh: 1099f053c2ee26ec + en: b53ef6f97fb9c092 + zh: 5a34538bff77e364 /workflow/events: en: de123821a128c1d1 zh: e50bcaea2812575a diff --git a/docs/subsystems/workflow.md b/docs/subsystems/workflow.md index 5b51dc1ff1..7b84c7f33b 100644 --- a/docs/subsystems/workflow.md +++ b/docs/subsystems/workflow.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## Failure discipline: `WorkflowError.fatal` -Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. +Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. Because `WorkflowResult` carries only the failure message, the `workflow` tool classifies a run that settled as `cancelled` with `CANCELLED` and one that settled as `error` with `RUN_FAILED`; when the calling step itself was aborted, the tool runtime's `AbortError` `ABORTED` result applies instead. ## Events diff --git a/docs/subsystems/workflow.zh.md b/docs/subsystems/workflow.zh.md index 1514fa31d6..56e3a0ff22 100644 --- a/docs/subsystems/workflow.zh.md +++ b/docs/subsystems/workflow.zh.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## 失败纪律:`WorkflowError.fatal` -脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。 +脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。由于 `WorkflowResult` 只携带失败消息,`workflow` 工具把以 `cancelled` 结束的运行归类为 `CANCELLED`,把以 `error` 结束的运行归类为 `RUN_FAILED`;调用方步骤本身被中止时,改为使用工具运行时的 `AbortError` `ABORTED` 结果。 ## 事件 diff --git a/packages/workflow/tool-workflow/README.i18n.yaml b/packages/workflow/tool-workflow/README.i18n.yaml index 8f307582b3..0fd0d3a6ed 100644 --- a/packages/workflow/tool-workflow/README.i18n.yaml +++ b/packages/workflow/tool-workflow/README.i18n.yaml @@ -18,8 +18,8 @@ en: a0a9d655187f285d zh: 230b4556fff9f08b /deepseek-ai-dsh-tool-workflow/use-this-package/calling-the-tool: - en: aeebba9469f0558d - zh: e2e74d4272e94201 + en: 8b9606845ce5caf1 + zh: af0b71be80e1bb7c /deepseek-ai-dsh-tool-workflow/use-this-package/what-to-expect-during-a-run: en: 19ec4f830edb8e1a zh: 8579ae5274aca6de @@ -36,8 +36,8 @@ en: 6d09119d1393c254 zh: a7cc03daa59650ec /deepseek-ai-dsh-tool-workflow/understand-the-implementation/run-lifecycle: - en: 8ea9ce564251249a - zh: a59b88cc14a25a1f + en: ef2c2a573b30c262 + zh: 5a078b9fe31e333d /deepseek-ai-dsh-tool-workflow/understand-the-implementation/background-lifecycle: en: 35950b2015800ec5 zh: 5ae6f5a5e53dc585 @@ -87,8 +87,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/what-the-model-sees: - en: acd5e87161ced588 - zh: 5ffe85926ee1b88d + en: 483515bf4c1dc710 + zh: 69b23bd7f331ddea /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/token-effect: en: 88cfc89c7dc19dbb zh: 75e674844f311937 diff --git a/packages/workflow/tool-workflow/README.md b/packages/workflow/tool-workflow/README.md index 5cdadb9ab5..7dc859d1f2 100644 --- a/packages/workflow/tool-workflow/README.md +++ b/packages/workflow/tool-workflow/README.md @@ -31,7 +31,7 @@ The `workflow` tool runs a model-authored orchestration script that fans work ou The model submits three parameters plus one flag: `meta` (required identity data: `name`, `description`, and optional `whenToUse` and `phases`), `script` (required plain JavaScript body — no `export const meta` statement; its parameter description carries the body rules and the tool description carries the hook contract), `args` (optional JSON object exposed to the script as the `args` global; wrap a bare list in a field so the wire schema stays honest), and `run_in_background` (optional; present only while `enableRunInBackground` holds). -A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancellation and execution failures return `Error: workflow run was cancelled` or `Error: workflow run failed: `; partial output is never reported as success. +A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancelling the calling step returns the tool runtime's `AbortError` `ABORTED` result; any other cancellation and execution failures return `Error: workflow run was cancelled` (`WorkflowError` `CANCELLED`) or `Error: workflow run failed: ` (`WorkflowError` `RUN_FAILED`); partial output is never reported as success. ### What to expect during a run @@ -67,7 +67,7 @@ The consumer owns the model-facing schema, the `tool:` system-prompt g ### Run lifecycle -`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. +`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason, rethrowing the caller's abort reason when `exec.signal` aborted and otherwise throwing a `WorkflowError`; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. ### Background lifecycle @@ -150,7 +150,7 @@ Prefix-stable while `toolName`, definition, and visibility are unchanged. Renami #### What the model sees -The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)`. Intermediate child messages are omitted. +The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures after a caller abort render the abort reason; other failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)` (`ToolContextUnavailableError`). Intermediate child messages are omitted. #### Token effect diff --git a/packages/workflow/tool-workflow/README.zh.md b/packages/workflow/tool-workflow/README.zh.md index dcc92b352c..5b9ebe44c1 100644 --- a/packages/workflow/tool-workflow/README.zh.md +++ b/packages/workflow/tool-workflow/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 模型提交三个参数外加一个开关:`meta`(必需的身份数据:`name`、`description`,以及可选的 `whenToUse` 与 `phases`)、`script`(必需的纯 JavaScript 脚本体——不含 `export const meta` 语句;其参数描述携带脚本体规则,工具描述携带钩子约定)、`args`(可选 JSON 对象,作为全局变量 `args` 向脚本公开;裸列表应包装到字段中,使协议 schema 如实表达形态),以及 `run_in_background`(可选;仅在 `enableRunInBackground` 生效时存在)。 -前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消与执行失败返回 `Error: workflow run was cancelled` 或 `Error: workflow run failed: `;部分输出绝不会被报告为成功。 +前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消调用方步骤时返回工具运行时的 `AbortError` `ABORTED` 结果;其他取消与执行失败返回 `Error: workflow run was cancelled`(`WorkflowError` `CANCELLED`)或 `Error: workflow run failed: `(`WorkflowError` `RUN_FAILED`);部分输出绝不会被报告为成功。 ### 运行期间的预期 @@ -67,7 +67,7 @@ kind: "package-reference" ### 运行生命周期 -`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 +`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果:`exec.signal` 已中止时重新抛出调用方的中止原因,否则抛出 `WorkflowError`;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 ### 后台生命周期 @@ -150,7 +150,7 @@ Use the tool ONLY when the user explicitly asks for a workflow or for #### 模型看到什么 -由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`。中间子 agent 消息会被省略。 +由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。调用方中止后的失败渲染中止原因;其他失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`(`ToolContextUnavailableError`)。中间子 agent 消息会被省略。 #### Token 影响 diff --git a/packages/workflow/tool-workflow/src/index.ts b/packages/workflow/tool-workflow/src/index.ts index 66fda2da15..c8e3135c1c 100644 --- a/packages/workflow/tool-workflow/src/index.ts +++ b/packages/workflow/tool-workflow/src/index.ts @@ -14,13 +14,14 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JobId, JobOutcome, JobToolCall } from '@deepseek-ai/dsh-jobs' import type { Session, SessionEventMap } from '@deepseek-ai/dsh-session' import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { WorkflowError } from '@deepseek-ai/dsh-workflow' import type { WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason, } from '@deepseek-ai/dsh-workflow' @@ -194,17 +195,17 @@ function presentWorkflowResult(args: WorkflowCallArgs, result: { content: Conten } /** A non-`completed` stop reason means the script did not finish cleanly. */ -function stopReasonError(result: WorkflowResult): string | undefined { +function stopReasonError(result: WorkflowResult): WorkflowError | undefined { switch (result.stopReason) { case 'completed': return undefined case 'cancelled': - return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}` + return new WorkflowError(`workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`, 'CANCELLED') case 'error': - return `workflow run failed: ${result.error ?? 'unknown error'}` + return new WorkflowError(`workflow run failed: ${result.error ?? 'unknown error'}`, 'RUN_FAILED') /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */ default: - return `workflow run ended abnormally (${String(result.stopReason satisfies never)})` + return new WorkflowError(`workflow run ended abnormally (${String(result.stopReason satisfies never)})`, 'RUN_FAILED') /* v8 ignore stop */ } } @@ -270,7 +271,7 @@ function startBackgroundRun( ): { kind: 'background'; jobId: JobId; runId: WorkflowRunId } { const jobs = ctx.get('jobs') if (jobs === undefined) { - throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + throw new ToolContextUnavailableError('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') } let run!: WorkflowRun const jobId = jobs.start({ @@ -412,11 +413,11 @@ export function apply(ctx: Context, config: Config): void { // The loop sets `exec.agent` for every model-driven call; its absence // means a non-agent caller invoked the tool directly, which has no // parent to attribute the children to. Fail loud rather than guess. - throw new Error('workflow tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('workflow tool requires a calling agent (exec.agent was undefined)') } if (args.run_in_background === true) { if (!enableRunInBackground) { - throw new Error('run_in_background is disabled for this tool') + throw new WorkflowError('run_in_background is disabled for this tool', 'UNSUPPORTED_OPTION') } // No pre-abort check here, unlike bash/pwsh: ToolRuntime re-reads the // caller signal right before execute(), and this branch reaches @@ -455,9 +456,11 @@ export function apply(ctx: Context, config: Config): void { result = await run.result const error = stopReasonError(result) if (error !== undefined) { - // Map a non-clean finish to an isError result (the registry turns a - // throw into an isError). Report the reason, not partial output. - throw new Error(error) + // Caller cancellation keeps the registry's AbortError identity; any + // other non-clean finish becomes a coded isError result. Report the + // reason, not partial output. + exec.signal.throwIfAborted() + throw error } return { kind: 'foreground' as const, @@ -473,7 +476,7 @@ export function apply(ctx: Context, config: Config): void { await run.dispose() if (recordsRun) { /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */ - if (result === undefined) throw new Error('workflow run settled without a result') + if (result === undefined) throw new WorkflowError('workflow run settled without a result', 'RUN_FAILED') recorder.finish(run.id, result.stopReason) } } finally { diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index 1502b428cd..98ea14d105 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' +import ToolRuntime, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow' @@ -303,6 +303,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'RUN_FAILED' }) expect(engine.disposed).toBe(1) }) @@ -314,6 +315,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'CANCELLED' }) const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests.length).toBe(2) }) @@ -337,6 +339,7 @@ describe('dsh-tool-workflow', () => { controller.abort() const result = await pending expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) expect(engine.cancels).toContain('parent step aborted') expect(engine.disposed).toBe(1) }) @@ -354,6 +357,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(engine.requests.length).toBe(0) }) @@ -614,6 +618,7 @@ describe('dsh-tool-workflow', () => { expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text) .toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('a disabled composition hides the parameter and rejects the call', async () => { @@ -624,6 +629,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META, run_in_background: true }, { agent: parent }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('run_in_background is disabled') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'UNSUPPORTED_OPTION' }) }) it('advertises the background semantics in the parameter', async () => { @@ -665,7 +671,7 @@ describe('dsh-tool-workflow', () => { controller.abort('user abort') const result = await pending expect(result.isError).toBe(true) - expect((result.content[0] as { text: string }).text).toContain('cancelled') + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) }) it('a background run over the sandboxed PTC engine settles its job with the rendered return value', async () => { diff --git a/packages/workflow/workflow/README.i18n.yaml b/packages/workflow/workflow/README.i18n.yaml index dbd14da4fe..5760add38c 100644 --- a/packages/workflow/workflow/README.i18n.yaml +++ b/packages/workflow/workflow/README.i18n.yaml @@ -42,8 +42,8 @@ en: 95b074d816b52323 zh: dfa070a1531651f9 /deepseek-ai-dsh-workflow/understand-the-implementation/failure-discipline: - en: e2c2a6e2876457e8 - zh: 764cba9eede4bb79 + en: 8b862e7714718ba4 + zh: 21a04481ea85ff52 /deepseek-ai-dsh-workflow/further-exploration: en: 6b3752bee67372c3 zh: 92492c01c4d786d3 diff --git a/packages/workflow/workflow/README.md b/packages/workflow/workflow/README.md index 0bf762913f..0c3c5650f1 100644 --- a/packages/workflow/workflow/README.md +++ b/packages/workflow/workflow/README.md @@ -86,7 +86,7 @@ A run is holder-owned: engine-plugin unload prevents new starts but does not rev ### Failure discipline -`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, and cancellation; the exact set and meanings live in [`src/index.ts`](src/index.ts). +`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, cancellation, and a consumer's classification of a run that settled with `stopReason: 'error'` (`RUN_FAILED`); the exact set and meanings live in [`src/index.ts`](src/index.ts). The per-item `null` is reserved for child-run failures and ordinary in-stage script errors, so a child that resolves normally with a non-completed stop reason is not an infrastructure exception: `agent()` returns `null`, letting the script handle an ordinary child failure. diff --git a/packages/workflow/workflow/README.zh.md b/packages/workflow/workflow/README.zh.md index 31c728a4f0..e6f1129263 100644 --- a/packages/workflow/workflow/README.zh.md +++ b/packages/workflow/workflow/README.zh.md @@ -86,7 +86,7 @@ return { reviewed: reviews.length } ### 失败纪律 -`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值与取消;完整集合与含义见 [`src/index.ts`](src/index.ts)。 +`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值、取消,以及消费方对以 `stopReason: 'error'` 结束的运行所作的分类(`RUN_FAILED`);完整集合与含义见 [`src/index.ts`](src/index.ts)。 逐项 `null` 只保留给子运行失败与阶段内普通脚本错误,因此以非完成结束原因正常结算的子 agent 不属于基础设施异常:`agent()` 返回 `null`,让脚本处理普通子 agent 失败。 diff --git a/packages/workflow/workflow/src/index.ts b/packages/workflow/workflow/src/index.ts index b78a972977..3d16d576be 100644 --- a/packages/workflow/workflow/src/index.ts +++ b/packages/workflow/workflow/src/index.ts @@ -102,8 +102,10 @@ export type WorkflowEventName = /** * Machine-routable fatal workflow failures: parse/meta/argument/schema errors, * resource caps, subagent infrastructure failures, unserializable boundary - * values, and cancellation. An ordinary child failure resolves its item to - * `null` and is not one of these fatal codes. + * values, and cancellation. `RUN_FAILED` is the consumer's classification of a + * run that settled with `stopReason: 'error'`, whose {@link WorkflowResult} + * carries only the failure message. An ordinary child failure resolves its item + * to `null` and is not one of these fatal codes. */ export type WorkflowErrorCode = | 'SCRIPT_PARSE' @@ -117,6 +119,7 @@ export type WorkflowErrorCode = | 'AGENT_RESULT' | 'RESULT_UNSERIALIZABLE' | 'CANCELLED' + | 'RUN_FAILED' /** * Typed error for workflow-seam failures. Extends {@link HarnessError}, so the From 5fe691f6e50c554a2db88a5af03bfc5998f00042 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:16 +0800 Subject: [PATCH 018/396] feat(team,goal,todo): code projection and argument failures A failed Team or goal projection now rejects with TeamError TEAM_STATE_CORRUPT or GoalError GOAL_STATE_CORRUPT, and GoalError assigns its name literally. team_task_list cursor, limit, and filter violations and todo_write content checks throw ToolArgsError; missing callers throw ToolContextUnavailableError. todo_write violation messages now name the offending item path. Refs #7869 --- packages/goal/goal/README.i18n.yaml | 4 ++-- packages/goal/goal/README.md | 2 +- packages/goal/goal/README.zh.md | 2 +- packages/goal/goal/src/domain.ts | 1 + packages/goal/goal/src/index.ts | 2 +- packages/goal/goal/src/runtime.ts | 3 +-- packages/goal/goal/tests/projection.spec.ts | 3 ++- packages/team/agent-team/README.i18n.yaml | 4 ++-- packages/team/agent-team/README.md | 2 +- packages/team/agent-team/README.zh.md | 2 +- packages/team/agent-team/src/journal.ts | 4 ++-- packages/team/agent-team/tests/team.spec.ts | 5 +++-- packages/team/tool-agent-team/src/index.ts | 10 +++++----- .../team/tool-agent-team/tests/tool-team.spec.ts | 6 +++--- packages/todo/tool-todo/README.i18n.yaml | 4 ++-- packages/todo/tool-todo/README.md | 2 +- packages/todo/tool-todo/README.zh.md | 2 +- packages/todo/tool-todo/src/index.ts | 12 ++++++------ .../todo/tool-todo/tests/loader-composition.spec.ts | 1 + packages/todo/tool-todo/tests/tool-todo.spec.ts | 3 +++ 20 files changed, 40 insertions(+), 34 deletions(-) diff --git a/packages/goal/goal/README.i18n.yaml b/packages/goal/goal/README.i18n.yaml index 4aa0d5c88d..8a267e47bb 100644 --- a/packages/goal/goal/README.i18n.yaml +++ b/packages/goal/goal/README.i18n.yaml @@ -39,8 +39,8 @@ en: 592af7e68423bd1c zh: 9b1f08393db1b14e /deepseek-ai-dsh-goal/understand-the-implementation/design: - en: 6f19e891ffc79754 - zh: 9599e3b142f1e6b5 + en: c14410306499e607 + zh: 99d1d91259127aba /deepseek-ai-dsh-goal/understand-the-implementation/source-map: en: aef62dff93f32796 zh: dba79da0466218a7 diff --git a/packages/goal/goal/README.md b/packages/goal/goal/README.md index 9e0a1ee60d..f7dea16728 100644 --- a/packages/goal/goal/README.md +++ b/packages/goal/goal/README.md @@ -98,7 +98,7 @@ This section explains how the service realizes the behavior above; the observabl - **Compare-and-set mutations.** `ctx.goals` accepts only the exact live `Agent` registered under its id. `get()` returns a detached `GoalView`; mutations take a `GoalRef { id, revision }` and reject stale refs. Creation resolves the deployment default internally before committing. - **Activation is process-local.** `armed` and `disarmed` live in a per-session cache and are never persisted. A fresh cache and every `agent/created` edge disarm continuation even when replay finds an active durable phase; `disarm()` removes authority without writing a revision or emitting a mutation. - **Strict replay.** The fold derives lifecycle mutations only from `goal/change` and rejects malformed shapes, discontinuous revisions, illegal phase transitions, non-monotonic per-goal timestamps, and non-sequential admitted rounds. Positive rounds advance only on admitted goal-sourced `user/message` events, and mutation timestamps clamp against the preceding update when wall time moves backward. -- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure. +- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure with `GoalError` `GOAL_STATE_CORRUPT`. ### Source map diff --git a/packages/goal/goal/README.zh.md b/packages/goal/goal/README.zh.md index ac8fd3837b..515c2e85e9 100644 --- a/packages/goal/goal/README.zh.md +++ b/packages/goal/goal/README.zh.md @@ -98,7 +98,7 @@ view.activation // 'armed' | 'disarmed' — not persisted - **比较并设置的变更。** `ctx.goals` 只接受以对应 id 注册的完全相同的活跃 `Agent` 实例。`get()` 返回脱离状态的 `GoalView`;变更携带 `GoalRef { id, revision }` 并拒绝陈旧引用。创建在提交前于内部解析部署默认值。 - **续行启用状态是进程本地的。** `armed` 与 `disarmed` 保存在每会话缓存中,绝不持久化。新缓存与每次 `agent/created` 边界都会停用续行,即使回放发现持久 phase 为 active;`disarm()` 移除续行权限,不写入 revision 也不发出变更事件。 - **严格回放。** 折叠只从 `goal/change` 派生生命周期变更,并拒绝形状错误、不连续 revision、非法 phase 转换、每目标时间戳非单调,以及不连续的已准入 Round。只有已准入的来源为 goal 的 `user/message` 事件会推进正数 Round;挂钟时间倒退时,变更时间戳会限制在不早于上一次更新的值。 -- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会拒绝访问。 +- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会以 `GoalError` `GOAL_STATE_CORRUPT` 拒绝访问。 ### 源码地图 diff --git a/packages/goal/goal/src/domain.ts b/packages/goal/goal/src/domain.ts index 63f1573dc7..68cba67262 100644 --- a/packages/goal/goal/src/domain.ts +++ b/packages/goal/goal/src/domain.ts @@ -100,6 +100,7 @@ export type GoalErrorCode = | 'GOAL_INVALID_BLOCK_REASON' | 'GOAL_INVALID_EDIT' | 'GOAL_INVALID_TRANSITION' + | 'GOAL_STATE_CORRUPT' declare module '@deepseek-ai/cordis' { interface Events { diff --git a/packages/goal/goal/src/index.ts b/packages/goal/goal/src/index.ts index 3d54ed75d6..a6530bf789 100644 --- a/packages/goal/goal/src/index.ts +++ b/packages/goal/goal/src/index.ts @@ -477,7 +477,7 @@ export class GoalService extends TypertRemoteService { /** Read the current durable projection maintained by the registry. */ private state(session: Session): GoalProjection | null { const state = this.goalProjectionHandle.stateOf(session) - if (state.failure !== null) throw new Error(state.failure) + if (state.failure !== null) throw new GoalError(state.failure, 'GOAL_STATE_CORRUPT') return state.current } diff --git a/packages/goal/goal/src/runtime.ts b/packages/goal/goal/src/runtime.ts index 2f5c40735a..b7b9ad4c6c 100644 --- a/packages/goal/goal/src/runtime.ts +++ b/packages/goal/goal/src/runtime.ts @@ -22,9 +22,8 @@ export class GoalError extends HarnessError { * @param message - human-readable rejection reason. * @param code - stable machine-routable classification. */ - // Keep the constructor to narrow HarnessError's string code at this boundary. - // oxlint-disable-next-line typescript/no-useless-constructor -- type-only narrowing constructor(message: string, code: GoalErrorCode) { super(message, code) + this.name = 'GoalError' } } diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index b2aa38622d..05b72eef6c 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -243,7 +243,8 @@ describe('goal projection unit', () => { await expect(agentEvents(bench.ctx, bench.agent).serial('agent/created', { source: 'resume' })) .resolves.toBeUndefined() - expect(() => bench.ctx.goals.get(bench.agent)).toThrow(failure) + expect(() => bench.ctx.goals.get(bench.agent)) + .toThrow(expect.objectContaining({ name: 'GoalError', code: 'GOAL_STATE_CORRUPT', message: failure })) expect(bench.tailValues().goal).toMatchObject({ goal: { objective: 'poisoned replay' } }) }) diff --git a/packages/team/agent-team/README.i18n.yaml b/packages/team/agent-team/README.i18n.yaml index 2f1733cd95..f8f298dda8 100644 --- a/packages/team/agent-team/README.i18n.yaml +++ b/packages/team/agent-team/README.i18n.yaml @@ -66,8 +66,8 @@ en: a8baf51f2fcd6d49 zh: 357c8db36823fe0e /deepseek-ai-dsh-agent-team/understand-the-implementation/browser-projection: - en: ed33e64ea55d2b75 - zh: eb326025ff156dea + en: 1f8e19f2c73b1cf5 + zh: 1e535d354ad47c08 /deepseek-ai-dsh-agent-team/further-exploration: en: 60d969ec526f5556 zh: ed4f813006f86215 diff --git a/packages/team/agent-team/README.md b/packages/team/agent-team/README.md index a58392c1c3..d5d6c2f507 100644 --- a/packages/team/agent-team/README.md +++ b/packages/team/agent-team/README.md @@ -147,7 +147,7 @@ Unloading the service unregisters the projection. The retained handle remains re ### Browser projection -The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. +The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations with `TeamError` `TEAM_STATE_CORRUPT` without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. The [Web UI](../../client/ui-agent-team/README.md) displays tasks only. Ordinary subagent navigation owns the member list; task owner labels display the owner's full name, or its Session id when the owner has no name. diff --git a/packages/team/agent-team/README.zh.md b/packages/team/agent-team/README.zh.md index 9e57943fa1..204407b12d 100644 --- a/packages/team/agent-team/README.zh.md +++ b/packages/team/agent-team/README.zh.md @@ -147,7 +147,7 @@ Team 在激活前要求 `sessionPersistence` 可用。`Service.init` 等待 `age ### 浏览器投影 -`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 +`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均以 `TeamError` `TEAM_STATE_CORRUPT` 报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 [Web UI](../../client/ui-agent-team/README.zh.md)仅展示任务。普通 subagent 导航负责成员列表;任务所有者标签显示所有者的完整名称,所有者没有名称时显示其 Session id。 diff --git a/packages/team/agent-team/src/journal.ts b/packages/team/agent-team/src/journal.ts index fd7c7fcfad..3e99c3b4d4 100644 --- a/packages/team/agent-team/src/journal.ts +++ b/packages/team/agent-team/src/journal.ts @@ -27,11 +27,11 @@ export class TeamJournal { * Read authoritative Team state for one exact live Lead. * @param root - exact live Team Lead. * @returns current projected state selected by the Lead Team id. - * @throws when the durable Team projection has failed. + * @throws {TeamError} `TEAM_STATE_CORRUPT` when the durable Team projection has failed. */ state(root: Agent): TeamState { const projection = this.teamProjectionHandle.stateOf(root.session) - if (projection.failure !== undefined) throw new Error(projection.failure) + if (projection.failure !== undefined) throw new TeamError(projection.failure, 'TEAM_STATE_CORRUPT') return projection } diff --git a/packages/team/agent-team/tests/team.spec.ts b/packages/team/agent-team/tests/team.spec.ts index f0724a9510..08d7d1e2c3 100644 --- a/packages/team/agent-team/tests/team.spec.ts +++ b/packages/team/agent-team/tests/team.spec.ts @@ -280,10 +280,11 @@ describe('Tree-owned task boards', () => { status: 'pending', blockedBy: [], writeScopes: [], }, }) - expect(() => ctx.agentTeams.listTasks(lead)).toThrow('must begin at revision 1') + const corrupt = { name: 'TeamError', code: 'TEAM_STATE_CORRUPT', message: expect.stringContaining('must begin at revision 1') as string } + expect(() => ctx.agentTeams.listTasks(lead)).toThrow(expect.objectContaining(corrupt)) const eventCount = lead.session.snapshotEvents().length await expect(ctx.agentTeams.createTask(lead, { subject: 'blocked', description: 'blocked' })) - .rejects.toThrow('must begin at revision 1') + .rejects.toMatchObject(corrupt) expect(lead.session.snapshotEvents()).toHaveLength(eventCount) }) diff --git a/packages/team/tool-agent-team/src/index.ts b/packages/team/tool-agent-team/src/index.ts index 353ad1c323..deaa07d572 100644 --- a/packages/team/tool-agent-team/src/index.ts +++ b/packages/team/tool-agent-team/src/index.ts @@ -6,7 +6,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { SubagentError } from '@deepseek-ai/dsh-subagent' import { TeamTaskId } from '@deepseek-ai/dsh-agent-team' import type { TeamTaskView } from '@deepseek-ai/dsh-agent-team' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { InferValue, ValueSchemaSpec } from '@deepseek-ai/dsh-tools' /** Cordis plugin name. */ @@ -82,7 +82,7 @@ type NamedTaskView = Omit & { readonly ow /** Recover the exact caller guaranteed by conditional Team-tool discovery. */ function callingAgent(agent: Agent | undefined, toolName: string): Agent { /* v8 ignore next 2 -- The Team condition rejects callers without an Agent before execution. */ - if (agent === undefined) throw new Error(`${toolName} requires a calling Agent`) + if (agent === undefined) throw new ToolContextUnavailableError(`${toolName} requires a calling Agent`) return agent } @@ -159,10 +159,10 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const cursor = args.cursor ?? 0 const limit = args.limit ?? 50 - if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('cursor must be a non-negative safe integer') - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('limit must be an integer from 1 through 100') + if (!Number.isSafeInteger(cursor) || cursor < 0) throw new ToolArgsError(['cursor must be a non-negative safe integer']) + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new ToolArgsError(['limit must be an integer from 1 through 100']) const caller = callingAgent(exec.agent, 'team_task_list') - if (args.owner !== undefined && args.unowned !== undefined) throw new Error('owner and unowned filters cannot be combined') + if (args.owner !== undefined && args.unowned !== undefined) throw new ToolArgsError(['owner and unowned filters cannot be combined']) const owner = args.owner === undefined ? undefined : await ctx.subagents.resolveName(caller, args.owner, exec.signal) diff --git a/packages/team/tool-agent-team/tests/tool-team.spec.ts b/packages/team/tool-agent-team/tests/tool-team.spec.ts index db51194163..b286befd59 100644 --- a/packages/team/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/team/tool-agent-team/tests/tool-team.spec.ts @@ -529,8 +529,8 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { cursor: 1, })))).not.toHaveProperty('nextCursor') - expect((await execute(ctx, lead, 'team_task_list', { cursor: -1 })).isError).toBe(true) - expect((await execute(ctx, lead, 'team_task_list', { limit: 101 })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { cursor: -1 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) + expect(await execute(ctx, lead, 'team_task_list', { limit: 101 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) const edited = await execute(ctx, lead, 'team_task_update', { task_id: first.id, @@ -588,7 +588,7 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { owner: 'unowned' })))).toMatchObject({ tasks: [{ id: assigned.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: true })))).toMatchObject({ tasks: [{ id: pending.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: false })))).toMatchObject({ tasks: [{ id: assigned.id }] }) - expect((await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) await child.dispose() }) diff --git a/packages/todo/tool-todo/README.i18n.yaml b/packages/todo/tool-todo/README.i18n.yaml index 2899c17810..4121828f2e 100644 --- a/packages/todo/tool-todo/README.i18n.yaml +++ b/packages/todo/tool-todo/README.i18n.yaml @@ -69,8 +69,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/what-the-model-sees: - en: 05644654d1bce8c6 - zh: ea2a42470fbb2ee1 + en: 98dbd1d31d6179af + zh: cd899d7c4ab9f2be /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/token-effect: en: 7763a0e875faf53d zh: fe33c3973215dc53 diff --git a/packages/todo/tool-todo/README.md b/packages/todo/tool-todo/README.md index 1c31e14ddd..d08b26801a 100644 --- a/packages/todo/tool-todo/README.md +++ b/packages/todo/tool-todo/README.md @@ -135,7 +135,7 @@ Prefix-stable while the definition and visibility are unchanged. Plugin lifecycl #### What the model sees -Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are ``Error: invalid todo: `content` must be a non-empty string``, `Error: invalid todos: duplicate content ""`, `Error: todo_write requires an owning agent session`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid todos: at most one task may be in_progress (got )`. The full `todo/write` session event is UI and replay state, not a second model message. +Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are `Error: invalid arguments: todos[].content must be a non-empty string`, `Error: invalid arguments: todos[].content duplicates ""`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid arguments: at most one task may be in_progress (got )`, all `ToolArgsError` `INVALID_ARGS`, plus `Error: todo_write requires an owning agent session` as `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE`. The full `todo/write` session event is UI and replay state, not a second model message. #### Token effect diff --git a/packages/todo/tool-todo/README.zh.md b/packages/todo/tool-todo/README.zh.md index 6ceae4cc3e..10ffd2f05f 100644 --- a/packages/todo/tool-todo/README.zh.md +++ b/packages/todo/tool-todo/README.zh.md @@ -135,7 +135,7 @@ agent 每次更新都发送完整列表;新列表替换旧列表,因此没 #### 模型看到什么 -每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 ``Error: invalid todo: `content` must be a non-empty string``、`Error: invalid todos: duplicate content ""`、`Error: todo_write requires an owning agent session`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid todos: at most one task may be in_progress (got )`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 +每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 `Error: invalid arguments: todos[].content must be a non-empty string`、`Error: invalid arguments: todos[].content duplicates ""`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid arguments: at most one task may be in_progress (got )`,均为 `ToolArgsError` `INVALID_ARGS`;另有 `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE` 的 `Error: todo_write requires an owning agent session`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 #### Token 影响 diff --git a/packages/todo/tool-todo/src/index.ts b/packages/todo/tool-todo/src/index.ts index 0f59f7be17..53ac76ac86 100644 --- a/packages/todo/tool-todo/src/index.ts +++ b/packages/todo/tool-todo/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { TodoItem } from './types.ts' // Type-only: resolves the required ctx.sessionProjections service declaration. import type {} from '@deepseek-ai/dsh-session-projection' @@ -81,20 +81,20 @@ function toTodoList(raw: { content: string; status: string }[], allowParallel: b const todos: TodoItem[] = [] const seen = new Set() let active = 0 - for (const item of raw) { + for (const [index, item] of raw.entries()) { const content = item.content.trim() if (content.length === 0) { - throw new Error('invalid todo: `content` must be a non-empty string') + throw new ToolArgsError([`todos[${index}].content must be a non-empty string`]) } if (seen.has(content)) { - throw new Error(`invalid todos: duplicate content ${JSON.stringify(content)}`) + throw new ToolArgsError([`todos[${index}].content duplicates ${JSON.stringify(content)}`]) } seen.add(content) if (item.status === 'in_progress') active++ todos.push({ content, status: item.status as TodoItem['status'] }) } if (!allowParallel && active > 1) { - throw new Error(`invalid todos: at most one task may be in_progress (got ${active})`) + throw new ToolArgsError([`at most one task may be in_progress (got ${active})`]) } return todos } @@ -195,7 +195,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (!exec.agent) { // The list is per-agent-session state; a non-agent caller (no owning // session) has nowhere to write it. Reject rather than silently no-op. - throw new Error('todo_write requires an owning agent session') + throw new ToolContextUnavailableError('todo_write requires an owning agent session') } exec.agent.session.append('todo/write', { todos }) const count = (status: TodoItem['status']): number => todos.filter(t => t.status === status).length diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index e6f39365b9..584d40c200 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -118,6 +118,7 @@ describe('tool-todo real Loader composition through cordis.yml', () => { }) expect(result.isError).toBe(true) expect(resultText(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(owner.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }, 30_000) diff --git a/packages/todo/tool-todo/tests/tool-todo.spec.ts b/packages/todo/tool-todo/tests/tool-todo.spec.ts index 1c8f49e221..01bfc8c638 100644 --- a/packages/todo/tool-todo/tests/tool-todo.spec.ts +++ b/packages/todo/tool-todo/tests/tool-todo.spec.ts @@ -157,6 +157,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: parallel }, { agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) // A rejected call must not reach the durable log. expect(agent.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }) @@ -198,6 +199,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos }) expect(result.isError).toBe(true) expect(text(result)).toContain(fragment) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a non-agent caller (the list has no owning session)', async () => { @@ -205,6 +207,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: [{ content: 'a', status: 'pending' }] }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('owning agent session') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('presents the call with a stable title and the list as raw input', async () => { From 5157e3205a8d7bb05387b5abfe6c1250ba9ee777 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:17 +0800 Subject: [PATCH 019/396] feat(user-questions): classify answerer failures and timed ask checks An answerer failure that is not a HarnessError now rejects with UserQuestionError PROVIDER_ERROR and keeps the original as cause, while a coded HarnessError keeps its name and code. The timed ask_user_question tool reports an invalid timeout as BAD_TIMEOUT, a repeated question id as the new DUPLICATE_QUESTION_ID, and a missing caller as CALLER_NOT_LIVE. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 8 ++++--- docs/subsystems/user-questions.zh.md | 8 ++++--- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tool-ask-user/README.i18n.yaml | 4 ++-- packages/interaction/tool-ask-user/README.md | 2 +- .../interaction/tool-ask-user/README.zh.md | 2 +- .../interaction/tool-ask-user/src/timed.ts | 10 +++++---- .../tool-ask-user/tests/tool-ask-user.spec.ts | 10 ++++++++- .../interaction/user-questions/src/index.ts | 9 +++++--- .../tests/user-questions.spec.ts | 21 +++++++++++-------- 11 files changed, 50 insertions(+), 30 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index 808a19468f..bacd251ef1 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: 5762b1498a426ab6 - zh: bb9987ec82103620 + en: eb0a4f94282f8c18 + zh: 92c41869431b120e diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index 2c86b22e1c..c87fe49f14 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index ad39e1004f..4dc465f750 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..199ff2c9a5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, or `DELEGATED_CALLER` when that live agent has subagent origin.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, diff --git a/packages/interaction/tool-ask-user/README.i18n.yaml b/packages/interaction/tool-ask-user/README.i18n.yaml index c065b0c79d..6bf59ccd8a 100644 --- a/packages/interaction/tool-ask-user/README.i18n.yaml +++ b/packages/interaction/tool-ask-user/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3e4bc86d1d86eaab zh: 3c4c41666135f55d /deepseek-ai-dsh-tool-ask-user/use-this-package/when-the-call-fails: - en: c4ac3c584f900230 - zh: bd8d227f0637b8f1 + en: f18fe6f907ad9fe8 + zh: 5ea600e24c781522 /deepseek-ai-dsh-tool-ask-user/understand-the-implementation: en: e9b9d46be0b45ca2 zh: c02403486473cd80 diff --git a/packages/interaction/tool-ask-user/README.md b/packages/interaction/tool-ask-user/README.md index c479ab53ff..f2f4b18d90 100644 --- a/packages/interaction/tool-ask-user/README.md +++ b/packages/interaction/tool-ask-user/README.md @@ -71,7 +71,7 @@ For a finite timed call, `{ "pending": true, "callId": "…" }` means the foregr ### When the call fails -Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. +Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A timed call rejects an out-of-range `timeout` with `BAD_TIMEOUT`, a repeated question id with `DUPLICATE_QUESTION_ID`, and a missing calling agent with `CALLER_NOT_LIVE`, all as `UserQuestionError`. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. ----- diff --git a/packages/interaction/tool-ask-user/README.zh.md b/packages/interaction/tool-ask-user/README.zh.md index 8c577cb40d..1f76d6ab68 100644 --- a/packages/interaction/tool-ask-user/README.zh.md +++ b/packages/interaction/tool-ask-user/README.zh.md @@ -71,7 +71,7 @@ kind: "package-reference" ### 调用何时失败 -Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 +Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。timed 调用会以 `BAD_TIMEOUT` 拒绝超出范围的 `timeout`,以 `DUPLICATE_QUESTION_ID` 拒绝重复的问题 id,以 `CALLER_NOT_LIVE` 拒绝缺少调用方 agent 的调用,均为 `UserQuestionError`。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 ----- diff --git a/packages/interaction/tool-ask-user/src/timed.ts b/packages/interaction/tool-ask-user/src/timed.ts index 9f3260ddcd..c5f3c5c1a8 100644 --- a/packages/interaction/tool-ask-user/src/timed.ts +++ b/packages/interaction/tool-ask-user/src/timed.ts @@ -4,14 +4,14 @@ import type { Context } from '@deepseek-ai/cordis' import { defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools' -import { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions' +import { TIMED_WAIT_PARAMETER, UserQuestionError } from '@deepseek-ai/dsh-user-questions' import type { AskUserQuestionAnswer, AskUserQuestionRequestEvent, } from '@deepseek-ai/dsh-user-questions/types' function validateTimeout(timeout: number): number { if (timeout !== -1 && (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483)) { - throw new Error('timeout must be -1 or a positive integer up to 2147483 seconds') + throw new UserQuestionError('timeout must be -1 or a positive integer up to 2147483 seconds', 'BAD_TIMEOUT') } return timeout } @@ -19,7 +19,9 @@ function validateTimeout(timeout: number): number { function validateQuestionIds(questions: readonly { readonly id: string }[]): void { const ids = new Set() for (const question of questions) { - if (ids.has(question.id)) throw new Error(`question id ${JSON.stringify(question.id)} must be unique within this call`) + if (ids.has(question.id)) { + throw new UserQuestionError(`question id ${JSON.stringify(question.id)} must be unique within this call`, 'DUPLICATE_QUESTION_ID') + } ids.add(question.id) } } @@ -197,7 +199,7 @@ export function registerTimedAskUser(ctx: Context, timeout = 120): void { validateQuestionIds(args.questions) const request = questionRequest(args.questions, exec) if (timeout !== -1) { - if (exec.agent === undefined) throw new Error('timed questions require a live agent') + if (exec.agent === undefined) throw new UserQuestionError('timed questions require a live agent', 'CALLER_NOT_LIVE') const result = await ctx.userQuestions.askTimed({ ...request, agent: exec.agent }, exec.callId, timeout * 1000) return 'pending' in result ? { ...result, message: pendingNotice } : answerResult(result) } diff --git a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts index 122b03023b..30e2c4629f 100644 --- a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts +++ b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts @@ -554,10 +554,16 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: timed questions require a live agent' }], + error: { info: { name: 'UserQuestionError', code: 'CALLER_NOT_LIVE' } }, }) }) - it.each([0, 1.5, 2_147_484])('rejects invalid timeout %s', async (timeout) => { + it.each([ + // The integer schema rejects a fraction before the tool body's range check. + { timeout: 0, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + { timeout: 1.5, info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { timeout: 2_147_484, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + ])('rejects invalid timeout $timeout', async ({ timeout, info }) => { const ctx = await setup({ mode: 'timed', timeout: -1 }) const result = await executeToolFixture(ctx, { @@ -570,6 +576,7 @@ describe('ask_user_question tool', () => { expect(result.isError).toBe(true) expect(result.content[0]).toMatchObject({ type: 'text' }) expect(result.content[0]?.type === 'text' ? result.content[0].text : '').toMatch(/timeout.*integer/i) + expect(result.error?.info).toEqual(info) }) it('rejects duplicate question ids before dispatching a timed call', async () => { @@ -590,6 +597,7 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: question id "scope" must be unique within this call' }], + error: { info: { name: 'UserQuestionError', code: 'DUPLICATE_QUESTION_ID' } }, }) expect(answerer).not.toHaveBeenCalled() }) diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 2804b9ca30..0242301291 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -285,8 +285,10 @@ export class UserQuestionService extends TypertRemoteService { * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -356,7 +358,8 @@ export class UserQuestionService extends TypertRemoteService { if (request.signal?.aborted) { throw abortedQuestion(error) } - throw restored + if (restored instanceof HarnessError) throw restored + throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index b2097ba376..d76ade47db 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,7 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -178,14 +178,16 @@ describe('UserQuestionService', () => { name: 'UserQuestionError', })], ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('preserves %s from the provider', async (_label, rejection) => { + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) - await expect(ctx.userQuestions.ask({ + const failure = await ctx.userQuestions.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }], - })).rejects.toBe(rejection) + }).then(() => undefined, (error: unknown) => error) + expect(failure).toBeInstanceOf(UserQuestionError) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -289,10 +291,10 @@ describe('UserQuestionService', () => { }) }) - it('preserves a provider rejection outside the UserQuestionError taxonomy', async () => { + it('preserves a coded provider rejection outside the UserQuestionError taxonomy', async () => { const ctx = new Context() await ctx.plugin(UserQuestionService) - const failure = new Error('provider failed') + const failure = new HarnessError('provider failed', 'PROVIDER_OFFLINE') registerAnswerer(ctx, { ask: () => Promise.reject(failure) }) await expect(ctx.userQuestions.ask({ @@ -568,14 +570,15 @@ describe('askTimed', () => { } }) - it('rethrows a provider failure that is not a question error', async () => { + it('classifies a provider failure that is not a question error as PROVIDER_ERROR', async () => { const ctx = await timedContext() const agent = liveAgent('timed-provider-crash') ctx.agents.enter(agent) - registerAnswerer(ctx, { ask: () => Promise.reject(new TypeError('provider crashed')) }) + const crash = new TypeError('provider crashed') + registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toThrow(TypeError) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) await ctx.fiber.dispose() }) From a2e31ad6f958f477d3a1073cfb068f3d9b201305 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:25 +0800 Subject: [PATCH 020/396] docs: regenerate catalogs for shifted source lines The config, persistence, and event producer-consumer catalogs record source line numbers that moved in the preceding error-code changes; no persisted type digest changed. Refs #7869 --- docs/config-catalog.md | 6 +++--- docs/config-catalog.zh.md | 6 +++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 12 ++++++------ docs/persistence-catalog.md | 6 +++--- docs/persistence-catalog.zh.md | 6 +++--- docs/persistence-schema.json | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..a0eb5198ce 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2670,7 +2670,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4480,7 +4480,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4627,7 +4627,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..3d137345e3 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2672,7 +2672,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4482,7 +4482,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4629,7 +4629,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..b610bfb030 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -53,7 +53,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..2d3999762a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -55,7 +55,7 @@ | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index a5fb682b48..6929a9f050 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 9ae5537eeae238de - zh: 6be761c7fd83fdce + en: bcc1f048e7a31f1e + zh: a9c29711722cd6c7 /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1227,8 +1227,8 @@ en: b45c7e8370d7be1e zh: 252fdc0ff2b9338c /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: - en: 9531468264499498 - zh: 9da23c0ad2776563 + en: 9815df505b8cd026 + zh: ce4f536eec979d77 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity~2: en: 13de8e35b749db45 zh: 01e4f3bcb6784fc8 @@ -1425,8 +1425,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: c861888d6239b700 - zh: a9b2271d3c6b8737 + en: 235f08eeb284a1a5 + zh: b6ebffbfd7b44a9b /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: 1282a0b3d5fa8d4d zh: aa533aea643dbefb diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6b80fbbc99..d75f7f9558 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -735,7 +735,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:53`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4779,7 +4779,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | Property | Presence | Type | |---|---|---| @@ -5870,7 +5870,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c73b594c28..df1efe0f1e 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -737,7 +737,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4781,7 +4781,7 @@ SHA-256: `bec5ca3a376f56f3d69df7f12a48e1cc07d4ea8305968773394c8734799faeb4` SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5872,7 +5872,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 3a1b058f36..caf3ea2b15 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -80,7 +80,7 @@ {"digest":"05a2796621b1ee6c03ef7abe560b25116bb4da4d592312117242a78415a32b04","names":[],"sources":[]}, {"digest":"05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf","names":["packages/interaction/user-approval/src/index.ts#ApprovalPolicy"],"sources":["packages/interaction/user-approval/src/index.ts:68"]}, {"digest":"0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7","names":["packages/core/session/src/types.ts#SessionSeq"],"sources":["packages/core/session/src/types.ts:33"]}, - {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:9"]}, + {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:11"]}, {"digest":"07eccc9ea2f9b5439d76cc77d5e062936677d43f07a23da749819b0a22ee36b7","names":[],"sources":[]}, {"digest":"09655b34d7f3cf1e9005974de2357de2d4a60deea165d16dac1eadaa6ec539a8","names":[],"sources":[]}, {"digest":"09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:151"]}, @@ -155,7 +155,7 @@ {"digest":"1f1385dbc3e875c021e387c7096d671d606f22daec51b25c80348735b6bbfa10","names":[],"sources":[]}, {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, - {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, + {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:55"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, From a528a6d33c7f0e25dfbe580a856e20b9f0a84a7b Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:16:20 +0800 Subject: [PATCH 021/396] feat(subagent): classify unavailable delegation presets A fresh delegation whose selected preset is unknown or cannot load received the registry's RemoteError, which is not a HarnessError, so the tool result had no error.code. applyChildComposition now converts that RemoteError into SubagentError PRESET_UNAVAILABLE, keeping its message and the original as cause. Restoration still propagates it so the manager reports NOT_RESUMABLE, and other mount failures are unchanged. Refs #7869 --- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 13 ++++++++++--- .../subagent/tests/continuation-presets.spec.ts | 15 +++++++++++++++ .../tool-subagent/tests/preset-selection.spec.ts | 3 +++ 6 files changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index ceaac3229a..d89a9ce18b 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: f5393c65bf8ee460 - zh: d037d42bc967f17b + en: bdb3204a71ee2a8f + zh: 74d7d4e9eca20e2a /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index dcad891799..916c73346e 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index dfe7d1f835..8cc7e6bda9 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 9f4626641c..89b2a59447 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,6 +25,7 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -183,8 +184,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the - * child cannot join its creator's preset revision. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh + * delegation's preset is unknown or cannot load, or the child cannot join its creator's + * preset revision. Restoration propagates the registry's `RemoteError` unchanged. */ export function applyChildComposition( childCtx: Context, @@ -196,7 +198,12 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - return presets.mount(childCtx, composition.agentPreset).then(() => { + const mounted = presets.mount(childCtx, composition.agentPreset) + // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. + return (parent === undefined ? mounted : mounted.catch((error: unknown) => { + const failure = remoteErrorOf(error) + throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) + })).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 594be164ac..0cd3e0f69b 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -139,6 +139,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + const { ctx, parent, adapter } = await setup() + await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'Unknown agent preset: absent', + cause: { code: 'agent-preset/not-found' }, + }) + const failure = new Error('binding failed') + vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) + await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 9bfa7e9e85..920697c323 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,6 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -179,6 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -363,6 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') + expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) From 80c3a3fe09365fdf62978c33ffda51b74beb5314 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 20:48:51 +0800 Subject: [PATCH 022/396] refactor(plan-mode): keep the code list off the plugin entry The plugin entry exports only the PlanModeError class and its code type; the code list stays module-local in src/error.ts, so the entry adds no value export that verify-plugin-entry-exports would reject. Refs #7869 --- packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index e0227893bb..38f98ee1d0 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -12,7 +12,7 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. */ -export const PLAN_MODE_ERROR_CODES = [ +const PLAN_MODE_ERROR_CODES = [ 'PLAN_NOT_ACTIVE', 'PLAN_REVIEW_INTERRUPTED', 'PLAN_REVISION_REQUESTED', diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 636165c5e3..685e060339 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -43,7 +43,7 @@ declare module '@deepseek-ai/dsh-llm' { } } export type * from './types.ts' -export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' +export { PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { From d212c0629af776d321e55dbdf021d8249c0cd0cb Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 21:55:52 +0800 Subject: [PATCH 023/396] refactor(plan-mode,user-questions): import HarnessError from dsh-error PlanModeError is the only base-class use this stack adds to plan-mode, so the package depends on the dependency-free dsh-error instead of reaching the base through dsh-llm; the user-questions test that builds a foreign HarnessError imports it from dsh-error as a dev dependency. Refs #7869 --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- packages/interaction/user-questions/package.json | 1 + .../interaction/user-questions/tests/user-questions.spec.ts | 3 ++- packages/plan/plan-mode/package.json | 2 ++ packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 8 files changed, 19 insertions(+), 4 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..6913c9fca6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -910,6 +910,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1814,7 +1815,7 @@ flowchart TD | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | -| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`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 a6070b4f5e..aa668a72c2 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -912,6 +912,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1816,7 +1817,7 @@ flowchart TD | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | | [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | -| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/packages/interaction/user-questions/package.json b/packages/interaction/user-questions/package.json index 3eb448ad83..4665aa742d 100644 --- a/packages/interaction/user-questions/package.json +++ b/packages/interaction/user-questions/package.json @@ -60,6 +60,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index d76ade47db..a4f3208de1 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,8 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' diff --git a/packages/plan/plan-mode/package.json b/packages/plan/plan-mode/package.json index b4685d4062..26a6273e2e 100644 --- a/packages/plan/plan-mode/package.json +++ b/packages/plan/plan-mode/package.json @@ -43,6 +43,7 @@ "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", @@ -65,6 +66,7 @@ "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-ptc-runtime": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index 38f98ee1d0..997eb5540e 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -4,7 +4,7 @@ * @module @deepseek-ai/dsh-plan-mode/error */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every machine-routable plan-mode failure: diff --git a/packages/plan/plan-mode/tsconfig.json b/packages/plan/plan-mode/tsconfig.json index f187853290..357509a9f0 100644 --- a/packages/plan/plan-mode/tsconfig.json +++ b/packages/plan/plan-mode/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../../util/error" + }, { "path": "../../core/tools" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..9d71501a7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13061,6 +13061,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -13905,6 +13908,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-llm': specifier: workspace:* version: link:../../llm/llm 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 024/396] 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 50577597e925fd37767dd9147b1ad9bb5d12a95c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 17:40:53 +0800 Subject: [PATCH 025/396] feat(cua-windows): port Windows provider from old branch Port the existing Windows CUA implementation from feat/cua-windows in deepseek-harness2 to the current branch, with adapters for the current app/window interfaces and Windows-only bundle activation. Retain the native Shell/UWP implementation for later interface work. --- package.json | 1 + .../experimental/cua-bundle/README.i18n.yaml | 16 +- packages/experimental/cua-bundle/README.md | 14 +- packages/experimental/cua-bundle/README.zh.md | 14 +- .../experimental/cua-bundle/cordis.patch.yml | 5 + packages/experimental/cua-bundle/package.json | 6 +- .../cua-bundle/tests/platform.spec.ts | 3 +- .../experimental/cua-windows/README.i18n.yaml | 10 + packages/experimental/cua-windows/README.md | 12 + .../experimental/cua-windows/README.zh.md | 12 + .../cua-windows/native/.gitignore | 3 + .../cua-windows/native/.npmignore | 3 + .../cua-windows/native/CuaWindows.csproj | 26 + .../cua-windows/native/Directory.Build.props | 6 + .../cua-windows/native/app.manifest | 13 + .../native/capture-probe/CaptureProbe.cs | 221 +++ .../capture-probe/CaptureProbe.exe.config | 6 + .../native/capture-probe/README.i18n.yaml | 28 + .../native/capture-probe/README.md | 93 ++ .../native/capture-probe/README.zh.md | 93 ++ .../native/capture-probe/app.manifest | 12 + .../cua-windows/native/capture-probe/run.ps1 | 28 + .../desktop-tests/DesktopFixture.csproj | 13 + .../native/desktop-tests/Program.cs | 95 ++ .../cua-windows/native/generate-protocol.ts | 9 + .../cua-windows/native/packages.lock.json | 95 ++ .../cua-windows/native/protocol.schema.json | 1414 +++++++++++++++++ .../native/protocol/AccessibilityText.cs | 74 + .../native/protocol/CuaProtocol.csproj | 14 + .../cua-windows/native/protocol/KeyChord.cs | 25 + .../native/protocol/NativeControlFrame.cs | 23 + .../native/protocol/NativeRequest.cs | 99 ++ .../native/protocol/TextSelection.cs | 49 + .../native/protocol/packages.lock.json | 37 + .../cua-windows/native/src/Accessibility.cs | 245 +++ .../native/src/AccessibilityActions.cs | 163 ++ .../cua-windows/native/src/Applications.cs | 291 ++++ .../native/src/CaptureAdmission.cs | 34 + .../cua-windows/native/src/ClipboardPaste.cs | 183 +++ .../cua-windows/native/src/DesktopExecutor.cs | 264 +++ .../cua-windows/native/src/DesktopSession.cs | 45 + .../cua-windows/native/src/DesktopWindows.cs | 109 ++ .../cua-windows/native/src/Dispatchers.cs | 178 +++ .../cua-windows/native/src/GlobalUsings.cs | 1 + .../cua-windows/native/src/Input.cs | 263 +++ .../cua-windows/native/src/LaunchEntries.cs | 88 + .../cua-windows/native/src/NativeServer.cs | 196 +++ .../cua-windows/native/src/Program.cs | 35 + .../cua-windows/native/src/SharedRuntime.cs | 110 ++ .../cua-windows/native/src/ShellBroker.cs | 111 ++ .../cua-windows/native/src/Win32.cs | 136 ++ .../cua-windows/native/src/WindowCapture.cs | 243 +++ .../cua-windows/native/src/Windows.cs | 176 ++ .../cua-windows/native/tests/Program.cs | 96 ++ .../native/tests/Protocol.Tests.csproj | 11 + .../native/tests/packages.lock.json | 40 + .../experimental/cua-windows/package.json | 95 ++ .../experimental/cua-windows/src/guidance.ts | 2 + .../experimental/cua-windows/src/index.ts | 91 ++ .../cua-windows/src/native-build.ts | 73 + .../cua-windows/src/native-runtime.ts | 354 +++++ .../cua-windows/src/native-transport.ts | 65 + .../cua-windows/src/windows-host.ts | 93 ++ .../cua-windows/tests/desktop-runtime.spec.ts | 22 + .../cua-windows/tests/desktop-smoke.mjs | 285 ++++ .../cua-windows/tests/desktop-tool.spec.ts | 71 + .../cua-windows/tests/native-build.spec.ts | 61 + .../cua-windows/tests/native-runtime.spec.ts | 448 ++++++ .../tests/native-transport.spec.ts | 29 + .../cua-windows/tests/protocol.spec.ts | 30 + .../tests/provider-lifecycle.spec.ts | 108 ++ .../cua-windows/tests/windows-host.spec.ts | 66 + .../experimental/cua-windows/tsconfig.json | 30 + packages/experimental/cua/src/access-types.ts | 4 +- packages/experimental/cua/src/access.ts | 2 +- .../cua/src/client/PermissionPanel.tsx | 12 +- packages/experimental/cua/src/guidance.ts | 2 +- .../cua/tests/panel.client.spec.tsx | 6 +- pnpm-lock.yaml | 115 ++ scripts/check-workspace-constraints.ts | 1 + scripts/experimental-package-policy.ts | 1 + scripts/release/families.spec.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 2 + 84 files changed, 7626 insertions(+), 34 deletions(-) create mode 100644 packages/experimental/cua-windows/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/README.md create mode 100644 packages/experimental/cua-windows/README.zh.md create mode 100644 packages/experimental/cua-windows/native/.gitignore create mode 100644 packages/experimental/cua-windows/native/.npmignore create mode 100644 packages/experimental/cua-windows/native/CuaWindows.csproj create mode 100644 packages/experimental/cua-windows/native/Directory.Build.props create mode 100644 packages/experimental/cua-windows/native/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.zh.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/run.ps1 create mode 100644 packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj create mode 100644 packages/experimental/cua-windows/native/desktop-tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/generate-protocol.ts create mode 100644 packages/experimental/cua-windows/native/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/protocol.schema.json create mode 100644 packages/experimental/cua-windows/native/protocol/AccessibilityText.cs create mode 100644 packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj create mode 100644 packages/experimental/cua-windows/native/protocol/KeyChord.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeRequest.cs create mode 100644 packages/experimental/cua-windows/native/protocol/TextSelection.cs create mode 100644 packages/experimental/cua-windows/native/protocol/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/src/Accessibility.cs create mode 100644 packages/experimental/cua-windows/native/src/AccessibilityActions.cs create mode 100644 packages/experimental/cua-windows/native/src/Applications.cs create mode 100644 packages/experimental/cua-windows/native/src/CaptureAdmission.cs create mode 100644 packages/experimental/cua-windows/native/src/ClipboardPaste.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopExecutor.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopSession.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopWindows.cs create mode 100644 packages/experimental/cua-windows/native/src/Dispatchers.cs create mode 100644 packages/experimental/cua-windows/native/src/GlobalUsings.cs create mode 100644 packages/experimental/cua-windows/native/src/Input.cs create mode 100644 packages/experimental/cua-windows/native/src/LaunchEntries.cs create mode 100644 packages/experimental/cua-windows/native/src/NativeServer.cs create mode 100644 packages/experimental/cua-windows/native/src/Program.cs create mode 100644 packages/experimental/cua-windows/native/src/SharedRuntime.cs create mode 100644 packages/experimental/cua-windows/native/src/ShellBroker.cs create mode 100644 packages/experimental/cua-windows/native/src/Win32.cs create mode 100644 packages/experimental/cua-windows/native/src/WindowCapture.cs create mode 100644 packages/experimental/cua-windows/native/src/Windows.cs create mode 100644 packages/experimental/cua-windows/native/tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj create mode 100644 packages/experimental/cua-windows/native/tests/packages.lock.json create mode 100644 packages/experimental/cua-windows/package.json create mode 100644 packages/experimental/cua-windows/src/guidance.ts create mode 100644 packages/experimental/cua-windows/src/index.ts create mode 100644 packages/experimental/cua-windows/src/native-build.ts create mode 100644 packages/experimental/cua-windows/src/native-runtime.ts create mode 100644 packages/experimental/cua-windows/src/native-transport.ts create mode 100644 packages/experimental/cua-windows/src/windows-host.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-smoke.mjs create mode 100644 packages/experimental/cua-windows/tests/desktop-tool.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-build.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-transport.spec.ts create mode 100644 packages/experimental/cua-windows/tests/protocol.spec.ts create mode 100644 packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts create mode 100644 packages/experimental/cua-windows/tests/windows-host.spec.ts create mode 100644 packages/experimental/cua-windows/tsconfig.json diff --git a/package.json b/package.json index 37b86b60d5..d50b670493 100644 --- a/package.json +++ b/package.json @@ -301,6 +301,7 @@ "@deepseek-ai/dsh-experimental-worktree": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*", "@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index b561f27e44..a04d2cf4b4 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/cua-bundle/README.md /: - en: cc518dcd97629a96 - zh: 465e999011282dc3 + en: 0df5d6f2b9e2ac15 + zh: d0a9bd1f4e172d25 /deepseek-ai-dsh-cua-bundle: en: 9084fb48d0f6489c zh: ce692972d91cf663 /deepseek-ai-dsh-cua-bundle/summary: - en: 0d93f44a8ce7404c - zh: 6a73ed42d0efc9ea + en: f9f318c0ddc27bff + zh: 8a0c5ec31a63eb05 /deepseek-ai-dsh-cua-bundle/table-of-contents: en: b563e4ec4727d0de zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: - en: 5c025a58990bb2eb - zh: c3d1280ccbdfe214 + en: f22a10946cefc2d8 + zh: 430d5f0cfc244ef0 /deepseek-ai-dsh-cua-bundle/understand-the-implementation: - en: b1011db52cfc17cd - zh: 6fa8798fedc5c0b6 + en: acb42fb7b181194b + zh: 6961f4cb732560e9 /deepseek-ai-dsh-cua-bundle/further-exploration: en: 9f15d56b5b16e1ca zh: 75eb08e8828c8877 diff --git a/packages/experimental/cua-bundle/README.md b/packages/experimental/cua-bundle/README.md index 50109f1066..9c19ccbbb1 100644 --- a/packages/experimental/cua-bundle/README.md +++ b/packages/experimental/cua-bundle/README.md @@ -1,5 +1,5 @@ --- -description: "Enable optional macOS Computer Use and its permission page." +description: "Enable optional Computer Use on macOS and Windows with its permission page." kind: "package-bundle" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance. +Enable Computer Use from Plugins on macOS and Windows for existing and new PTC sessions. The bundle ships with DSH switched off and appears in the Experimental plugins list on supported Hosts. Each Host loads its platform's native provider and the shared permission page. Disabled profiles prepare no native components and register neither CUA tools nor their model guidance. ## Table of Contents @@ -24,7 +24,11 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window ## Use this package -On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: +On macOS or Windows, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. Open its details and choose PTC if needed. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. + +On macOS, the bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Grant Accessibility and Screen Recording to `DSH Computer Use.app`. + +Native preparation and access requirements belong to the [macOS provider](../cua-macos/README.md) and [Windows provider](../cua-windows/README.md). For source Web, run these commands from the repository root: ```sh pnpm run build @@ -37,7 +41,7 @@ The switch saves bundle selection in the profile’s `package.json`. Computer Us Disabling unloads the provider and withdraws CUA tools from its Agent scopes. Runtime configuration, the new-session default and saved grants remain. -Computer Use is available only on a macOS DSH Host. The native provider is an optional dependency installed only on macOS; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported Mac Host. +The bundle supports macOS and native Windows DSH Hosts; it does not enable Windows Computer Use from WSL. Native providers are optional dependencies, and each Host loads only its matching provider; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported DSH Host. If preparation fails, the saved selection remains and CUA operations stay unavailable. Refresh or reopen the plugin page to read the component diagnostic, correct its cause, then restart DSH. @@ -51,7 +55,7 @@ Explicit activation runs a read-only permission check, which may start a helper
Maintainer details -The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level condition skips the optional macOS provider on other Hosts. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal. +The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level conditions load the macOS provider only on macOS and the Windows provider only on native Windows. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal.
diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index b7d8804e91..2318aeb313 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -1,5 +1,5 @@ --- -description: "开启可选 macOS Computer Use 及权限页面。" +description: "在 macOS 和 Windows 上开启可选 Computer Use 及权限页面。" kind: "package-bundle" --- @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 +在 macOS 和 Windows 的插件页为已有和新建 PTC 会话开启 Computer Use。组合包随 DSH 提供且默认关闭,在受支持 Host 的实验性插件列表中显示。各 Host 加载对应平台的原生提供方和共享权限页面。关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 ## 目录 @@ -24,7 +24,11 @@ kind: "package-bundle" ## 使用本包 -在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: +在 macOS 或 Windows 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。打开详情,按需设置 PTC。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。 + +在 macOS 上,组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。请为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 + +各平台的原生准备和访问要求分别见 [macOS 提供方](../cua-macos/README.zh.md)和 [Windows 提供方](../cua-windows/README.zh.md)。源码 Web 在仓库根目录运行以下命令: ```sh pnpm run build @@ -37,7 +41,7 @@ pnpm dsh web 关闭会卸载提供方,并从其 Agent 作用域中撤回 CUA 工具。执行器配置、新会话默认值和已保存的授权保留。 -Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的可选依赖,共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 Mac Host。 +组合包支持 macOS 和原生 Windows DSH Host,不在 WSL 中启用 Windows Computer Use。原生提供方作为可选依赖提供,各 Host 只加载对应平台的提供方;共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 DSH Host。 准备失败时,已保存的选择保留,CUA 操作不可用。刷新或重新打开插件页查看组件诊断,修复后重启 DSH。 @@ -51,7 +55,7 @@ Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的
维护者说明 -组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件会在其他 Host 上跳过可选的 macOS 提供方。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。 +组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件确保 macOS 提供方仅在 macOS 加载,Windows 提供方仅在原生 Windows 加载。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。
diff --git a/packages/experimental/cua-bundle/cordis.patch.yml b/packages/experimental/cua-bundle/cordis.patch.yml index 5d5fb48b6f..82d3d0960f 100644 --- a/packages/experimental/cua-bundle/cordis.patch.yml +++ b/packages/experimental/cua-bundle/cordis.patch.yml @@ -6,5 +6,10 @@ disabled: !!js process.platform !== 'darwin' config: agentPreset: ptc + - id: cua-windows + name: '@deepseek-ai/dsh-cua-windows' + disabled: !!js process.platform !== 'win32' + config: + agentPreset: ptc - id: ui-cua name: '@deepseek-ai/dsh-cua' diff --git a/packages/experimental/cua-bundle/package.json b/packages/experimental/cua-bundle/package.json index f9ba508721..699b5bae93 100644 --- a/packages/experimental/cua-bundle/package.json +++ b/packages/experimental/cua-bundle/package.json @@ -40,7 +40,8 @@ "bundle": { "patch": "./cordis.patch.yml", "platforms": [ - "darwin" + "darwin", + "win32" ] } }, @@ -58,6 +59,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:~" }, "optionalDependencies": { - "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" + "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*" } } diff --git a/packages/experimental/cua-bundle/tests/platform.spec.ts b/packages/experimental/cua-bundle/tests/platform.spec.ts index 4230e4f406..912e2c56b9 100644 --- a/packages/experimental/cua-bundle/tests/platform.spec.ts +++ b/packages/experimental/cua-bundle/tests/platform.spec.ts @@ -6,7 +6,7 @@ import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' import { load } from 'js-yaml' import { expect, it, vi } from 'vitest' -it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and imports the native provider only on Darwin', async (platform) => { +it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and selects its native provider', async (platform) => { const patch = load(await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8'), { schema: entryListSchema, }) as { insert: EntryOptions[] }[] @@ -28,6 +28,7 @@ it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s a expect(imports).toContain('@deepseek-ai/dsh-cua') expect(imports).toContain('@deepseek-ai/dsh-computer-use') expect(imports.includes('@deepseek-ai/dsh-experimental-cua-macos')).toBe(platform === 'darwin') + expect(imports.includes('@deepseek-ai/dsh-cua-windows')).toBe(platform === 'win32') } finally { await ctx.fiber.dispose() imported.mockRestore() diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml new file mode 100644 index 0000000000..30b2eb4f1f --- /dev/null +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -0,0 +1,10 @@ +# Bilingual-pair consistency record for README.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 packages/experimental/cua-windows/README.md +/: + en: 74cec3b0e35e9bf4 + zh: 8c7eb35b11ada2b5 +/deepseek-ai-dsh-cua-windows: + en: f31869d4398aa0ae + zh: b94122bb2bc53a53 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md new file mode 100644 index 0000000000..40a31c5e3f --- /dev/null +++ b/packages/experimental/cua-windows/README.md @@ -0,0 +1,12 @@ +--- +description: "TODO: Windows Computer Use documentation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +English | [中文](README.zh.md) + +TODO: Document the migrated provider after the interface is finalized. + +TODO: Expose the retained native Shell/UWP discovery and launch operations. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md new file mode 100644 index 0000000000..9f118ebe6f --- /dev/null +++ b/packages/experimental/cua-windows/README.zh.md @@ -0,0 +1,12 @@ +--- +description: "TODO:Windows Computer Use 文档。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +[English](README.md) | 中文 + +TODO:接口定稿后统一补齐迁移后提供方的文档。 + +TODO:暴露保留的 native Shell/UWP 发现和启动操作。 diff --git a/packages/experimental/cua-windows/native/.gitignore b/packages/experimental/cua-windows/native/.gitignore new file mode 100644 index 0000000000..d519714059 --- /dev/null +++ b/packages/experimental/cua-windows/native/.gitignore @@ -0,0 +1,3 @@ +**/bin/ +**/obj/ +.build/ diff --git a/packages/experimental/cua-windows/native/.npmignore b/packages/experimental/cua-windows/native/.npmignore new file mode 100644 index 0000000000..6fd41ce451 --- /dev/null +++ b/packages/experimental/cua-windows/native/.npmignore @@ -0,0 +1,3 @@ +obj/ +protocol/bin/ +tests/bin/ diff --git a/packages/experimental/cua-windows/native/CuaWindows.csproj b/packages/experimental/cua-windows/native/CuaWindows.csproj new file mode 100644 index 0000000000..0cc65b6907 --- /dev/null +++ b/packages/experimental/cua-windows/native/CuaWindows.csproj @@ -0,0 +1,26 @@ + + + Exe + net10.0-windows10.0.19041.0 + true + true + true + false + enable + enable + true + dsh-cua-windows + app.manifest + true + win-x64;win-arm64 + true + true + none + false + + + + + + + diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props new file mode 100644 index 0000000000..b4fbcbc808 --- /dev/null +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -0,0 +1,6 @@ + + + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/bin/ + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ + + diff --git a/packages/experimental/cua-windows/native/app.manifest b/packages/experimental/cua-windows/native/app.manifest new file mode 100644 index 0000000000..a2e299ca4e --- /dev/null +++ b/packages/experimental/cua-windows/native/app.manifest @@ -0,0 +1,13 @@ + + + + + + + + + PerMonitorV2 + true + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs new file mode 100644 index 0000000000..6f118d63ae --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs @@ -0,0 +1,221 @@ +// Private .NET Framework experiment. Each blocking capture runs in a disposable child process. +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using System.Windows.Automation; +using System.Windows.Forms; + +internal static class CaptureProbe +{ + private static readonly JavaScriptSerializer Json = new JavaScriptSerializer(); + private static readonly string[] Methods = { "screen", "window-dc", "print", "print-full" }; + + [STAThread] + private static int Main(string[] args) + { + try + { + SetProcessDpiAwarenessContext(new IntPtr(-4)); + if (args.Length == 4 && args[0] == "--one") + { + Capture(new IntPtr(long.Parse(args[1])), args[2], args[3]); + return 0; + } + if (args.Length == 3 && args[0] == "--compare") + { + var output = NewOutput(args[2]); + Compare(new IntPtr(long.Parse(args[1])), output, "selected"); + return 0; + } + if (args.Length != 2 || args[0] != "--demo") + throw new ArgumentException("Expected --demo OUTPUT or --compare DECIMAL_HWND OUTPUT"); + var directory = NewOutput(args[1]); + Application.EnableVisualStyles(); + using (var target = new Form()) + using (var cover = new Form()) + { + target.Text = "DSH capture probe: owned target"; + target.StartPosition = cover.StartPosition = FormStartPosition.Manual; + target.Bounds = new Rectangle(100, 100, 520, 400); + target.BackColor = Color.FromArgb(20, 180, 60); + target.TopMost = true; + cover.Text = "DSH capture probe: owned cover"; + cover.Bounds = target.Bounds; + cover.BackColor = Color.Magenta; + cover.TopMost = true; + Exception failure = null; + target.Shown += async delegate + { + try + { + var hwnd = target.Handle; + var automation = await Task.Run(() => AutomationElement.FromHandle(hwnd).Current.Name); + Write(Path.Combine(directory, "runtime.json"), new + { + framework = Environment.Version.ToString(), + automationName = automation, + os = Environment.OSVersion.VersionString, + pointerBytes = IntPtr.Size + }); + target.Refresh(); + var center = new Point(target.Left + target.Width / 2, target.Top + target.Height / 2); + await WaitForPixel(center, target.BackColor); + await Task.Run(() => Compare(hwnd, directory, "visible")); + cover.Show(); + cover.Refresh(); + await WaitForPixel(center, cover.BackColor); + // A new marker distinguishes a fresh covered image from a cached visible image. + target.BackColor = Color.FromArgb(30, 90, 220); + target.Refresh(); + await Task.Run(() => Compare(hwnd, directory, "covered-updated")); + target.WindowState = FormWindowState.Minimized; + await Task.Run(() => Compare(hwnd, directory, "minimized")); + } + catch (Exception error) { failure = error; } + finally { cover.Close(); target.Close(); } + }; + Application.Run(target); + if (failure != null) throw failure; + } + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error); + return 1; + } + } + + private static string NewOutput(string path) + { + var result = Path.GetFullPath(path); + if (Directory.Exists(result)) throw new IOException("Use a new output directory for each experiment"); + Directory.CreateDirectory(result); + return result; + } + + private static async Task WaitForPixel(Point point, Color expected) + { + var clock = Stopwatch.StartNew(); + using (var sample = new Bitmap(1, 1)) + using (var graphics = Graphics.FromImage(sample)) + { + while (true) + { + graphics.CopyFromScreen(point.X, point.Y, 0, 0, sample.Size); + if (sample.GetPixel(0, 0).ToArgb() == expected.ToArgb()) return; + if (clock.ElapsedMilliseconds > 5000) throw new TimeoutException("The owned window marker is not visible"); + await Task.Delay(25); + } + } + } + + private static void Compare(IntPtr window, string directory, string scenario) + { + foreach (var method in Methods) + { + var prefix = Path.Combine(directory, scenario + "-" + method); + var start = new ProcessStartInfo(Application.ExecutablePath, + "--one " + window.ToInt64() + " " + method + " \"" + prefix + "\"") + { + UseShellExecute = false, + CreateNoWindow = true + }; + using (var process = Process.Start(start)) + { + if (!process.WaitForExit(5000)) + { + process.Kill(); + process.WaitForExit(); + Write(prefix + ".json", new { method, timeout = true }); + } + else if (process.ExitCode != 0) + throw new InvalidOperationException(method + " child exited " + process.ExitCode); + } + Console.WriteLine(File.ReadAllText(prefix + ".json")); + } + } + + private static void Capture(IntPtr window, string method, string prefix) + { + Rect bounds; + if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Window no longer exists"); + var width = bounds.Right - bounds.Left; + var height = bounds.Bottom - bounds.Top; + if (width <= 0 || height <= 0 || (long)width * height > 40000000) + throw new InvalidOperationException("Window dimensions exceed the experiment limit"); + var foreground = GetForegroundWindow(); + var clock = Stopwatch.StartNew(); + using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) + { + bool returned; + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.Yellow); + if (method == "screen") + { + graphics.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, new Size(width, height)); + returned = true; + } + else if (method == "window-dc") + { + var source = GetWindowDC(window); + if (source == IntPtr.Zero) throw new InvalidOperationException("Window DC is unavailable"); + try + { + var destination = graphics.GetHdc(); + try { returned = BitBlt(destination, 0, 0, width, height, source, 0, 0, 0x00CC0020); } + finally { graphics.ReleaseHdc(destination); } + } + finally { ReleaseDC(window, source); } + } + else + { + var dc = graphics.GetHdc(); + try { returned = PrintWindow(window, dc, method == "print-full" ? 2u : 0u); } + finally { graphics.ReleaseHdc(dc); } + } + } + clock.Stop(); + var markers = new Dictionary { { "green", 0 }, { "blue", 0 }, { "cover", 0 }, { "black", 0 } }; + for (var y = 0; y < height; y += 4) + for (var x = 0; x < width; x += 4) + { + var pixel = bitmap.GetPixel(x, y); + if (pixel.R == 20 && pixel.G == 180 && pixel.B == 60) markers["green"]++; + if (pixel.R == 30 && pixel.G == 90 && pixel.B == 220) markers["blue"]++; + if (pixel.R == 255 && pixel.G == 0 && pixel.B == 255) markers["cover"]++; + if (pixel.R == 0 && pixel.G == 0 && pixel.B == 0) markers["black"]++; + } + bitmap.Save(prefix + ".png", ImageFormat.Png); + Write(prefix + ".json", new + { + method, returned, width, height, elapsedMs = clock.ElapsedMilliseconds, markers, + minimized = IsIconic(window), foregroundChanged = foreground != GetForegroundWindow() + }); + } + } + + private static void Write(string path, object value) + { + File.WriteAllText(path, Json.Serialize(value) + Environment.NewLine); + } + + [StructLayout(LayoutKind.Sequential)] + private struct Rect { internal int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect); + [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hwnd); + [DllImport("user32.dll")] private static extern IntPtr GetWindowDC(IntPtr hwnd); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hwnd, IntPtr dc); + [DllImport("gdi32.dll")] private static extern bool BitBlt(IntPtr destination, int x, int y, int width, int height, + IntPtr source, int sourceX, int sourceY, uint operation); +} diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config new file mode 100644 index 0000000000..6c3273cff7 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml b/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml new file mode 100644 index 0000000000..29c76d358f --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for README.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 packages/experimental/cua-windows/native/capture-probe/README.md +/: + en: eeabe421bc58f08c + zh: decfb432f67c7a10 +/windows-capture-experiment: + en: 04636b80e16e9c77 + zh: 1939a876909a0728 +/windows-capture-experiment/summary: + en: b7d5300b63fbf75d + zh: 7ac6fff1d0e0ff39 +/windows-capture-experiment/table-of-contents: + en: 5fe6d5c7d6ef2980 + zh: 1b6c59a3a0dae8cd +/windows-capture-experiment/run-the-experiment: + en: 0a3af6cd49068299 + zh: 8efa8e90294c4f28 +/windows-capture-experiment/interpret-the-output: + en: aa765881c455c6c0 + zh: 6d76f02d287f5260 +/windows-capture-experiment/further-exploration: + en: e886759b879c9754 + zh: 0dfaea2ea703055f +/windows-capture-experiment/further-exploration/dev-note: + en: 8a4492cdafa89a70 + zh: b2d7be08c34a0b10 diff --git a/packages/experimental/cua-windows/native/capture-probe/README.md b/packages/experimental/cua-windows/native/capture-probe/README.md new file mode 100644 index 0000000000..737fe1306d --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.md @@ -0,0 +1,93 @@ +--- +description: "Run Windows capture comparisons with the installed .NET Framework and review the native runtime migration plan." +--- + +# Windows capture experiment + +English | [中文](README.zh.md) + +## Summary + +Compare screen copying, window DC copying, and PrintWindow without installing a .NET SDK or third-party library. The private experiment targets .NET Framework 4.8 and uses the compiler and assemblies installed with Windows. It does not replace the provider's capture implementation. + +## Table of Contents + +- [Run the experiment](#run-the-experiment) +- [Interpret the output](#interpret-the-output) +- [Further Exploration](#further-exploration) +- [Dev Note](#dev-note) + +----- + + +## Run the experiment + +On an interactive x64 Windows desktop, run this command from the repository root in Windows PowerShell. The demo creates two temporary windows, tests a visible green target, covers it while changing its content to blue, then minimizes it. It closes both windows on completion. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +The printed output directory contains PNGs and JSON measurements. The script compiles into a unique temporary directory and removes the executable afterward. A new output directory is required for every run. Compilation errors, unavailable windows, and failed captures produce a nonzero exit. + +To compare an application you select, pass its decimal top-level HWND and a new output directory. This mode captures its current state without changing focus, position, or visibility. Obtain the HWND with a window inspector; a PID is not a window handle. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +Replace the example HWND and output directory. Repeat with the window covered, after its content changes, and after resizing. The screen-copy image includes whatever occupies those screen coordinates. Keep evidence local when other applications can appear there. + +----- + + +## Interpret the output + +Each capture runs in a separate process with a five-second deadline. A hung capture is terminated and recorded as a timeout. JSON records the API return value, image dimensions, elapsed capture time, sampled foreground change, and counts of known marker colors. A successful API return or a valid PNG does not establish that the image contains current target content. + +| Method | Windows facility | What to inspect | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | Whether another window replaces the target pixels. | +| `window-dc` | `GetWindowDC` and GDI `BitBlt` | Whether compositor-backed content is missing or stale. | +| `print` | `PrintWindow`, flags `0` | Whether the target handles print requests. | +| `print-full` | `PrintWindow`, `PW_RENDERFULLCONTENT` | Whether the complete, current client content appears. | + +The demo waits until its visible marker reaches the screen before comparing methods. It samples UI Automation from an MTA thread and records the result in `runtime.json`. Marker checks are intended for the owned fixture; other applications require visual comparison against their actual state. This experiment does not test WGC, clipboard restoration, input, service sharing, or ARM64 compatibility. + +----- + + +## Further Exploration + +- [Provider behavior and desktop acceptance](../../README.md) +- [PrintWindow and its synchronous execution](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK capture flags](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework system requirements](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack window capture source](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### Dev Note + +Research and proposed work below are non-authoritative; the production helper still targets .NET 10 and captures through WGC/Direct3D11. + +The Windows x64 machine used on 2026-10-20 has Framework release `533509` (4.8.1). The Framework-only probe compiled, queried the owned window through `System.Windows.Automation`, and captured images without NuGet dependencies. The current self-contained production helper is approximately 192 MiB; the probe is much smaller because it implements only this experiment. Its size is not an estimate of a complete port. + +For the painted WinForms fixture, all four methods captured the visible green content. After covering the window and changing it to blue, screen copying returned the magenta cover, while window DC copying and both PrintWindow variants returned the new blue content. After minimization, every API reported success but returned only a 314 × 50 image without the content marker. These observations do not establish behavior for other rendering engines or monitors. + +For an owned local HTML page in Edge, window DC copying and ordinary PrintWindow returned black images even while visible. Full-content PrintWindow captured the visible green page. After covering it, JavaScript changed the background to blue and updated the title; full-content PrintWindow captured the updated title with the old green client content. The fresh-content requirement remains unresolved for this case, including whether WGC behaves differently. This is a reason to compare rendering engines before replacing the backend. + +The capture decision must preserve background window observation. `CopyFromScreen` and desktop duplication observe the composed desktop, so they cannot substitute for covered-window capture. DWM thumbnails display another window in a destination window rather than directly returning PNG pixels. WGC supplies Direct3D11 frames by design; removing the Vortice wrapper does not remove that dependency from the API. + +Windows API Code Pack is useful reference material for Shell objects, links, common dialogs, and taskbar integration. Its `TabbedThumbnailScreenCapture` wraps GDI window DC copying and documents limitations for hidden or obstructed controls. It does not provide a general replacement for WGC or target-confirmed clipboard consumption. WinForms already provides ordinary clipboard access, drawing, images, and a message loop; UI Automation is also in the Framework. Add a Code Pack dependency only for a specific capability that removes more maintained code than it introduces. + +Proposed implementation order: + +1. Compare PrintWindow's full-content mode against WGC on Chromium/Electron, WPF, classic controls, changed covered content, mixed DPI, and a hung target. Keep the saved PNGs and observed state together. Select a production backend only after this comparison; do not silently fall back to screen pixels when a window capture fails. +2. Use .NET Framework 4.8 as the runtime port candidate for x64. Keep `System.Windows.Automation`, WinForms, `System.Drawing`, and Windows P/Invoke. Verify the ARM64 runtime and delivery requirements separately; this x64 experiment cannot establish them. +3. Port runtime APIs deliberately: pipe and mutex access control, cancellation and disposal, hashing, and JSON handling. Framework `JavaScriptSerializer` can emit the probe's JSON, but replacing `System.Text.Json` must preserve protocol validation, duplicate-property rejection, numeric limits, and escaping. `JsonSchema.Net` has a netstandard2.0 asset; the installed Vortice version has only modern .NET assets. Avoid introducing a handwritten JSON/schema framework merely to remove a package. +4. Run the owned desktop smoke and shared-service lifetime checks against the selected runtime, then update source preparation and packaging. Remove superseded implementations and dependencies after those checks pass. Keep the shared `cua` API and the macOS provider outside this Windows runtime change. + +The current desktop smoke exposed clipboard prefetch by the Remote Desktop client before the selected editor consumed the data. The pending fix identifies the requesting window's process and leaves the format delayed for other readers. Readers that open the clipboard without an HWND cannot be attributed and time out. The revised native binary cross-compiles, but Smart App Control blocked its execution on this machine. The branch is handed over for human-owned Windows acceptance with an approved signed build or test environment. Earlier smoke results must not be represented as validation of that binary. diff --git a/packages/experimental/cua-windows/native/capture-probe/README.zh.md b/packages/experimental/cua-windows/native/capture-probe/README.zh.md new file mode 100644 index 0000000000..cf07001498 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.zh.md @@ -0,0 +1,93 @@ +--- +description: "使用系统安装的 .NET Framework 对比 Windows 截图方案,并审阅原生运行时迁移计划。" +--- + +# Windows 截图实验 + +[English](README.md) | 中文 + +## 摘要 + +无需安装 .NET SDK 或第三方库,即可对比屏幕复制、窗口 DC 复制和 PrintWindow。此私有实验以 .NET Framework 4.8 为目标,使用 Windows 已安装的编译器和程序集。它不替换提供方的截图实现。 + +## 目录 + +- [运行实验](#run-the-experiment) +- [解读输出](#interpret-the-output) +- [延伸阅读](#further-exploration) +- [开发备注](#dev-note) + +----- + + +## 运行实验 + +在交互式 x64 Windows 桌面上,从仓库根目录使用 Windows PowerShell 运行以下命令。演示创建两个临时窗口,测试可见的绿色目标,在遮挡后将其内容改为蓝色,然后将其最小化。完成后关闭两个窗口。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +打印的输出目录包含 PNG 和 JSON 测量结果。脚本在唯一临时目录中编译,运行后删除可执行文件。每次运行必须使用新的输出目录。编译错误、窗口不可用和截图失败均产生非零退出状态。 + +要对比自行选择的应用,传入其十进制顶层窗口 HWND 和新的输出目录。此模式捕获当前状态,不改变焦点、位置或可见性。可用窗口检查工具取得 HWND;PID 不是窗口句柄。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +替换示例中的 HWND 和输出目录。在窗口被遮挡、内容变化和尺寸变化后重复运行。屏幕复制的图片包含相应屏幕坐标上实际显示的内容;当其他应用可能出现在该位置时,证据应保留在本地。 + +----- + + +## 解读输出 + +每次截图在独立进程中执行,期限为五秒。卡住的截图会被终止,并记录为超时。JSON 记录 API 返回值、图片尺寸、截图耗时、采样到的前台变化以及已知标记颜色的数量。API 返回成功或生成有效 PNG,并不能证明图片包含目标的最新内容。 + +| 方法 | Windows 功能 | 检查内容 | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | 其他窗口是否替代了目标像素。 | +| `window-dc` | `GetWindowDC` 与 GDI `BitBlt` | 合成器承载的内容是否缺失或过时。 | +| `print` | `PrintWindow`,标志 `0` | 目标是否处理打印请求。 | +| `print-full` | `PrintWindow`,`PW_RENDERFULLCONTENT` | 是否包含完整、最新的客户区内容。 | + +演示等待可见标记实际显示到屏幕后,再比较各方法。它在 MTA 线程读取 UI Automation,并将结果记入 `runtime.json`。标记检查适用于自有测试窗口;其他应用需要与实际状态进行视觉比较。本实验不测试 WGC、剪贴板恢复、输入、服务共享或 ARM64 兼容性。 + +----- + + +## 延伸阅读 + +- [提供方行为与桌面验收](../../README.zh.md) +- [PrintWindow 及其同步执行](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK 截图标志](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework 系统要求](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack 窗口截图源码](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### 开发备注 + +以下调研和拟议工作不是正式约定;生产 helper 仍以 .NET 10 为目标,并通过 WGC/Direct3D11 截图。 + +2026-10-20 使用的 Windows x64 机器安装了 Framework 版本标识 `533509`(4.8.1)。仅依赖 Framework 的探针已完成编译,通过 `System.Windows.Automation` 查询自有窗口并截图,无需 NuGet 依赖。当前自包含生产 helper 约为 192 MiB;探针小得多,因为它只实现本实验。其大小不能用来估算完整移植的大小。 + +对于完成绘制的 WinForms 测试窗口,四种方法均捕获了可见的绿色内容。遮挡窗口并将内容改为蓝色后,屏幕复制返回紫红色遮挡窗口,窗口 DC 复制和两种 PrintWindow 模式则返回新的蓝色内容。最小化后,各 API 都报告成功,但仅返回不含内容标记的 314 × 50 图片。这些结果不能证明其他渲染引擎或显示器上的行为。 + +对于 Edge 中的自有本地 HTML 页面,窗口 DC 复制和普通 PrintWindow 即使在窗口可见时也返回黑图。完整内容模式的 PrintWindow 捕获了可见的绿色页面。遮挡后,JavaScript 将背景改为蓝色并更新标题;完整内容模式捕获了更新后的标题,但客户区仍为旧的绿色内容。此场景的内容新鲜度要求尚未解决,包括 WGC 是否有不同行为。这说明替换后端前需要比较不同渲染引擎。 + +截图选型必须保留后台窗口观察能力。`CopyFromScreen` 和桌面复制读取合成后的桌面,因此不能替代遮挡窗口截图。DWM 缩略图在目标窗口中显示另一窗口,而不直接返回 PNG 像素。WGC 的接口本身就提供 Direct3D11 帧;删除 Vortice 包装库并不能消除该 API 的此项依赖。 + +Windows API Code Pack 可用于参考 Shell 对象、链接、通用对话框和任务栏集成。其 `TabbedThumbnailScreenCapture` 封装了 GDI 窗口 DC 复制,并明确说明隐藏或遮挡控件的限制。它不提供 WGC 或确认目标消费剪贴板数据的通用替代品。WinForms 已提供普通剪贴板访问、绘图、图片和消息循环;UI Automation 也属于 Framework。只有在具体能力能删除更多自有维护代码时,才引入 Code Pack 依赖。 + +拟议实现顺序: + +1. 在 Chromium/Electron、WPF、传统控件、遮挡后的内容变化、混合 DPI 及卡死目标上,对比 PrintWindow 完整内容模式与 WGC。将保存的 PNG 与实际状态放在一起。完成对比后再选择生产后端;窗口截图失败时不得静默改用屏幕像素。 +2. 将 .NET Framework 4.8 作为 x64 运行时移植候选,保留 `System.Windows.Automation`、WinForms、`System.Drawing` 和 Windows P/Invoke。单独验证 ARM64 运行时及交付要求;本次 x64 实验不能证明它们。 +3. 明确迁移运行时 API:命名管道和互斥量访问控制、取消和释放、散列及 JSON 处理。Framework 的 `JavaScriptSerializer` 可以输出探针的 JSON,但替代 `System.Text.Json` 必须保留协议校验、重复属性拒绝、数字限制和转义行为。`JsonSchema.Net` 有 netstandard2.0 产物;当前 Vortice 版本只有现代 .NET 产物。避免仅为删除一个依赖包而手写 JSON/schema 框架。 +4. 在所选运行时上执行自有桌面验收和共享服务生命周期检查,再更新源码准备和打包。检查通过后删除被替代的实现与依赖。此 Windows 运行时改动不扩展到共享 `cua` API 或 macOS 提供方。 + +当前桌面验收发现远程桌面客户端会在选定编辑器消费前预读剪贴板。待验证的修复会确认请求窗口所属进程,并为其他读取方继续延迟提供该格式。未携带 HWND 打开剪贴板的读取方无法归属,将超时。修订后的原生二进制已通过交叉编译,但本机 Smart App Control 阻止了它执行。分支交由用户在已获准的签名构建或测试环境中完成 Windows 验收。不能把此前的验收结果视为对该二进制的验证。 diff --git a/packages/experimental/cua-windows/native/capture-probe/app.manifest b/packages/experimental/cua-windows/native/capture-probe/app.manifest new file mode 100644 index 0000000000..64eb2db51c --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/app.manifest @@ -0,0 +1,12 @@ + + + + + + + + + PerMonitorV2 + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/run.ps1 b/packages/experimental/cua-windows/native/capture-probe/run.ps1 new file mode 100644 index 0000000000..4edba996d1 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/run.ps1 @@ -0,0 +1,28 @@ +# Compile and run a private capture experiment using only the installed .NET Framework. +param( + [long]$WindowHandle = 0, + [string]$OutputDirectory = (Join-Path $env:TEMP ("dsh-capture-" + [guid]::NewGuid().ToString("N"))) +) +$ErrorActionPreference = "Stop" +$framework = Join-Path $env:WINDIR "Microsoft.NET\Framework64\v4.0.30319" +$build = Join-Path $PSScriptRoot ("..\..\.probe-build-" + [guid]::NewGuid().ToString("N")) +New-Item -ItemType Directory -Path $build | Out-Null +try { + $executable = Join-Path $build "CaptureProbe.exe" + $compilerArguments = @("/nologo", "/target:exe", "/platform:x64", "/out:$executable", + ("/win32manifest:" + (Join-Path $PSScriptRoot "app.manifest")), + "/r:System.Drawing.dll", "/r:System.Windows.Forms.dll", "/r:System.Web.Extensions.dll", + "/r:$framework\WPF\UIAutomationClient.dll", "/r:$framework\WPF\UIAutomationTypes.dll", + "/r:$framework\WPF\WindowsBase.dll", (Join-Path $PSScriptRoot "CaptureProbe.cs")) + $compiler = Start-Process (Join-Path $framework "csc.exe") -NoNewWindow -Wait -PassThru ` + -ArgumentList ($compilerArguments | ForEach-Object { '"' + $_ + '"' }) + if ($compiler.ExitCode -ne 0) { throw "Capture probe compilation failed: $($compiler.ExitCode)" } + Copy-Item (Join-Path $PSScriptRoot "CaptureProbe.exe.config") "$executable.config" + $probeArguments = if ($WindowHandle -eq 0) { @("--demo", $OutputDirectory) } + else { @("--compare", $WindowHandle, $OutputDirectory) } + $probe = Start-Process $executable -NoNewWindow -Wait -PassThru ` + -ArgumentList ($probeArguments | ForEach-Object { '"' + $_ + '"' }) + if ($probe.ExitCode -ne 0) { throw "Capture probe failed; inspect $OutputDirectory" } + Write-Output "Capture evidence: $OutputDirectory" +} +finally { Remove-Item -LiteralPath $build -Recurse -Force } diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj new file mode 100644 index 0000000000..cb0fda00a0 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0-windows + true + true + enable + enable + dsh-cua-desktop-fixture + true + true + + diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs new file mode 100644 index 0000000000..ed6948f482 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -0,0 +1,95 @@ +// Private desktop fixture: commands inspect or arrange only the windows owned by this process. +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Security.Cryptography; +using System.Text; + +internal sealed class FixtureForm : Form +{ + protected override bool ShowWithoutActivation => true; + internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; + private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; + private int clicks; + private readonly ToolTip tooltip = new(); + + internal FixtureForm(string title) + { + Text = title; + StartPosition = FormStartPosition.Manual; + Location = new(100, 100); + ClientSize = new(500, 300); + Controls.Add(Editor); + Controls.Add(button); + button.Click += (_, _) => clicks++; + tooltip.SetToolTip(button, "CUA hover is retained"); + } + + internal object Inspect() => new + { + text = Editor.Text, clicks, window = Handle.ToInt64(), foreground = GetForegroundWindow().ToInt64(), + cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, + selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, + buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + }; + + protected override void Dispose(bool disposing) + { + if (disposing) tooltip.Dispose(); + base.Dispose(disposing); + } + + [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); +} + +internal static class Program +{ + private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + + [STAThread] + private static void Main() + { + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + Application.EnableVisualStyles(); + using var form = new FixtureForm("DSH CUA owned test window"); + using var sibling = new FixtureForm("DSH CUA sibling test window"); + form.Shown += (_, _) => + { + Write(new { pid = Environment.ProcessId, state = form.Inspect() }); + _ = Task.Run(() => + { + while (Console.ReadLine() is { } command) + { + form.Invoke(() => + { + switch (command) + { + case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; + case "inspect": Write(form.Inspect()); break; + case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; + case "hide": form.Hide(); Write(form.Inspect()); break; + case "resize": form.Width += 50; Write(form.Inspect()); break; + case "clipboard-digest": + Write(new { digest = Convert.ToHexString(SHA256.HashData(Encoding.Unicode.GetBytes(Clipboard.GetText()))) }); + break; + case "close": form.Close(); break; + default: + if (command.StartsWith("allow:", StringComparison.Ordinal) && uint.TryParse(command[6..], out var pid)) + Write(new { allowed = AllowSetForegroundWindow(pid) }); + else Write(new { error = "Unknown fixture command" }); + break; + } + }); + if (command == "close") return; + } + if (!form.IsDisposed) form.BeginInvoke(form.Close); + }); + }; + Application.Run(form); + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AllowSetForegroundWindow(uint processId); +} diff --git a/packages/experimental/cua-windows/native/generate-protocol.ts b/packages/experimental/cua-windows/native/generate-protocol.ts new file mode 100644 index 0000000000..3a23f8140f --- /dev/null +++ b/packages/experimental/cua-windows/native/generate-protocol.ts @@ -0,0 +1,9 @@ +/** Generate Windows native admission from the shared CUA operation definitions. */ +import { readFile, writeFile } from 'node:fs/promises' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' + +const path = new URL('protocol.schema.json', import.meta.url) +const content = nativeProtocol().json +if (process.argv.includes('--check')) { + if (await readFile(path, 'utf8') !== content) throw new Error('Stale Windows CUA native request schema') +} else await writeFile(path, content) diff --git a/packages/experimental/cua-windows/native/packages.lock.json b/packages/experimental/cua-windows/native/packages.lock.json new file mode 100644 index 0000000000..dee2e0c44b --- /dev/null +++ b/packages/experimental/cua-windows/native/packages.lock.json @@ -0,0 +1,95 @@ +{ + "version": 1, + "dependencies": { + "net10.0-windows10.0.19041": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.14, )", + "resolved": "10.0.14", + "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" + }, + "Vortice.Direct3D11": { + "type": "Direct", + "requested": "[3.8.3, )", + "resolved": "3.8.3", + "contentHash": "JgFUswu2mgrSwcd0KRF2AnfeE5VbMEgcicmxPD1g2yXyomPIHbnX3wldBNHPOzzD0URC1WJ/pO1ymfi3imZwvg==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DXGI": "3.8.3" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "SharpGen.Runtime": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "niTtWAUov1F7wZGAlVeEvW+Tnqvg5yTmhI7rxmYu2Utoyu2TbC9tWWpUpMs0PQg5lu5svoYpCAztNjxCqMFP/w==" + }, + "SharpGen.Runtime.COM": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "9lxDFMiepqo3lJQzMSjECCIONeCc2f3Drokgj6HtrTLZcJSftNgcLbD6/iXYj2iphkwgrZb1oLsDOZxoFZkawQ==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta" + } + }, + "Vortice.DirectX": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "nKwSavv0w5rDF7prSefqAVPDcTyqrfZxKFMVfttiXPfm62VdA/1d+b3PhCZpW4xO7jXczXDwjQdWgD1zGsvM8w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "SharpGen.Runtime.COM": "2.4.2-beta", + "Vortice.Mathematics": "2.1.0" + } + }, + "Vortice.DXGI": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "MbAUnTeQ6WD99ctAdrj5CQO2I7oaax0Kt2eVdWSUj0bYP9Ed0726+s7dIHe4+tqhpmINW/dcPt0mNtc72o+E0w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DirectX": "3.8.3" + } + }, + "Vortice.Mathematics": { + "type": "Transitive", + "resolved": "2.1.0", + "contentHash": "KK+SjNSuKdP+zbavekubi+vaeb1Jo4k87ZF6CMkVWjr6RjJwc8peVtmgzXXDIMy4ZC3ZISyk3llY3q65ISOkBQ==" + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + }, + "net10.0-windows10.0.19041/win-arm64": {}, + "net10.0-windows10.0.19041/win-x64": {} + } +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json new file mode 100644 index 0000000000..c25c65c1e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -0,0 +1,1414 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$comment": "Generated from the shared CUA operation schema. Do not edit.", + "title": "dsh-cua native request", + "description": "Host resource fields and private continuations are not model tool parameters. App handles and snapshots belong to one helper; coordinates use window-local native units.", + "oneOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getCapabilities" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listApps" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "findApps" + }, + "params": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "maxAppMatches": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "required": [ + "query", + "maxAppMatches" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getApp" + }, + "params": { + "type": "object", + "properties": { + "selector": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "selector" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "activate" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "show" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listWindows" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getState" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "includeMenus": { + "description": "Expand menu contents; omitted or false shows menu-bar entries only.", + "type": "boolean" + }, + "details": { + "description": "Include identifiers, global native bounds and complete action names.", + "type": "boolean" + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listActions" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "performAction" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "action": { + "type": "string", + "minLength": 1 + }, + "argument": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "action" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:performAction" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "invoke" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "mouseMove" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "click" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "setValue" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "value": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "value" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:setValue" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "selectText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "text": { + "type": "string", + "minLength": 1 + }, + "prefix": { + "type": "string" + }, + "suffix": { + "type": "string" + }, + "selectionType": { + "type": "string", + "enum": [ + "text", + "cursor_before", + "cursor_after" + ] + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "typeText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + } + }, + "required": [ + "appHandle", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "paste" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + }, + "format": { + "type": "string", + "enum": [ + "text", + "html" + ] + }, + "maxClipboardBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 9007199254740991 + }, + "pasteReadTimeoutMs": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "text", + "maxClipboardBytes", + "pasteReadTimeoutMs", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "pressKey" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "modifiers": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "appHandle", + "key" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "sendKeyEvent" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "key", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "scroll" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "deltaLinesX": { + "type": "integer", + "minimum": -10, + "maximum": 10 + }, + "deltaLinesY": { + "type": "integer", + "minimum": -10, + "maximum": 10 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y", + "deltaLinesX", + "deltaLinesY" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "drag" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "fromX": { + "type": "number", + "minimum": 0 + }, + "fromY": { + "type": "number", + "minimum": 0 + }, + "toX": { + "type": "number", + "minimum": 0 + }, + "toY": { + "type": "number", + "minimum": 0 + }, + "durationMs": { + "type": "integer", + "minimum": 1, + "maximum": 5000 + }, + "steps": { + "type": "integer", + "minimum": 1, + "maximum": 240 + } + }, + "required": [ + "appHandle", + "windowId", + "fromX", + "fromY", + "toX", + "toY", + "durationMs", + "steps" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "screenshot" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle", + "windowId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "launchApp" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "permissionStatus" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "applicationIcons" + }, + "params": { + "type": "object", + "properties": { + "paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "paths" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "requestPermission" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "openPermissionSettings" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + } + ] +} diff --git a/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs new file mode 100644 index 0000000000..35c6acdb75 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs @@ -0,0 +1,74 @@ +// Formatting owns no native references or snapshot indices. +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public sealed record AccessibilityNode +{ + public required string Role { get; init; } + public string Name { get; init; } = ""; + public string? Subrole { get; init; } + public string? Help { get; init; } + public string? Identifier { get; init; } + public string? Value { get; init; } + public string? Placeholder { get; init; } + public bool HasValue { get; init; } + public bool? Enabled { get; init; } + public bool? Focused { get; init; } + public bool? Selected { get; init; } + public bool? Expanded { get; init; } + public string? ValueWritable { get; init; } + public bool? SelectionWritable { get; init; } + public bool HasSelection { get; init; } + public TextMatch? Selection { get; init; } + public string? SelectedText { get; init; } + public string[] Actions { get; init; } = []; + public (double X, double Y, double Width, double Height)? Bounds { get; init; } +} + +public static class AccessibilityText +{ + private static string Quote(string value) => JsonSerializer.Serialize(value, WireJson.Options); + + public static bool Retain(AccessibilityNode node) => node.Role is not ("AXGroup" or "AXScrollArea") + || node.Name.Length != 0 || !string.IsNullOrEmpty(node.Help) || node.HasValue || node.Actions.Length != 0 + || node.Enabled == false || node.Focused == true || node.Selected.HasValue || node.Expanded.HasValue; + + public static string Format(AccessibilityNode node, int? index, bool details) + { + var text = new StringBuilder("- "); + if (index is { } number) text.Append('[').Append(number).Append("] "); + text.Append(node.Role); + if (node.Subrole is { Length: > 0 } subrole) text.Append(" subrole=").Append(Quote(subrole)); + if (node.Enabled == false) text.Append(" disabled"); + if (node.Focused == true) text.Append(" focused"); + if (node.Selected is { } selected) text.Append(" selected=").Append(selected ? "true" : "false"); + if (node.Expanded is { } expanded) text.Append(" expanded=").Append(expanded ? "true" : "false"); + if (node.ValueWritable is { } writable) text.Append(" valueWritable=").Append(writable); + if (node.SelectionWritable is { } selectionWritable) text.Append(" selectionWritable=").Append(selectionWritable ? "true" : "false"); + if (node.Name.Length != 0) text.Append(' ').Append(Quote(node.Name)); + if (node.HasValue) text.Append(" = ").Append(node.Value is { } value ? Quote(value) : "unavailable"); + if (node.Placeholder is { } placeholder) text.Append(" placeholder=").Append(Quote(placeholder)); + if (node.Help is { Length: > 0 } help && help != node.Name) text.Append(" help=").Append(Quote(help)); + if (node.HasSelection) + { + if (node.Selection is { } range && node.Value is { } value && range.Start >= 0 && range.Length >= 0 + && range.Start <= value.Length - range.Length) + text.Append(" selection=[").Append(range.Start).Append(',').Append(range.Length).Append(']'); + else text.Append(" selection=unavailable"); + if (node.SelectedText is { Length: > 0 } selectedText) text.Append(" selectedText=").Append(Quote(selectedText)); + } + var actions = details ? node.Actions : node.Actions.Where(action => action is not ("Press" or "Pick" or "ScrollToVisible")).ToArray(); + if (actions.Length != 0) text.Append(" actions=[").Append(string.Join(", ", actions.Select(Quote))).Append(']'); + if (details) + { + if (!string.IsNullOrEmpty(node.Identifier)) text.Append(" id=").Append(Quote(node.Identifier)); + if (index.HasValue && node.Bounds is { } bounds) + text.Append(" bounds=[").Append(string.Join(',', new[] { bounds.X, bounds.Y, bounds.Width, bounds.Height } + .Select(number => number.ToString("G", CultureInfo.InvariantCulture)))).Append(']'); + } + return text.ToString(); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj new file mode 100644 index 0000000000..353ac1afa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -0,0 +1,14 @@ + + + net10.0 + enable + enable + true + win-x64;win-arm64 + false + + + + + + diff --git a/packages/experimental/cua-windows/native/protocol/KeyChord.cs b/packages/experimental/cua-windows/native/protocol/KeyChord.cs new file mode 100644 index 0000000000..74d375ab35 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/KeyChord.cs @@ -0,0 +1,25 @@ +namespace DeepSeek.Cua.Protocol; + +public sealed record KeyChord(string Key, string[] Modifiers) +{ + public static KeyChord Parse(string text, IEnumerable extra) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key name is required"); + var plus = text == "+" || text.EndsWith("++", StringComparison.Ordinal); + var parts = plus ? text[..^1].TrimEnd('+').Split('+', StringSplitOptions.RemoveEmptyEntries) : text.Split('+'); + var key = plus ? "+" : parts[^1]; + if (key.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key chord must end with a key"); + var modifiers = (plus ? parts : parts[..^1]).Concat(extra).Select(NormalizeModifier).Distinct().ToArray(); + return new(key, modifiers); + } + + public static string NormalizeModifier(string value) => value.ToLowerInvariant() switch + { + "control" or "ctrl" => "control", + "shift" => "shift", + "option" or "alt" => "option", + "command" or "cmd" or "meta" or "win" or "windows" => "command", + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows has no general Fn-key injection; use an available application action"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs new file mode 100644 index 0000000000..fe3fe18efc --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs @@ -0,0 +1,23 @@ +// Connection controls never enter the model operation schema. +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public enum NativeControl { Close, Cancel, CompletedCancel } + +/// Cancellation matches the latest request; a late cancellation after its completion is a no-op. +public static class NativeControlFrame +{ + public static NativeControl Parse(JsonElement value, string? requestId, bool completed = false) + { + if (value.ValueKind != JsonValueKind.Object || !value.TryGetProperty("type", out var type) + || type.ValueKind != JsonValueKind.String) + throw new NativeFailure("INVALID_REQUEST", "Expected a native connection control"); + if (type.GetString() == "close" && value.EnumerateObject().Count() == 1) return NativeControl.Close; + if (type.GetString() == "cancel" && value.EnumerateObject().Count() == 2 + && value.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String + && !string.IsNullOrEmpty(requestId) && id.GetString() == requestId) + return completed ? NativeControl.CompletedCancel : NativeControl.Cancel; + throw new NativeFailure("INVALID_REQUEST", "Cancellation requires a matching request; close accepts no fields"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeRequest.cs b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs new file mode 100644 index 0000000000..8cdd6a3293 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs @@ -0,0 +1,99 @@ +// Strict JSONL admission shares the TypeScript operation schema with the macOS provider. +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using Json.Schema; + +namespace DeepSeek.Cua.Protocol; + +/// A native refusal whose code remains visible through the shared CUA client. +public sealed class NativeFailure(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} + +/// Wire encoding preserves readable task text and always emits one JSON value per line. +public static class WireJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + public static readonly UTF8Encoding Utf8 = new(false, true); + + public static JsonElement Parse(string text) + { + using var document = JsonDocument.Parse(text); + RejectDuplicates(document.RootElement); + return document.RootElement.Clone(); + } + + private static void RejectDuplicates(JsonElement value) + { + if (value.ValueKind == JsonValueKind.Object) + { + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in value.EnumerateObject()) + { + if (!names.Add(property.Name)) throw new NativeFailure("INVALID_REQUEST", "Repeated JSON property"); + RejectDuplicates(property.Value); + } + } + else if (value.ValueKind == JsonValueKind.Array) + foreach (var item in value.EnumerateArray()) RejectDuplicates(item); + } +} + +/// Validated operation parameters. Resource fields are supplied only by the Host. +public sealed record NativeRequest(string Id, string Method, JsonElement Params) +{ + private static readonly JsonSchema Schema = LoadSchema(); + + private static JsonSchema LoadSchema() + { + using var stream = typeof(NativeRequest).Assembly.GetManifestResourceStream("DeepSeek.Cua.NativeRequestSchema.json") + ?? throw new InvalidOperationException("The native request schema is missing"); + using var reader = new StreamReader(stream, WireJson.Utf8); + return JsonSchema.FromText(reader.ReadToEnd()); + } + + public static NativeRequest Parse(JsonElement value) + { + if (!Schema.Evaluate(value, new EvaluationOptions { OutputFormat = OutputFormat.Flag }).IsValid) + throw new NativeFailure("INVALID_ARGUMENT", "The request does not match the CUA operation schema"); + return new(value.GetProperty("id").GetString()!, value.GetProperty("method").GetString()!, value.GetProperty("params")); + } +} + +/// Reads bounded UTF-8 frames without allowing an unterminated line to grow without limit. +public sealed class FrameReader(Stream stream) +{ + private readonly byte[] buffer = new byte[4096]; + private int start; + private int end; + + public async Task ReadAsync(int maximumBytes, CancellationToken cancellation) + { + using var line = new MemoryStream(); + while (true) + { + if (start == end) + { + end = await stream.ReadAsync(buffer, cancellation); + start = 0; + if (end == 0) + { + if (line.Length != 0) throw new NativeFailure("INVALID_REQUEST", "Native input ended inside a frame"); + return null; + } + } + var newline = Array.IndexOf(buffer, (byte)'\n', start, end - start); + var count = (newline < 0 ? end : newline + 1) - start; + if (line.Length + count > maximumBytes) throw new NativeFailure("NATIVE_REQUEST_LIMIT", "Request exceeded its byte limit"); + line.Write(buffer, start, count); + start += count; + if (newline >= 0) return WireJson.Utf8.GetString(line.GetBuffer(), 0, checked((int)line.Length - 1)); + } + } +} diff --git a/packages/experimental/cua-windows/native/protocol/TextSelection.cs b/packages/experimental/cua-windows/native/protocol/TextSelection.cs new file mode 100644 index 0000000000..251474b5ab --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/TextSelection.cs @@ -0,0 +1,49 @@ +// Literal selection and CF_HTML encoding are independent of Windows UI Automation. +using System.Globalization; +using System.Text; + +namespace DeepSeek.Cua.Protocol; + +public readonly record struct TextMatch(int Start, int Length); + +public static class TextSelection +{ + /// Find one literal UTF-16 range, with immediately adjacent optional context. + public static TextMatch Find(string value, string text, string? prefix, string? suffix) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "Selection text must not be empty"); + TextMatch? selected = null; + for (var offset = 0; offset <= value.Length - text.Length;) + { + var start = value.IndexOf(text, offset, StringComparison.Ordinal); + if (start < 0) break; + var end = start + text.Length; + var before = prefix is null || (start >= prefix.Length && value.AsSpan(start - prefix.Length, prefix.Length).SequenceEqual(prefix)); + var after = suffix is null || (end + suffix.Length <= value.Length && value.AsSpan(end, suffix.Length).SequenceEqual(suffix)); + if (before && after) + { + if (selected is not null) throw new NativeFailure("AMBIGUOUS_TEXT", "Add immediately adjacent prefix or suffix text"); + selected = new(start, text.Length); + } + offset = start + 1; + } + return selected ?? throw new NativeFailure("TEXT_NOT_FOUND", "Read fresh state before selecting text"); + } +} + +public static class HtmlClipboard +{ + /// CF_HTML offsets count UTF-8 bytes, independently of UTF-16 selection offsets. + public static byte[] Encode(string fragment) + { + const string before = ""; + const string after = ""; + const string template = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\n"; + var headerSize = Encoding.UTF8.GetByteCount(string.Format(CultureInfo.InvariantCulture, template, 0, 0, 0, 0)); + var start = headerSize + Encoding.UTF8.GetByteCount(before); + var end = start + Encoding.UTF8.GetByteCount(fragment); + var header = string.Format(CultureInfo.InvariantCulture, template, headerSize, + end + Encoding.UTF8.GetByteCount(after), start, end); + return Encoding.UTF8.GetBytes(header + before + fragment + after + "\0"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/packages.lock.json b/packages/experimental/cua-windows/native/protocol/packages.lock.json new file mode 100644 index 0000000000..4118720b93 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/packages.lock.json @@ -0,0 +1,37 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "JsonSchema.Net": { + "type": "Direct", + "requested": "[9.4.0, )", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + } + }, + "net10.0/win-arm64": {}, + "net10.0/win-x64": {} + } +} diff --git a/packages/experimental/cua-windows/native/src/Accessibility.cs b/packages/experimental/cua-windows/native/src/Accessibility.cs new file mode 100644 index 0000000000..f1068643f2 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Accessibility.cs @@ -0,0 +1,245 @@ +// One traversal owns both the disclosed indices and their retained UI Automation elements. +using System.Globalization; +using System.Text; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ElementReference(AutomationElement Element, WindowState Window); +internal sealed record Snapshot(string Id, uint Scope, WindowState[] Windows, IReadOnlyDictionary Elements); + +internal static class Accessibility +{ + private static readonly AutomationProperty[] Properties = [ + AutomationElement.ControlTypeProperty, AutomationElement.NameProperty, AutomationElement.HelpTextProperty, + AutomationElement.AutomationIdProperty, AutomationElement.ClassNameProperty, AutomationElement.IsEnabledProperty, + AutomationElement.HasKeyboardFocusProperty, AutomationElement.IsKeyboardFocusableProperty, AutomationElement.IsPasswordProperty, + AutomationElement.BoundingRectangleProperty, AutomationElement.IsInvokePatternAvailableProperty, + AutomationElement.IsValuePatternAvailableProperty, AutomationElement.IsRangeValuePatternAvailableProperty, + AutomationElement.IsTextPatternAvailableProperty, AutomationElement.IsSelectionItemPatternAvailableProperty, + AutomationElement.IsTogglePatternAvailableProperty, AutomationElement.IsExpandCollapsePatternAvailableProperty, + AutomationElement.IsScrollItemPatternAvailableProperty, ValuePattern.ValueProperty, ValuePattern.IsReadOnlyProperty, + RangeValuePattern.ValueProperty, RangeValuePattern.IsReadOnlyProperty, SelectionItemPattern.IsSelectedProperty, + TogglePattern.ToggleStateProperty, ExpandCollapsePattern.ExpandCollapseStateProperty, + ]; + + internal static object State(AppState app, uint selected, int maximumElements, int maximumDepth, + bool includeMenus, bool details, RequestContext context) + { + var all = Windows.Refresh(app, context); + var targets = new[] { all.SingleOrDefault(window => window.Id == selected) + ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window") }; + var rows = new List { "AX scope=window offsets=UTF-16" }; + var elements = new Dictionary(); + var observations = new List<(WindowState Window, WindowGeometry Geometry)>(); + var visited = new HashSet(StringComparer.Ordinal); + var cache = new CacheRequest { AutomationElementMode = AutomationElementMode.Full, TreeScope = TreeScope.Element }; + foreach (var property in Properties) cache.Add(property); + var truncated = false; + var count = 0; + var nextIndex = 0; + var bytes = Encoding.UTF8.GetByteCount(rows[0]); + void Add(string row) + { + bytes += Encoding.UTF8.GetByteCount(row) + 1; + if (bytes > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Accessibility text exceeds the response limit; select a narrower window or reduce traversal limits"); + rows.Add(row); + } + foreach (var window in targets) + { + if (count >= maximumElements) { truncated = true; break; } + var geometry = window.Geometry(app, context); + try + { + var root = context.Ax(() => AutomationElement.FromHandle(window.Handle).GetUpdatedCache(cache)); + Walk(root, window, geometry, 0, 0); + } + catch (ElementNotAvailableException) { throw new NativeFailure("STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state without repeating input"); } + var after = window.Geometry(app, context); + if (after.Pixels.Width != geometry.Pixels.Width || after.Pixels.Height != geometry.Pixels.Height || after.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during AX observation; read fresh state"); + observations.Add((window, after)); + } + if (truncated) Add($"[truncated: maxElements={maximumElements}, maxDepth={maximumDepth}]"); + DesktopSession.RequireInteractive(); + var scope = selected; + var snapshot = new Snapshot(Guid.NewGuid().ToString("N"), scope, targets, elements); + var result = new + { + appHandle = app.Handle, pid = 4, windowId = selected, + focusedWindowId = (uint?)Windows.Focused(app, all)?.Id, + snapshotId = snapshot.Id, tree = string.Join('\n', rows), windows = all.Select(window => window.Describe(app, context)).ToArray(), truncated, + }; + context.Check(); + app.Snapshots[scope] = snapshot; + foreach (var observation in observations) observation.Window.Observe(observation.Geometry); + return result; + + void Walk(AutomationElement element, WindowState window, WindowGeometry geometry, int depth, int indent) + { + context.Check(); + if (count >= maximumElements || depth >= maximumDepth) { truncated = true; return; } + count++; + if (!visited.Add(string.Join(',', context.Ax(element.GetRuntimeId)))) return; + var node = Read(element, window, geometry, context); + var retained = AccessibilityText.Retain(node); + if (retained) + { + int? index = null; + if (node.Enabled != false && (node.Actions.Length != 0 || node.ValueWritable == "true" || node.SelectionWritable == true)) + { + index = nextIndex++; + elements.Add(index.Value, new(element, window)); + } + Add(new string(' ', indent * 2) + AccessibilityText.Format(node, index, details)); + } + if (!includeMenus && node.Role == "AXMenu") + { + Add(new string(' ', (indent + 1) * 2) + "[menu contents omitted; includeMenus:true]"); + return; + } + var first = context.Ax(() => TreeWalker.ControlViewWalker.GetFirstChild(element, cache)); + if (first is not null && depth + 1 >= maximumDepth) { truncated = true; return; } + for (var child = first; child is not null; + child = context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache))) + { + Walk(child, window, geometry, depth + 1, indent + (retained ? 1 : 0)); + if (count >= maximumElements) + { + if (context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache)) is not null) truncated = true; + break; + } + } + } + } + + private static object Property(AutomationElement element, AutomationProperty property) => element.GetCachedPropertyValue(property, true); + private static bool Flag(AutomationElement element, AutomationProperty property) => Property(element, property) is true; + private static string Text(AutomationElement element, AutomationProperty property) => Property(element, property) as string ?? ""; + + private static AccessibilityNode Read(AutomationElement element, WindowState window, WindowGeometry geometry, RequestContext context) + { + var type = Property(element, AutomationElement.ControlTypeProperty) as ControlType ?? ControlType.Custom; + var actions = new List(); + if (Flag(element, AutomationElement.IsInvokePatternAvailableProperty)) actions.Add("Press"); + if (Flag(element, AutomationElement.IsTogglePatternAvailableProperty)) actions.Add("Toggle"); + if (Flag(element, AutomationElement.IsSelectionItemPatternAvailableProperty)) actions.Add("Pick"); + if (Flag(element, AutomationElement.IsExpandCollapsePatternAvailableProperty)) { actions.Add("Expand"); actions.Add("Collapse"); } + if (Flag(element, AutomationElement.IsScrollItemPatternAvailableProperty)) actions.Add("ScrollToVisible"); + if (Flag(element, AutomationElement.IsKeyboardFocusableProperty)) actions.Add("Focus"); + if (type == ControlType.Window) actions.Add("Raise"); + var password = Flag(element, AutomationElement.IsPasswordProperty); + string? value = null; + var hasValue = false; + string? writable = type == ControlType.Edit || type == ControlType.Document ? "unknown" : null; + if (Flag(element, AutomationElement.IsValuePatternAvailableProperty)) + { + hasValue = true; + if (!password) value = Property(element, ValuePattern.ValueProperty) as string; + writable = Property(element, ValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Flag(element, AutomationElement.IsRangeValuePatternAvailableProperty)) + { + hasValue = true; + if (Property(element, RangeValuePattern.ValueProperty) is double number) value = number.ToString("G", CultureInfo.InvariantCulture); + writable = Property(element, RangeValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Property(element, TogglePattern.ToggleStateProperty) is ToggleState toggle) + { + hasValue = true; value = toggle == ToggleState.Indeterminate ? "mixed" : toggle == ToggleState.On ? "true" : "false"; + } + bool? selectionWritable = null; + var hasSelection = false; + TextMatch? selection = null; + string? selectedText = null; + if (!password && Flag(element, AutomationElement.IsTextPatternAvailableProperty)) + { + var text = context.Ax(() => (TextPattern)element.GetCurrentPattern(TextPattern.Pattern)); + var document = context.Ax(() => text.DocumentRange); + value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + hasValue = true; + selectionWritable = context.Ax(() => text.SupportedTextSelection) != SupportedTextSelection.None; + hasSelection = true; + var ranges = context.Ax(text.GetSelection); + if (ranges.Length == 1) + { + var prefix = context.Ax(document.Clone); + context.Ax(() => { prefix.MoveEndpointByRange(TextPatternRangeEndpoint.End, ranges[0], TextPatternRangeEndpoint.Start); return true; }); + var start = context.Ax(() => prefix.GetText(context.Config.MaxResponseBytes)).Length; + selectedText = context.Ax(() => ranges[0].GetText(context.Config.MaxResponseBytes)); + selection = new(start, selectedText.Length); + } + } + var role = Role(type, password, value); + var bounds = Property(element, AutomationElement.BoundingRectangleProperty) is System.Windows.Rect rectangle && !rectangle.IsEmpty + ? ((double, double, double, double)?)(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height) : null; + var expanded = Property(element, ExpandCollapsePattern.ExpandCollapseStateProperty) is ExpandCollapseState state + ? state == ExpandCollapseState.Expanded ? true : state == ExpandCollapseState.Collapsed ? false : (bool?)null : null; + return new() + { + Role = role, Name = Text(element, AutomationElement.NameProperty), Help = Text(element, AutomationElement.HelpTextProperty), + Identifier = Text(element, AutomationElement.AutomationIdProperty), Subrole = type == ControlType.Custom ? Text(element, AutomationElement.ClassNameProperty) : null, + Value = value, HasValue = hasValue, ValueWritable = writable, + Enabled = Property(element, AutomationElement.IsEnabledProperty) as bool?, Focused = Property(element, AutomationElement.HasKeyboardFocusProperty) as bool?, + Selected = Property(element, SelectionItemPattern.IsSelectedProperty) as bool?, Expanded = expanded, + HasSelection = hasSelection, Selection = selection, SelectedText = selectedText, SelectionWritable = selectionWritable, + Actions = actions.ToArray(), Bounds = bounds, + }; + } + + private static string Role(ControlType type, bool password, string? value) + { + if (password) return "AXSecureTextField"; + if (type == ControlType.Edit) return value?.Contains('\n') == true ? "AXTextArea" : "AXTextField"; + if (type == ControlType.Document) return "AXTextArea"; + if (type == ControlType.Button) return "AXButton"; + if (type == ControlType.CheckBox) return "AXCheckBox"; + if (type == ControlType.RadioButton) return "AXRadioButton"; + if (type == ControlType.Text) return "AXStaticText"; + if (type == ControlType.Window) return "AXWindow"; + if (type == ControlType.MenuBar) return "AXMenuBar"; + if (type == ControlType.Menu) return "AXMenu"; + if (type == ControlType.MenuItem) return "AXMenuItem"; + if (type == ControlType.ComboBox) return "AXComboBox"; + if (type == ControlType.List) return "AXList"; + if (type == ControlType.ListItem) return "AXRow"; + if (type == ControlType.Tree) return "AXOutline"; + if (type == ControlType.TreeItem) return "AXRow"; + if (type == ControlType.Tab) return "AXTabGroup"; + if (type == ControlType.TabItem) return "AXRadioButton"; + if (type == ControlType.Slider) return "AXSlider"; + if (type == ControlType.Spinner) return "AXIncrementor"; + if (type == ControlType.ScrollBar) return "AXScrollBar"; + if (type == ControlType.Image) return "AXImage"; + if (type == ControlType.Hyperlink) return "AXLink"; + if (type == ControlType.Table || type == ControlType.DataGrid) return "AXTable"; + return "AXGroup"; + } + + internal static ElementReference Element(AppState app, string snapshotId, string elementId, RequestContext context) + { + if (!int.TryParse(elementId, NumberStyles.None, CultureInfo.InvariantCulture, out var index)) + throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + Windows.Refresh(app, context); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before using element identifiers"); + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId) + ?? throw new NativeFailure("STALE_SNAPSHOT", "Read fresh AX state before using element identifiers"); + if (snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != selected.Id) + throw new NativeFailure("STALE_SNAPSHOT", "Use an observation from the selected window"); + if (!snapshot.Elements.TryGetValue(index, out var element)) throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + element.Window.Geometry(app, context); + if (!context.Ax(() => element.Element.Current.IsEnabled)) throw new NativeFailure("ELEMENT_DISABLED", "The element is disabled"); + return element; + } + + internal static void RequireSnapshot(AppState app, string snapshotId, uint windowId) + { + var selected = app.SelectedWindow; + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId); + if (snapshot is null || selected is null || selected.Id != windowId + || snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != windowId) + throw new NativeFailure("STALE_SNAPSHOT", "Use a fresh observation from the selected window"); + } +} diff --git a/packages/experimental/cua-windows/native/src/AccessibilityActions.cs b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs new file mode 100644 index 0000000000..ae21c9610f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs @@ -0,0 +1,163 @@ +// Actions use retained UIA references only after snapshot and window validation. +using System.Globalization; +using System.Text.Json; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class AccessibilityActions +{ + private static T Pattern(AutomationElement element, AutomationPattern pattern, RequestContext context) where T : BasePattern + { + object? value = null; + if (!context.Ax(() => element.TryGetCurrentPattern(pattern, out value))) + throw new NativeFailure("UNSUPPORTED", "The control does not expose this accessibility action"); + return (T)value!; + } + + internal static string[] Actions(ElementReference reference, RequestContext context) + { + var element = reference.Element; + var actions = new List(); + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out _))) actions.Add("Press"); + if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out _))) actions.Add("Toggle"); + if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out _))) actions.Add("Pick"); + if (context.Ax(() => element.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out _))) { actions.Add("Expand"); actions.Add("Collapse"); } + if (context.Ax(() => element.TryGetCurrentPattern(ScrollItemPattern.Pattern, out _))) actions.Add("ScrollToVisible"); + if (context.Ax(() => element.Current.IsKeyboardFocusable)) actions.Add("Focus"); + if (context.Ax(() => element.Current.ControlType) == ControlType.Window) actions.Add("Raise"); + return actions.ToArray(); + } + + internal static void Perform(AppState app, ElementReference reference, string action, JsonElement? argument, RequestContext context) + { + if (argument is { } value && value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + throw new NativeFailure("INVALID_ARGUMENT", "This accessibility action does not accept an argument"); + Secondary(app, reference, action, context); + } + + internal static bool Invoke(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else return false; + return true; + } + + internal static bool Click(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out pattern))) + context.Ax(() => { ((TogglePattern)pattern!).Toggle(); return true; }); + else return false; + return true; + } + + internal static void SetValue(ElementReference reference, JsonElement value, RequestContext context) + { + if (value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number) + || value.ValueKind == JsonValueKind.Number && (!value.TryGetDouble(out var numeric) || !double.IsFinite(numeric))) + throw new NativeFailure("INVALID_ARGUMENT", "The value must be a string or a finite number"); + object? pattern = null; + if (context.Ax(() => reference.Element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))) + { + var setter = (ValuePattern)pattern!; + if (context.Ax(() => setter.Current.IsReadOnly)) throw new NativeFailure("UNSUPPORTED", "The control value is read-only"); + var text = value.ValueKind == JsonValueKind.String + ? value.GetString()! : value.GetDouble().ToString("G", CultureInfo.InvariantCulture); + context.Ax(() => { setter.SetValue(text); return true; }); + return; + } + var number = double.NaN; + if (value.ValueKind == JsonValueKind.Number) { if (!value.TryGetDouble(out number)) number = double.NaN; } + else if (!double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out number)) number = double.NaN; + if (!double.IsFinite(number)) throw new NativeFailure("INVALID_ARGUMENT", "This control requires a finite numeric value"); + var range = Pattern(reference.Element, RangeValuePattern.Pattern, context); + var current = context.Ax(() => range.Current); + if (current.IsReadOnly || number < current.Minimum || number > current.Maximum) + throw new NativeFailure("UNSUPPORTED", "The control cannot accept this value"); + context.Ax(() => { range.SetValue(number); return true; }); + } + + internal static void Secondary(AppState app, ElementReference reference, string action, RequestContext context) + { + switch (action.ToLowerInvariant()) + { + case "press": + context.Ax(() => { Pattern(reference.Element, InvokePattern.Pattern, context).Invoke(); return true; }); + break; + case "pick": + context.Ax(() => { Pattern(reference.Element, SelectionItemPattern.Pattern, context).Select(); return true; }); + break; + case "toggle": + context.Ax(() => { Pattern(reference.Element, TogglePattern.Pattern, context).Toggle(); return true; }); + break; + case "expand": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Expand(); return true; }); + break; + case "collapse": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Collapse(); return true; }); + break; + case "scrolltovisible": + context.Ax(() => { Pattern(reference.Element, ScrollItemPattern.Pattern, context).ScrollIntoView(); return true; }); + break; + case "focus": + context.Ax(() => { reference.Element.SetFocus(); return true; }); + break; + case "raise": + if (context.Ax(() => reference.Element.Current.ControlType) != ControlType.Window) + throw new NativeFailure("UNSUPPORTED", "Raise is available only on the observed window element"); + Windows.Activate(app, reference.Window, context); + break; + default: throw new NativeFailure("UNSUPPORTED", "Use an action name from a fresh details:true observation"); + } + } + + internal static void SelectText(ElementReference reference, string text, string? prefix, string? suffix, + string selectionType, RequestContext context) + { + var pattern = Pattern(reference.Element, TextPattern.Pattern, context); + if (context.Ax(() => pattern.SupportedTextSelection) == SupportedTextSelection.None) + throw new NativeFailure("UNSUPPORTED", "The control does not support text selection"); + var document = context.Ax(() => pattern.DocumentRange); + var value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + var expected = TextSelection.Find(value, text, prefix, suffix); + var search = context.Ax(document.Clone); + TextPatternRange? selected = null; + while (true) + { + context.Check(); + var found = context.Ax(() => search.FindText(text, false, false)); + if (found is null) break; + var before = context.Ax(document.Clone); + context.Ax(() => { before.MoveEndpointByRange(TextPatternRangeEndpoint.End, found, TextPatternRangeEndpoint.Start); return true; }); + if (context.Ax(() => before.GetText(context.Config.MaxResponseBytes)).Length == expected.Start) { selected = found; break; } + var oldStart = context.Ax(search.Clone); + context.Ax(() => { search.MoveEndpointByRange(TextPatternRangeEndpoint.Start, found, TextPatternRangeEndpoint.Start); + search.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1); return true; }); + if (context.Ax(() => search.CompareEndpoints(TextPatternRangeEndpoint.Start, oldStart, TextPatternRangeEndpoint.Start)) <= 0) break; + } + if (selected is null || context.Ax(() => selected.GetText(context.Config.MaxResponseBytes)) != text) + throw new NativeFailure("SELECTION_CHANGED", "The control text changed; read fresh state before selecting"); + if (selectionType == "cursor_before") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.Start); return true; }); + else if (selectionType == "cursor_after") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.End); return true; }); + context.Ax(() => { selected.Select(); return true; }); + var actual = context.Ax(pattern.GetSelection); + if (actual.Length != 1 || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.Start)) != 0 + || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.End)) != 0) + throw new NativeFailure("SELECTION_CHANGED", "The control did not retain the requested selection; read fresh state"); + } +} diff --git a/packages/experimental/cua-windows/native/src/Applications.cs b/packages/experimental/cua-windows/native/src/Applications.cs new file mode 100644 index 0000000000..eff65c0497 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Applications.cs @@ -0,0 +1,291 @@ +// Application consent identifies the executable before any launch or UI observation. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.Win32; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ApplicationIdentity(string Id, string Name, string ExecutablePath, bool Persistable); +internal sealed record RunningApplication(int Pid, long Started, string Path, string Name); +internal sealed record InstalledApplication(string Name, string Path); + +internal sealed class AppState(string handle, ApplicationIdentity authorization, string digest, RunningApplication? process) : IDisposable +{ + internal string Handle { get; } = handle; + internal WindowState? SelectedWindow { get; set; } + internal ApplicationIdentity Authorization { get; } = authorization; + internal string Digest { get; } = digest; + internal RunningApplication? Process { get; set; } = process; + internal Dictionary Windows { get; } = []; + internal Dictionary Snapshots { get; } = []; + private uint nextWindowId; + private System.Diagnostics.Process? owner; + internal uint AllocateWindowId() + { + if (nextWindowId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Select the application again to allocate new window identifiers"); + return ++nextWindowId; + } + internal RunningApplication RequireProcess() + { + var selected = Process ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Application launch requires Host authorization"); + try + { + owner ??= System.Diagnostics.Process.GetProcessById(selected.Pid); + if (owner.HasExited || Applications.Started(owner) != selected.Started) + throw new NativeFailure("STALE_APP", "Select the application again after its process changes"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "Select the application again after it exits"); } + return selected; + } + public void Dispose() { owner?.Dispose(); Snapshots.Clear(); Windows.Clear(); } +} + +internal static class Applications +{ + internal static object Icons(JsonElement parameters, RequestContext context) + { + var paths = parameters.GetProperty("paths"); + if (paths.ValueKind != JsonValueKind.Array) + throw new NativeFailure("INVALID_ARGUMENT", "paths must be an array"); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var element in paths.EnumerateArray()) + { + context.Check(); + if (element.ValueKind != JsonValueKind.String || string.IsNullOrEmpty(element.GetString())) + throw new NativeFailure("INVALID_ARGUMENT", "paths must contain nonempty strings"); + var path = element.GetString()!; + try + { + using var icon = System.Drawing.Icon.ExtractAssociatedIcon(path); + if (icon is null) continue; + using var original = icon.ToBitmap(); + using var bitmap = new System.Drawing.Bitmap(original, new System.Drawing.Size(64, 64)); + using var stream = new MemoryStream(); + bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); + result[path] = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException + or System.ComponentModel.Win32Exception) + { + // Missing or unreadable executable metadata has no icon; application access is unchanged. + } + } + return result; + } + + private static readonly int SessionId = CurrentSession(); + private static int CurrentSession() { using var process = System.Diagnostics.Process.GetCurrentProcess(); return process.SessionId; } + internal static long Started(System.Diagnostics.Process process) + { + if (!Win32.GetProcessTimes(process.SafeHandle, out var created, out _, out _, out _)) + throw new NativeFailure("STALE_APP", "The process lifetime is unavailable; select the application again"); + return created; + } + internal static string CanonicalPath(string path) + { + using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + var capacity = Win32.GetFinalPathNameByHandle(handle, new StringBuilder(), 0, 0); + if (capacity == 0) throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path could not be resolved"); + var text = new StringBuilder(checked((int)capacity + 1)); + if (Win32.GetFinalPathNameByHandle(handle, text, (uint)text.Capacity, 0) == 0) + throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path changed during selection"); + var resolved = text.ToString(); + return resolved.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase) + ? @"\\" + resolved[8..] : resolved.StartsWith(@"\\?\", StringComparison.Ordinal) ? resolved[4..] : resolved; + } + + internal static string Digest(string path) + { + using var file = File.OpenRead(path); + return Convert.ToHexStringLower(SHA256.HashData(file)); + } + + private static string? VerifiedSigner(string path) + { + var file = new Win32.TrustFile { Size = (uint)Marshal.SizeOf(), Path = path }; + var memory = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(file, memory, false); + var data = new Win32.TrustData + { + Size = (uint)Marshal.SizeOf(), UiChoice = 2, UnionChoice = 1, + File = memory, StateAction = 1, ProviderFlags = 0x1000 | 0x80, + }; + var action = new Guid("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); + try + { + if (Win32.WinVerifyTrust(0, ref action, ref data) != 0) return null; + var provider = Win32.WTHelperProvDataFromStateData(data.StateData); + var signerPointer = provider == 0 ? 0 : Win32.WTHelperGetProvSignerFromChain(provider, 0, false, 0); + if (signerPointer == 0) return null; + var signer = Marshal.PtrToStructure(signerPointer); + if (signer.CertificateCount == 0 || signer.Certificates == 0) return null; + var certificate = Marshal.PtrToStructure(signer.Certificates); + if (certificate.Certificate == 0) return null; + var context = Marshal.PtrToStructure(certificate.Certificate); + if (context.Encoded == 0 || context.EncodedSize == 0 || context.EncodedSize > int.MaxValue) return null; + var bytes = new byte[(int)context.EncodedSize]; + Marshal.Copy(context.Encoded, bytes, 0, bytes.Length); + return Convert.ToHexStringLower(SHA256.HashData(bytes)); + } + catch (CryptographicException) { return null; } + finally + { + data.StateAction = 2; + Win32.WinVerifyTrust(0, ref action, ref data); + Marshal.DestroyStructure(memory); + Marshal.FreeHGlobal(memory); + } + } + + internal static (ApplicationIdentity Identity, string Digest) Identify(string path, string name, RunningApplication? process) + { + var canonical = CanonicalPath(path); + var digest = Digest(canonical); + var signer = VerifiedSigner(canonical); + var requirement = signer is not null ? "signed:" + signer + : process is null ? "pending:" + digest : $"process:{process.Pid}:{process.Started}:{digest}"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("win32\0" + canonical + "\0" + requirement))); + return (new(id, name, canonical, signer is not null), digest); + } + + internal static RunningApplication Running(int pid) + { + try + { + using var process = System.Diagnostics.Process.GetProcessById(pid); + if (process.SessionId != SessionId) + throw new NativeFailure("UNSUPPORTED_SESSION", "Select an application in this interactive desktop session"); + var path = process.MainModule?.FileName + ?? throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The application executable is unavailable"); + return new(pid, Started(process), CanonicalPath(path), process.ProcessName); + } + catch (System.ComponentModel.Win32Exception) + { + throw new NativeFailure("PERMISSION_DENIED", "Windows refused the application identity; its privilege level may exceed the helper's"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "The selected process has exited"); } + } + + internal static IReadOnlyList List() + { + var ids = new HashSet(); + Win32.EnumWindows((window, _) => + { + if (Win32.IsWindowVisible(window)) + { + Win32.GetWindowThreadProcessId(window, out var pid); + if (pid != 0 && pid <= int.MaxValue) ids.Add((int)pid); + } + return true; + }, 0); + var result = new List(); + foreach (var pid in ids.Order()) + { + try { result.Add(Running(pid)); } + catch (NativeFailure) { /* Processes can exit or deny metadata while the desktop is enumerated. */ } + catch (IOException) { /* A disappearing executable is not a selectable application. */ } + } + return result; + } + + internal static IReadOnlyList Find(string query, int maximum, bool exact = false) + { + var found = new Dictionary(StringComparer.Ordinal); + void Add(string name, string path) + { + if (exact ? !string.Equals(name, query, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetFileName(path), query, StringComparison.OrdinalIgnoreCase) + : !name.Contains(query, StringComparison.OrdinalIgnoreCase) && !Path.GetFileName(path).Contains(query, StringComparison.OrdinalIgnoreCase)) return; + if (!Path.IsPathFullyQualified(path) || !path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || !File.Exists(path)) return; + found.TryAdd(CanonicalPath(path), new(name, CanonicalPath(path))); + if (found.Count > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific application name or executable path"); + } + foreach (var app in List()) Add(app.Name, app.Path); + foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine }) + foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }) + { + using var registry = RegistryKey.OpenBaseKey(hive, view); + using var paths = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"); + if (paths is null) continue; + foreach (var key in paths.GetSubKeyNames()) + { + using var app = paths.OpenSubKey(key); + if (app?.GetValue(null) is string path) Add(Path.GetFileNameWithoutExtension(key), Environment.ExpandEnvironmentVariables(path.Trim('"'))); + } + } + foreach (var directory in new[] { Environment.SpecialFolder.Programs, Environment.SpecialFolder.CommonPrograms }) + { + var root = Environment.GetFolderPath(directory); + if (!Directory.Exists(root)) continue; + foreach (var link in Directory.EnumerateFiles(root, "*.lnk", new EnumerationOptions + { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint })) + { + var name = Path.GetFileNameWithoutExtension(link); + if (!name.Contains(query, StringComparison.OrdinalIgnoreCase)) continue; + var target = ShellBroker.ShortcutTarget(link); + if (target is not null) Add(name, target); + } + } + return found.Values.OrderBy(app => app.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + } + + internal static AppState Select(string selector, IEnumerable retained) + { + RunningApplication? running = null; + string path, name; + if (int.TryParse(selector, out var pid)) + { + running = Running(pid); path = running.Path; name = running.Name; + } + else + { + var absolute = Path.IsPathFullyQualified(selector) ? CanonicalPath(selector) : null; + var matches = List().Where(app => absolute is not null ? string.Equals(app.Path, absolute, StringComparison.Ordinal) : string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase) + ).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Select one of the observed process IDs"); + if (matches.Length == 1) { running = matches[0]; path = running.Path; name = running.Name; } + else if (absolute is not null) { path = absolute; name = Path.GetFileNameWithoutExtension(path); } + else + { + var installed = Find(selector, 1, true).Where(app => string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (installed.Length != 1) throw new NativeFailure(installed.Length == 0 ? "APP_NOT_FOUND" : "AMBIGUOUS_APP", "Use findApps, an executable path, or an observed PID"); + path = installed[0].Path; name = installed[0].Name; + } + } + if (!path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) throw new NativeFailure("UNSUPPORTED", "Select a Windows application executable"); + if (running is not null) + { + var previous = retained.FirstOrDefault(app => app.Process?.Pid == running.Pid && app.Process.Started == running.Started); + if (previous is not null) return previous; + } + var identity = Identify(path, name, running); + return new(Guid.NewGuid().ToString("N"), identity.Identity, identity.Digest, running); + } + + internal static async Task Launch(AppState app, RequestContext context) + { + if (app.Process is not null) { app.RequireProcess(); return; } + var identity = app.Authorization; + if (Digest(identity.ExecutablePath) != app.Digest) throw new NativeFailure("STALE_APP", "The selected executable changed before launch; select it again"); + context.Check(); + await context.Sta.Invoke(() => ShellBroker.Launch(identity.ExecutablePath), context.Cancellation); + while (true) + { + context.Check(); + var matches = List().Where(candidate => string.Equals(candidate.Path, identity.ExecutablePath, StringComparison.Ordinal)).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Several matching processes started; select an observed PID"); + if (matches.Length == 1) + { + if (Digest(matches[0].Path) != app.Digest) throw new NativeFailure("STALE_APP", "The launched executable differs from the approved file"); + app.Process = matches[0]; + return; + } + await Task.Delay(context.Config.PollIntervalMs, context.Cancellation); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/CaptureAdmission.cs b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs new file mode 100644 index 0000000000..5014f34f85 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs @@ -0,0 +1,34 @@ +// The native operation owns its capture slot until cleanup finishes, independently of the caller's await. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class CaptureAdmission +{ + private readonly object gate = new(); + private Task? pending; + + internal Task Start(Func> operation) + { + lock (gate) + { + if (pending is { IsCompleted: false }) + throw new NativeFailure("CAPTURE_BUSY", "The previous Windows capture is still releasing its resources; UIA and input remain available"); + pending = operation(); + _ = pending.ContinueWith(completed => { _ = completed.Exception; }, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + return pending; + } + } + + internal async Task Join() + { + Task? active; + lock (gate) active = pending; + if (active is not null) + { + try { await active; } + catch (Exception error) { _ = error; /* The requesting connection owns the capture failure. */ } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs new file mode 100644 index 0000000000..6244fc9fa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs @@ -0,0 +1,183 @@ +// Delayed rendering waits for clipboard data consumption before restoring the previous formats. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClipboardPaste +{ + private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) + { + internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private uint sequence = originalSequence; + private bool replaced; + private bool restoring; + private bool changed; + private bool rendered; + + internal void Begin() + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) throw new NativeFailure("CLIPBOARD_CHANGED", "The clipboard changed before paste; it was not replaced"); + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); + replaced = true; + control.ClipboardMessage = Message; + Marshal.SetLastPInvokeError(0); + Win32.SetClipboardData(format, 0); + var error = Marshal.GetLastPInvokeError(); + sequence = Win32.GetClipboardSequenceNumber(); + if (error != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused the temporary clipboard format"); + } + finally { Win32.CloseClipboard(); } + // CloseClipboard can add synthesized formats and advance the sequence. + sequence = Win32.GetClipboardSequenceNumber(); + } + + private bool Message(int message, nint parameter) + { + if (message == 0x0307 && !restoring) + { + changed = true; + Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer replaced the clipboard; observe before deciding on further input")); + return true; + } + if (message is not (0x0305 or 0x0306)) return false; + if (message == 0x0305 && (uint)parameter != format) return false; + if (message == 0x0305) + { + Win32.GetWindowThreadProcessId(Win32.GetOpenClipboardWindow(), out var readerPid); + // Clipboard monitors can request data before the target handles Control+V. + // Leave the format delayed until the selected application requests it. + if (readerPid != targetPid) return true; + } + var opened = false; + try + { + if (Win32.GetClipboardOwner() != control.Handle) return true; + if (message == 0x0306) + { + if (!Win32.OpenClipboard(control.Handle)) return true; + opened = true; + } + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + Publish(format, payload); + rendered = true; + sequence = Win32.GetClipboardSequenceNumber(); + if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); + else if (message == 0x0305) Consumed.TrySetResult(); + } + catch (Exception error) { Consumed.TrySetException(error); } + finally { if (opened) Win32.CloseClipboard(); } + return true; + } + + internal bool Restore() + { + if (!replaced) return true; + if (Win32.GetClipboardOwner() != control.Handle) { control.ClipboardMessage = null; return true; } + if (!Win32.OpenClipboard(control.Handle)) return false; + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + if (changed) + { + // A later writer keeps its data; fulfill any remaining promise before releasing its renderer. + if (!rendered) Publish(format, payload); + return true; + } + restoring = true; + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard restoration"); + foreach (var original in previous) Publish(original.Format, original.Data); + return true; + } + finally { control.ClipboardMessage = null; Win32.CloseClipboard(); } + } + } + + private static void Publish(uint format, byte[] bytes) + { + var memory = Win32.GlobalAlloc(0x0002, (nuint)bytes.Length); + if (memory == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory allocation failed"); + try + { + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory could not be locked"); + try { Marshal.Copy(bytes, 0, pointer, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + if (Win32.SetClipboardData(format, memory) == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard data"); + memory = 0; + } + finally { if (memory != 0) Win32.GlobalFree(memory); } + } + + private static Transaction Prepare(ServiceControl control, int targetPid, string text, string format, int maximumBytes) + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + var previous = new List<(uint, byte[])>(); + long total = 0; + uint current = 0; + while (true) + { + Marshal.SetLastPInvokeError(0); + current = Win32.EnumClipboardFormats(current); + if (current == 0) + { + if (Marshal.GetLastPInvokeError() != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The existing clipboard formats could not be enumerated"); + break; + } + if (current is 3 or 0x0083) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The clipboard contains a metafile with nested handles; paste left it unchanged"); + var memory = Win32.GetClipboardData(current); + var size = memory == 0 ? 0 : Win32.GlobalSize(memory); + if (size == 0 || size > int.MaxValue) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard includes a format that cannot be preserved as bytes; paste left it unchanged"); + total += (long)size; + if (total > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The existing clipboard exceeds maxClipboardBytes; it was not replaced"); + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard data could not be read; it was not replaced"); + var bytes = new byte[(int)size]; + try { Marshal.Copy(pointer, bytes, 0, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + previous.Add((current, bytes)); + } + var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); + var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; + if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); + return new(control, targetPid, nativeFormat, payload, previous, Win32.GetClipboardSequenceNumber()); + } + finally { Win32.CloseClipboard(); } + } + + internal async Task Paste(AppState app, string text, string format, int maximumBytes, int readTimeoutMs, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var targetPid = app.RequireProcess().Pid; + var transaction = await context.Sta.Invoke(control => Prepare(control, targetPid, text, format, maximumBytes), context.Cancellation); + try + { + await context.Sta.Invoke(() => transaction.Begin(), context.Cancellation); + Input.Press(app, "v", ["control"], context); + try { await transaction.Consumed.Task.WaitAsync(TimeSpan.FromMilliseconds(readTimeoutMs), context.Cancellation); } + catch (TimeoutException) + { + throw new NativeFailure("PASTE_NOT_CONSUMED", "The target did not request clipboard data before pasteReadTimeoutMs; observe before deciding on further input"); + } + } + finally + { + var clock = Stopwatch.StartNew(); + while (!await context.Sta.Invoke(_ => transaction.Restore(), CancellationToken.None)) + { + if (clock.ElapsedMilliseconds >= context.Config.GraceMs) + NativeServer.Fatal("CLIPBOARD_CLEANUP", "Clipboard cleanup did not finish before the native grace deadline"); + await Task.Delay(context.Config.PollIntervalMs); + } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs new file mode 100644 index 0000000000..7e9b33a9e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs @@ -0,0 +1,264 @@ +// The shared Host policy authorizes handles before these platform operations execute. +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClientState +{ + internal DesktopWindows Desktop { get; } = new(); + internal Dictionary Launches { get; } = new(StringComparer.Ordinal); + internal Dictionary Apps { get; } = new(StringComparer.Ordinal); + internal AppState App(string handle) => Apps.GetValueOrDefault(handle) + ?? throw new NativeFailure("STALE_APP", "Select the application again on this connection"); + internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); Launches.Clear(); } +} + +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int graceMs) : IAsyncDisposable +{ + private readonly WindowCapture capture = new(); + private readonly ClipboardPaste clipboard = new(); + private readonly SemaphoreSlim queue = new(1); + + private static object ActionResult(nint before) => new + { + dispatched = true, + foregroundChanged = before == 0 || Win32.GetForegroundWindow() == 0 ? (bool?)null : before != Win32.GetForegroundWindow(), + }; + private static string String(JsonElement value, string key) => value.GetProperty(key).GetString()!; + private static string? OptionalString(JsonElement value, string key) => value.TryGetProperty(key, out var item) ? item.GetString() : null; + private static bool Flag(JsonElement value, string key) => value.TryGetProperty(key, out var item) && item.GetBoolean(); + private static uint? WindowId(JsonElement value) => value.TryGetProperty("windowId", out var id) ? id.GetUInt32() : null; + private static string[] Modifiers(JsonElement value) => value.TryGetProperty("modifiers", out var items) ? items.EnumerateArray().Select(item => item.GetString()!).ToArray() : []; + + // Window-scoped operations act only on the window authorized at getApp; the request must name it. + private static WindowState Selected(AppState app, JsonElement parameters, RequestContext context) + { + if (!parameters.TryGetProperty("windowId", out var raw)) + throw new NativeFailure("UNSUPPORTED", "This operation requires a window target; select a window with getApp and pass its windowId"); + if (!raw.TryGetUInt32(out var id)) + throw new NativeFailure("INVALID_ARGUMENT", "windowId must be a non-negative 32-bit identifier"); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before this operation"); + if (selected.Id != id) + throw new NativeFailure("WINDOW_CHANGED", "The request targets another window; select that window with getApp"); + selected.Geometry(app, context); + return selected; + } + + private static (WindowState Window, double X, double Y) Coordinate(AppState app, JsonElement parameters, RequestContext context) + { + var window = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, window.Id); + return (window, parameters.GetProperty("x").GetDouble(), parameters.GetProperty("y").GetDouble()); + } + + internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation) + { + if (request.Method == "screenshot") + { + var context = new RequestContext(config, cancellation, mta, sta); + AppState app; + WindowState window; + await queue.WaitAsync(cancellation); + try + { + DesktopSession.RequireInteractive(); + app = state.App(String(request.Params, "appHandle")); + window = Selected(app, request.Params, context); + } + finally { queue.Release(); } + return await capture.Capture(app, window, context); + } + await queue.WaitAsync(cancellation); + try + { + var context = new RequestContext(config, cancellation, mta, sta); + context.Check(); + var parameters = request.Params; + if (request.Method == "permissionStatus") return DesktopSession.Status(await capture.IsSupported(cancellation)); + if (request.Method == "applicationIcons") return await sta.Invoke(_ => Applications.Icons(parameters, context), cancellation); + if (request.Method == "getCapabilities") + { + var locked = DesktopSession.Locked(); + return new { permissions = new { accessibility = locked == false, + screenRecording = locked == false && await capture.IsSupported(cancellation) }, + sessionLocked = locked }; + } + if (request.Method is "requestPermission" or "openPermissionSettings") + throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); + DesktopSession.RequireInteractive(); + if (request.Method == "listApps") return state.Desktop.ListApps(context); + if (request.Method == "findApps") + throw new NativeFailure("UNSUPPORTED", "Windows discovers selectable windows with listApps; installed launch entries are not part of this selection"); + if (request.Method == "getApp") + { + var selected = state.Desktop.Select(String(parameters, "selector"), context); + state.Apps[selected.Handle] = selected; + return new { appHandle = selected.Handle, pid = 4, name = selected.Authorization.Name, + running = true, authorization = selected.Authorization }; + } + if (request.Method == "launchApp") + throw new NativeFailure("UNSUPPORTED", "A selected Windows window cannot be launched; select an observed window from listApps"); + var app = state.App(String(parameters, "appHandle")); + app.RequireProcess(); + var foreground = Win32.GetForegroundWindow(); + switch (request.Method) + { + case "listWindows": return Windows.Refresh(app, context).Select(window => window.Describe(app, context)).ToArray(); + case "getState": + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => Accessibility.State(app, target.Id, parameters.GetProperty("maxElements").GetInt32(), + parameters.GetProperty("maxDepth").GetInt32(), Flag(parameters, "includeMenus"), Flag(parameters, "details"), context), cancellation); + } + case "activate": Windows.Activate(app, null, context); return ActionResult(foreground); + case "show": return Windows.Show(app, WindowId(parameters), context); + case "typeText": + Selected(app, parameters, context); + await Input.Type(app, String(parameters, "text"), context); + return ActionResult(foreground); + case "pressKey": + Selected(app, parameters, context); + Input.Press(app, String(parameters, "key"), Modifiers(parameters), context); + return ActionResult(foreground); + case "sendKeyEvent": + throw new NativeFailure("UNSUPPORTED", "Held key events are not supported on current platform."); + case "paste": + Selected(app, parameters, context); + await clipboard.Paste(app, String(parameters, "text"), OptionalString(parameters, "format") ?? "text", + parameters.GetProperty("maxClipboardBytes").GetInt32(), parameters.GetProperty("pasteReadTimeoutMs").GetInt32(), context); + return ActionResult(foreground); + case "mouseMove": + { + if (parameters.TryGetProperty("elementId", out _)) + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + return Input.MouseMove(app, element.Window, (bounds.X + bounds.Width / 2 - geometry.Pixels.Left), + (bounds.Y + bounds.Height / 2 - geometry.Pixels.Top), context); + }, cancellation); + } + var pointed = Coordinate(app, parameters, context); + return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); + } + case "scroll": + { + var target = Coordinate(app, parameters, context); + Input.Scroll(app, target.Window, target.X, target.Y, parameters.GetProperty("deltaLinesX").GetInt32(), + parameters.GetProperty("deltaLinesY").GetInt32(), context); + return ActionResult(foreground); + } + case "drag": + { + var target = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, target.Id); + await Input.Drag(app, target, parameters.GetProperty("fromX").GetDouble(), + parameters.GetProperty("fromY").GetDouble(), parameters.GetProperty("toX").GetDouble(), parameters.GetProperty("toY").GetDouble(), + OptionalString(parameters, "mouseButton") ?? "left", Modifiers(parameters), parameters.GetProperty("durationMs").GetInt32(), + parameters.GetProperty("steps").GetInt32(), context); + return ActionResult(foreground); + } + case "click": + { + var target = Selected(app, parameters, context); + int? hold = null; + if (parameters.TryGetProperty("holdMs", out var duration)) + { + if (!duration.TryGetInt32(out var value) || value > config.MaxClickHoldMs) + throw new NativeFailure("INVALID_ARGUMENT", "The requested click exceeds maxClickHoldMs"); + hold = value; + } + var button = OptionalString(parameters, "mouseButton") ?? "left"; + var count = parameters.TryGetProperty("clickCount", out var clickCount) ? clickCount.GetInt32() : 1; + var modifiers = Modifiers(parameters); + (WindowState Window, double X, double Y)? pointer = null; + if (parameters.TryGetProperty("elementId", out _)) + { + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + if (!hold.HasValue && button == "left" && count == 1 && modifiers.Length == 0 && AccessibilityActions.Click(element, context)) return true; + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + pointer = (element.Window, bounds.X + bounds.Width / 2 - geometry.Pixels.Left, + bounds.Y + bounds.Height / 2 - geometry.Pixels.Top); + return true; + }, cancellation); + } + else pointer = Coordinate(app, parameters, context); + if (pointer is { } targetPoint) + { + if (hold is { } held) await Input.HoldClick(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, held, context); + else Input.Click(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, context); + } + return ActionResult(foreground); + } + case "listActions": + { + Selected(app, parameters, context); + return await mta.Invoke(() => AccessibilityActions.Actions( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + } + case "performAction": + { + Selected(app, parameters, context); + var argument = parameters.TryGetProperty("argument", out var raw) ? raw : (JsonElement?)null; + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.Perform(app, element, String(parameters, "action"), argument, context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "invoke": + { + Selected(app, parameters, context); + var dispatched = await mta.Invoke(() => AccessibilityActions.Invoke( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + return new { dispatched }; + } + case "setValue": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SetValue(element, parameters.GetProperty("value"), context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "selectText": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SelectText(element, String(parameters, "text"), OptionalString(parameters, "prefix"), OptionalString(parameters, "suffix"), + OptionalString(parameters, "selectionType") ?? "text", context); + return true; + }, cancellation); + return ActionResult(foreground); + } + default: throw new NativeFailure("UNSUPPORTED", "Unknown native CUA operation"); + } + } + finally { queue.Release(); } + } + + public async ValueTask DisposeAsync() + { + try { await capture.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { NativeServer.Fatal("NATIVE_CLEANUP", "The idle desktop service could not release capture resources"); } + queue.Dispose(); + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopSession.cs b/packages/experimental/cua-windows/native/src/DesktopSession.cs new file mode 100644 index 0000000000..d9969a3a56 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopSession.cs @@ -0,0 +1,45 @@ +// Observations stop when the interactive input desktop is unavailable. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class DesktopSession +{ + internal static bool? Locked() + { + using var process = Process.GetCurrentProcess(); + if (!Win32.WTSQuerySessionInformation(0, process.SessionId, 8, out var state, out var bytes)) return null; + try { if (bytes < sizeof(int) || Marshal.ReadInt32(state) != 0) return true; } + finally { Win32.WTSFreeMemory(state); } + var desktop = Win32.OpenInputDesktop(0, false, 1); + if (desktop == 0) return Marshal.GetLastWin32Error() == 5 ? true : null; + try + { + var name = new StringBuilder(256); + if (!Win32.GetUserObjectInformation(desktop, 2, name, name.Capacity * sizeof(char), out _)) return null; + return !string.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase); + } + finally { Win32.CloseDesktop(desktop); } + } + + internal static void RequireInteractive() + { + if (Locked() != false) throw new NativeFailure("SESSION_LOCKED", "Unlock Windows and return to an interactive desktop before observing or sending input"); + } + + internal static object Status(bool captureAvailable) + { + using var identity = WindowsIdentity.GetCurrent(); + return new + { + platform = "windows", sessionLocked = Locked(), + captureAvailable, + elevated = new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator), + helper = new { pid = 4, path = Environment.ProcessPath, name = "dsh-cua-windows" }, + }; + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopWindows.cs b/packages/experimental/cua-windows/native/src/DesktopWindows.cs new file mode 100644 index 0000000000..e70b1b1d1e --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopWindows.cs @@ -0,0 +1,109 @@ +// Discovery IDs are connection-owned and never reused for another HWND lifetime. +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record DiscoveredWindow(WindowState Window, RunningApplication Process, string Selector); + +internal sealed class DesktopWindows +{ + private readonly Dictionary windows = []; + private uint nextId; + + internal object[] ListApps(RequestContext context) + { + var result = new List(); + foreach (var entry in Discover(context)) + { + context.Check(); + try + { + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(new { pid = 4, name = owner.Authorization.Name, id = entry.Selector }); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing window cannot remain selectable from this connection. + windows.Remove(entry.Window.Handle); + } + } + return result.ToArray(); + } + + internal AppState Select(string selector, RequestContext context) + { + if (string.IsNullOrEmpty(selector)) throw new NativeFailure("INVALID_ARGUMENT", "A window selector from listApps is required"); + Discover(context); + var entry = windows.Values.SingleOrDefault(value => string.Equals(value.Selector, selector, StringComparison.Ordinal)) + ?? throw new NativeFailure("WINDOW_CHANGED", "Discover applications again; this window selector belongs to another connection or an expired window"); + var app = Owner(entry, true, context); + try { entry.Window.Geometry(app, context); return app; } + catch { app.Dispose(); throw; } + } + + private List Discover(RequestContext context) + { + var current = new List(); + Win32.EnumWindows((handle, _) => + { + var extended = Win32.GetWindowLongPtr(handle, -20).ToInt64(); + if (Win32.IsWindowVisible(handle) && (extended & 0x80) == 0 + && Win32.GetWindowRect(handle, out var bounds) && bounds.Width > 0 && bounds.Height > 0) + current.Add(handle); + return true; + }, 0); + var result = new List(); + foreach (var handle in current) + { + context.Check(); + try + { + Win32.GetWindowThreadProcessId(handle, out var pid); + var process = Applications.Running(checked((int)pid)); + var epoch = context.Sta.WindowEpoch(handle); + if (!windows.TryGetValue(handle, out var entry) || entry.Process.Pid != process.Pid + || entry.Process.Started != process.Started || entry.Window.Epoch != epoch) + { + if (nextId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Reconnect before discovering more windows"); + entry = new(new(++nextId, handle, epoch), process, Guid.NewGuid().ToString("N")); + windows[handle] = entry; + } + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(entry); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing or inaccessible window cannot be selected from this discovery. + windows.Remove(handle); + } + } + foreach (var handle in windows.Keys.Where(handle => !current.Contains(handle)).ToArray()) windows.Remove(handle); + return result; + } + + private static AppState Owner(DiscoveredWindow entry, bool authorize, RequestContext context) + { + var window = entry.Window; + var process = entry.Process; + var length = Win32.GetWindowTextLength(window.Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(window.Handle, title, title.Capacity); + var name = $"Window: {title} ({process.Name})"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( + $"window\0{process.Pid}\0{process.Started}\0{window.Handle}\0{window.Epoch}"))); + var identity = new ApplicationIdentity(id, name, process.Path, false); + var app = new AppState(Guid.NewGuid().ToString("N"), identity, "", process); + if (authorize) + { + var selected = new WindowState(window.Id, window.Handle, window.Epoch); + app.SelectedWindow = selected; + app.Windows.Add(window.Handle, selected); + } + return app; + } +} diff --git a/packages/experimental/cua-windows/native/src/Dispatchers.cs b/packages/experimental/cua-windows/native/src/Dispatchers.cs new file mode 100644 index 0000000000..3bc7785457 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Dispatchers.cs @@ -0,0 +1,178 @@ +// UI Automation and clipboard COM objects each stay on their owning apartment. +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Text.Json; +using DeepSeek.Cua.Protocol; +using Forms = System.Windows.Forms; +using Timer = System.Threading.Timer; + +namespace DeepSeek.Cua.Windows; + +internal sealed record NativeConfig(int MaxRequestBytes, int MaxResponseBytes, int AxTimeoutMs, + double TextEventIntervalMs, int ScreenshotTimeoutMs, int TimeoutMs, int GraceMs, int PollIntervalMs, int MaxClickHoldMs) +{ + internal static NativeConfig Parse(JsonElement value) + { + string[] fields = ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "screenshotTimeoutMs", "timeoutMs", "graceMs", "pollIntervalMs", "maxClickHoldMs"]; + if (value.ValueKind != JsonValueKind.Object || value.EnumerateObject().Any(item => !fields.Contains(item.Name)) + || fields.Any(field => !value.TryGetProperty(field, out _))) throw new NativeFailure("INVALID_CONFIG", "Expected explicit native resource limits"); + int Positive(string field) + { + if (!value.GetProperty(field).TryGetInt32(out var number) || number <= 0) throw new NativeFailure("INVALID_CONFIG", field + " must be a positive Int32"); + return number; + } + var interval = value.GetProperty("textEventIntervalMs").GetDouble(); + if (!double.IsFinite(interval) || interval < 0 || interval > 1000) throw new NativeFailure("INVALID_CONFIG", "Invalid text event interval"); + return new(Positive("maxRequestBytes"), Positive("maxResponseBytes"), Positive("axTimeoutMs"), interval, + Positive("screenshotTimeoutMs"), Positive("timeoutMs"), Positive("graceMs"), Positive("pollIntervalMs"), Positive("maxClickHoldMs")); + } +} + +internal sealed class MtaDispatcher : IAsyncDisposable +{ + private readonly BlockingCollection queue = new(); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Thread thread; + + internal MtaDispatcher() + { + thread = new Thread(() => + { + var initialized = false; + try + { + Marshal.ThrowExceptionForHR(Win32.RoInitialize(1)); + initialized = true; + Win32.SetThreadDpiAwarenessContext(-4); + ready.SetResult(); + foreach (var work in queue.GetConsumingEnumerable()) work(); + } + catch (Exception error) { ready.TrySetException(error); } + finally { if (initialized) Win32.RoUninitialize(); stopped.TrySetResult(); } + }) { IsBackground = true, Name = "dsh-cua-uia" }; + thread.SetApartmentState(ApartmentState.MTA); + thread.Start(); + } + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.Add(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(); cancellation.ThrowIfCancellationRequested(); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + public async ValueTask DisposeAsync() + { + queue.CompleteAdding(); + await stopped.Task; + queue.Dispose(); + } +} + +internal sealed class ServiceControl : Forms.Control +{ + internal Func? ClipboardMessage; + protected override Forms.CreateParams CreateParams + { + get { var value = base.CreateParams; value.Parent = -3; return value; } + } + protected override void WndProc(ref Forms.Message message) + { + if (ClipboardMessage?.Invoke(message.Msg, message.WParam) == true) return; + base.WndProc(ref message); + } +} + +internal sealed class StaDispatcher : IAsyncDisposable +{ + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentDictionary epochs = new(); + private readonly Thread thread; + private Win32.WinEvent? windowEvents; + + internal StaDispatcher() + { + thread = new Thread(() => + { + nint hook = 0; + try + { + Win32.SetThreadDpiAwarenessContext(-4); + using var control = new ServiceControl(); + _ = control.Handle; + windowEvents = (_, eventType, window, objectId, childId, _, _) => + { + if (eventType == 0x8001 && objectId == 0 && childId == 0 && epochs.TryGetValue(window, out var epoch)) + epochs.TryUpdate(window, epoch + 1, epoch); + }; + hook = Win32.SetWinEventHook(0x8001, 0x8001, 0, windowEvents, 0, 0, 0); + if (hook == 0) throw new NativeFailure("NATIVE_STARTUP", "Window lifecycle observation could not start"); + ready.SetResult(control); + Forms.Application.Run(); + } + catch (Exception error) { ready.TrySetException(error); } + finally + { + if (hook != 0) Win32.UnhookWinEvent(hook); + stopped.TrySetResult(); + } + }) { IsBackground = true, Name = "dsh-cua-clipboard" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + internal long WindowEpoch(nint window) => epochs.GetOrAdd(window, 0); + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + var control = await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + control.BeginInvoke(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(control); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + internal Task Invoke(Action work, CancellationToken cancellation) => Invoke(_ => { work(); return true; }, cancellation); + + public async ValueTask DisposeAsync() + { + try { await ready.Task; } + catch (Exception error) { _ = error; await stopped.Task; return; } + await Invoke(() => Forms.Application.ExitThread(), CancellationToken.None); + await stopped.Task; + } +} + +internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta) +{ + internal NativeConfig Config { get; } = config; + internal CancellationToken Cancellation { get; } = cancellation; + internal MtaDispatcher Mta { get; } = mta; + internal StaDispatcher Sta { get; } = sta; + internal void Check() => Cancellation.ThrowIfCancellationRequested(); + + internal T Ax(Func call) + { + Check(); + var completed = 0; + using var timer = new Timer(_ => + { + if (Interlocked.Exchange(ref completed, 1) == 0) + NativeServer.Fatal("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline"); + }, null, Config.AxTimeoutMs, Timeout.Infinite); + try { var result = call(); Cancellation.ThrowIfCancellationRequested(); return result; } + finally { Interlocked.Exchange(ref completed, 1); } + } +} diff --git a/packages/experimental/cua-windows/native/src/GlobalUsings.cs b/packages/experimental/cua-windows/native/src/GlobalUsings.cs new file mode 100644 index 0000000000..30f1415d24 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/GlobalUsings.cs @@ -0,0 +1 @@ +global using System.IO; diff --git a/packages/experimental/cua-windows/native/src/Input.cs b/packages/experimental/cua-windows/native/src/Input.cs new file mode 100644 index 0000000000..ec6570591d --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Input.cs @@ -0,0 +1,263 @@ +// Global key and pointer injection requires an explicitly foregrounded target. +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Input +{ + private static readonly int[] ModifierKeys = [0x10, 0x11, 0x12, 0x5B, 0x5C]; + private static ushort Modifier(string name) => name switch + { + "shift" => 0x10, "control" => 0x11, "option" => 0x12, + "command" => throw new NativeFailure("UNSUPPORTED", "Windows-key shortcuts act outside the selected application; use Control for application shortcuts"), + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows does not expose a portable Fn input event"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; + private static Win32.Input Keyboard(ushort key, ushort scan = 0, uint flags = 0) => new() + { Type = 1, Data = new() { Keyboard = new() { Key = key, Scan = scan, Flags = flags } } }; + private static Win32.Input Mouse(uint flags, int x = 0, int y = 0, uint data = 0) => new() + { Type = 0, Data = new() { Mouse = new() { X = x, Y = y, Data = data, Flags = flags } } }; + + private static void Send(params Win32.Input[] events) + { + if (Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()) != events.Length) + throw new NativeFailure("INPUT_BLOCKED", "Windows did not dispatch all input; privileges or user input may have intervened. Observe before retrying"); + } + + private static void Release(Win32.Input input) => Win32.SendInput(1, [input], Marshal.SizeOf()); + + private static void RequireIdleModifiers() + { + if (ModifierKeys.Concat([0x01, 0x02, 0x04, 0x05, 0x06]).Any(key => (Win32.GetAsyncKeyState(key) & 0x8000) != 0)) + throw new NativeFailure("INPUT_BUSY", "A modifier or mouse button is already held; wait for the user to release it before sending input"); + } + + private static void WithModifiers(IEnumerable modifiers, Action action) + { + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + action(); + } + finally { foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); } + } + + private static (ushort Key, bool Extended, string[] Modifiers) ResolveKey(string name, AppState app) + { + var key = name.ToLowerInvariant(); + if (key.StartsWith("kp_", StringComparison.Ordinal)) + { + var keypad = key[3..]; + if (keypad.Length == 1 && char.IsAsciiDigit(keypad[0])) return ((ushort)(0x60 + keypad[0] - '0'), false, []); + return keypad switch + { + "enter" => (0x0D, true, []), "add" or "plus" => (0x6B, false, []), "subtract" or "minus" => (0x6D, false, []), + "multiply" => (0x6A, false, []), "divide" => (0x6F, true, []), "decimal" or "period" => (0x6E, false, []), + _ => throw new NativeFailure("UNSUPPORTED", "Unknown numeric-keypad key"), + }; + } + if (key.Length > 1 && key[0] == 'f' && int.TryParse(key[1..], out var function) && function is >= 1 and <= 24) + return ((ushort)(0x70 + function - 1), false, []); + ushort named = key switch + { + "enter" or "return" => 0x0D, "tab" => 0x09, "escape" or "esc" => 0x1B, "backspace" => 0x08, + "delete" or "forwarddelete" => 0x2E, "insert" => 0x2D, "home" => 0x24, "end" => 0x23, + "pageup" => 0x21, "pagedown" => 0x22, "left" or "arrowleft" => 0x25, "up" or "arrowup" => 0x26, + "right" or "arrowright" => 0x27, "down" or "arrowdown" => 0x28, "space" => 0x20, + "capslock" => 0x14, "numlock" => 0x90, "scrolllock" => 0x91, "printscreen" => 0x2C, + _ => 0, + }; + if (named != 0) return (named, named is >= 0x21 and <= 0x2E || named == 0x90, []); + var character = key == "plus" ? '+' : name.Length == 1 ? char.IsAsciiLetter(name[0]) ? char.ToLowerInvariant(name[0]) : name[0] : '\0'; + if (character == '\0') throw new NativeFailure("UNSUPPORTED", "Unknown key name; use typeText for text input"); + var foreground = Win32.GetForegroundWindow(); + var thread = Win32.GetWindowThreadProcessId(foreground, out _); + var mapped = Win32.VkKeyScanEx(character, Win32.GetKeyboardLayout(thread)); + if (mapped == -1) throw new NativeFailure("UNSUPPORTED", "This character has no key in the target keyboard layout; use typeText"); + var modifiers = new List(); + if ((mapped & 0x100) != 0) modifiers.Add("shift"); + if ((mapped & 0x200) != 0) modifiers.Add("control"); + if ((mapped & 0x400) != 0) modifiers.Add("option"); + return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); + } + + internal static void Press(AppState app, string key, string[] modifiers, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var chord = new KeyChord(key, modifiers.Select(KeyChord.NormalizeModifier).Distinct().ToArray()); + var name = chord.Key.ToLowerInvariant(); + if (name == "printscreen" || chord.Modifiers.Contains("option") && name is "tab" or "escape" or "esc" + || chord.Modifiers.Contains("control") && name is "escape" or "esc" + || chord.Modifiers.Contains("control") && chord.Modifiers.Contains("option") && name == "delete") + throw new NativeFailure("UNSUPPORTED", "This shortcut acts on the system rather than the selected application"); + var resolved = ResolveKey(chord.Key, app); + WithModifiers(chord.Modifiers.Concat(resolved.Modifiers), () => + { + Windows.RequireForeground(app, null, context); + var flags = resolved.Extended ? 1u : 0; + try { Send(Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)); } + catch { Release(Keyboard(resolved.Key, flags: flags | 2)); throw; } + }); + } + + internal static async Task Type(AppState app, string text, RequestContext context) + { + if (text.Contains('\0')) throw new NativeFailure("INVALID_ARGUMENT", "Text input cannot contain NUL"); + RequireIdleModifiers(); + for (var index = 0; index < text.Length; index++) + { + Windows.RequireForeground(app, null, context); + RequireIdleModifiers(); + var character = text[index]; + if (character is '\r' or '\n' or '\t') + { + if (character == '\r' && index + 1 < text.Length && text[index + 1] == '\n') index++; + Press(app, character == '\t' ? "Tab" : "Enter", [], context); + } + else + { + try { Send(Keyboard(0, character, 4), Keyboard(0, character, 6)); } + catch { Release(Keyboard(0, character, 6)); throw; } + } + if (context.Config.TextEventIntervalMs > 0) + await Task.Delay(TimeSpan.FromMilliseconds(context.Config.TextEventIntervalMs * 2), context.Cancellation); + } + } + + private static Win32.Input Move(Win32.Point point) + { + int left = Win32.GetSystemMetrics(76), top = Win32.GetSystemMetrics(77); + int width = Win32.GetSystemMetrics(78), height = Win32.GetSystemMetrics(79); + if (width <= 1 || height <= 1) throw new NativeFailure("SESSION_LOCKED", "The virtual desktop has no usable bounds"); + return Mouse(0x8000 | 0x4000 | 0x0001, + (int)Math.Round((point.X - left) * 65535d / (width - 1)), (int)Math.Round((point.Y - top) * 65535d / (height - 1))); + } + + private static (uint Down, uint Up) Button(string button) => button switch + { + "left" => (0x0002, 0x0004), "right" => (0x0008, 0x0010), "middle" => (0x0020, 0x0040), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown mouse button"), + }; + + private static void Hit(AppState app, WindowState window, Win32.Point point, RequestContext context) + { + Windows.RequireForeground(app, window, context); + if (Win32.GetAncestor(Win32.WindowFromPoint(point), 2) != window.Handle) + throw new NativeFailure("WINDOW_OBSCURED", "Another window covers the target coordinate; restore or raise the selected window and observe again"); + } + + internal static object MouseMove(AppState app, WindowState window, double x, double y, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + if (!Win32.GetCursorPos(out var before)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Send(Move(point)); + return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; + } + + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var geometry = window.RequireObservation(app, context); + var point = WindowState.Point(geometry, x, y); + var flags = Button(button); + Hit(app, window, point, context); + WithModifiers(modifiers, () => + { + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + var events = new List { Move(point) }; + for (var click = 0; click < count; click++) { events.Add(Mouse(flags.Down)); events.Add(Mouse(flags.Up)); } + try { Send(events.ToArray()); } catch { Release(Mouse(flags.Up)); throw; } + }); + } + + internal static async Task HoldClick(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, int holdMs, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + Hit(app, window, point, context); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key)); } + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + Send(Move(point)); + for (var click = 0; click < count; click++) + { + Hit(app, window, point, context); + buttonAttempted = true; + Send(Mouse(flags.Down)); + await Task.Delay(holdMs, context.Cancellation); + Windows.RequireForeground(app, window, context); + Send(Mouse(flags.Up)); + buttonAttempted = false; + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2)); + } + } + + internal static void Scroll(AppState app, WindowState window, double x, double y, int deltaX, int deltaY, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + uint lines = 1, columns = 1; + if (deltaY != 0 && (!Win32.SystemParametersInfo(0x0068, 0, out lines, 0) || lines == uint.MaxValue || lines == 0) + || deltaX != 0 && (!Win32.SystemParametersInfo(0x006C, 0, out columns, 0) || columns == 0)) + throw new NativeFailure("UNSUPPORTED", "Windows wheel scrolling does not currently use line/character units"); + var events = new List { Move(point) }; + if (deltaY != 0) events.Add(Mouse(0x0800, data: unchecked((uint)(int)Math.Round(deltaY * 120d / lines)))); + if (deltaX != 0) events.Add(Mouse(0x1000, data: unchecked((uint)(int)Math.Round(-deltaX * 120d / columns)))); + Send(events.ToArray()); + } + + internal static async Task Drag(AppState app, WindowState window, double fromX, double fromY, double toX, double toY, + string button, string[] modifiers, int durationMs, int steps, RequestContext context) + { + var geometry = window.RequireObservation(app, context); + var from = WindowState.Point(geometry, fromX, fromY); + _ = WindowState.Point(geometry, toX, toY); + Hit(app, window, from, context); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + geometry = window.RequireObservation(app, context); + from = WindowState.Point(geometry, fromX, fromY); + Hit(app, window, from, context); + buttonAttempted = true; + Send(Move(from), Mouse(flags.Down)); + for (var step = 1; step <= steps; step++) + { + await Task.Delay(TimeSpan.FromMilliseconds(durationMs / (double)steps), context.Cancellation); + geometry = window.RequireObservation(app, context); + Windows.RequireForeground(app, window, context); + Send(Move(WindowState.Point(geometry, fromX + (toX - fromX) * step / steps, fromY + (toY - fromY) * step / steps))); + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/LaunchEntries.cs b/packages/experimental/cua-windows/native/src/LaunchEntries.cs new file mode 100644 index 0000000000..cc97dfd8bf --- /dev/null +++ b/packages/experimental/cua-windows/native/src/LaunchEntries.cs @@ -0,0 +1,88 @@ +// Shell namespace enumeration and activation run on the existing STA dispatcher. +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record LaunchEntry(string Id, string DisplayName, string Kind, string? Path); +internal sealed class PreparedLaunch(LaunchEntry entry, ApplicationIdentity authorization, string? digest) +{ + internal string Handle { get; } = Guid.NewGuid().ToString("N"); + internal ApplicationIdentity Authorization { get; } = authorization; + private bool dispatched; + + internal void Dispatch() + { + if (dispatched) throw new NativeFailure("LAUNCH_ALREADY_DISPATCHED", "Discover windows before deciding whether another launch is needed"); + if (entry.Kind == "executable") + { + if (Applications.CanonicalPath(entry.Id) != entry.Id || Applications.Digest(entry.Id) != digest) + throw new NativeFailure("STALE_APP", "The approved executable changed; select it again"); + } + else if (!LaunchEntries.All().Any(current => current.Id == entry.Id)) + throw new NativeFailure("STALE_APP", "The Shell entry disappeared; discover launch entries again"); + // Dispatch may succeed even if Explorer subsequently reports a failure. Never replay this selection. + dispatched = true; + ShellBroker.Launch(entry.Id, show: 1); + } +} + +internal static class LaunchEntries +{ + internal static LaunchEntry[] All() + { + var owned = new List(); + object Own(object value) { owned.Add(value); return value; } + try + { + dynamic shell = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"), true)!)!); + dynamic folder = Own((object)shell.NameSpace("shell:AppsFolder")); + dynamic items = Own((object)folder.Items()); + var result = new List(); + for (var index = 0; index < (int)items.Count; index++) + { + dynamic item = Own((object)items.Item(index)); + string parsingName = item.Path; + string name = item.Name; + if (string.IsNullOrWhiteSpace(parsingName) || string.IsNullOrWhiteSpace(name)) continue; + var target = parsingName.StartsWith("::", StringComparison.Ordinal) ? parsingName : "shell:AppsFolder\\" + parsingName; + result.Add(new(target, name, "shell", null)); + } + return result.DistinctBy(entry => entry.Id, StringComparer.OrdinalIgnoreCase).ToArray(); + } + catch (Exception error) when (error is COMException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("APP_DISCOVERY_FAILED", "Windows Shell could not enumerate AppsFolder; retry discovery after Explorer is available"); + } + finally + { + foreach (var item in owned.AsEnumerable().Reverse()) + if (Marshal.IsComObject(item)) Marshal.ReleaseComObject(item); + } + } + + internal static LaunchEntry[] Find(string query, int maximum) + { + var matches = All().Where(entry => entry.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase) + || entry.Id.Contains(query, StringComparison.OrdinalIgnoreCase)).OrderBy(entry => entry.DisplayName, StringComparer.OrdinalIgnoreCase).ToArray(); + if (matches.Length > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific launch entry name"); + return matches; + } + + internal static PreparedLaunch Prepare(string target) + { + if (Path.IsPathFullyQualified(target) && target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + var path = Applications.CanonicalPath(target); + var name = Path.GetFileNameWithoutExtension(path); + var identity = Applications.Identify(path, "Launch: " + name, null); + return new(new(path, name, "executable", path), identity.Identity with { Persistable = false }, identity.Digest); + } + var shell = All().SingleOrDefault(entry => string.Equals(entry.Id, target, StringComparison.OrdinalIgnoreCase)) + ?? throw new NativeFailure("APP_NOT_FOUND", "Use an ID from findApps or a user-specified absolute executable path"); + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("launch\0" + shell.Id))); + return new(shell, new(id, "Launch: " + shell.DisplayName, shell.Id, false), null); + } +} diff --git a/packages/experimental/cua-windows/native/src/NativeServer.cs b/packages/experimental/cua-windows/native/src/NativeServer.cs new file mode 100644 index 0000000000..866cc0588b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/NativeServer.cs @@ -0,0 +1,196 @@ +// The per-user service serves isolated Agent connections and Host leases on a private named pipe. +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text.Json; +using System.Windows.Automation; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class NativeServer +{ + [DoesNotReturn] + internal static void Fatal(string code, string message) + { + Console.Error.WriteLine($"{code}: {message}; native handles are no longer usable"); + Environment.Exit(70); + throw new InvalidOperationException("Process exit returned"); + } + + internal static async Task Run(string instance, string expectedRuntime, int connectTimeoutMs, int graceMs) + { + if (!Guid.TryParseExact(instance, "N", out _)) throw new NativeFailure("INVALID_ARGUMENT", "A Host instance identifier is required"); + var executable = Environment.ProcessPath ?? throw new NativeFailure("NATIVE_STARTUP", "The executable identity is unavailable"); + using var source = File.OpenRead(executable); + var runtime = Convert.ToHexStringLower(SHA256.HashData(source)); + if (runtime != expectedRuntime) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + var pipeName = SharedRuntime.PipeName(runtime); + using var lifetime = new CancellationTokenSource(); + lifetime.CancelAfter(connectTimeoutMs); + await using var mta = new MtaDispatcher(); + await using var sta = new StaDispatcher(); + await sta.Invoke(() => { }, lifetime.Token); + await mta.Invoke(() => true, lifetime.Token); + await using var executor = new DesktopExecutor(mta, sta, graceMs); + var clients = new ConcurrentDictionary(); + NamedPipeServerStream? listener = NewPipe(pipeName); + var membership = new object(); + var connections = 0; + try + { + while (!lifetime.IsCancellationRequested) + { + await listener.WaitForConnectionAsync(lifetime.Token); + var connected = listener; + lock (membership) + { + lifetime.Token.ThrowIfCancellationRequested(); + connections++; + lifetime.CancelAfter(Timeout.Infinite); + } + listener = NewPipe(pipeName); + var task = Serve(connected, executor, instance, runtime, connectTimeoutMs, lifetime.Token); + clients.TryAdd(task, 0); + _ = task.ContinueWith(completed => + { + clients.TryRemove(completed, out _); + if (completed.IsFaulted) { _ = completed.Exception; Console.Error.WriteLine("NATIVE_CONNECTION: Connection cleanup failed"); } + lock (membership) { if (--connections == 0) lifetime.Cancel(); } + }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + catch (OperationCanceledException error) when (lifetime.IsCancellationRequested) { _ = error; /* Host shutdown cancels the pending read. */ } + finally + { + lifetime.Cancel(); + listener?.Dispose(); + await Task.WhenAll(clients.Keys); + } + } + + private static NamedPipeServerStream NewPipe(string name) => new(name, PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + + private static async Task Serve(NamedPipeServerStream pipe, DesktopExecutor executor, + string instance, string runtime, int connectTimeoutMs, CancellationToken serverLifetime) + { + using (pipe) + using (var lifetime = CancellationTokenSource.CreateLinkedTokenSource(serverLifetime)) + using (var writer = new SemaphoreSlim(1)) + { + var state = new ClientState(); + Task? active = null; + CancellationTokenSource? cancellation = null; + string? latestRequestId = null; + var closeRequested = false; + var cleanupTimeoutMs = connectTimeoutMs; + try + { + var reader = new FrameReader(pipe); + string? line; + using (var greeting = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)) + { + greeting.CancelAfter(connectTimeoutMs); + line = await reader.ReadAsync(8192, greeting.Token) ?? throw new NativeFailure("INVALID_REQUEST", "A native hello is required"); + } + var hello = WireJson.Parse(line); + if (hello.ValueKind == JsonValueKind.Object && hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["runtimeKey", "type"]) + && hello.GetProperty("type").GetString() == "lease" && hello.GetProperty("runtimeKey").GetString() == runtime) + { + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, + 8192, connectTimeoutMs, lifetime.Token); + if (await reader.ReadAsync(8192, lifetime.Token) is not null) throw new NativeFailure("INVALID_REQUEST", "A service lease cannot send desktop operations"); + return; + } + if (hello.ValueKind != JsonValueKind.Object || hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["config", "protocol", "runtimeKey", "type"]) == false + || hello.GetProperty("type").GetString() != "hello" || hello.GetProperty("protocol").GetInt32() != 1 || hello.GetProperty("runtimeKey").GetString() != runtime) + throw new NativeFailure("INVALID_REQUEST", "The native handshake did not match this helper"); + var config = NativeConfig.Parse(hello.GetProperty("config")); + cleanupTimeoutMs = config.GraceMs; + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, 8192, config.GraceMs, lifetime.Token); + while ((line = await reader.ReadAsync(config.MaxRequestBytes, lifetime.Token)) is not null) + { + var value = WireJson.Parse(line); + if (value.ValueKind == JsonValueKind.Object && value.TryGetProperty("type", out _)) + { + var control = NativeControlFrame.Parse(value, latestRequestId, active?.IsCompleted != false); + if (control == NativeControl.Close) { closeRequested = true; break; } + if (control == NativeControl.Cancel) cancellation!.Cancel(); + continue; + } + var request = NativeRequest.Parse(value); + if (active is { IsCompleted: false }) throw new NativeFailure("NATIVE_BUSY", "Native requests must be sequential"); + if (active is not null) await active; + cancellation?.Dispose(); + cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); + cancellation.CancelAfter(request.Method == "screenshot" ? Math.Min(config.TimeoutMs, config.ScreenshotTimeoutMs) : config.TimeoutMs); + latestRequestId = request.Id; + active = Dispatch(request, state, executor, config, pipe, writer, cancellation.Token, lifetime.Token); + } + } + catch (Exception error) + { + if (error is not (IOException or OperationCanceledException)) Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); + } + finally + { + lifetime.Cancel(); + cancellation?.Cancel(); + if (active is not null) + { + try { await active; } + catch (Exception error) { Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); } + } + cancellation?.Dispose(); + state.Clear(); + if (closeRequested) + await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); + } + } + } + + private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, + Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) + { + var operation = executor.Execute(request, state, config, cancellation); + using var monitorStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + var monitor = WatchOperation(operation, monitorStop.Token, config.GraceMs); + object response; + try { response = new { id = request.Id, result = await operation }; } + catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } + catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } + catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } + catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } + catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } + catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } + finally { monitorStop.Cancel(); await monitor; } + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + } + + private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; + + private static async Task WatchOperation(Task operation, CancellationToken cancellation, int graceMs) + { + await Task.WhenAny(operation, Task.Delay(Timeout.Infinite, cancellation)); + if (operation.IsCompleted) return; + try { await operation.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { Fatal("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline"); } + catch (Exception error) when (operation.IsCompleted) { _ = error; /* Dispatch owns the operation result. */ } + } + + private static async Task Write(Stream pipe, SemaphoreSlim writer, object value, int maximum, int timeoutMs, CancellationToken cancellation) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(value, WireJson.Options); + if (bytes.Length + 1 > maximum) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The native frame exceeds its byte limit"); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + deadline.CancelAfter(timeoutMs); + await writer.WaitAsync(deadline.Token); + try { await pipe.WriteAsync(bytes, deadline.Token); await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); } + finally { writer.Release(); } + } +} diff --git a/packages/experimental/cua-windows/native/src/Program.cs b/packages/experimental/cua-windows/native/src/Program.cs new file mode 100644 index 0000000000..d46db4479c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Program.cs @@ -0,0 +1,35 @@ +// The executable is a private helper launched by the dsh Windows provider. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Program +{ + private static int Main(string[] args) + { + try + { + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); + var server = args.Length == 7 && args[0] == "--shared-server"; + var bridge = args.Length == 7 && args[0] == "--bridge"; + var connector = args.Length == 9 && args[0] == "--serve" && args[1] == "--instance-id" && Guid.TryParseExact(args[2], "N", out _); + var offset = server || bridge ? 1 : 3; + if ((!server && !connector && !bridge) || args[offset] != "--runtime-key" || args[offset + 2] != "--connect-timeout-ms" + || args[offset + 4] != "--grace-ms" + || !int.TryParse(args[offset + 3], out var connectTimeoutMs) || connectTimeoutMs <= 0 + || !int.TryParse(args[offset + 5], out var graceMs) || graceMs <= 0) + throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); + var runtime = Applications.Digest(Environment.ProcessPath!); + if (runtime != args[offset + 1]) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + if (server) SharedRuntime.Serve(runtime, connectTimeoutMs, graceMs); + else if (bridge) SharedRuntime.Bridge(runtime, connectTimeoutMs).GetAwaiter().GetResult(); + else SharedRuntime.Connect(args[2], runtime, connectTimeoutMs, graceMs).GetAwaiter().GetResult(); + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error is NativeFailure failure ? $"{failure.Code}: {failure.Message}" : $"NATIVE_STARTUP: {error.Message}"); + return 1; + } + } +} diff --git a/packages/experimental/cua-windows/native/src/SharedRuntime.cs b/packages/experimental/cua-windows/native/src/SharedRuntime.cs new file mode 100644 index 0000000000..974adf160b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/SharedRuntime.cs @@ -0,0 +1,110 @@ +// A managed Host connector leases an Explorer-launched service outside the Host's kill-on-close Job. +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class SharedRuntime +{ + internal static string PipeName(string runtime) + { + using var identity = WindowsIdentity.GetCurrent(); + using var process = Process.GetCurrentProcess(); + var user = identity.User?.Value ?? throw new NativeFailure("NATIVE_STARTUP", "The Windows user identity is unavailable"); + var scope = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes($"{user}:{process.SessionId}"))); + return $"dsh-cua-{scope}-{runtime}"; + } + + internal static async Task Connect(string launcherId, string runtime, int timeoutMs, int graceMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try { pipe.Connect(0); } + catch (TimeoutException) + { + await using var sta = new StaDispatcher(); + var executable = Environment.ProcessPath!; + await sta.Invoke(() => ShellBroker.Launch(executable, + $"--shared-server --runtime-key {runtime} --connect-timeout-ms {timeoutMs} --grace-ms {graceMs}", 0), deadline.Token); + await pipe.ConnectAsync(deadline.Token); + } + var pid = VerifyServer(pipe, runtime); + var hello = JsonSerializer.SerializeToUtf8Bytes(new { type = "lease", runtimeKey = runtime }, WireJson.Options); + await pipe.WriteAsync(hello, deadline.Token); + await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); + var reader = new FrameReader(pipe); + var line = await reader.ReadAsync(8192, deadline.Token) + ?? throw new NativeFailure("NATIVE_EOF", "The shared service exited during connection"); + var ready = WireJson.Parse(line); + if (ready.GetProperty("runtimeKey").GetString() != runtime || ready.GetProperty("pid").GetInt32() != pid) + throw new NativeFailure("NATIVE_PROTOCOL", "The shared service returned a different process identity"); + Console.WriteLine(JsonSerializer.Serialize(new + { + type = "ready", protocol = 1, runtimeKey = runtime, pid, + instanceId = ready.GetProperty("instanceId").GetString(), launcherId, endpoint = @"\\.\pipe\" + PipeName(runtime), + }, WireJson.Options)); + await Console.Out.FlushAsync(); + // Console.In's synchronized reader can block before it returns an asynchronous result. + var parent = Task.Run(() => Console.In.ReadLine()); + var stopped = reader.ReadAsync(8192, CancellationToken.None); + if (await Task.WhenAny(parent, stopped) == stopped) + throw new NativeFailure("NATIVE_EXITED", "The shared desktop service stopped; select applications again"); + await parent; + } + + // Windows owns the named pipe; WSL forwards the unchanged protocol over standard streams. + internal static async Task Bridge(string runtime, int timeoutMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.ConnectAsync(deadline.Token); + VerifyServer(pipe, runtime); + using var input = Console.OpenStandardInput(); + using var output = Console.OpenStandardOutput(); + // Inherited standard-input handles can be synchronous; never block pipe output on their reads. + var upload = Task.Run(() => input.CopyToAsync(pipe)); + var download = pipe.CopyToAsync(output); + try + { + var completed = await Task.WhenAny(upload, download); + await completed; + await output.FlushAsync(); + } + finally + { + // Process exit ends a pending synchronous stdin read; it must not delay pipe cleanup. + pipe.Dispose(); + } + } + + private static uint VerifyServer(NamedPipeClientStream pipe, string runtime) + { + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var pid)) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe server identity is unavailable"); + var server = Applications.Running(checked((int)pid)); + if (Applications.Digest(server.Path) != runtime) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe belongs to another executable"); + return pid; + } + + internal static void Serve(string runtime, int timeoutMs, int graceMs) + { + using var mutex = new Mutex(false, PipeName(runtime), new NamedWaitHandleOptions { CurrentUserOnly = true, CurrentSessionOnly = true }); + bool acquired; + try { acquired = mutex.WaitOne(0); } + catch (AbandonedMutexException) { acquired = true; } + if (!acquired) return; + try { NativeServer.Run(Guid.NewGuid().ToString("N"), runtime, timeoutMs, graceMs).GetAwaiter().GetResult(); } + finally { mutex.ReleaseMutex(); } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverProcessId); +} diff --git a/packages/experimental/cua-windows/native/src/ShellBroker.cs b/packages/experimental/cua-windows/native/src/ShellBroker.cs new file mode 100644 index 0000000000..291833ac1c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ShellBroker.cs @@ -0,0 +1,111 @@ +// Explorer owns user-launched applications, independently of the helper's managed process Job. +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class ShellBroker +{ + internal static void Launch(string path, string arguments = "", int show = 4) + { + var owned = new List(); + T Own(T value) where T : class { owned.Add(value); return value; } + try + { + dynamic windows = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39"), true)!)!); + object location = 0, root = null!; + int handle; + object desktop = Own((object)windows.FindWindowSW(ref location, ref root, 8, out handle, 1)); + var service = new Guid("4C96BE40-915C-11CF-99D3-00AA004AE837"); + var browserId = typeof(IShellBrowser).GUID; + Marshal.ThrowExceptionForHR(((IServiceProvider)desktop).QueryService(ref service, ref browserId, out var rawBrowser)); + var browser = (IShellBrowser)Own(rawBrowser); + Marshal.ThrowExceptionForHR(browser.QueryActiveShellView(out var view)); + Own(view); + var dispatchId = new Guid("00020400-0000-0000-C000-000000000046"); + Marshal.ThrowExceptionForHR(view.GetItemObject(0, ref dispatchId, out var folder)); + Own(folder); + var shell = Own(folder.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, folder, null)!); + shell.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, shell, + [path, arguments, Path.IsPathFullyQualified(path) ? Path.GetDirectoryName(path)! : "", "open", show]); + } + catch (Exception error) when (error is COMException or TargetInvocationException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("LAUNCH_FAILED", "Windows Explorer could not launch this executable; open the application and select its observed PID"); + } + finally + { + var released = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var value in owned.AsEnumerable().Reverse()) + if (released.Add(value) && Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value); + } + } + + internal static string? ShortcutTarget(string path) + { + object? instance = null; + try + { + instance = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true)!); + ((IPersistFile)instance!).Load(path, 0); + var target = new StringBuilder(32768); + ((IShellLink)instance).GetPath(target, target.Capacity, 0, 4); + return target.Length == 0 ? null : Environment.ExpandEnvironmentVariables(target.ToString()); + } + catch (COMException) { return null; } + finally { if (instance is not null) Marshal.FinalReleaseComObject(instance); } + } + + [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IServiceProvider + { + [PreserveSig] int QueryService(ref Guid service, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellBrowser + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int InsertMenusSB(nint menu, nint widths); + [PreserveSig] int SetMenuSB(nint menu, nint holemenu, nint active); + [PreserveSig] int RemoveMenusSB(nint menu); + [PreserveSig] int SetStatusTextSB([MarshalAs(UnmanagedType.LPWStr)] string text); + [PreserveSig] int EnableModelessSB([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int TranslateAcceleratorSB(nint message, ushort command); + [PreserveSig] int BrowseObject(nint list, uint flags); + [PreserveSig] int GetViewStateStream(uint mode, out nint stream); + [PreserveSig] int GetControlWindow(uint id, out nint window); + [PreserveSig] int SendControlMsg(uint id, uint message, nuint wparam, nint lparam, out nint result); + [PreserveSig] int QueryActiveShellView(out IShellView view); + [PreserveSig] int OnViewWindowActive(IShellView view); + [PreserveSig] int SetToolbarItems(nint buttons, uint count, uint flags); + } + + [ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellView + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int TranslateAccelerator(nint message); + [PreserveSig] int EnableModeless([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int UIActivate(uint state); + [PreserveSig] int Refresh(); + [PreserveSig] int CreateViewWindow(nint previous, nint settings, nint browser, nint bounds, out nint window); + [PreserveSig] int DestroyViewWindow(); + [PreserveSig] int GetCurrentInfo(nint settings); + [PreserveSig] int AddPropertySheetPages(uint reserved, nint callback, nint parameter); + [PreserveSig] int SaveViewState(); + [PreserveSig] int SelectItem(nint list, uint flags); + [PreserveSig] int GetItemObject(uint item, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellLink + { + void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int capacity, nint findData, uint flags); + } +} diff --git a/packages/experimental/cua-windows/native/src/Win32.cs b/packages/experimental/cua-windows/native/src/Win32.cs new file mode 100644 index 0000000000..957e3bcb98 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Win32.cs @@ -0,0 +1,136 @@ +// Native desktop operations keep physical pixels and process identity at the Windows edge. +using System.Runtime.InteropServices; +using System.Text; + +namespace DeepSeek.Cua.Windows; + +internal static class Win32 +{ + [DllImport("combase.dll")] internal static extern int RoInitialize(uint initialization); + [DllImport("combase.dll")] internal static extern void RoUninitialize(); + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] internal static extern nint GetWindowLongPtr(nint window, int index); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(out Point point); + internal delegate bool WindowVisitor(nint window, nint parameter); + internal delegate void WinEvent(nint hook, uint eventType, nint window, int objectId, int childId, uint threadId, uint time); + + [StructLayout(LayoutKind.Sequential)] internal struct Point { internal int X, Y; } + [StructLayout(LayoutKind.Sequential)] internal struct Rect + { + internal int Left, Top, Right, Bottom; + internal int Width => Right - Left; + internal int Height => Bottom - Top; + } + [StructLayout(LayoutKind.Sequential)] internal struct GuiThreadInfo + { + internal uint Size, Flags; + internal nint Active, Focus, Capture, MenuOwner, MoveSize, Caret; + internal Rect CaretRect; + } + [StructLayout(LayoutKind.Sequential)] internal struct Input { internal uint Type; internal InputData Data; } + [StructLayout(LayoutKind.Explicit)] internal struct InputData + { + [FieldOffset(0)] internal MouseInput Mouse; + [FieldOffset(0)] internal KeyboardInput Keyboard; + } + [StructLayout(LayoutKind.Sequential)] internal struct MouseInput + { + internal int X, Y; + internal uint Data, Flags, Time; + internal nuint Extra; + } + [StructLayout(LayoutKind.Sequential)] internal struct KeyboardInput + { + internal ushort Key, Scan; + internal uint Flags, Time; + internal nuint Extra; + } + + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EnumWindows(WindowVisitor visitor, nint parameter); + [DllImport("user32.dll")] internal static extern uint GetWindowThreadProcessId(nint window, out uint processId); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindowVisible(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsIconic(nint window); + [DllImport("user32.dll")] internal static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] internal static extern nint GetAncestor(nint window, uint flags); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowText(nint window, StringBuilder text, int maximum); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowTextLength(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowRect(nint window, out Rect rectangle); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out Rect rectangle, int size); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out int value, int size); + [DllImport("user32.dll")] internal static extern uint GetDpiForWindow(nint window); + [DllImport("user32.dll")] internal static extern nint SetThreadDpiAwarenessContext(nint context); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetForegroundWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindowAsync(nint window, int command); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, Input[] inputs, int size); + [DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key); + [DllImport("user32.dll")] internal static extern nint GetKeyboardLayout(uint thread); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern short VkKeyScanEx(char character, nint layout); + [DllImport("user32.dll")] internal static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] internal static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SystemParametersInfo(uint action, uint parameter, out uint value, uint flags); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint OpenInputDesktop(uint flags, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint access); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseDesktop(nint desktop); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetUserObjectInformation(nint handle, int index, StringBuilder value, int length, out int needed); + [DllImport("wtsapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WTSQuerySessionInformation(nint server, int session, int information, out nint buffer, out int bytes); + [DllImport("wtsapi32.dll")] internal static extern void WTSFreeMemory(nint memory); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetWinEventHook(uint minimum, uint maximum, nint module, WinEvent callback, uint process, uint thread, uint flags); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWinEvent(nint hook); + + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenClipboard(nint owner); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseClipboard(); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EmptyClipboard(); + [DllImport("user32.dll")] internal static extern nint GetClipboardOwner(); + [DllImport("user32.dll")] internal static extern nint GetOpenClipboardWindow(); + [DllImport("user32.dll")] internal static extern uint GetClipboardSequenceNumber(); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint EnumClipboardFormats(uint previous); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint GetClipboardData(uint format); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetClipboardData(uint format, nint data); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterClipboardFormat(string name); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalAlloc(uint flags, nuint bytes); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalLock(nint memory); + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GlobalUnlock(nint memory); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nuint GlobalSize(nint memory); + [DllImport("kernel32.dll")] internal static extern nint GlobalFree(nint memory); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint GetFinalPathNameByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, StringBuilder path, uint length, uint flags); + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetProcessTimes(Microsoft.Win32.SafeHandles.SafeProcessHandle process, out long created, out long exited, out long kernel, out long user); + [DllImport("wintrust.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int WinVerifyTrust(nint window, ref Guid action, ref TrustData data); + [DllImport("wintrust.dll")] internal static extern nint WTHelperProvDataFromStateData(nint state); + [DllImport("wintrust.dll")] internal static extern nint WTHelperGetProvSignerFromChain(nint provider, uint signer, [MarshalAs(UnmanagedType.Bool)] bool counterSigner, uint counter); + + [StructLayout(LayoutKind.Sequential)] internal struct ProviderSigner + { + internal uint Size, VerifyTimeLow, VerifyTimeHigh, CertificateCount; + internal nint Certificates; + } + [StructLayout(LayoutKind.Sequential)] internal struct ProviderCertificate + { + internal uint Size; + internal nint Certificate; + } + [StructLayout(LayoutKind.Sequential)] internal struct CertificateContext + { + internal uint Encoding; + internal nint Encoded; + internal uint EncodedSize; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TrustFile + { + internal uint Size; + [MarshalAs(UnmanagedType.LPWStr)] internal string Path; + internal nint Handle, Subject; + } + [StructLayout(LayoutKind.Sequential)] internal struct TrustData + { + internal uint Size; + internal nint PolicyCallback, SipClient; + internal uint UiChoice, RevocationChecks, UnionChoice; + internal nint File; + internal uint StateAction; + internal nint StateData, UrlReference; + internal uint ProviderFlags, UiContext; + internal nint SignatureSettings; + } +} diff --git a/packages/experimental/cua-windows/native/src/WindowCapture.cs b/packages/experimental/cua-windows/native/src/WindowCapture.cs new file mode 100644 index 0000000000..b72a219b3f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/WindowCapture.cs @@ -0,0 +1,243 @@ +// Windows Graphics Capture returns the selected window even when another window covers it. +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; +using Vortice.Direct3D; +using Vortice.Direct3D11; +using Vortice.DXGI; +using WinRT; +using global::Windows.Graphics.Capture; +using global::Windows.Graphics.DirectX; +using global::Windows.Graphics.DirectX.Direct3D11; + +namespace DeepSeek.Cua.Windows; + +internal sealed class WindowCapture : IAsyncDisposable +{ + private readonly MtaDispatcher dispatcher = new(); + private readonly CaptureAdmission admission = new(); + private ID3D11Device? device; + private ID3D11DeviceContext? immediate; + private IDirect3DDevice? captureDevice; + + internal Task IsSupported(CancellationToken cancellation) + => dispatcher.Invoke(GraphicsCaptureSession.IsSupported, cancellation); + + private void EnsureDevice() + { + if (device is not null) return; + var created = D3D11.D3D11CreateDevice(DriverType.Hardware, DeviceCreationFlags.BgraSupport); + try + { + using var dxgi = created.QueryInterface(); + Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi.NativePointer, out var pointer)); + try { captureDevice = MarshalInterface.FromAbi(pointer); } + finally { Marshal.Release(pointer); } + immediate = created.ImmediateContext; + device = created; + } + catch { created.Dispose(); throw; } + } + + internal async Task Capture(AppState app, WindowState window, RequestContext context) + { + if (!await IsSupported(context.Cancellation)) throw new NativeFailure("UNSUPPORTED", "Windows Graphics Capture is unavailable on this desktop"); + var geometry = window.Geometry(app, context); + if (!window.IsOnScreen()) throw new NativeFailure("WINDOW_NOT_VISIBLE", "Restore the selected window with show and observe again before capturing"); + try + { + var operation = admission.Start(() => CaptureOwned(window.Handle, geometry, context)); + var data = await operation.WaitAsync(context.Cancellation); + var current = window.Geometry(app, context); + if (current.Pixels.Width != geometry.Pixels.Width || current.Pixels.Height != geometry.Pixels.Height || current.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during capture; observe again"); + DesktopSession.RequireInteractive(); + window.Observe(current); + return new { mimeType = "image/png", data = Convert.ToBase64String(data), pixelWidth = geometry.Pixels.Width, + pixelHeight = geometry.Pixels.Height, windowId = window.Id, bounds = current.Bounds, coordinateSpace = "window-pixels" }; + } + catch (COMException error) + { + throw new NativeFailure(error.HResult == unchecked((int)0x80070005) ? "PERMISSION_DENIED" : "CAPTURE_FAILED", + $"Windows refused the selected window capture (0x{error.HResult:X8}); restore the window and read fresh state"); + } + } + + private async Task CaptureOwned(nint window, WindowGeometry geometry, RequestContext context) + { + CaptureRequest? request = null; + try + { + await dispatcher.Invoke(() => + { + EnsureDevice(); + request = new CaptureRequest(this, window, geometry, context); + return true; + }, context.Cancellation); + return await request!.Result.WaitAsync(context.Cancellation); + } + finally + { + if (request is not null) await dispatcher.Invoke(() => { request.Dispose(); return true; }, CancellationToken.None); + } + } + + private sealed class CaptureRequest : IDisposable + { + private readonly object gate = new(); + private readonly TaskCompletionSource result = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly WindowCapture owner; + private readonly WindowGeometry geometry; + private readonly RequestContext context; + private readonly GraphicsCaptureItem item; + private Direct3D11CaptureFramePool? pool; + private GraphicsCaptureSession? session; + private bool disposed; + + internal Task Result => result.Task; + + internal CaptureRequest(WindowCapture owner, nint window, WindowGeometry geometry, RequestContext context) + { + this.owner = owner; this.geometry = geometry; this.context = context; + item = ItemForWindow(window); + if (item.Size.Width != geometry.Pixels.Width || item.Size.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "Windows capture bounds differ from the observed window; restore it and observe again"); + try + { + pool = Direct3D11CaptureFramePool.CreateFreeThreaded(owner.captureDevice!, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); + pool.FrameArrived += Frame; + item.Closed += Closed; + session = pool.CreateCaptureSession(item); + session.IsCursorCaptureEnabled = false; + session.StartCapture(); + } + catch { Dispose(); throw; } + } + + private void Closed(GraphicsCaptureItem sender, object args) => result.TrySetException(new NativeFailure("WINDOW_CHANGED", "The selected window closed during capture")); + + private void Frame(Direct3D11CaptureFramePool sender, object args) + { + lock (gate) + { + if (disposed || result.Task.IsCompleted) return; + try + { + context.Check(); + using var frame = sender.TryGetNextFrame(); + if (frame is null) return; + if (frame.ContentSize.Width != geometry.Pixels.Width || frame.ContentSize.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "The capture frame dimensions changed"); + result.TrySetResult(owner.Encode(frame.Surface, geometry.Pixels.Width, geometry.Pixels.Height, context)); + } + catch (Exception error) { result.TrySetException(error); } + } + } + + public void Dispose() + { + lock (gate) + { + if (disposed) return; + disposed = true; + item.Closed -= Closed; + if (pool is not null) pool.FrameArrived -= Frame; + } + // Native disposal can wait for callbacks; queued callbacks must be able to observe disposed. + session?.Dispose(); + pool?.Dispose(); + } + } + + private byte[] Encode(IDirect3DSurface surface, int width, int height, RequestContext context) + { + var access = surface.As(); + var textureId = typeof(ID3D11Texture2D).GUID; + Marshal.ThrowExceptionForHR(access.GetInterface(ref textureId, out var pointer)); + using var texture = new ID3D11Texture2D(pointer); + if (texture.Description.Width != width || texture.Description.Height != height || texture.Description.Format != Format.B8G8R8A8_UNorm) + throw new NativeFailure("WINDOW_CHANGED", "The captured texture differs from the selected window geometry"); + var description = new Texture2DDescription(Format.B8G8R8A8_UNorm, (uint)width, (uint)height, + mipLevels: 1, bindFlags: BindFlags.None, usage: ResourceUsage.Staging, cpuAccessFlags: CpuAccessFlags.Read); + using var staging = device!.CreateTexture2D(description); + immediate!.CopyResource(staging, texture); + var mapped = immediate.Map(staging, 0, MapMode.Read); + using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + try + { + var pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + var row = new byte[checked(width * 4)]; + for (var y = 0; y < height; y++) + { + context.Check(); + Marshal.Copy(mapped.DataPointer + checked(y * (int)mapped.RowPitch), row, 0, row.Length); + Marshal.Copy(row, 0, pixels.Scan0 + y * pixels.Stride, row.Length); + } + } + finally { bitmap.UnlockBits(pixels); } + } + finally { immediate.Unmap(staging, 0); } + context.Check(); + using var output = new MemoryStream(); + bitmap.Save(output, ImageFormat.Png); + if (output.Length * 4 / 3 > context.Config.MaxResponseBytes) + throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The screenshot exceeds the response byte limit"); + return output.ToArray(); + } + + private static GraphicsCaptureItem ItemForWindow(nint window) + { + const string className = "Windows.Graphics.Capture.GraphicsCaptureItem"; + Marshal.ThrowExceptionForHR(WindowsCreateString(className, className.Length, out var name)); + nint factoryPointer = 0; + object? factory = null; + try + { + var factoryId = typeof(IGraphicsCaptureItemInterop).GUID; + Marshal.ThrowExceptionForHR(RoGetActivationFactory(name, ref factoryId, out factoryPointer)); + factory = Marshal.GetObjectForIUnknown(factoryPointer); + var itemId = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); + Marshal.ThrowExceptionForHR(((IGraphicsCaptureItemInterop)factory).CreateForWindow(window, ref itemId, out var item)); + try { return MarshalInterface.FromAbi(item); } + finally { Marshal.Release(item); } + } + finally + { + if (factory is not null) Marshal.FinalReleaseComObject(factory); + if (factoryPointer != 0) Marshal.Release(factoryPointer); + WindowsDeleteString(name); + } + } + + public async ValueTask DisposeAsync() + { + await admission.Join(); + await dispatcher.Invoke(() => + { + captureDevice?.Dispose(); + immediate?.Dispose(); + device?.Dispose(); + return true; + }, CancellationToken.None); + await dispatcher.DisposeAsync(); + } + + [ComImport, Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IGraphicsCaptureItemInterop + { + [PreserveSig] int CreateForWindow(nint window, ref Guid id, out nint item); + [PreserveSig] int CreateForMonitor(nint monitor, ref Guid id, out nint item); + } + [ComImport, Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IDirect3DDxgiInterfaceAccess + { + [PreserveSig] int GetInterface(ref Guid id, out nint value); + } + [DllImport("d3d11.dll", ExactSpelling = true)] private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint device, out nint result); + [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern int WindowsCreateString(string source, int length, out nint value); + [DllImport("combase.dll")] private static extern int WindowsDeleteString(nint value); + [DllImport("combase.dll")] private static extern int RoGetActivationFactory(nint name, ref Guid id, out nint value); +} diff --git a/packages/experimental/cua-windows/native/src/Windows.cs b/packages/experimental/cua-windows/native/src/Windows.cs new file mode 100644 index 0000000000..08ec60d145 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Windows.cs @@ -0,0 +1,176 @@ +// Public window IDs never expose or revive a reused HWND. +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal readonly record struct Bounds(double X, double Y, double Width, double Height); +internal readonly record struct WindowGeometry(Win32.Rect Pixels, uint Dpi) +{ + internal Bounds Bounds => new(Pixels.Left, Pixels.Top, Pixels.Width, Pixels.Height); +} + +internal sealed class WindowState(uint id, nint handle, long epoch) +{ + internal uint Id { get; } = id; + internal nint Handle { get; } = handle; + internal long Epoch { get; } = epoch; + private WindowGeometry? observation; + + internal WindowGeometry Geometry(AppState app, RequestContext context) + { + context.Check(); + var process = app.RequireProcess(); + Win32.GetWindowThreadProcessId(Handle, out var pid); + if (!Win32.IsWindow(Handle) || pid != process.Pid || context.Sta.WindowEpoch(Handle) != Epoch) + throw new NativeFailure("WINDOW_CHANGED", "The selected window was destroyed or replaced; read fresh application state"); + if (Win32.DwmGetWindowAttribute(Handle, 9, out Win32.Rect rectangle, Marshal.SizeOf()) != 0 + && !Win32.GetWindowRect(Handle, out rectangle)) throw new NativeFailure("WINDOW_CHANGED", "The selected window geometry is unavailable"); + var dpi = Win32.GetDpiForWindow(Handle); + if (dpi == 0 || rectangle.Width <= 0 || rectangle.Height <= 0) + throw new NativeFailure("WINDOW_CHANGED", "The selected window has no usable bounds"); + return new(rectangle, dpi); + } + + internal void Observe(WindowGeometry value) => observation = value; + + internal WindowGeometry RequireObservation(AppState app, RequestContext context) + { + var current = Geometry(app, context); + if (observation is not { } previous) throw new NativeFailure("OBSERVATION_REQUIRED", "Read AX state or capture this window before using coordinates"); + if (current.Pixels.Width != previous.Pixels.Width || current.Pixels.Height != previous.Pixels.Height || current.Dpi != previous.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window size or display scale changed; read fresh state before input"); + return current; + } + + internal static Win32.Point Point(WindowGeometry geometry, double x, double y) + { + if (!double.IsFinite(x) || !double.IsFinite(y) || x < 0 || y < 0 || x >= geometry.Bounds.Width || y >= geometry.Bounds.Height) + throw new NativeFailure("INVALID_ARGUMENT", "Coordinates must be inside the observed window"); + return new() + { + X = geometry.Pixels.Left + Math.Min(geometry.Pixels.Width - 1, (int)Math.Round(x)), + Y = geometry.Pixels.Top + Math.Min(geometry.Pixels.Height - 1, (int)Math.Round(y)), + }; + } + + internal object Describe(AppState app, RequestContext context) + { + var geometry = Geometry(app, context); + var length = Win32.GetWindowTextLength(Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(Handle, title, title.Capacity); + return new + { + windowId = Id, pid = 4, appName = app.RequireProcess().Name, + title = title.ToString(), bounds = geometry.Bounds, isOnScreen = IsOnScreen(), onCurrentSpace = (bool?)null, + }; + } + + internal bool IsOnScreen() => Win32.IsWindowVisible(Handle) && !Win32.IsIconic(Handle) + && (Win32.DwmGetWindowAttribute(Handle, 14, out int cloaked, sizeof(int)) != 0 || cloaked == 0); +} + +internal static class Windows +{ + internal static WindowState[] Refresh(AppState app, RequestContext context) + { + var process = app.RequireProcess(); + if (app.SelectedWindow is { } selected) { selected.Geometry(app, context); return [selected]; } + var handles = new List(); + Win32.EnumWindows((window, _) => + { + Win32.GetWindowThreadProcessId(window, out var pid); + var style = Win32.GetWindowLongPtr(window, -16).ToInt64(); + var extended = Win32.GetWindowLongPtr(window, -20).ToInt64(); + if (pid == process.Pid && (extended & 0x80) == 0 + && (Win32.IsWindowVisible(window) || (style & 0x00C00000) == 0x00C00000) + && Win32.GetWindowRect(window, out var bounds) && bounds.Width > 0 && bounds.Height > 0) handles.Add(window); + return true; + }, 0); + foreach (var pair in app.Windows.ToArray()) + { + if (handles.Contains(pair.Key) && pair.Value.Epoch == context.Sta.WindowEpoch(pair.Key)) continue; + app.Windows.Remove(pair.Key); + foreach (var scope in app.Snapshots.Where(item => item.Value.Windows.Any(window => window.Id == pair.Value.Id)).Select(item => item.Key).ToArray()) + app.Snapshots.Remove(scope); + } + foreach (var handle in handles) + { + if (!app.Windows.ContainsKey(handle)) + { + app.Windows.Add(handle, new(app.AllocateWindowId(), handle, context.Sta.WindowEpoch(handle))); + } + } + return handles.Select(handle => app.Windows[handle]).ToArray(); + } + + internal static WindowState Resolve(AppState app, uint id, RequestContext context) => Refresh(app, context) + .SingleOrDefault(window => window.Id == id) ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window from getWindows"); + + internal static WindowState? Focused(AppState app, WindowState[] windows) + { + var foreground = Win32.GetAncestor(Win32.GetForegroundWindow(), 2); + var front = windows.FirstOrDefault(window => window.Handle == foreground); + if (front is not null) return front; + var roots = new HashSet(); + foreach (var thread in windows.Select(window => Win32.GetWindowThreadProcessId(window.Handle, out _)).Distinct()) + { + var info = new Win32.GuiThreadInfo { Size = (uint)Marshal.SizeOf() }; + if (Win32.GetGUIThreadInfo(thread, ref info)) + { + var focused = Win32.GetAncestor(info.Focus != 0 ? info.Focus : info.Active, 2); + if (focused != 0) roots.Add(focused); + } + } + var matches = windows.Where(window => roots.Contains(window.Handle)).ToArray(); + return matches.Length == 1 ? matches[0] : null; + } + + internal static WindowState? Default(AppState app, WindowState[] windows) + { + var visible = windows.Where(window => window.IsOnScreen()).ToArray(); + var focused = Focused(app, visible); + if (focused is not null) return focused; + if (visible.Length == 1) return visible[0]; + if (visible.Length == 0 && windows.Length <= 1) return windows.SingleOrDefault(); + throw new NativeFailure("AMBIGUOUS_WINDOW", "Select a window explicitly from getWindows"); + } + + internal static object Show(AppState app, uint? id, RequestContext context) + { + var target = id is { } selected ? Resolve(app, selected, context) : Default(app, Refresh(app, context)); + var before = Win32.GetForegroundWindow(); + if (target is not null) + { + target.Geometry(app, context); + if (!Win32.ShowWindowAsync(target.Handle, 4)) throw new NativeFailure("UNSUPPORTED", "Windows refused background restoration; explicitly activate the application if needed"); + } + var after = Win32.GetForegroundWindow(); + return new { dispatched = true, windowId = (uint?)target?.Id, + foregroundChanged = before == 0 || after == 0 ? (bool?)null : before != after }; + } + + internal static void Activate(AppState app, WindowState? target, RequestContext context) + { + target ??= Default(app, Refresh(app, context)) ?? throw new NativeFailure("WINDOW_NOT_FOUND", "The application has no window to activate"); + target.Geometry(app, context); + if (Win32.IsIconic(target.Handle)) Win32.ShowWindowAsync(target.Handle, 9); + if (Win32.GetForegroundWindow() != target.Handle && !Win32.SetForegroundWindow(target.Handle)) + throw new NativeFailure("FOREGROUND_DENIED", "Windows refused foreground access; ask the user to focus the target window"); + } + + internal static void RequireForeground(AppState app, WindowState? target, RequestContext context) + { + context.Check(); + DesktopSession.RequireInteractive(); + target ??= app.SelectedWindow; + target?.Geometry(app, context); + var foreground = Win32.GetForegroundWindow(); + Win32.GetWindowThreadProcessId(foreground, out var pid); + if (pid != app.RequireProcess().Pid || target is not null && Win32.GetAncestor(foreground, 2) != target.Handle) + throw new NativeFailure("FOREGROUND_REQUIRED", "This input needs the target in front; explain why, explicitly activate or raise it, then observe again"); + } +} diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs new file mode 100644 index 0000000000..b12458997a --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -0,0 +1,96 @@ +// Portable checks exercise admission, framing, text offsets, and model-visible formatting. +using System.Text; +using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; + +var checks = 0; +void Check(bool condition, string message) +{ + if (!condition) throw new Exception(message); + checks++; +} +void Refuses(Action action, string code) +{ + try { action(); throw new Exception("Expected refusal: " + code); } + catch (NativeFailure failure) { Check(failure.Code == code, "Unexpected refusal: " + failure.Code); } +} + +var request = NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":20,"maxDepth":5}}""")); +Check(request.Method == "getState" && request.Id == "one", "Valid requests retain correlation and method"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"click","params":{"appHandle":"app","windowId":1,"x":-1,"y":2}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":0,"maxDepth":5}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"typeText","params":{"appHandle":"app","text":"hello","unowned":1}}""")), "INVALID_ARGUMENT"); +Refuses(() => WireJson.Parse("""{"id":"one","id":"two"}"""), "INVALID_REQUEST"); +Refuses(() => WireJson.Parse("""{"params":{"x":1,"x":2}}"""), "INVALID_REQUEST"); +Check(NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")).Method == "launchApp", "Host launch continuation remains admitted"); + +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"close"}"""), null) == NativeControl.Close, "Connection close needs no active operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one") == NativeControl.Cancel, "Cancellation matches the live operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one", completed: true) == NativeControl.CompletedCancel, + "Cancellation arriving after the matching response is a no-op"); +foreach (var frame in new[] { "null", "[]", "{}", "{\"type\":1}", + "{\"type\":\"close\",\"extra\":1}", "{\"type\":\"cancel\"}", + "{\"type\":\"cancel\",\"id\":null}", "{\"type\":\"cancel\",\"id\":1}", + "{\"type\":\"cancel\",\"id\":\"other\"}", "{\"type\":\"cancel\",\"id\":\"one\",\"extra\":1}" }) + Refuses(() => NativeControlFrame.Parse(WireJson.Parse(frame), "one"), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":null}"""), null), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), null), "INVALID_REQUEST"); + +var bytes = Encoding.UTF8.GetBytes("你好\nnext\n"); +var reader = new FrameReader(new MemoryStream(bytes)); +Check(await reader.ReadAsync(7, CancellationToken.None) == "你好", "Frame limits count UTF-8 bytes including newline"); +Check(await reader.ReadAsync(5, CancellationToken.None) == "next", "Buffered next frames remain readable"); +Check(await reader.ReadAsync(1, CancellationToken.None) is null, "Clean EOF is distinct from a partial frame"); +try { await new FrameReader(new MemoryStream(bytes)).ReadAsync(6, CancellationToken.None); throw new Exception("Oversized frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "NATIVE_REQUEST_LIMIT", "Oversized UTF-8 frames fail before parsing"); } +try { await new FrameReader(new MemoryStream("partial"u8.ToArray())).ReadAsync(20, CancellationToken.None); throw new Exception("Partial frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "INVALID_REQUEST", "Partial EOF is rejected"); } +try { await new FrameReader(new MemoryStream([0xff, 0x0a])).ReadAsync(2, CancellationToken.None); throw new Exception("Invalid UTF-8 accepted"); } +catch (DecoderFallbackException) { checks++; } + +Check(TextSelection.Find("😀 first repeat; second repeat", "repeat", "second ", null) == new TextMatch(24, 6), "Offsets use UTF-16 including surrogate pairs"); +Refuses(() => TextSelection.Find("repeat repeat", "repeat", null, null), "AMBIGUOUS_TEXT"); +Refuses(() => TextSelection.Find("repeat", "other", null, null), "TEXT_NOT_FOUND"); +Refuses(() => TextSelection.Find("text", "", null, null), "INVALID_ARGUMENT"); +Check(TextSelection.Find("aaaa", "aa", "aa", null) == new TextMatch(2, 2), "Overlapping literal matches retain adjacent context"); + +var html = HtmlClipboard.Encode("你好😀"); +var header = Encoding.UTF8.GetString(html); +int Offset(string name) => int.Parse(header.Split('\n').Single(line => line.StartsWith(name + ':')).Split(':')[1].Trim()); +Check(Encoding.UTF8.GetString(html, Offset("StartFragment"), Offset("EndFragment") - Offset("StartFragment")) == "你好😀", "CF_HTML byte offsets preserve Unicode"); +Check(Offset("EndHTML") == html.Length - 1, "CF_HTML excludes the terminating NUL"); + +Check(KeyChord.Parse("ctrl++", []).Key == "+", "Plus key remains a key after chord parsing"); +Check(KeyChord.Parse("+", []).Modifiers.Length == 0, "Bare plus has no modifier"); +Check(KeyChord.Parse("Control+a", ["ctrl"]).Modifiers.SequenceEqual(["control"]), "Equivalent modifiers deduplicate"); +Refuses(() => KeyChord.Parse("ctrl+", []), "INVALID_ARGUMENT"); +Refuses(() => KeyChord.Parse("fn+a", []), "UNSUPPORTED"); + +var node = new AccessibilityNode { Role = "AXTextField", Name = "Title", Value = "", HasValue = true, Placeholder = "Title", ValueWritable = "true", Actions = ["Press", "Focus"] }; +var text = AccessibilityText.Format(node, 3, false); +Check(text.Contains("= \"\" placeholder=\"Title\""), "Empty values and placeholders remain distinct"); +Check(!text.Contains("\"Press\"") && text.Contains("\"Focus\""), "Common actions compact without hiding secondary actions"); +Check(AccessibilityText.Format(node, 3, true).Contains("\"Press\""), "Details retain complete action names"); +Check(!AccessibilityText.Retain(new() { Role = "AXGroup" }), "Empty structural containers can collapse"); +Check(AccessibilityText.Retain(new() { Role = "AXGroup", Actions = ["Copy"] }), "Actionable containers retain their row"); +Check(AccessibilityText.Format(new() { Role = "AXTextArea", Value = "abc", HasValue = true, HasSelection = true, Selection = new(2, 5) }, 0, false) + .Contains("selection=unavailable"), "Out-of-range selections do not describe valid text"); +var captures = new CaptureAdmission(); +var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); +var ownedCapture = captures.Start(() => cleanup.Task); +using var cancelled = new CancellationTokenSource(); +cancelled.Cancel(); +try { await ownedCapture.WaitAsync(cancelled.Token); throw new Exception("Cancelled capture caller remained attached"); } +catch (OperationCanceledException) { checks++; } +Refuses(() => captures.Start(() => Task.FromResult(new byte[] { 2 })), "CAPTURE_BUSY"); +var joined = captures.Join(); +Check(!joined.IsCompleted, "Native cleanup retains ownership after its caller stops waiting"); +cleanup.SetResult([1]); +await joined; +Check((await captures.Start(() => Task.FromResult(new byte[] { 2 })))[0] == 2, "Completed cleanup admits a fresh capture"); +var failed = captures.Start(() => Task.FromException(new NativeFailure("CAPTURE_FAILED", "device lost"))); +try { await failed; throw new Exception("Capture error disappeared"); } +catch (NativeFailure failure) { Check(failure.Code == "CAPTURE_FAILED", "Capture failure remains attached to its requesting connection"); } +await captures.Join(); +Check((await captures.Start(() => Task.FromResult(new byte[] { 3 })))[0] == 3, "A settled capture failure does not reserve a permanent slot"); +Console.WriteLine($"{checks} portable CUA checks passed"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj new file mode 100644 index 0000000000..9ad2abfcee --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + true + + + + diff --git a/packages/experimental/cua-windows/native/tests/packages.lock.json b/packages/experimental/cua-windows/native/tests/packages.lock.json new file mode 100644 index 0000000000..f693fbd9af --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/packages.lock.json @@ -0,0 +1,40 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + } + } +} diff --git a/packages/experimental/cua-windows/package.json b/packages/experimental/cua-windows/package.json new file mode 100644 index 0000000000..b2779ebe25 --- /dev/null +++ b/packages/experimental/cua-windows/package.json @@ -0,0 +1,95 @@ +{ + "name": "@deepseek-ai/dsh-cua-windows", + "description": "Windows C# computer use through shared application and window objects", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/cua-windows" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*" + }, + "dependencies": { + "zod": "4.6.6", + "@deepseek-ai/dsh-cua": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-native-command": "workspace:*", + "@deepseek-ai/dsh-atomic-write": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-sandbox-local": "workspace:*", + "@deepseek-ai/dsh-sandbox-policy": "workspace:*", + "sharp": "^0.35.3", + "@deepseek-ai/dsh-ptc-runtime": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*", + "@deepseek-ai/dsh-settings": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", + "@deepseek-ai/dsh-config-editor": "workspace:*", + "@deepseek-ai/dsh-hmr": "workspace:*", + "@deepseek-ai/cordis-plugin-timer": "workspace:~" + }, + "files": [ + "lib/index.js", + "native/bin", + "native/CuaWindows.csproj", + "native/Directory.Build.props", + "native/app.manifest", + "native/src", + "native/protocol", + "native/protocol.schema.json", + "native/packages.lock.json", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "scripts": { + "build:native": "dotnet publish native/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableWindowsTargeting=true" + }, + "os": [ + "win32", + "linux" + ] +} diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts new file mode 100644 index 0000000000..7c844eb1a0 --- /dev/null +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -0,0 +1,2 @@ +/** TODO: Windows platform guidance after the interface migration. */ +export const GUIDANCE = 'TODO: Windows Computer Use guidance.' diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts new file mode 100644 index 0000000000..f74f61b539 --- /dev/null +++ b/packages/experimental/cua-windows/src/index.ts @@ -0,0 +1,91 @@ +/** Windows C# provider for the shared Computer Use application and window API. */ +import { isAbsolute, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import Schema from '@deepseek-ai/schemastery' +import { CuaConfig, installCua, type CuaStartupCapabilities } from '@deepseek-ai/dsh-cua' +import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' +import { prepareNativeExecutable, nativeHostArchitecture } from './native-build.ts' +import { WindowsNativeRuntime } from './native-runtime.ts' +import { GUIDANCE } from './guidance.ts' +import { windowsHost, prepareWsl, retainWslHelper } from './windows-host.ts' + +const CAPABILITIES: CuaStartupCapabilities = { + platform: 'windows', + methods: [ + 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'typeText', 'paste', 'pressKey', 'scroll', 'drag', 'screenshot', + ], + appLevelAccessibility: false, + keyboard: ['window'], + browser: false, + coordinateSpace: 'screenshot-pixels', +} + +/** Loader identity of the Windows provider. */ +export const name = 'cua-windows' +/** Services required by shared CUA execution and managed native preparation. */ +export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] + +/** Windows compiler and native waiting policy, alongside shared CUA resource limits. */ +export interface Config extends CuaConfig { + /** .NET SDK executable used for source preparation; installed payloads do not require it. */ + dotnetPath: string + /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ + windowsPowerShellPath: string + /** Milliseconds between application-readiness and clipboard-release observations. */ + pollIntervalMs: number +} + +/** Validate platform configuration before launching the compiler or helper. */ +export const Config = Schema.object({ + ...CuaConfigFields, + connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), + dotnetPath: Schema.string().min(1).default('dotnet'), + windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), + pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), + textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), + maxRequestBytes: CuaConfigFields.maxRequestBytes.max(2 ** 31 - 1), + maxResponseBytes: CuaConfigFields.maxResponseBytes.max(2 ** 31 - 1), + maxClipboardBytes: CuaConfigFields.maxClipboardBytes.max(2 ** 31 - 1), +}) satisfies Schema, Config> + +/** + * Prepare the Windows payload and install the shared authorized operation pipeline. + * @param ctx - Owning provider context. + * @param config - Validated compiler, operation bounds, and application grants. + * @returns Completion after preparation and reversible registrations. + */ +export async function apply(ctx: Context, config: Config): Promise { + const host = windowsHost() + if (config.helperPath !== undefined && !isAbsolute(config.helperPath)) throw new Error('Windows CUA helperPath must be absolute') + const controller = new AbortController() + const prepare = async () => { + const wsl = host === 'wsl' ? await prepareWsl({ subprocess: ctx.subprocess, signal: controller.signal, + timeoutMs: config.connectTimeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined + let helperPath = config.helperPath + if (helperPath === undefined) { + const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) + helperPath = await prepareNativeExecutable({ + packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), architecture, dotnetPath: config.dotnetPath, + subprocess: ctx.subprocess, signal: controller.signal, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, + }) + } + return wsl ? retainWslHelper(helperPath, wsl.cacheDirectory, controller.signal) : helperPath + } + const prepared = prepare() + ctx.effect(() => async () => { + controller.abort() + // Activation owns preparation failures; disposal joins the same operation. + await prepared.catch(() => {}) + }, 'cua-windows.native-preparation') + const helperPath = await prepared + controller.signal.throwIfAborted() + const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, host === 'wsl' ? 'stdio' : 'pipe') + ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') + installCua(ctx, config, { + helperPath, createChannel: (_owner, native) => runtime.connect(native), guidance: GUIDANCE, capabilities: CAPABILITIES, + permissionParameters: (_method, permission) => ({ permission }), + }) +} diff --git a/packages/experimental/cua-windows/src/native-build.ts b/packages/experimental/cua-windows/src/native-build.ts new file mode 100644 index 0000000000..f87e93390f --- /dev/null +++ b/packages/experimental/cua-windows/src/native-build.ts @@ -0,0 +1,73 @@ +/** Source compilation and installed Windows C# helper resolution. */ +import { constants } from 'node:fs' +import { access } from 'node:fs/promises' +import { join } from 'node:path' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable as compileExecutable, sourceNativePackage } from '@deepseek-ai/dsh-cua/native-build' + +/** Architectures supported by the Windows helper payload. */ +export type NativeArchitecture = 'arm64' | 'x64' + +/** Compiler invocation and resource ownership for one Windows payload. */ +export interface NativeBuildSpec { + packageRoot: string + architecture: NativeArchitecture + dotnetPath: string + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number +} + +/** + * Validate the runtime host before preparing Windows native code. + * @param platform - Node host platform. + * @param architecture - Node process architecture. + * @returns Supported Windows architecture. + */ +export function nativeHostArchitecture(platform: string, architecture: string): NativeArchitecture { + if (platform !== 'win32' || (architecture !== 'arm64' && architecture !== 'x64')) + throw new Error('The Windows Computer Use provider requires Windows on x64 or ARM64') + return architecture +} + +/** + * Locate the package-owned Windows executable. + * @param packageRoot - Directory containing the Windows provider manifest. + * @param architecture - Architecture of the process running the helper. + * @returns Absolute payload path. + */ +export function nativeExecutablePath(packageRoot: string, architecture: NativeArchitecture): string { + return join(packageRoot, 'native', 'bin', `win-${architecture}`, 'dsh-cua-windows.exe') +} + +/** + * Publish a self-contained C# executable; the build can run on macOS with Windows targeting enabled. + * @param spec - SDK command, target, compiler ownership, and deadlines. + * @returns Immutable content-addressed executable after compiler cleanup. + */ +export function buildNativeExecutable(spec: NativeBuildSpec): Promise { + const native = join(spec.packageRoot, 'native') + const output = join(native, '.build', `win-${spec.architecture}`) + return compileExecutable({ ...spec, + argv: [spec.dotnetPath, 'publish', join(native, 'CuaWindows.csproj'), '--configuration', 'Release', + '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', output, + '-p:EnableWindowsTargeting=true'], + outputPath: join(output, 'dsh-cua-windows.exe'), executablePath: nativeExecutablePath(spec.packageRoot, spec.architecture), + lockPath: join(native, '.build', 'publish'), + retainedDirectory: join(native, '.build', 'prepared', spec.architecture), binaryName: 'dsh-cua-windows.exe', + }) +} + +/** + * Compile only source checkouts; installed packages require their packaged native payload. + * @param spec - Source build and runtime target inputs. + * @returns The ready executable path. + */ +export async function prepareNativeExecutable(spec: NativeBuildSpec): Promise { + if (await sourceNativePackage(spec.packageRoot, 'packages/experimental/cua-windows')) return buildNativeExecutable(spec) + const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) + await access(executable, constants.X_OK) + spec.signal.throwIfAborted() + return executable +} diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts new file mode 100644 index 0000000000..bf5da9aff3 --- /dev/null +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -0,0 +1,354 @@ +/** Host-owned connector and independently disposable Agent connections to a shared Windows helper. */ +import { createHash, randomUUID } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { addAbortListener } from 'node:events' +import { realpath } from 'node:fs/promises' +import { PassThrough, Writable, type Readable, type Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeChannel, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { z } from 'zod' +import { connectWindowsPipe, type WindowsConnection, type WindowsTransport } from './native-transport.ts' + +const Ready = z.object({ + type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string(), instanceId: z.string().min(1), +}).strict() +const Started = Ready.extend({ endpoint: z.string().min(1), launcherId: z.string().min(1) }).strict() +// Private transport control frames have fixed encoding; operation replies pass through unchanged. +const closedFrame = Buffer.from('{"type":"closed"}\n') +type Owner = { subprocess: Pick } + +function failure(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)) } + +async function interruptible(operation: Promise, signal: AbortSignal): Promise { + const cancelled = Promise.withResolvers() + using _listener = addAbortListener(signal, () => { cancelled.reject(signal.reason) }) + return await Promise.race([operation, cancelled.promise]) +} + +function firstFrame(stream: Readable, signal: AbortSignal): Promise<{ value: unknown; rest: Buffer }> { + signal.throwIfAborted() + return new Promise((resolve, reject) => { + let bytes = Buffer.alloc(0) + const clean = () => { + stream.off('data', data).off('error', rejectFrame).off('end', ended).off('close', ended) + signal.removeEventListener('abort', aborted) + } + const rejectFrame = (error: Error) => { clean(); reject(error) } + const ended = () => { rejectFrame(new NativeError('NATIVE_EOF', 'Helper ended before native readiness')) } + const aborted = () => { rejectFrame(failure(signal.reason)) } + const data = (chunk: Buffer) => { + const newline = chunk.indexOf(10) + const size = newline < 0 ? chunk.length : newline + 1 + if (bytes.length + size > 8192) { rejectFrame(new NativeError('NATIVE_PROTOCOL', 'Native readiness exceeded its byte limit')); return } + bytes = Buffer.concat([bytes, chunk.subarray(0, size)]) + if (newline < 0) return + stream.pause() + clean() + try { + resolve({ value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, -1))), rest: chunk.subarray(size) }) + } catch (error) { reject(new NativeError('NATIVE_PROTOCOL', 'Invalid native readiness frame', { cause: error })) } + } + stream.on('data', data).on('error', rejectFrame).on('end', ended).on('close', ended) + signal.addEventListener('abort', aborted, { once: true }) + }) +} + +class WindowsHelper { + readonly ready: Promise> + readonly done: Promise + readonly sockets = new Set() + private readonly readiness = Promise.withResolvers>() + private readonly startup = new AbortController() + private handle: SubprocessHandle | undefined + private phase: 'starting' | 'ready' | 'closing' | 'closed' = 'starting' + private stopTimer: ReturnType | undefined + private error: Error | undefined + + constructor(private readonly owner: Owner, private readonly config: NativeClientConfig) { + this.ready = this.readiness.promise + void this.ready.catch(() => {}) + this.done = this.run() + void this.done.catch(() => {}) + } + + get ended(): boolean { return this.phase === 'closing' || this.phase === 'closed' } + + async stop(): Promise { + if (!this.ended) { + this.phase = 'closing' + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Computer Use is shutting down')) + this.handle?.stdin?.end() + this.stopTimer = setTimeout(() => { this.handle?.terminate() }, this.config.graceMs) + } + await this.done + } + + private async run(): Promise { + const startupTimer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows helper did not become ready before connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, this.config.connectTimeoutMs) + try { + const helperPath = await realpath(this.config.helperPath) + const digest = createHash('sha256') + for await (const chunk of createReadStream(helperPath, { signal: this.startup.signal })) digest.update(chunk as Buffer) + const runtimeKey = digest.digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + this.startup.signal.throwIfAborted() + const handle = this.owner.subprocess.spawn({ + argv: [helperPath, '--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(this.config.connectTimeoutMs), '--grace-ms', String(this.config.graceMs)], + cwd: this.config.cwd, graceMs: this.config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + this.handle = handle + assert(handle.stdin && handle.stdout, 'The helper requested piped control and readiness streams') + handle.stdout.on('error', (error: Error) => { this.error ??= error; this.startup.abort(error) }) + const exit = handle.done.then((outcome) => { + const diagnostic = handle.collected.stderr?.readFrom(0).text.trim() || 'no diagnostic output' + throw new NativeError('NATIVE_EXITED', + `Windows helper exited before readiness (${String(outcome.exitCode)}): ${diagnostic}. Check Windows application-control policy and helper signing.`) + }) + let frame: Awaited> + try { frame = await Promise.race([firstFrame(handle.stdout, this.startup.signal), exit]) } catch (error) { + // EOF can precede process settlement and its final collected stderr. + if (error instanceof NativeError && error.code === 'NATIVE_EOF') await interruptible(exit, this.startup.signal) + throw error + } + const ready = Started.parse(frame.value) + if (ready.runtimeKey !== runtimeKey || ready.launcherId !== instanceId || frame.rest.length !== 0) + throw new NativeError('NATIVE_PROTOCOL', 'Windows helper readiness has another identity or unexpected output') + this.startup.signal.throwIfAborted() + handle.stdout.on('data', () => { + this.error ??= new NativeError('NATIVE_PROTOCOL', 'Windows helper wrote unsolicited readiness data') + void this.stop().catch((error: unknown) => { this.error ??= failure(error) }) + }) + handle.stdout.resume() + clearTimeout(startupTimer) + this.phase = 'ready' + this.readiness.resolve(ready) + const outcome = await handle.done + if (!this.ended) this.error ??= new NativeError('NATIVE_EXITED', + `Windows helper stopped (${String(outcome.exitCode)}, ${String(outcome.signal)}); select applications again`) + } catch (error) { this.error ??= failure(error) } + finally { + clearTimeout(startupTimer) + this.phase = 'closing' + const error = this.error ?? new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') + for (const socket of this.sockets) socket.destroy(error) + const handle = this.handle + try { + if (handle) { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, this.config.graceMs) + try { + await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows helper process range did not exit') + } finally { clearTimeout(timer) } + } + } finally { + clearTimeout(this.stopTimer) + this.phase = 'closed' + this.readiness.reject(error) + } + } + } +} + +class WindowsChannel implements NativeChannel { + readonly stdout = new PassThrough() + readonly stdin: Writable + readonly done: Promise + private readonly startup = new AbortController() + private readonly readiness = Promise.withResolvers() + private readonly closed: PromiseWithResolvers = Promise.withResolvers() + private socket: Duplex | undefined + private closing = false + private closeTimer: ReturnType | undefined + + constructor(helper: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport) { + this.stdin = new Writable({ + write: (chunk: Buffer, _encoding, callback) => { + void this.readiness.promise.then((socket) => { + if (this.closing) { callback(new NativeError('NATIVE_CLOSED', 'Native connection is closing')); return } + socket.write(chunk, callback) + }, callback) + }, + final: (callback) => { this.close(); callback() }, + destroy: (error, callback) => { this.close(); callback(error) }, + }) + for (const stream of [this.stdin, this.stdout]) stream.on('error', () => {}) + void this.readiness.promise.catch(() => {}) + void this.closed.promise.catch(() => {}) + this.done = this.run(helper, config, pollIntervalMs, owner, transport) + void this.done.catch(() => {}) + } + + close(): void { + if (this.closing) return + this.closing = true + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Native connection closed before readiness')) + if (this.socket && !this.socket.destroyed) this.socket.write('{"type":"close"}\n') + } + + waitForClose(): Promise { return this.closed.promise } + + private async run(helperPromise: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport): Promise { + let helper: WindowsHelper | undefined + let connection: WindowsConnection | undefined + let closed: Promise | undefined + let caught: Error | undefined + let admitted = false + const observation = { acknowledged: false } + const timer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows native connection exceeded connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, config.connectTimeoutMs) + try { + helper = await interruptible(helperPromise, this.startup.signal) + const ready = await interruptible(helper.ready, this.startup.signal) + this.startup.signal.throwIfAborted() + connection = connectWindowsPipe(owner.subprocess, config, ready.endpoint, ready.runtimeKey, transport) + const socket = connection.stream + this.socket = socket + helper.sockets.add(socket) + let socketError: Error | undefined + closed = new Promise((resolve, reject) => { + socket.on('error', (error: Error) => { socketError = error }) + socket.on('close', () => { + if (socketError) reject(socketError) + else if (!observation.acknowledged) reject(new NativeError('NATIVE_EOF', 'Windows pipe closed without cleanup acknowledgement')) + else resolve() + }) + }) + void closed.catch(() => {}) + const abort = () => { socket.destroy(failure(this.startup.signal.reason)) } + this.startup.signal.addEventListener('abort', abort, { once: true }) + try { + const frame = firstFrame(socket, this.startup.signal) + void frame.catch(() => {}) + await connection.connected + this.startup.signal.throwIfAborted() + { + const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, + screenshotTimeoutMs, timeoutMs, graceMs, maxClickHoldMs } = config + socket.write(JSON.stringify({ type: 'hello', protocol: 1, runtimeKey: ready.runtimeKey, + config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs, pollIntervalMs, maxClickHoldMs } }) + '\n') + } + const response = await frame + const accepted = Ready.parse(response.value) + if (accepted.runtimeKey !== ready.runtimeKey || accepted.instanceId !== ready.instanceId || accepted.pid !== ready.pid) + throw new NativeError('NATIVE_PROTOCOL', 'Windows pipe belongs to another helper instance') + this.startup.signal.throwIfAborted() + admitted = true + this.startup.signal.removeEventListener('abort', abort) + clearTimeout(timer) + const close = () => { + this.closeTimer ??= setTimeout(() => { socket.destroy(new NativeError('NATIVE_CLEANUP', 'Windows pipe did not acknowledge cleanup')) }, config.graceMs) + } + this.startup.signal.addEventListener('abort', close, { once: true }) + let prefix: Buffer | undefined = Buffer.alloc(0) + const receive = (chunk: Buffer) => { + let offset = 0 + while (offset < chunk.length) { + const newline = chunk.indexOf(10, offset) + const end = newline < 0 ? chunk.length : newline + 1 + const piece = chunk.subarray(offset, end) + if (prefix !== undefined) prefix = prefix.length + piece.length <= closedFrame.length + ? Buffer.concat([prefix, piece]) : undefined + if (newline >= 0) { + if (prefix?.equals(closedFrame)) { + if (!this.closing) { + socket.destroy(new NativeError('NATIVE_PROTOCOL', 'Unexpected Windows cleanup acknowledgement')) + return + } + observation.acknowledged = true + } + prefix = Buffer.alloc(0) + } + offset = end + } + if (!this.closing) this.stdout.write(chunk) + } + socket.on('data', receive) + if (response.rest.length !== 0) receive(response.rest) + socket.resume() + this.readiness.resolve(socket) + try { await closed } finally { this.startup.signal.removeEventListener('abort', close) } + } finally { this.startup.signal.removeEventListener('abort', abort) } + } catch (error) { + const cause = failure(error) + if (!this.closing || admitted) caught = cause + this.readiness.reject(cause) + } + finally { + clearTimeout(timer) + clearTimeout(this.closeTimer) + this.closing = true + this.socket?.destroy() + if (closed) { + try { await closed } catch (error) { if (admitted) caught ??= failure(error) } + } + if (this.socket) helper?.sockets.delete(this.socket) + let cleanupError: Error | undefined + try { await connection?.dispose() } catch (error) { cleanupError = failure(error); caught ??= cleanupError } + if (admitted && !observation.acknowledged) { + cleanupError = new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement') + } + this.stdin.destroy() + if (caught) this.stdout.destroy(caught) + else this.stdout.end() + if (cleanupError) this.closed.reject(cleanupError) + else this.closed.resolve() + } + if (caught) throw caught + } +} + +/** One provider owns a service lease; Agent connections own only their application and snapshot state. */ +export class WindowsNativeRuntime { + private helper: WindowsHelper | undefined + private disposal: Promise | undefined + private readonly channels = new Set() + + /** + * @param owner Managed subprocess provider. + * @param pollIntervalMs Clipboard and application-readiness polling interval. + * @param transport Resolved native Windows or WSL connection method. + */ + constructor(private readonly owner: Owner, private readonly pollIntervalMs: number, private readonly transport: WindowsTransport = 'pipe') {} + + /** + * Connect one Agent without transferring process ownership to that Agent. + * @param config Executable identity and per-connection limits. + * @returns The byte stream used by the shared native request client. + */ + connect(config: NativeClientConfig): NativeChannel { + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + const acquire = async () => { + if (this.helper?.ended) await this.helper.done + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + if (!this.helper || this.helper.ended) this.helper = new WindowsHelper(this.owner, config) + return this.helper + } + const channel = new WindowsChannel(acquire(), config, this.pollIntervalMs, this.owner, this.transport) + this.channels.add(channel) + void channel.done.then(() => this.channels.delete(channel), () => this.channels.delete(channel)) + return channel + } + + /** Close Agent pipes and join this Host's connector; other Hosts retain their service leases. */ + dispose(): Promise { + return this.disposal ??= (async () => { + for (const channel of this.channels) channel.close() + const channels = await Promise.allSettled([...this.channels].map(channel => channel.waitForClose())) + let processError: unknown + try { await this.helper?.stop() } catch (error) { processError = error } + const errors: unknown[] = [] + for (const result of channels) { if (result.status === 'rejected') errors.push(result.reason) } + if (processError !== undefined) errors.push(processError) + if (errors.length) throw new AggregateError(errors, 'Windows Computer Use cleanup failed') + })() + } +} diff --git a/packages/experimental/cua-windows/src/native-transport.ts b/packages/experimental/cua-windows/src/native-transport.ts new file mode 100644 index 0000000000..d72b47b4eb --- /dev/null +++ b/packages/experimental/cua-windows/src/native-transport.ts @@ -0,0 +1,65 @@ +/** Direct Windows pipes and WSL subprocess streams for the same native protocol. */ +import { Socket } from 'node:net' +import { Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' + +/** Transport selected from the resolved Host environment. */ +export type WindowsTransport = 'pipe' | 'stdio' + +/** One connection owns its stream and, for WSL, a Windows bridge process. */ +export interface WindowsConnection { + stream: Duplex + connected: Promise + dispose(): Promise +} + +/** + * Connect to a Windows desktop service without exposing a network listener. + * @param subprocess Managed process owner for the WSL bridge. + * @param config Helper executable and connection/cleanup limits. + * @param endpoint Named pipe reported by the verified service lease. + * @param runtimeKey Expected executable digest, verified again by the Windows bridge. + * @param transport Native pipe or standard streams through WSL interoperation. + * @returns Owned connection; disposal joins the bridge process after stream closure. + */ +export function connectWindowsPipe(subprocess: Pick, config: NativeClientConfig, + endpoint: string, runtimeKey: string, transport: WindowsTransport): WindowsConnection { + if (transport === 'pipe') { + const stream = new Socket() + const connected = new Promise((resolve, reject) => { + stream.once('connect', resolve) + stream.once('error', reject) + }) + void connected.catch(() => {}) + stream.connect(endpoint) + return { stream, connected, dispose: async () => {} } + } + const handle = subprocess.spawn({ + argv: [config.helperPath, '--bridge', '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(config.connectTimeoutMs), '--grace-ms', String(config.graceMs)], + cwd: config.cwd, graceMs: config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + assert(handle.stdin && handle.stdout, 'The Windows bridge requires standard input and output') + const stream = Duplex.from({ readable: handle.stdout, writable: handle.stdin }) + stream.once('end', () => { stream.end() }) + void handle.done.then((outcome) => { + if (outcome.exitCode !== 0 || outcome.signal !== null) + stream.destroy(new NativeError('NATIVE_EXITED', `Windows bridge failed: ${handle.collected.stderr?.readFrom(0).text ?? String(outcome.exitCode)}`)) + }, (error: unknown) => { stream.destroy(error instanceof Error ? error : new Error(String(error))) }) + return { + stream, connected: Promise.resolve(), + async dispose() { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, config.graceMs) + try { + const outcome = await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows bridge process did not exit') + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('NATIVE_CLEANUP', `Windows bridge exited unsuccessfully (${String(outcome.exitCode)}, ${String(outcome.signal)})`) + } finally { clearTimeout(timer) } + }, + } +} diff --git a/packages/experimental/cua-windows/src/windows-host.ts b/packages/experimental/cua-windows/src/windows-host.ts new file mode 100644 index 0000000000..584b53f2d1 --- /dev/null +++ b/packages/experimental/cua-windows/src/windows-host.ts @@ -0,0 +1,93 @@ +/** Windows desktop execution from native Windows or a WSL process. */ +import { createHash } from 'node:crypto' +import { mkdir, readFile } from 'node:fs/promises' +import { join, win32 } from 'node:path' +import { isWsl, type HostEnvironmentFacts } from '@deepseek-ai/dsh-native-command' +import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' +import { NativeError } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { z } from 'zod' +import type { NativeArchitecture } from './native-build.ts' + +/** DSH execution environment, independently of the Windows desktop it controls. */ +export type WindowsHost = 'windows' | 'wsl' + +/** + * Resolve the Host before compiling or launching native code. + * @param facts Process and kernel facts; omitted fields use the current Host. + * @returns Native Windows or WSL; ordinary Linux has no Windows desktop provider. + */ +export function windowsHost(facts: HostEnvironmentFacts = {}): WindowsHost { + if ((facts.platform ?? process.platform) === 'win32') return 'windows' + if (isWsl(facts)) return 'wsl' + throw new NativeError('UNSUPPORTED', 'Windows Computer Use requires native Windows or WSL; ordinary Linux is unsupported') +} + +/** Managed command lifetime for WSL capability and path queries. */ +export interface WslPreparation { + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number + powershellPath: string +} + +async function command(spec: WslPreparation, argv: string[]): Promise { + spec.signal.throwIfAborted() + const signal = AbortSignal.any([spec.signal, AbortSignal.timeout(spec.timeoutMs)]) + const handle = spec.subprocess.spawn({ argv, cwd: process.cwd(), signal, graceMs: spec.graceMs, + stdio: { stdin: 'ignore', stdout: { maxBytes: 8192 }, stderr: { maxBytes: 8192 } } }) + try { + const outcome = await handle.done + signal.throwIfAborted() + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('WSL_INTEROP', `Windows interoperation failed: ${handle.collected.stderr?.readFrom(0).text ?? outcome.exitCode}`) + return handle.collected.stdout?.readFrom(0).text.trim() ?? '' + } finally { + handle.terminate() + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows preparation process did not exit') + } +} + +/** + * Verify that WSL can start Windows programs and resolve the Windows runtime architecture. + * @param spec Managed process policy and Windows PowerShell executable. + * @returns Windows architecture and a WSL-visible cache directory on the Windows filesystem. + */ +export async function prepareWsl(spec: WslPreparation): Promise<{ architecture: NativeArchitecture; cacheDirectory: string }> { + const script = "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); @{ architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant(); cache = [IO.Path]::Combine([Environment]::GetFolderPath('LocalApplicationData'), 'DeepSeekHarness', 'cua') } | ConvertTo-Json -Compress" + try { + const output = await command(spec, [spec.powershellPath, '-NoProfile', '-NonInteractive', '-Command', script]) + const result = z.object({ architecture: z.enum(['x64', 'arm64']), cache: z.string().refine(value => win32.isAbsolute(value)) }).strict().parse(JSON.parse(output)) + const cacheDirectory = await command(spec, ['wslpath', '-u', result.cache]) + if (!cacheDirectory.startsWith('/')) throw new NativeError('WSL_INTEROP', 'wslpath did not return an absolute cache directory') + return { architecture: result.architecture, cacheDirectory } + } catch (error) { + spec.signal.throwIfAborted() + throw new NativeError('WSL_INTEROP', 'WSL cannot prepare Windows Computer Use; check Windows interoperation and windowsPowerShellPath', { cause: error }) + } +} + +/** + * Retain the helper on the Windows filesystem so Explorer can launch the shared desktop service. + * @param helperPath Absolute executable path visible to WSL. + * @param cacheDirectory Windows user cache translated to a WSL path. + * @param signal Provider preparation lifetime. + * @returns Content-addressed executable path, without modifying the source payload. + */ +export async function retainWslHelper(helperPath: string, cacheDirectory: string, signal: AbortSignal): Promise { + const bytes = await readFile(helperPath, { signal }) + const digest = createHash('sha256').update(bytes).digest('hex') + const directory = join(cacheDirectory, digest) + const retained = join(directory, 'dsh-cua-windows.exe') + await mkdir(directory, { recursive: true }) + let existing: Buffer | undefined + try { existing = await readFile(retained, { signal }) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + signal.throwIfAborted() + if (existing && !existing.equals(bytes)) throw new NativeError('NATIVE_STARTUP', 'The cached Windows helper does not match its executable digest') + if (!existing) await writeFileAtomic(retained, bytes, { mode: 0o755 }) + signal.throwIfAborted() + return retained +} diff --git a/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts new file mode 100644 index 0000000000..369fd2f546 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts @@ -0,0 +1,22 @@ +/** Opt-in real desktop admission through the shipped managed subprocess provider. */ +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it, onTestFinished } from 'vitest' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +it.skipIf(!helperPath)('admits Windows desktop requests through managed WSL or native Windows processes', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(LocalSubprocessRuntime) + const runtime = new WindowsNativeRuntime(ctx, 25, process.platform === 'win32' ? 'pipe' : 'stdio') + onTestFinished(() => runtime.dispose()) + const client = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => runtime.connect(config)) + onTestFinished(() => client.dispose()) + expect(await client.request('getCapabilities', {}, new AbortController().signal)).toMatchObject({ + permissions: { accessibility: expect.any(Boolean), screenRecording: expect.any(Boolean) }, + }) +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/desktop-smoke.mjs b/packages/experimental/cua-windows/tests/desktop-smoke.mjs new file mode 100644 index 0000000000..2a476cc65d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-smoke.mjs @@ -0,0 +1,285 @@ +/** Real Windows acceptance against private fixture windows; no existing document is modified. */ +// TODO: migrate this old window-RPC smoke (discoverWindows/prepareWindows/prepareLaunch) to the listApps/getApp facade before running it again. +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { createHash, randomUUID } from 'node:crypto' +import { readFile, writeFile } from 'node:fs/promises' +import { createConnection } from 'node:net' +import { Duplex } from 'node:stream' +import { release } from 'node:os' +import { createInterface } from 'node:readline' +import { once } from 'node:events' +import { resolve } from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' + +const wsl = process.platform === 'linux' && (process.env.WSL_DISTRO_NAME || release().toLowerCase().includes('microsoft')) +assert(process.platform === 'win32' || wsl, 'Run with native Windows Node or WSL on an interactive Windows desktop') +const [helperFile, fixtureFile, outputFile] = process.argv.slice(2).map(path => resolve(path)) +assert(helperFile && fixtureFile && outputFile, 'Expected helper, fixture, and evidence file paths') +const resources = [] +const results = [] + +function lines(stream) { + const reader = createInterface({ input: stream }) + const iterator = reader[Symbol.asyncIterator]() + return async () => { + const result = await iterator.next() + assert(!result.done, 'The native stream ended before a response') + return JSON.parse(result.value) + } +} + +function child(file, args = []) { + const process = spawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) + const exit = once(process, 'exit') + const read = args.includes('--bridge') ? undefined : lines(process.stdout) + process.stderr.pipe(globalThis.process.stderr) + const resource = { process, exit, read } + resources.push(resource) + return resource +} + +async function checked(name, operation) { + const start = performance.now() + const detail = await operation() + results.push({ name, elapsedMs: Math.round(performance.now() - start), detail }) + console.log(JSON.stringify(results.at(-1))) + return detail +} + +const deadline = setTimeout(() => { + console.error('Desktop smoke exceeded its 90-second deadline') + process.exitCode = 1 + for (const resource of resources) resource.process.kill() +}, 90_000) +let socket +let bridge +try { + const fixture = child(fixtureFile) + const initial = await fixture.read() + const inspect = async command => { fixture.process.stdin.write(command + '\n'); return await fixture.read() } + const sentinel = child(fixtureFile) + const sentinelReady = await sentinel.read() + const cover = async () => { + await inspect(`allow:${sentinelReady.pid}`) + sentinel.process.stdin.write('focus\n') + const focused = await sentinel.read() + assert.equal(focused.foreground, focused.window, 'The sentinel needs foreground access') + return await inspect('inspect') + } + await cover() + const runtimeKey = createHash('sha256').update(await readFile(helperFile)).digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + const helper = child(helperFile, ['--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const other = child(helperFile, ['--serve', '--instance-id', randomUUID().replaceAll('-', ''), '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const [ready] = await checked('Concurrent Host connectors share one desktop service', async () => { + const pair = await Promise.all([helper.read(), other.read()]) + assert.equal(pair[0].pid, pair[1].pid) + assert.equal(pair[0].instanceId, pair[1].instanceId) + return pair + }) + assert.equal(ready.runtimeKey, runtimeKey) + if (wsl) { + bridge = child(helperFile, ['--bridge', '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + socket = Duplex.from({ readable: bridge.process.stdout, writable: bridge.process.stdin }) + socket.once('end', () => { socket?.end() }) + } else { + socket = createConnection(ready.endpoint) + await once(socket, 'connect') + } + const read = lines(socket) + const exchange = async value => { socket.write(JSON.stringify(value) + '\n'); return await read() } + const hello = await exchange({ type: 'hello', protocol: 1, runtimeKey, config: { + maxRequestBytes: 1_048_576, maxResponseBytes: 33_554_432, axTimeoutMs: 5000, textEventIntervalMs: 0, + screenshotTimeoutMs: 10000, timeoutMs: 15000, graceMs: 3000, pollIntervalMs: 25, maxClickHoldMs: 1000, + } }) + assert.equal(hello.instanceId, ready.instanceId) + other.process.stdin.end() + assert.deepEqual(await other.exit, [0, null]) + let sequence = 0 + const request = async (method, params = {}) => { + const response = await exchange({ id: String(++sequence), method, params }) + if (response.error) throw Object.assign(new Error(response.error.message), { code: response.error.code }) + return response.result + } + await checked('AppsFolder discovery and launch reach the Settings window', async () => { + const entries = await request('findApps', { query: 'immersivecontrolpanel', maxAppMatches: 20 }) + const entry = entries.find(entry => entry.kind === 'shell') + assert(entry, 'AppsFolder must expose the system Settings entry') + const prepared = await request('prepareLaunch', { target: entry.id }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + await assert.rejects(request('dispatchLaunch', { appHandle: prepared.appHandle }), { code: 'LAUNCH_ALREADY_DISPATCHED' }) + const until = performance.now() + 10000 + let target + do { + target = (await request('discoverWindows')).find(window => window.title === entry.displayName) + assert(performance.now() < until, 'Settings did not expose a selectable window') + if (!target) await delay(25) + } while (!target) + const [selected] = await request('prepareWindows', { ids: [target.windowId] }) + const observed = await request('getState', { appHandle: selected.appHandle, windowId: target.windowId, maxElements: 100, maxDepth: 20 }) + assert.equal(observed.windowId, target.windowId) + assert(observed.tree.length > 0) + return { entry: entry.id, window: target.title, axLength: observed.tree.length } + }) + await checked('An explicit executable path dispatches independently of Shell discovery', async () => { + const prepared = await request('prepareLaunch', { target: 'C:\\Windows\\System32\\notepad.exe' }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + return { target: prepared.authorization.executablePath } + }) + const windows = await request('discoverWindows') + const selected = windows.filter(window => window.pid === initial.pid && window.title === 'DSH CUA owned test window') + assert.equal(selected.length, 1) + assert.equal(selected[0].appName, 'dsh-cua-desktop-fixture') + const windowId = selected[0].windowId + const [app] = await request('prepareWindows', { ids: [windowId] }) + const appHandle = app.appHandle + const state = () => request('getState', { appHandle, windowId, maxElements: 100, maxDepth: 20, details: true }) + const baseline = await cover() + let observation = await checked('UIA observation without foreground change', async () => { + const result = await state() + const after = await inspect('inspect') + assert.equal(after.foreground, baseline.foreground) + assert.deepEqual(after.cursor, baseline.cursor) + return result + }) + const index = (text) => { + const row = observation.tree.split('\n').find(row => row.includes(text)) + assert(row, `Missing UIA row for ${text}`) + const match = row.match(/\[(\d+)\]/) + assert(match, `Missing actionable index for ${text}`) + return Number(match[1]) + } + await checked('Background UIA value and invoke affect the target', async () => { + const valueResult = await request('setValue', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('CUA test text'), value: '你好 😀 Windows' }) + const valued = await inspect('inspect') + assert.equal(typeof valueResult.foregroundChanged, 'boolean') + const clickResult = await request('click', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + const after = await inspect('inspect') + assert.equal(after.text, '你好 😀 Windows') + assert.equal(after.clicks, 1) + // UIA providers can activate after dispatch returns; later observations are separate samples. + assert.equal(typeof clickResult.foregroundChanged, 'boolean') + assert.deepEqual(after.cursor, baseline.cursor) + return { valueResult, clickResult, foregroundBefore: baseline.foreground, foregroundAfterValue: valued.foreground, after } + }) + for (const command of ['minimize', 'hide']) { + await checked(`show restores a ${command} window without activation`, async () => { + const foreground = (await cover()).foreground + const hidden = await inspect(command) + assert(command === 'minimize' ? hidden.minimized : !hidden.visible) + const restored = await request('show', { appHandle, windowId }) + assert.equal(restored.windowId, windowId) + const until = performance.now() + 5000 + let current + do { + current = await inspect('inspect') + assert(performance.now() < until, 'show did not restore the window') + } while (current.minimized || !current.visible) + assert.equal(current.foreground, foreground) + observation = await state() + return { restored, state: current } + }) + } + const covered = await cover() + await checked('Window capture without foreground change', async () => { + const capture = await request('screenshot', { appHandle, windowId }) + const after = await inspect('inspect') + assert.equal(after.foreground, covered.foreground) + assert.deepEqual(after.cursor, covered.cursor) + assert(capture.pixelWidth > 0 && capture.pixelHeight > 0) + assert(Buffer.from(capture.data, 'base64').subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) + return { width: capture.pixelWidth, height: capture.pixelHeight, bounds: capture.bounds } + }) + await checked('Background global input refuses before typing', async () => { + const before = await inspect('inspect') + assert.notEqual(before.foreground, before.window, 'Fixture must be in the background for this check') + await assert.rejects(request('typeText', { appHandle, text: 'MUST NOT TYPE' }), { code: 'FOREGROUND_REQUIRED' }) + assert.equal((await inspect('inspect')).text, before.text) + }) + await checked('Explicit fixture focus permits Unicode input', async () => { + sentinel.process.stdin.write(`allow:${initial.pid}\n`) + assert.equal((await sentinel.read()).allowed, true) + const focused = await inspect('focus') + assert.equal(focused.foreground, focused.window) + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('typeText', { appHandle, text: '实机 😀\r\nsecond line' }) + assert.equal((await inspect('inspect')).text, '实机 😀\r\nsecond line') + }) + await checked('Paste waits for consumption and updates the focused editor', async () => { + const previousClipboard = await inspect('clipboard-digest') + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('paste', { appHandle, text: '剪贴板 😀', format: 'text', maxClipboardBytes: 4_194_304, + pasteReadTimeoutMs: 1000, maxElements: 100, maxDepth: 20 }) + // Clipboard consumption can precede the editor applying the retrieved text. + const until = performance.now() + 5000 + while ((await inspect('inspect')).text !== '剪贴板 😀') { + assert(performance.now() < until, 'The editor did not apply the pasted text') + await delay(25) + } + assert.deepEqual(await inspect('clipboard-digest'), previousClipboard, 'Paste must restore the prior clipboard text') + }) + observation = await state() + await checked('Hover remains in place through observation and capture', async () => { + const result = await request('hover', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + assert.equal(result.hoverRoute, 'system-pointer') + const hovered = await inspect('inspect') + await state() + await request('screenshot', { appHandle, windowId }) + assert.deepEqual((await inspect('inspect')).cursor, hovered.cursor) + }) + observation = await state() + await checked('Cancelled timed click releases its button before replying', async () => { + const id = String(++sequence) + socket.write(JSON.stringify({ id, method: 'click', params: { + appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click'), holdMs: 1000, + } }) + '\n') + const until = performance.now() + 5000 + while ((await inspect('inspect')).buttons !== 'Left') { + assert(performance.now() < until, 'Timed click never pressed its button') + } + socket.write(JSON.stringify({ type: 'cancel', id }) + '\n') + const cancelled = await read() + assert.equal(cancelled.error?.code, 'NATIVE_CANCELLED') + assert.equal((await inspect('inspect')).buttons, 'None') + }) + await checked('A sibling window in the same process cannot borrow the selected window grant', async () => { + const sibling = await inspect('sibling') + assert.equal(sibling.foreground, sibling.window) + await assert.rejects(request('typeText', { appHandle, text: 'must not arrive' }), { code: 'FOREGROUND_REQUIRED' }) + const entries = await request('discoverWindows') + const otherWindow = entries.find(window => window.pid === initial.pid && window.title === 'DSH CUA sibling test window') + assert(otherWindow) + await assert.rejects(request('getState', { appHandle, windowId: otherWindow.windowId, maxElements: 100, maxDepth: 20 }), { code: 'WINDOW_CHANGED' }) + await inspect('focus') + return { siblingWindowId: otherWindow.windowId, selectedWindowId: windowId } + }) + await checked('Resize invalidates coordinates before pointer input', async () => { + await inspect('resize') + await assert.rejects(request('click', { appHandle, windowId, x: 20, y: 20 }), { code: 'WINDOW_CHANGED' }) + }) + const closed = once(socket, 'close') + await checked('Agent cleanup returns an explicit acknowledgement before EOF', async () => { + assert.deepEqual(await exchange({ type: 'close' }), { type: 'closed' }) + await closed + if (bridge) assert.deepEqual(await bridge.exit, [0, null]) + }) + socket = undefined + helper.process.stdin.end() + assert.deepEqual(await helper.exit, [0, null]) + fixture.process.stdin.write('close\n') + assert.deepEqual(await fixture.exit, [0, null]) + sentinel.process.stdin.write('close\n') + assert.deepEqual(await sentinel.exit, [0, null]) +} finally { + socket?.destroy() + for (const resource of resources) { + resource.process.stdin.end() + if (resource.process.exitCode === null && resource.process.signalCode === null) resource.process.kill() + } + await Promise.allSettled(resources.map(resource => resource.exit)) + clearTimeout(deadline) + await writeFile(outputFile, JSON.stringify({ platform: process.platform, environment: wsl ? 'wsl' : 'windows', results }, null, 2) + '\n') +} diff --git a/packages/experimental/cua-windows/tests/desktop-tool.spec.ts b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts new file mode 100644 index 0000000000..5fcb5c3c6d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts @@ -0,0 +1,71 @@ +/** Opt-in desktop screenshots through the actual CUA tool and attachment store. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use' +import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' +import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import { LlmAdapter, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { expect, it, onTestFinished } from 'vitest' +import { createCuaApi } from '@deepseek-ai/dsh-cua/api' +import sharp from 'sharp' +import * as Provider from '../src/index.ts' + +class ImageAdapter extends LlmAdapter { + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) + } + stream(): AsyncIterable { throw new Error('Desktop tests do not request model generation') } +} +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const selector = process.env.DSH_CUA_DESKTOP_TEST_APP +it.skipIf(!helperPath || !selector)('admits real application screenshots through the CUA tool', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-cua-desktop-tool-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestHarness(ctx) + await ctx.plugin(ComputerUseRegistry) + await ctx.plugin(SubprocessLocal) + await ctx.plugin(LocalAttachmentStore, { dshHome: root }) + await ctx.plugin(UserQuestions) + ctx.on('user-questions/request', async () => ({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] })) + await ctx.plugin(Provider, { helperPath: helperPath!, agentPreset: false }) + ctx.llm.registerAdapter(['desktop-test'], new ImageAdapter()) + const owner = await ctx.agents.create({ sessionId: SessionId('desktop-screenshot'), agentOptions: { provider: 'desktop-test', model: 'vision' } }) + let sequence = 0 + const dispatch: Parameters[0] = async (operation) => { + const batch = await ctx.tools.execute({ agent: owner.agent, signal: new AbortController().signal, + calls: [{ type: 'tool-call', id: ToolCallId(`desktop-${++sequence}`), name: 'cua', arguments: JSON.stringify(operation) }] }) + expect(batch.results).toHaveLength(1) + const result = batch.results[0]!.result + expect(result.isError, JSON.stringify(result.content)).toBe(false) + return result.value! + } + const emitted: string[] = [] + const api = createCuaApi(dispatch, { + text: (text) => { emitted.push(text) }, + image: (image) => { expect(image.bytes.byteLength).toBeGreaterThan(0) }, + }) + const discovered = (await api.listApps({ emit: false })).find(app => + app.id === selector || app.displayName.toLowerCase() === selector?.toLowerCase()) + expect(discovered).toBeDefined() + const app = await api.getApp(discovered!.id) + const target = (await app.getWindows({ emit: false })).find(window => + window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) + expect(target).toBeDefined() + const window = await app.getWindow(target!.windowId) + expect(emitted).toEqual([]) + await window.getAccessibilityTree() + expect(emitted).toHaveLength(1) + for (let i = 0; i < 5; ++i) { + const screenshot = await window.getScreenshot() + const decoded = await sharp(screenshot.bytes).raw().toBuffer({ resolveWithObject: true }) + expect(decoded.info.width).toBe(screenshot.pixelWidth) + expect(decoded.info.height).toBe(screenshot.pixelHeight) + } +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/native-build.spec.ts b/packages/experimental/cua-windows/tests/native-build.spec.ts new file mode 100644 index 0000000000..9c9eb60aa9 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-build.spec.ts @@ -0,0 +1,61 @@ +/** The Windows compiler publishes one immutable executable and installed packages need no SDK. */ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'cua-windows-build-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const packageRoot = join(root, 'packages/experimental/cua-windows') + await mkdir(packageRoot, { recursive: true }) + const bytes = Buffer.from('MZ Windows executable fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => ({ + stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, + done: (async () => { + const output = request.argv[request.argv.indexOf('--output') + 1]! + await mkdir(output, { recursive: true }) + await writeFile(join(output, 'dsh-cua-windows.exe'), bytes) + return { exitCode: 0, signal: null } + })(), + terminate: vi.fn(), waitForExit: async () => true, + })) + const spec = { packageRoot, architecture: 'x64' as const, dotnetPath: 'fixture-dotnet', subprocess: { spawn }, + signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 1000 } + return { root, spec, spawn, bytes } +} + +it.each(['x64', 'arm64'])('accepts the Windows %s process target', (architecture) => { + expect(nativeHostArchitecture('win32', architecture)).toBe(architecture) +}) +it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects unsupported %s/%s runtime targets', (platform, architecture) => { + expect(() => nativeHostArchitecture(platform, architecture)).toThrow('requires Windows') +}) + +it('passes an explicit Windows RID and SDK to the managed compiler and retains the bytes', async () => { + const f = await fixture() + const output = await buildNativeExecutable(f.spec) + expect(await readFile(output)).toEqual(f.bytes) + expect(await readFile(nativeExecutablePath(f.spec.packageRoot, 'x64'))).toEqual(f.bytes) + expect(f.spawn.mock.calls[0]![0].argv).toEqual(expect.arrayContaining([ + 'fixture-dotnet', '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', + ])) + expect(await buildNativeExecutable(f.spec)).toBe(output) +}) + +it('compiles a recognized source package and resolves an installed payload without a compiler', async () => { + const f = await fixture() + await writeFile(join(f.root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) + expect(await prepareNativeExecutable(f.spec)).toContain('prepared') + expect(f.spawn).toHaveBeenCalledOnce() + await rm(join(f.root, 'package.json')) + expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) + expect(f.spawn).toHaveBeenCalledOnce() + const controller = new AbortController() + controller.abort() + await expect(prepareNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow() + await rm(nativeExecutablePath(f.spec.packageRoot, 'x64')) + await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/native-runtime.spec.ts b/packages/experimental/cua-windows/tests/native-runtime.spec.ts new file mode 100644 index 0000000000..b3eb03caf2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-runtime.spec.ts @@ -0,0 +1,448 @@ +/** Real local pipes exercise Host ownership, Agent isolation, cancellation, and startup admission. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createConnection, createServer, type Socket } from 'node:net' +import { PassThrough } from 'node:stream' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { NativeClient, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +interface Frame { type?: string; id?: string; method?: string; runtimeKey?: string; config?: Record } +interface FixtureOptions { + transport?: 'pipe' | 'stdio' + startupDiagnostic?: string + startup?: 'wrong-runtime' | 'wrong-instance' | 'extra' | 'malformed' | 'oversized' | 'invalid-utf8' | 'exit' | 'silent' | 'stdout-error' | 'stdout-close' + handshake?: 'wrong-instance' | 'wrong-pid' | 'extra' | 'malformed' | 'oversized' | 'silent' | 'initial-result' + ignoreClose?: boolean + eofOnClose?: boolean + connectionCleanup?: Promise + ignoreParent?: boolean + processCleanup?: false | 'reject' + cleanupGate?: Promise + onSpawn?: () => void + split?: boolean +} + +async function fixture(options: FixtureOptions = {}) { + const directory = await mkdtemp(join(tmpdir(), 'cua-windows-pipes-')) + const clients: NativeClient[] = [] + const generations: Array<{ stop: () => Promise; stdout: PassThrough; received: Frame[]; peers: Set; endpoint: string }> = [] + const resources: { runtime?: WindowsNativeRuntime } = {} + onTestFinished(async () => { + await Promise.allSettled(clients.map(client => client.dispose())) + try { await resources.runtime?.dispose().catch(() => {}) } finally { + await Promise.all(generations.map(generation => generation.stop())) + await rm(directory, { recursive: true, force: true }) + } + }) + const helperPath = join(directory, 'helper.exe') + await writeFile(helperPath, 'Windows helper identity fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => { + if (request.argv.includes('--bridge')) { + const socket = createConnection(generations.at(-1)!.endpoint) + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + stdin.pipe(socket).pipe(stdout) + socket.on('error', (error) => { stdout.destroy(error) }) + socket.on('close', () => { done.resolve({ exitCode: 0, signal: null }) }) + return { stdin, stdout, stderr: undefined, control: undefined, collected: {}, done: done.promise, + terminate: () => { socket.destroy() }, waitForExit: async () => { await done.promise; return true } } + } + const instanceId = request.argv[request.argv.indexOf('--instance-id') + 1]! + const runtimeKey = request.argv[request.argv.indexOf('--runtime-key') + 1]! + const endpoint = process.platform === 'win32' ? `\\\\.\\pipe\\cua-test-${randomUUID()}` : join(directory, `${generations.length}.sock`) + const pid = 100 + generations.length + const stdin = new PassThrough(), stdout = new PassThrough() + const exited = Promise.withResolvers() + const ready: PromiseWithResolvers = Promise.withResolvers() + const peers = new Set() + const received: Frame[] = [] + let stopped: Promise | undefined + let diagnostic = '' + let nextConnection = 0 + const server = createServer({ allowHalfOpen: true }, (socket) => { + peers.add(socket) + socket.on('end', () => { socket.end() }) + const connection = ++nextConnection + socket.on('error', () => {}) + socket.on('close', () => { peers.delete(socket) }) + let buffered = '' + socket.on('data', (chunk: Buffer) => { + buffered += chunk.toString('utf8') + for (;;) { + const newline = buffered.indexOf('\n') + if (newline < 0) return + const frame = JSON.parse(buffered.slice(0, newline)) as Frame + buffered = buffered.slice(newline + 1) + received.push(frame) + if (frame.type === 'hello') { + if (options.handshake === 'silent') return + const response = { type: 'ready', protocol: 1, runtimeKey, instanceId: options.handshake === 'wrong-instance' ? 'other' : instanceId, + pid: options.handshake === 'wrong-pid' ? pid + 1 : pid, ...options.handshake === 'extra' ? { extra: true } : {} } + const text = options.handshake === 'malformed' ? '{bad}\n' : options.handshake === 'oversized' ? 'x'.repeat(8193) : JSON.stringify(response) + '\n' + if (options.split) { socket.write(text.slice(0, 4)); socket.write(text.slice(4)) } + else socket.write(text + (options.handshake === 'initial-result' ? '{"id":"early","result":true}\n' : '')) + } else if (frame.type === 'close') { + if (!options.ignoreClose) void (async () => { + await options.connectionCleanup + if (!options.eofOnClose) { + if (options.split) { socket.write('{"type":'); socket.write('"closed"}\n') } + else socket.write('{"type":"closed"}\n') + } + socket.end() + })() + } else if (frame.type === 'cancel') socket.write(JSON.stringify({ id: frame.id, error: { code: 'NATIVE_CANCELLED', message: 'Cancelled' } }) + '\n') + else if (frame.method !== 'hold') socket.write(JSON.stringify({ id: frame.id, result: { connection, pid, method: frame.method } }) + '\n') + } + }) + }) + const stop = (): Promise => stopped ??= (async () => { + await ready.promise + const closedPeers = [...peers].map(peer => once(peer, 'close')) + for (const peer of peers) peer.destroy() + await Promise.all(closedPeers) + await new Promise((resolve, reject) => server.close((error) => { if (error) reject(error); else resolve() })) + const ended = options.startup === 'exit' ? once(stdout, 'end') : undefined + stdout.end() + await ended + diagnostic = options.startupDiagnostic ?? '' + exited.resolve({ exitCode: options.startup === 'exit' ? 1 : 0, signal: null }) + })() + stdin.on('finish', () => { if (!options.ignoreParent) void stop() }) + server.on('error', (error) => { ready.reject(error); exited.reject(error) }) + server.listen(endpoint, () => { + ready.resolve() + if (options.startup === 'silent') return + if (options.startup === 'stdout-error') { stdout.destroy(new Error('readiness IO failure')); return } + if (options.startup === 'stdout-close') { stdout.end(); return } + if (options.startup === 'exit') { void stop(); return } + const response = { type: 'ready', protocol: 1, endpoint, pid, + runtimeKey: options.startup === 'wrong-runtime' ? 'other' : runtimeKey, + instanceId, launcherId: options.startup === 'wrong-instance' ? 'other' : instanceId } + const text = options.startup === 'malformed' ? '{bad}\n' : options.startup === 'oversized' ? 'x'.repeat(8193) + : JSON.stringify(response) + '\n' + (options.startup === 'extra' ? 'extra' : '') + if (options.startup === 'invalid-utf8') stdout.write(Buffer.from([255, 10])) + else if (options.split) { stdout.write(text.slice(0, 5)); stdout.write(text.slice(5)) } + else stdout.write(text) + }) + generations.push({ stop, stdout, received, peers, endpoint }) + options.onSpawn?.() + return { stdin, stdout, stderr: undefined, control: undefined, + collected: { stderr: { readFrom: () => ({ text: diagnostic, nextOffset: Buffer.byteLength(diagnostic), lossy: false }) } }, + done: exited.promise, + terminate: () => { void stop() }, waitForExit: async () => { await exited.promise; await options.cleanupGate; if (options.processCleanup === 'reject') throw new Error('cleanup failed'); return options.processCleanup !== false } } + }) + const owner = { subprocess: { spawn } } + const runtime = new WindowsNativeRuntime(owner, 25, options.transport) + resources.runtime = runtime + const activeRuntime = runtime + const config: NativeClientConfig = { helperPath, cwd: directory, timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const client = () => { + const value = new NativeClient(owner, config, (_owner, native) => activeRuntime.connect(native)) + clients.push(value) + return value + } + return { directory, config, spawn, generations, runtime, client } +} + +it('shares one Host helper while closing only the selected Agent connection', async () => { + const f = await fixture({ split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('one', {}, signal)).toMatchObject({ connection: 1, pid: 100 }) + expect(await b.request('two', {}, signal)).toMatchObject({ connection: 2, pid: 100 }) + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.generations[0]!.received[0]?.config?.pollIntervalMs).toBe(25) + await a.dispose() + expect(await b.request('after-close', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await vi.waitFor(() => { expect(f.generations[0]!.peers.size).toBe(0) }) + await f.runtime.dispose() + expect(() => f.runtime.connect(f.config)).toThrow('disposed') +}) + +it('cancels a request without replacing the connection or replaying input', async () => { + const f = await fixture() + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const refused = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await refused + expect(client.disposed).toBe(false) + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('starts a fresh helper after process loss and makes the old client unusable', async () => { + const f = await fixture(), signal = new AbortController().signal + const first = f.client() + await first.request('first', {}, signal) + await f.generations[0]!.stop() + await vi.waitFor(() => { expect(first.disposed).toBe(true) }) + await expect(first.dispose()).rejects.toThrow('cleanup acknowledgement') + const next = f.client() + expect(await next.request('fresh', {}, signal)).toMatchObject({ pid: 101, connection: 1 }) + expect(f.spawn).toHaveBeenCalledTimes(2) +}) + +it.each(['wrong-runtime', 'wrong-instance', 'extra', 'malformed', 'oversized', 'invalid-utf8', 'exit'] as const)( + 'rejects %s startup before sending any desktop request', async (startup) => { + const f = await fixture({ startup }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it.each(['wrong-instance', 'wrong-pid', 'extra', 'malformed', 'oversized'] as const)( + 'rejects a %s Agent handshake before dispatch', async (handshake) => { + const f = await fixture({ handshake }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it('reports the helper exit diagnostic when stdout ends before process settlement', async () => { + const f = await fixture({ startup: 'exit', startupDiagnostic: 'Application-control policy refused the executable' }) + const pending = f.client().request('getCapabilities', {}, new AbortController().signal) + await expect(pending).rejects.toMatchObject({ code: 'NATIVE_EXITED' }) + await expect(pending).rejects.toThrow('Application-control policy refused the executable') + expect(f.generations[0]!.received).toEqual([]) + await f.runtime.dispose() +}) + +it('joins a connection closed before helper readiness', async () => { + const f = await fixture() + const client = f.client() + await client.dispose() + expect(client.disposed).toBe(true) + await f.runtime.dispose() +}) + +it('settles a queued write when its connection is closed before readiness', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const written = new Promise(resolve => channel.stdin.write('input\n', resolve)) + channel.close() + expect(await written).toBeInstanceOf(Error) + await channel.waitForClose() +}) + +it('ends the native connection when its writable stream is finalized', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + channel.stdin.end() + await channel.done + await channel.waitForClose() +}) + +it('rejects unsolicited process output and closes the admitted Agent', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('closes all active Agent connections when the Host unloads', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await f.runtime.dispose() + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) +}) + +it.each(['silent', 'stdout-error', 'stdout-close'] as const)('settles %s process startup and joins cleanup', async (startup) => { + const f = await fixture({ startup }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() + expect(f.generations[0]!.received).toEqual([]) +}) + +it('bounds a silent Agent handshake without sending desktop input', async () => { + const f = await fixture({ handshake: 'silent' }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.map(frame => frame.type)).toEqual(['hello']) +}) + +it('preserves bytes after pipe readiness for the request parser', async () => { + const f = await fixture({ handshake: 'initial-result' }) + const channel = f.runtime.connect(f.config) + const data = new Promise(resolve => channel.stdout.once('data', (chunk) =>{ resolve(String(chunk)) })) + expect(await data).toContain('"id":"early"') + channel.close() + await channel.waitForClose() +}) + +it('rejects a connection cleanup deadline and stops the Host process', async () => { + const f = await fixture({ ignoreClose: true, ignoreParent: true }) + f.config.graceMs = 100 + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') + await expect(channel.done).rejects.toThrow('cleanup') + await expect(channel.waitForClose()).rejects.toThrow('cleanup acknowledgement') +}) + +it.each([false, 'reject'] as const)('reports unsuccessful process-range cleanup: %s', async (processCleanup) => { + const f = await fixture({ processCleanup }) + await f.client().request('one', {}, new AbortController().signal) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('refuses writes after a ready connection starts closing', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + channel.close() + const error = await new Promise(resolve => channel.stdin.write('late\n', resolve)) + expect(error?.message).toContain('closing') + await channel.waitForClose() +}) + +it('joins shutdown requested synchronously while the subprocess is being acquired', async () => { + const options: FixtureOptions = {} + const f = await fixture(options) + let closing: Promise | undefined + options.onSpawn = () => { closing = f.runtime.dispose() } + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await closing +}) + +it('reports an untyped subprocess rejection as a request failure', async () => { + const f = await fixture() + f.spawn.mockImplementationOnce(() => { throw 'subprocess failure' }) + const channel = f.runtime.connect(f.config) + await expect(channel.done).rejects.toThrow('subprocess failure') + await channel.waitForClose() +}) + +it('forces a helper that ignores parent closure to stop after malformed readiness', async () => { + const f = await fixture({ startup: 'malformed', ignoreParent: true }) + f.config.graceMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() +}) + +it('contains a cleanup failure after unsolicited process output', async () => { + const f = await fixture({ processCleanup: 'reject' }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('does not restart a stopped helper while the Host is unloading', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + onTestFinished(() =>{ release.resolve() }) + const f = await fixture({ cleanupGate: release.promise }) + await f.client().request('ready', {}, new AbortController().signal) + await f.generations[0]!.stop() + await vi.waitFor(() =>{ expect(f.generations[0]!.stdout.readableEnded).toBe(true) }) + const channel = f.runtime.connect(f.config) + const done = expect(channel.done).resolves.toBeUndefined() + const closing = f.runtime.dispose() + release.resolve() + await Promise.all([done, closing]) + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('waits for the native cleanup frame even after an operation has completed', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + const f = await fixture({ connectionCleanup: release.promise }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + let settled = false + const closing = client.dispose().then(() => { settled = true }) + try { + await vi.waitFor(() => { expect(f.generations[0]!.received.some(frame => frame.type === 'close')).toBe(true) }) + expect(settled).toBe(false) + } finally { release.resolve() } + await closing + expect(settled).toBe(true) +}) + +it('refuses EOF as evidence that native connection cleanup completed', async () => { + const f = await fixture({ eofOnClose: true }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('rejects an unsolicited cleanup frame while an Agent is still active', async () => { + const f = await fixture() + const client = f.client() + await client.request('one', {}, new AbortController().signal) + for (const peer of f.generations[0]!.peers) peer.write('{"type":"closed"}\n') + await vi.waitFor(() => { expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('recognizes fragmented cleanup controls without buffering operation payloads', async () => { + const f = await fixture({ ignoreClose: true }) + const channel = f.runtime.connect(f.config) + const ready = once(channel.stdout, 'data') + channel.stdin.write('{"id":"one","method":"probe"}\n') + await ready + const peer = [...f.generations[0]!.peers][0]! + const send = async (part: string) => { + const received = once(channel.stdout, 'data') + peer.write(part) + expect(String((await received)[0])).toBe(part) + } + await send('{"id":') + await send('"two","result":"a long ') + await send('fragmented operation payload') + await send('"}\n') + channel.close() + peer.write('{"type":') + peer.end('"closed"}\n') + await channel.waitForClose() +}) + + +it('joins WSL bridge EOF after cleanup while keeping other Agents usable', async () => { + const f = await fixture({ transport: 'stdio', split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('first', {}, signal)).toMatchObject({ connection: 1 }) + expect(await b.request('second', {}, signal)).toMatchObject({ connection: 2 }) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--serve'))).toHaveLength(1) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--bridge'))).toHaveLength(2) + await a.dispose() + expect(await b.request('still-open', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await f.runtime.dispose() + expect(f.generations[0]!.peers.size).toBe(0) +}) + +it('forwards cancellation over WSL without replaying the request', async () => { + const f = await fixture({ transport: 'stdio' }) + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const rejected = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await rejected + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('rejects WSL EOF without a desktop cleanup acknowledgement', async () => { + const f = await fixture({ transport: 'stdio', eofOnClose: true }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) diff --git a/packages/experimental/cua-windows/tests/native-transport.spec.ts b/packages/experimental/cua-windows/tests/native-transport.spec.ts new file mode 100644 index 0000000000..276b5ad786 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-transport.spec.ts @@ -0,0 +1,29 @@ +/** WSL bridge exit is part of native connection cleanup, independently of protocol EOF. */ +import { PassThrough } from 'node:stream' +import { expect, it, onTestFinished } from 'vitest' +import type { NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import { connectWindowsPipe } from '../src/native-transport.ts' + +it.each([ + { exitCode: 0, signal: null, joined: true, error: undefined }, + { exitCode: 1, signal: null, joined: true, error: 'exited unsuccessfully' }, + { exitCode: 0, signal: null, joined: false, error: 'did not exit' }, +] as const)('joins bridge exit $exitCode with process cleanup $joined', async ({ exitCode, signal, joined, error }) => { + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + const handle: SubprocessHandle = { stdin, stdout, stderr: undefined, control: undefined, collected: {}, + done: done.promise, terminate: () => { done.resolve({ exitCode: null, signal: 'SIGTERM' }) }, + waitForExit: async () => joined } + const config: NativeClientConfig = { helperPath: '/fixture.exe', cwd: '/', timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const connection = connectWindowsPipe({ spawn: () => handle }, config, 'pipe', 'digest', 'stdio') + connection.stream.on('error', () => {}) + onTestFinished(() => { connection.stream.destroy(); stdin.destroy(); stdout.destroy() }) + const closing = connection.dispose() + expect(stdin.writableEnded).toBe(true) + done.resolve({ exitCode, signal }) + if (error) await expect(closing).rejects.toThrow(error) + else await closing +}) diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts new file mode 100644 index 0000000000..0064d22ccb --- /dev/null +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -0,0 +1,30 @@ +/** Both native languages admit the same generated model and Host operation fields. */ +import { readFile } from 'node:fs/promises' +import { expect, it } from 'vitest' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' +import { ActionResult, NativeScreenshotResult } from '@deepseek-ai/dsh-cua/protocol' +import { Config } from '../src/index.ts' + +it('keeps the C# admission schema identical to the shared generated schema', async () => { + expect(await readFile(new URL('../native/protocol.schema.json', import.meta.url), 'utf8')).toBe(nativeProtocol().json) +}) + +it('preserves Windows physical capture units and observed foreground changes', () => { + const image = { mimeType: 'image/png', data: 'AAAA', pixelWidth: 1200, pixelHeight: 800, windowId: 1, + bounds: { x: -1200, y: 0, width: 1200, height: 800 }, coordinateSpace: 'window-pixels' } + expect(NativeScreenshotResult.parse(image).coordinateSpace).toBe('window-pixels') + expect(() => NativeScreenshotResult.parse({ ...image, coordinateSpace: 'screen-pixels' })).toThrow() + expect(ActionResult.parse({ dispatched: true, verified: false, foregroundChanged: true })).toEqual({ + dispatched: true, foregroundChanged: true, + }) +}) + +it('resolves Windows compiler and input defaults while rejecting unsupported numeric limits', () => { + const resolved = Config({}) + expect(resolved.dotnetPath).toBe('dotnet') + expect(resolved.pollIntervalMs).toBe(25) + expect(resolved.textEventIntervalMs).toBe(0) + expect(() => Config({ dotnetPath: '' })).toThrow() + expect(() => Config({ pollIntervalMs: 0 })).toThrow() + expect(() => Config({ maxResponseBytes: 2 ** 31 })).toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts new file mode 100644 index 0000000000..4b1f2bf622 --- /dev/null +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -0,0 +1,108 @@ +/** Provider preparation must finish before installation and join cancellation on unload. */ +import { resolve } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { WslPreparation } from '../src/windows-host.ts' +import type { NativeBuildSpec } from '../src/native-build.ts' +import type { installCua } from '@deepseek-ai/dsh-cua' +import { beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { apply, Config } from '../src/index.ts' +import { GUIDANCE } from '../src/guidance.ts' + +const native = vi.hoisted(() => ({ + prepare: vi.fn<(spec: NativeBuildSpec) => Promise>(), + host: vi.fn<() => 'windows' | 'wsl'>(() => 'windows'), + wsl: vi.fn<(spec: WslPreparation) => Promise<{ architecture: 'arm64'; cacheDirectory: string }>>(), + retain: vi.fn<(path: string, cache: string, signal: AbortSignal) => Promise>(), + architecture: vi.fn(() => 'x64' as const), + install: vi.fn(), connect: vi.fn(), dispose: vi.fn(), construct: vi.fn(), +})) +vi.mock('../src/windows-host.ts', () => ({ windowsHost: native.host, prepareWsl: native.wsl, retainWslHelper: native.retain })) +vi.mock('../src/native-build.ts', async original => ({ + ...await original(), + prepareNativeExecutable: native.prepare, nativeHostArchitecture: native.architecture, +})) +vi.mock('@deepseek-ai/dsh-cua', async original => ({ + ...await original(), installCua: native.install, +})) +vi.mock('../src/native-runtime.ts', () => ({ WindowsNativeRuntime: class { + constructor(...args: unknown[]) { native.construct(...args) } + connect = native.connect + dispose = native.dispose +} })) +beforeEach(() => { vi.clearAllMocks(); native.host.mockReturnValue('windows'); native.prepare.mockResolvedValue(resolve('prepared-helper')); native.dispose.mockResolvedValue(undefined) }) +function owner() { const ctx = new Context(); onTestFinished(() => ctx.fiber.dispose()); return ctx } + +it('rejects relative overrides before installing a native provider', async () => { + await expect(apply(owner(), Config({ helperPath: 'relative.exe' }))).rejects.toThrow('must be absolute') + expect(native.install).not.toHaveBeenCalled() +}) +it('uses an absolute fixture without compiling and disposes the Host runtime', async () => { + const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) + await apply(ctx, config) + expect(native.prepare).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 13, 'pipe') + const backend = native.install.mock.calls[0]![2] + expect(backend.guidance).toBe(GUIDANCE) + expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) + const channel = { marker: 'native stream' } + native.connect.mockReturnValue(channel) + const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } + expect(backend.createChannel(ctx, options)).toBe(channel) + expect(native.connect).toHaveBeenCalledWith(options) + await ctx.fiber.dispose() + expect(native.dispose).toHaveBeenCalledOnce() +}) +it('prepares before installation and aborts the completed preparation scope on unload', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + native.prepare.mockReturnValueOnce(prepared.promise) + const pending = apply(ctx, Config({})) + expect(native.install).not.toHaveBeenCalled() + prepared.resolve(resolve('compiled.exe')) + await pending + expect(native.install.mock.calls[0]![2].helperPath).toBe(resolve('compiled.exe')) + await ctx.fiber.dispose() + expect(native.prepare.mock.calls[0]![0].signal.aborted).toBe(true) +}) +it('reports compiler failure without installing tool registrations', async () => { + native.prepare.mockRejectedValueOnce(new Error('compiler unavailable')) + const ctx = owner() + await expect(apply(ctx, Config({}))).rejects.toThrow('compiler unavailable') + await ctx.fiber.dispose() + expect(native.install).not.toHaveBeenCalled() +}) +it('joins canceled preparation and rejects its late success', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + onTestFinished(() =>{ prepared.resolve(resolve('late.exe')) }) + native.prepare.mockReturnValueOnce(prepared.promise) + const starting = apply(ctx, Config({})) + const rejected = expect(starting).rejects.toThrow() + const signal = native.prepare.mock.calls[0]![0].signal + const aborted = new Promise((resolve) =>{ signal.addEventListener('abort', () =>{ resolve() }, { once: true }) }) + let closed = false + const closing = ctx.fiber.dispose().then(() => { closed = true }) + await aborted + expect(closed).toBe(false) + prepared.resolve(resolve('late.exe')) + await Promise.all([rejected, closing]) + expect(native.install).not.toHaveBeenCalled() +}) + +it('prepares the Windows architecture and stdio transport for WSL', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockResolvedValue({ architecture: 'arm64', cacheDirectory: '/mnt/c/cache' }) + native.retain.mockResolvedValue('/mnt/c/cache/helper.exe') + const ctx = owner() + await apply(ctx, Config({})) + expect(native.prepare.mock.calls[0]![0].architecture).toBe('arm64') + expect(native.architecture).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 25, 'stdio') + expect(native.install.mock.calls[0]![2].helperPath).toBe('/mnt/c/cache/helper.exe') +}) + +it('does not compile or register CUA when WSL interoperation fails', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockRejectedValue(new Error('Windows interoperation unavailable')) + await expect(apply(owner(), Config({}))).rejects.toThrow('interoperation unavailable') + expect(native.prepare).not.toHaveBeenCalled() + expect(native.install).not.toHaveBeenCalled() +}) diff --git a/packages/experimental/cua-windows/tests/windows-host.spec.ts b/packages/experimental/cua-windows/tests/windows-host.spec.ts new file mode 100644 index 0000000000..3d27b5d1dc --- /dev/null +++ b/packages/experimental/cua-windows/tests/windows-host.spec.ts @@ -0,0 +1,66 @@ +/** WSL classification is independent of Windows interoperation and executable preparation. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { prepareWsl, retainWslHelper, windowsHost } from '../src/windows-host.ts' + +it('distinguishes Windows Node, WSL Linux Node, and ordinary Linux', () => { + expect(windowsHost({ platform: 'win32', env: { WSL_DISTRO_NAME: 'Ubuntu' } })).toBe('windows') + expect(windowsHost({ platform: 'linux', env: {}, osRelease: '6.6.87-microsoft-standard-WSL2' })).toBe('wsl') + expect(() => windowsHost({ platform: 'linux', env: {}, osRelease: '6.8.0-generic' })).toThrow('ordinary Linux') +}) + +function fixture(output = '{"architecture":"arm64","cache":"C:\\\\Users\\\\test user\\\\AppData\\\\Local\\\\DeepSeekHarness\\\\cua"}', exitCode = 0) { + const terminate = vi.fn(), waitForExit = vi.fn(async () => true) + const spawn = vi.fn((spec: SubprocessSpawnSpec): SubprocessHandle => { + const text = spec.argv[0] === 'wslpath' ? '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua\n' : output + return { stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, + collected: { stdout: { readFrom: () => ({ text, nextOffset: Buffer.byteLength(text), lossy: false }) } }, + done: Promise.resolve({ exitCode, signal: null }), terminate, waitForExit } + }) + return { spec: { subprocess: { spawn }, signal: new AbortController().signal, timeoutMs: 10_000, graceMs: 1000, powershellPath: 'powershell.exe' }, spawn, terminate, waitForExit } +} + +it('uses the Windows architecture and translates the cache without shell interpolation', async () => { + const f = fixture() + expect(await prepareWsl(f.spec)).toEqual({ architecture: 'arm64', cacheDirectory: '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua' }) + expect(f.spawn.mock.calls[1]![0].argv).toEqual(['wslpath', '-u', 'C:\\Users\\test user\\AppData\\Local\\DeepSeekHarness\\cua']) + expect(f.waitForExit).toHaveBeenCalledTimes(2) +}) + +it.each(['not json', '{"architecture":"ia32","cache":"C:\\\\cache"}', '{"architecture":"x64","cache":"relative"}'])( + 'rejects invalid Windows capability output %s before using it as a path', async (output) => { + const f = fixture(output) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.waitForExit).toHaveBeenCalledOnce() + }, +) + +it('reports unavailable interoperation and does not launch path conversion', async () => { + const f = fixture('', 1) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('rejects canceled preparation before starting a Windows command', async () => { + const f = fixture(), controller = new AbortController() + controller.abort(new Error('provider unloaded')) + await expect(prepareWsl({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') + expect(f.spawn).not.toHaveBeenCalled() +}) + +it('retains exact helper bytes once and rejects a changed cached executable', async () => { + const directory = await mkdtemp(join(tmpdir(), 'cua-wsl-cache-')) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const helper = join(directory, 'source.exe'), signal = new AbortController().signal + const bytes = Buffer.from('signed payload bytes') + await writeFile(helper, bytes) + const result = await retainWslHelper(helper, join(directory, 'cache'), signal) + expect(await readFile(result)).toEqual(bytes) + expect(await retainWslHelper(helper, join(directory, 'cache'), signal)).toBe(result) + await writeFile(result, 'changed') + await expect(retainWslHelper(helper, join(directory, 'cache'), signal)).rejects.toThrow('digest') +}) diff --git a/packages/experimental/cua-windows/tsconfig.json b/packages/experimental/cua-windows/tsconfig.json new file mode 100644 index 0000000000..0d2d829073 --- /dev/null +++ b/packages/experimental/cua-windows/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../cua/tsconfig.host.json" + }, + { + "path": "../../subprocess/subprocess" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/native-command" + }, + { + "path": "../../util/atomic-write" + } + ] +} diff --git a/packages/experimental/cua/src/access-types.ts b/packages/experimental/cua/src/access-types.ts index 4679f7ba14..0a587124d4 100644 --- a/packages/experimental/cua/src/access-types.ts +++ b/packages/experimental/cua/src/access-types.ts @@ -10,7 +10,7 @@ export interface CuaPermissionProcess { path?: string | undefined name?: string | undefined } -/** Native access observations tagged with Node platform identifiers; distinct from model capability platform names. */ +/** Native access observations tagged with the provider's CUA platform; distinct from Node process.platform values. */ export type CuaSystemPermissionState = { platform: 'darwin' accessibility: boolean @@ -20,7 +20,7 @@ export type CuaSystemPermissionState = { /** Application macOS reports as responsible for the helper, captured at startup; absent when it cannot be identified. */ launchApplication?: { name: string; path: string; icon?: string | undefined } | undefined } | { - platform: 'win32' + platform: 'windows' sessionLocked: boolean | null captureAvailable: boolean elevated: boolean diff --git a/packages/experimental/cua/src/access.ts b/packages/experimental/cua/src/access.ts index 35fe5a60a1..535bfe84fb 100644 --- a/packages/experimental/cua/src/access.ts +++ b/packages/experimental/cua/src/access.ts @@ -24,7 +24,7 @@ const systemPermissions = z.discriminatedUnion('platform', [z.object({ platform: z.literal('darwin'), accessibility: z.boolean(), screenRecording: z.boolean(), helper: permissionProcess, parent: permissionProcess, launchApplication: z.object({ name: z.string().min(1), path: z.string().min(1), icon: ApplicationIcon.optional() }).optional(), }), z.object({ - platform: z.literal('win32'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), + platform: z.literal('windows'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), elevated: z.boolean(), helper: permissionProcess, })]) diff --git a/packages/experimental/cua/src/client/PermissionPanel.tsx b/packages/experimental/cua/src/client/PermissionPanel.tsx index 699fd8b413..fdc43b5e7c 100644 --- a/packages/experimental/cua/src/client/PermissionPanel.tsx +++ b/packages/experimental/cua/src/client/PermissionPanel.tsx @@ -142,7 +142,7 @@ function UnknownStatus({ loading, t }: Pick & { loading: b } function WindowsStatus({ system, uncertain, t }: Pick & { - system: Extract + system: Extract uncertain: boolean }) { const unlocked = system.sessionLocked === false @@ -161,7 +161,7 @@ function WindowsStatus({ system, uncertain, t }: Pick & { function systemReady(system: CuaSystemPermissionState): boolean { switch (system.platform) { case 'darwin': return system.accessibility && system.screenRecording - case 'win32': return system.sessionLocked === false && system.captureAvailable + case 'windows': return system.sessionLocked === false && system.captureAvailable /* v8 ignore next -- Native permission responses validate the closed platform union. */ default: return assertNever(system) } @@ -195,7 +195,7 @@ export function PermissionPanel(props: PermissionPanelProps) { } {observed === null ? - : observed.platform === 'win32' ? + : observed.platform === 'windows' ? : (['accessibility', 'screenRecording'] as const).map(permission =>
@@ -207,7 +207,7 @@ export function PermissionPanel(props: PermissionPanelProps) { busy={busy} request={props.request} openSettings={props.openSettings} t={t} />
)}
-

{observed?.platform === 'win32' +

{observed?.platform === 'windows' ? <>{t('windowsInstructions')} {t(observed.elevated ? 'elevated' : 'standardPrivileges')} : t('permissionHint')}

@@ -241,12 +241,12 @@ export function PermissionSetup({ t, refresh, useCuaPermissions, onDismiss, onOp && systemReady(state.value) useEffect(() => { if (ready && !state.busy) onDismiss() }, [ready, state.busy, onDismiss]) return }> -

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'win32' ? 'setupBody' +

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'windows' ? 'setupBody' : state.value.sessionLocked === null ? 'windowsSessionUnknown' : state.value.sessionLocked ? 'windowsSetupBody' : 'windowsCaptureUnavailable')}

diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 93947ad32c..df935f6525 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -4,7 +4,7 @@ export const COMMON_GUIDANCE = `Use cua to observe and operate native applicatio In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes. -Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid. +Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. diff --git a/packages/experimental/cua/tests/panel.client.spec.tsx b/packages/experimental/cua/tests/panel.client.spec.tsx index 6558fd06d4..613f24fce3 100644 --- a/packages/experimental/cua/tests/panel.client.spec.tsx +++ b/packages/experimental/cua/tests/panel.client.spec.tsx @@ -439,7 +439,7 @@ it('retains a known read-only configuration and query failure throughout managem it.each([true, false, null] as const)('shows Windows desktop access for lock state %s without macOS permission actions', (sessionLocked) => { const f = fixture() - f.publish({ ...observe(value), system: { value: { platform: 'win32', sessionLocked, captureAvailable: true, + f.publish({ ...observe(value), system: { value: { platform: 'windows', sessionLocked, captureAvailable: true, elevated: false, helper: { pid: 9, path: 'C:\\helper.exe' } }, error: null, busy: false } }) render() const desktop = screen.getByRole('group', { name: en.windowsDesktop }) @@ -451,7 +451,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta expect(screen.queryByRole('button', { name: en.request })).toBeNull() expect(screen.queryByRole('button', { name: en.granted })).toBeNull() expect(screen.queryByText('C:\\helper.exe')).toBeNull() - f.publish({ system: { value: { platform: 'win32', sessionLocked: false, captureAvailable: false, + f.publish({ system: { value: { platform: 'windows', sessionLocked: false, captureAvailable: false, elevated: true, helper: { pid: 9 } }, error: null, busy: false } }) expect(within(capture).getByText(en.unavailable)).toBeTruthy() expect(screen.getByText(en.elevated, { exact: false })).toBeTruthy() @@ -461,7 +461,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta it.each([[true, true], [false, true], [false, false], [null, true]] as const)('offers Windows setup for lock=%s and capture=%s', (sessionLocked, captureAvailable) => { const f = fixture(), onDismiss = vi.fn() - f.publish({ system: { value: { platform: 'win32', sessionLocked, captureAvailable, + f.publish({ system: { value: { platform: 'windows', sessionLocked, captureAvailable, elevated: false, helper: { pid: 9 } }, error: null, busy: false } }) render() const needsSetup = sessionLocked !== false || !captureAvailable diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..f910604ac9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,6 +45,9 @@ importers: '@deepseek-ai/dsh-cua-bundle': specifier: workspace:* version: link:packages/experimental/cua-bundle + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:packages/experimental/cua-windows '@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp': specifier: workspace:* version: link:packages/experimental/browser-use-chrome-devtools-mcp @@ -9965,6 +9968,9 @@ importers: specifier: ^4.2.0 version: 4.3.2 optionalDependencies: + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:../cua-windows '@deepseek-ai/dsh-experimental-cua-macos': specifier: workspace:* version: link:../cua-macos @@ -10093,6 +10099,115 @@ importers: specifier: ^0.35.3 version: 0.35.5(@types/node@22.20.1) + packages/experimental/cua-windows: + dependencies: + '@deepseek-ai/dsh-atomic-write': + specifier: workspace:* + version: link:../../util/atomic-write + '@deepseek-ai/dsh-cua': + specifier: workspace:* + version: link:../cua + '@deepseek-ai/dsh-native-command': + specifier: workspace:* + version: link:../../util/native-command + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: ^4.4.3 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/cordis-plugin-timer': + specifier: workspace:~ + version: link:../../../vendor/timer + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:* + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:* + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-app-boot': + specifier: workspace:* + version: link:../../boot/app-boot + '@deepseek-ai/dsh-attachment': + specifier: workspace:* + version: link:../../attachment/attachment + '@deepseek-ai/dsh-attachment-local': + specifier: workspace:* + version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-computer-use': + specifier: workspace:* + version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-config-editor': + specifier: workspace:* + version: link:../../boot/config-editor + '@deepseek-ai/dsh-fs-local': + specifier: workspace:* + version: link:../../fs/fs-local + '@deepseek-ai/dsh-hmr': + specifier: workspace:* + version: link:../../boot/hmr + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:* + version: link:../../llm/llm-deepseek + '@deepseek-ai/dsh-ptc-runtime': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime + '@deepseek-ai/dsh-ptc-runtime-node': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime-node + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:* + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:* + version: link:../../sandbox/sandbox-policy + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-settings': + specifier: workspace:* + version: link:../../settings/settings + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-user-questions': + specifier: workspace:* + version: link:../../interaction/user-questions + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory + sharp: + specifier: ^0.35.3 + version: 0.35.5(@types/node@22.20.1) + packages/experimental/forge: dependencies: '@deepseek-ai/dsh-brand': diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index f759eca7ec..a9ec59f11b 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -190,6 +190,7 @@ const packageFileExtras: Readonly> = { // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'], '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/CuaWindows.csproj', 'native/Directory.Build.props', 'native/app.manifest', 'native/src', 'native/protocol', 'native/protocol.schema.json', 'native/packages.lock.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports. Its `./types` export is a type-only module, so diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index df85af1620..705eab4ec0 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -8,6 +8,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly> = { 'packages/experimental/cua': '@deepseek-ai/dsh-cua', 'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle', + 'packages/experimental/cua-windows': '@deepseek-ai/dsh-cua-windows', 'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query', 'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm', 'packages/experimental/tool-terminal': '@deepseek-ai/dsh-tool-terminal', diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index feed57673f..1f15a4de89 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -72,6 +72,7 @@ describe('release families', () => { '@deepseek-ai/dsh-creation-recommendations', '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-cua-macos', + '@deepseek-ai/dsh-cua-windows', '@deepseek-ai/dsh-cua', '@deepseek-ai/dsh-experimental-forge-bundle', '@deepseek-ai/dsh-experimental-forge-github', diff --git a/tsconfig.base.json b/tsconfig.base.json index cfecbdc02b..ba550bee2d 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -113,6 +113,7 @@ "@deepseek-ai/dsh-computer-use/brand": ["./packages/computer-use/computer-use/src/brand.ts"], "@deepseek-ai/dsh-experimental-computer-use-cua-driver-mcp": ["./packages/experimental/computer-use-cua-driver-mcp/src/index.ts"], "@deepseek-ai/dsh-experimental-cua-macos": ["./packages/experimental/cua-macos/src/index.ts"], + "@deepseek-ai/dsh-cua-windows": ["./packages/experimental/cua-windows/src/index.ts"], "@deepseek-ai/dsh-cua/config": ["./packages/experimental/cua/src/config.ts"], "@deepseek-ai/dsh-cua/native-schema": ["./packages/experimental/cua/src/native-schema.ts"], "@deepseek-ai/dsh-cua/native-build": ["./packages/experimental/cua/src/native-build.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index ea675b53ba..e82ffd9f53 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -251,6 +251,7 @@ "benchmarks/**/*.ts", "packages/*/*/tests/**/*.ts", "packages/experimental/cua-macos/native/generate-protocol.ts", + "packages/experimental/cua-windows/native/generate-protocol.ts", "packages/experimental/claude-code-mods/examples/*/index.ts", "packages/experimental/inspector/scripts/**/*.ts", "packages/llm/llm-pi-ai/scripts/**/*.ts", @@ -322,6 +323,7 @@ { "path": "./packages/experimental/cua/tsconfig.host.json" }, { "path": "./packages/experimental/cua-bundle" }, { "path": "./packages/experimental/cua-macos" }, + { "path": "./packages/experimental/cua-windows" }, { "path": "./packages/client/ui-sidebar-documentpreview/tsconfig.host.json" }, { "path": "./packages/client/ui-sidebar-browser/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, 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 026/396] 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 027/396] 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 fda29f726da9c2d23269d4a3638eef296a830f61 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:08 +0800 Subject: [PATCH 028/396] fix(user-questions): keep the answerer's message in PROVIDER_ERROR Wrapping a non-HarnessError answerer failure replaced its message with a generic sentence, so callers and the model lost the concrete reason, such as a closed connection. The PROVIDER_ERROR wrapper now keeps the original message and falls back to the generic sentence only for a value that is not an Error. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 9 +++++---- docs/subsystems/user-questions.zh.md | 9 +++++---- packages/interaction/user-questions/src/index.ts | 10 ++++++---- .../user-questions/tests/user-questions.spec.ts | 12 ++++++------ packages/plan/plan-mode/tests/plan-mode.spec.ts | 2 +- 6 files changed, 25 insertions(+), 21 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index bacd251ef1..483df1b1a4 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: eb0a4f94282f8c18 - zh: 92c41869431b120e + en: 832b165cfa48839d + zh: 6989f734b373c1f9 diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index c87fe49f14..daf0db242a 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original message and the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index 4dc465f750..aeb1818584 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,保留原 message,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 0242301291..5c850eeb54 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -286,9 +286,10 @@ export class UserQuestionService extends TypertRemoteService { * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -359,7 +360,8 @@ export class UserQuestionService extends TypertRemoteService { throw abortedQuestion(error) } if (restored instanceof HarnessError) throw restored - throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) + const message = error instanceof Error ? error.message : 'the user-questions answerer failed before the user answered' + throw new UserQuestionError(message, 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index a4f3208de1..09a32fd961 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -174,12 +174,12 @@ describe('UserQuestionService', () => { }) it.each([ - ['an ordinary Error', new Error('provider failed')], + ['an ordinary Error', new Error('provider failed'), 'provider failed'], ['a namesake Error without a string code', Object.assign(new Error('provider failed'), { name: 'UserQuestionError', - })], - ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { + }), 'provider failed'], + ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }, 'the user-questions answerer failed before the user answered'], + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection, message) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) @@ -188,7 +188,7 @@ describe('UserQuestionService', () => { questions: [{ id: 'confirm', question: 'Proceed?' }], }).then(() => undefined, (error: unknown) => error) expect(failure).toBeInstanceOf(UserQuestionError) - expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message, cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -579,7 +579,7 @@ describe('askTimed', () => { registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message: 'provider crashed', cause: crash }) await ctx.fiber.dispose() }) diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 0ebe17cb31..b65e283886 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1177,7 +1177,7 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) From 1440cf2fb97b6f393ae526a479958d631dcefaf6 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:10 +0800 Subject: [PATCH 029/396] test(subagent-dsh-sdk): expect ToolArgsError for effort-only delegation An effort-only route request now fails as ToolArgsError, whose message carries the "invalid arguments:" prefix; the production-profile e2e asserts that text and the recorded INVALID_ARGS identity. Refs #7869 --- .../subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts index b6d6e3d03f..bf7d3e394f 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts @@ -157,8 +157,9 @@ describe('SDK subagent routing and diagnostics through the production profile', expect(results[0]!.data.message.isError).toBe(true) expect(results[0]!.data.message.content).toEqual([{ type: 'text', - text: 'Error: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', + text: 'Error: invalid arguments: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', }]) + expect(results[0]!.data.error).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(events.some(event => event.type === 'subagent/catalog')).toBe(false) expect(existsSync(join(child.childHome, 'sessions'))).toBe(false) }, From de273ffe2d57d69dcd1aa327d8525421e00eab3d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:11 +0800 Subject: [PATCH 030/396] feat(typert): make RemoteError a HarnessError RemoteError extended plain Error because dsh-llm, which owned HarnessError, depends on dsh-typert-protocol. With HarnessError in the dependency-free dsh-error package, RemoteError now extends it and keeps its name, Remote code, details, and constructor, so a tool body that throws one records name RemoteError and its code on tool/result. An unknown or unloadable delegation preset therefore keeps the registry's agent-preset/not-found or agent-preset/invalid identity, and the subagent runtime no longer rewraps it as PRESET_UNAVAILABLE. Client bundles inline dsh-error with the protocol layer; no client code depends on HarnessError identity. Refs #7869 --- ...28-ctx-remote-failure-vocabulary.i18n.yaml | 4 ++-- ...026-08-28-ctx-remote-failure-vocabulary.md | 6 +++--- ...-08-28-ctx-remote-failure-vocabulary.zh.md | 6 +++--- docs/module-graph.md | 7 ++++--- docs/module-graph.zh.md | 7 ++++--- packages/client/tsdown.client.ts | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 8 ++++++-- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/package.json | 1 + packages/subagent/subagent/src/child-agent.ts | 14 ++++--------- .../tests/continuation-presets.spec.ts | 15 +++++--------- .../tests/preset-selection.spec.ts | 6 +++--- packages/typert/protocol/README.i18n.yaml | 4 ++-- packages/typert/protocol/README.md | 2 +- packages/typert/protocol/README.zh.md | 2 +- packages/typert/protocol/package.json | 6 ++++-- packages/typert/protocol/src/remote-error.ts | 12 ++++++----- .../protocol/tests/remote-error.spec.ts | 20 +++++++++++++++++++ packages/typert/protocol/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 22 files changed, 84 insertions(+), 55 deletions(-) create mode 100644 packages/typert/protocol/tests/remote-error.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml index 2e76fba547..2589183c49 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml @@ -9,8 +9,8 @@ en: 990d46f713fb6303 zh: 592cd6128a9640b1 /agent-note-one-remote-failure-vocabulary-for-ctx-remote/decision: - en: 120e2fb97ac765d8 - zh: 5d5f110db4a9b717 + en: b54b9d98a34eeaa1 + zh: ac8e3d493b554c2d /agent-note-one-remote-failure-vocabulary-for-ctx-remote/code-ownership: en: cc1d8b88f7349b77 zh: 70f010e3310e2667 diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md index 7238ae23b4..146a359889 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md @@ -16,12 +16,12 @@ Fixed Host facts bypassed `ctx.remote` too: the Host home came from `(ctx.get('c ## Decision -`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a real `Error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. +`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a `HarnessError` from the dependency-free `@deepseek-ai/dsh-error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md index db0b2969bc..12b2ad4f8e 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md @@ -16,12 +16,12 @@ Host 固定事实同样绕过了 `ctx.remote`:Host home 取自 `(ctx.get('conn ## Decision -`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个真 `Error`,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 +`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个继承无依赖包 `@deepseek-ai/dsh-error` 中 `HarnessError` 的错误,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/docs/module-graph.md b/docs/module-graph.md index 6913c9fca6..ef941e1c54 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -506,8 +506,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -553,6 +553,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1687,7 +1688,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1704,8 +1704,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | @@ -1728,6 +1728,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index aa668a72c2..ff50815bc6 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -508,8 +508,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -555,6 +555,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1689,7 +1690,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1706,8 +1706,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | @@ -1730,6 +1730,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 7df6b6f529..592b634dfb 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 199ff2c9a5..4b650a2362 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the original message, when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, @@ -6802,6 +6802,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'GrantRecord', declaration: 'export interface GrantRecord {\n readonly kind: \'grant\';\n readonly payload: unknown;\n}', }, + { + name: 'HarnessError', + declaration: 'export class HarnessError extends Error {\n readonly code: string;\n constructor(message: string, code: string, options?: ErrorOptions);\n}', + }, { name: 'HookBudget', declaration: 'export interface HookBudget {\n readonly ms: number;\n readonly remainingMs: number;\n}', @@ -8132,7 +8136,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RemoteError', - declaration: 'export class RemoteError extends Error {\n readonly isDSHRemoteError: true;\n constructor(readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', + declaration: 'export class RemoteError extends HarnessError {\n readonly isDSHRemoteError: true;\n constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', }, { name: 'RemoteErrorCode', diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index d89a9ce18b..01bc38e2e5 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: bdb3204a71ee2a8f - zh: 74d7d4e9eca20e2a + en: 4815c56bfcb844e9 + zh: 424c6133c4805a66 /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 916c73346e..6cac06daba 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE` (an unknown or unloadable selected preset keeps the registry's `RemoteError` code), a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index 8cc7e6bda9..1e8dbb6355 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝(所选 preset 未知或无法加载时保留 registry 的 `RemoteError` code),缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/package.json b/packages/subagent/subagent/package.json index 6bff46b9ee..7bfdb4194b 100644 --- a/packages/subagent/subagent/package.json +++ b/packages/subagent/subagent/package.json @@ -109,6 +109,7 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 89b2a59447..bbc669b363 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,7 +25,6 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -184,9 +183,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh - * delegation's preset is unknown or cannot load, or the child cannot join its creator's - * preset revision. Restoration propagates the registry's `RemoteError` unchanged. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. An unknown or unloadable selected + * preset rejects with the registry's `RemoteError` code. */ export function applyChildComposition( childCtx: Context, @@ -198,12 +197,7 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - const mounted = presets.mount(childCtx, composition.agentPreset) - // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. - return (parent === undefined ? mounted : mounted.catch((error: unknown) => { - const failure = remoteErrorOf(error) - throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) - })).then(() => { + return presets.mount(childCtx, composition.agentPreset).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 0cd3e0f69b..1dad8a15b1 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -13,6 +13,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry' +import { HarnessError } from '@deepseek-ai/dsh-error' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -139,17 +140,11 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) - it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + it('rejects an unknown independent preset with the registry RemoteError as a HarnessError', async () => { const { ctx, parent, adapter } = await setup() - await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ - name: 'SubagentError', - code: 'PRESET_UNAVAILABLE', - message: 'Unknown agent preset: absent', - cause: { code: 'agent-preset/not-found' }, - }) - const failure = new Error('binding failed') - vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) - await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + const failure: unknown = await ctx.subagents.startActivation(startSpec(parent, 'absent')).catch((error: unknown) => error) + expect(failure).toBeInstanceOf(HarnessError) + expect(failure).toMatchObject({ name: 'RemoteError', code: 'agent-preset/not-found', message: 'Unknown agent preset: absent' }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(adapter.requests).toEqual([]) }) diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 920697c323..a29e780d36 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,7 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -180,7 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/invalid' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -365,7 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') - expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(failed.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) diff --git a/packages/typert/protocol/README.i18n.yaml b/packages/typert/protocol/README.i18n.yaml index 018aebf137..aebf5c816e 100644 --- a/packages/typert/protocol/README.i18n.yaml +++ b/packages/typert/protocol/README.i18n.yaml @@ -27,8 +27,8 @@ en: 3db384ae6f215632 zh: 56207184b09d4018 /deepseek-ai-dsh-typert-protocol/use-this-package/reporting-and-reading-a-remote-failure: - en: 4ba5266ddb014029 - zh: e31ae6438b9b4aa5 + en: 32d5fdd4b678d86c + zh: 00af91a97b891592 /deepseek-ai-dsh-typert-protocol/use-this-package/receiving-forwarded-host-events-on-the-client: en: 1101bd1d1419618c zh: 6ff036538d237e0a diff --git a/packages/typert/protocol/README.md b/packages/typert/protocol/README.md index 8613555bf7..c85039ab3e 100644 --- a/packages/typert/protocol/README.md +++ b/packages/typert/protocol/README.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. +An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. `RemoteError` extends `HarnessError` from [`@deepseek-ai/dsh-error`](../../util/error/README.md), so a tool body that throws one records `name: 'RemoteError'` and its Remote `code` on `tool/result`. ### Receiving forwarded Host events on the Client diff --git a/packages/typert/protocol/README.zh.md b/packages/typert/protocol/README.zh.md index f02a8f5217..849a9c07be 100644 --- a/packages/typert/protocol/README.zh.md +++ b/packages/typert/protocol/README.zh.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。 +拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。`RemoteError` 继承 [`@deepseek-ai/dsh-error`](../../util/error/README.zh.md) 的 `HarnessError`,因此工具体抛出它时,`tool/result` 会记录 `name: 'RemoteError'` 及其 Remote `code`。 ### 在 Client 侧接收转发的 Host 事件 diff --git a/packages/typert/protocol/package.json b/packages/typert/protocol/package.json index 7fcc8f87f0..efb5f07aed 100644 --- a/packages/typert/protocol/package.json +++ b/packages/typert/protocol/package.json @@ -43,9 +43,11 @@ "zod": "4.6.6" }, "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/typert/protocol/src/remote-error.ts b/packages/typert/protocol/src/remote-error.ts index 90430a2093..476787eab9 100644 --- a/packages/typert/protocol/src/remote-error.ts +++ b/packages/typert/protocol/src/remote-error.ts @@ -1,15 +1,17 @@ /** The one Remote failure class shared by owners, the Gateway, and consumers. */ +import { HarnessError } from '@deepseek-ai/dsh-error' import type { RemoteErrorCode, RemoteErrorDetailsMap, RemoteFailure } from './types.ts' /** - * One Remote call failure: a real Error carrying its stable code and typed + * One Remote call failure: a `HarnessError` carrying its stable code and typed * details. Owners throw it at the failure point; the Host Gateway encodes it * onto the wire unchanged; the Client face rebuilds an instance for the * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. - * Discrimination is always by `code`, never by instanceof. + * A tool body that throws it records `name: 'RemoteError'` and its Remote code + * on `tool/result`. Discrimination is always by `code`, never by instanceof. */ -export class RemoteError extends Error { +export class RemoteError extends HarnessError { /** Structural marker: cross-realm/bundle identification never uses instanceof. */ readonly isDSHRemoteError: true = true @@ -20,12 +22,12 @@ export class RemoteError extends * @param options - standard Error options (`cause` survives in-process only). */ constructor( - readonly code: Code, + override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions, ) { - super(message, options) + super(message, code, options) this.name = 'RemoteError' } } diff --git a/packages/typert/protocol/tests/remote-error.spec.ts b/packages/typert/protocol/tests/remote-error.spec.ts new file mode 100644 index 0000000000..54c8388018 --- /dev/null +++ b/packages/typert/protocol/tests/remote-error.spec.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' + +describe('RemoteError', () => { + it('is a HarnessError that keeps its Remote code, details, and cause', () => { + const cause = new Error('backend closed') + const error = new RemoteError('gateway/bad-request', 'name is required', { issues: [{ path: ['name'] }] }, { cause }) + + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ + name: 'RemoteError', + code: 'gateway/bad-request', + message: 'name is required', + details: { issues: [{ path: ['name'] }] }, + cause, + }) + expect(remoteErrorOf(error)).toBe(error) + }) +}) diff --git a/packages/typert/protocol/tsconfig.json b/packages/typert/protocol/tsconfig.json index 342f636170..4f9fae2080 100644 --- a/packages/typert/protocol/tsconfig.json +++ b/packages/typert/protocol/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9d71501a7c..29ea75b0e4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16442,6 +16442,9 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-sandbox': specifier: workspace:* version: link:../../fs/fs-sandbox @@ -17708,6 +17711,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error packages/typert/registry: dependencies: From 8a5ebd2351a1d1b58fff676fe5be576411f07e83 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 18:07:56 +0800 Subject: [PATCH 031/396] refactor(cua): derive NativeError from HarnessError Use the shared coded-error base while preserving the NativeError constructor, name, code, message and cause. Add the error dependency, compiler reference and error-type assertions. --- packages/experimental/cua/package.json | 2 ++ packages/experimental/cua/src/native-client.ts | 8 ++++---- packages/experimental/cua/tests/native-client.spec.ts | 3 +++ packages/experimental/cua/tsconfig.host.json | 3 +++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..c74c702566 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -96,6 +96,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", @@ -119,6 +120,7 @@ "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index 25c93e15ce..25b5f4e5a9 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -1,6 +1,7 @@ /** Agent-scoped JSONL requests over a connection to the shared native helper. */ import { randomUUID } from 'node:crypto' import assert from 'node:assert/strict' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' @@ -19,15 +20,14 @@ const ScreenshotDiagnostic = z.object({ const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })]) /** Native refusal or transport failure with a stable machine-readable code. */ -export class NativeError extends Error { +export class NativeError extends HarnessError { /** * @param code - Native error code or a transport-owned NATIVE_* code. * @param message - Actionable diagnostic, without its code prefix. * @param options - Original failure when available. */ - constructor(readonly code: string, message: string, options?: ErrorOptions) { - super(`${code}: ${message}`, options) - this.name = 'NativeError' + constructor(code: string, message: string, options?: ErrorOptions) { + super(`${code}: ${message}`, code, options) } } diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index f7a9007f42..b23f4bb48c 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -1,5 +1,6 @@ /** Controlled connection streams exercise the platform-independent native protocol client. */ import { PassThrough, Writable } from 'node:stream' +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' @@ -391,6 +392,8 @@ describe('native helper transport', () => { it('keeps native codes available to callers and in the model-visible diagnostic', () => { const error = new NativeError('PERMISSION_DENIED', 'Enable Accessibility') + expect(error).toBeInstanceOf(HarnessError) + expect(error.name).toBe('NativeError') expect(error.code).toBe('PERMISSION_DENIED') expect(error.message).toBe('PERMISSION_DENIED: Enable Accessibility') }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..91b18de2b9 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -36,6 +36,9 @@ { "path": "../../util/brand" }, + { + "path": "../../util/error" + }, { "path": "../../util/atomic-write" }, From 3aee25862d5d9b1681a15998cb9086c448a7224f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 18:15:52 +0800 Subject: [PATCH 032/396] ci(preview): link the snapshot diff page from the source chooser and harden it Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .github/preview-sizing/README.i18n.yaml | 4 +- .github/preview-sizing/README.md | 2 +- .github/preview-sizing/README.zh.md | 2 +- .../workflows/build-preview-cloudflare.yml | 36 ++- apps/web/tests/preview-boot.e2e.ts | 1 + .../experimental/webworker-packer/src/bin.ts | 1 + .../webworker-runtime/README.i18n.yaml | 4 +- .../experimental/webworker-runtime/README.md | 2 +- .../webworker-runtime/README.zh.md | 2 +- .../webworker-runtime/src/client/index.ts | 2 +- .../src/client/source-chooser.ts | 21 +- .../webworker-runtime/src/fixture-manifest.ts | 31 ++- .../webworker-runtime/src/index.ts | 2 +- .../tests/client/source-chooser.spec.ts | 26 ++ .../tests/fixture-manifest.spec.ts | 13 + scripts/preview-workflow.spec.ts | 15 +- scripts/snapshot-diff-page.spec.ts | 90 ++++--- scripts/snapshot-diff-page.ts | 229 ++++++++++++------ 18 files changed, 345 insertions(+), 138 deletions(-) diff --git a/.github/preview-sizing/README.i18n.yaml b/.github/preview-sizing/README.i18n.yaml index 065a63ad3e..2bb1cc7311 100644 --- a/.github/preview-sizing/README.i18n.yaml +++ b/.github/preview-sizing/README.i18n.yaml @@ -15,8 +15,8 @@ en: 2374f332d040ece2 zh: 7f914fb83cfb5caa /pr-preview-runner-sizing/publication-semantics: - en: 25ee2f4b26ef7770 - zh: 788b7fb4bee6e159 + en: 0d86702bcbbe23f4 + zh: cd0041c917ac8c55 /pr-preview-runner-sizing/dev-note: en: c3e8959997c4d5d0 zh: 109a391915c2bdfb diff --git a/.github/preview-sizing/README.md b/.github/preview-sizing/README.md index 5fcec8ad2c..fe47f0119e 100644 --- a/.github/preview-sizing/README.md +++ b/.github/preview-sizing/README.md @@ -26,7 +26,7 @@ A build-only benchmark does not deploy, access Cloudflare credentials, or post p ## Publication semantics -Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. +Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site and the snapshot diff page to the PR branch alias; that page embeds committed `snapshots/` diff text, never package sources. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. diff --git a/.github/preview-sizing/README.zh.md b/.github/preview-sizing/README.zh.md index 43258d716a..36770bb7c5 100644 --- a/.github/preview-sizing/README.zh.md +++ b/.github/preview-sizing/README.zh.md @@ -26,7 +26,7 @@ ## 发布语义 -运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 +运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点和 snapshot diff 页面上传至 PR 分支别名;该页面嵌入已提交的 `snapshots/` diff 文本,不含包源码。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index c8cb718234..c9f60f3282 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -2,7 +2,8 @@ name: Build PR preview # Every push to a pull request publishes that pull request's preview to # Cloudflare Pages under its own branch alias, behind Cloudflare Access. The -# upload carries build products only: the workflow never grants the deployment +# upload carries build products plus the snapshot diff page, which embeds +# committed `snapshots/` diff text: the workflow never grants the deployment # platform access to this repository's sources. This lane also owns the # aggregate test and script type checks that the required Linux consumers no # longer repeat on every pull request. @@ -102,9 +103,16 @@ jobs: cp apps/web/dist/preview.html apps/web/dist/index.html # Reviewers read snapshot changes at /snapshot-diff/, which opens on the - # SDK blank-Session catalog (system prompt and tool schemas). + # SDK blank-Session catalog (system prompt and tool schemas); the source + # chooser links to it. The page serves review only, so a failure warns + # like publication instead of failing the build. - name: Render the snapshot diff page - run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + id: snapshot-diff + continue-on-error: true + run: >- + pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD + --out apps/web/dist/snapshot-diff/index.html + --preview-manifest apps/web/dist/preview/fixtures.json - name: Upload to Cloudflare Pages id: upload @@ -180,29 +188,33 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR: ${{ github.event.pull_request.number }} + SNAPSHOT_DIFF: ${{ steps.snapshot-diff.outcome }} run: | marker='' url="https://pr-$PR.${CF_PROJECT}.pages.dev" + links="[Preview for #$PR]($url)" + if [ "$SNAPSHOT_DIFF" = success ]; then links="$links · [snapshot changes]($url/snapshot-diff/)"; fi # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - body=$(printf '%s\n\n%s\n' \ - "$marker" \ - "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + body=$(printf '%s\n\n%s\n' "$marker" "$links (requires Cloudflare Access sign-in)") existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ - --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + --jq "[.[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\")))] | first // empty | [.id, .body] | @json") if [ -z "$existing" ]; then - printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + printf '%s' "$body" | gh pr comment "$PR" --body-file - elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null else echo "preview URL already commented" fi - # Publishing stays outside the required verdict: a Cloudflare, Access, or - # comment failure warns, while a build failure still fails this check. + # Publishing stays outside the required verdict: a snapshot diff page, + # Cloudflare, Access, or comment failure warns, while a build failure + # still fails this check. - name: Report preview publication failures - if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' + if: >- + steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure' + || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' run: | - message='preview publication failed; the build passed, see the upload, verify, and comment steps' + message='preview publication failed; the build passed, see the snapshot diff, upload, verify, and comment steps' echo "::warning::$message" echo "$message" >> "$GITHUB_STEP_SUMMARY" diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f1ea40b25c..70542e08d3 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -200,6 +200,7 @@ function requireVfsAssets(): PreviewAssets { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeAsset(`preview/${PREVIEW_FIXTURE_MANIFEST_FILE}`, `${JSON.stringify(fixtureManifest, null, 2)}\n`) return { overrides, manifest, cleanup: () => { rmSync(directory, { recursive: true, force: true }) } } diff --git a/packages/experimental/webworker-packer/src/bin.ts b/packages/experimental/webworker-packer/src/bin.ts index 18bf398e59..202b382724 100644 --- a/packages/experimental/webworker-packer/src/bin.ts +++ b/packages/experimental/webworker-packer/src/bin.ts @@ -80,6 +80,7 @@ const manifest: PreviewFixtureManifest = { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeFileSync( join(dirname(outputFile), PREVIEW_FIXTURE_MANIFEST_FILE), diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index 68deb797c2..c4578dcd12 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-runtime/use-this-package: - en: 9f4c76d6c4391037 - zh: c55611045f4667e2 + en: 33c27e81e1e6212c + zh: 6e32be50142bdb44 /deepseek-ai-dsh-experimental-webworker-runtime/model-experience: en: 61fce9b4c7dc96e6 zh: dc2d931063a38327 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index e2bd1605ef..eeae07447e 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -31,7 +31,7 @@ Three build artifacts and one source-owned process layer: - **Lazy archives** — the manifest registers each page chunk the packer moved out of the base image by path and size, with its archive name relative to the image URL. Existence, stats, and listings answer at once; the first asynchronous read (`fs.promises.readFile`, `fs.promises.open`, `fs.createReadStream`, `fs.promises.cp`) fetches and inflates that archive once for every waiting reader, checks it against the registration, and mounts its files without publishing a mutation. A failed fetch rejects the read and leaves the files registered, so the next read fetches again. Until then, synchronous reads, writes, appends, truncation, chmod, rename, and link of a registered file fail with `ERR_DSH_VFS_DEFERRED` naming the archive; unlink and recursive removal drop the registration, and seeding the path replaces it. The archive name derives from its content digest, and the fetch checks only the registered paths and sizes, not the digest. An image that registers lazy archives must be passed as a URL. - **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. `node-addon-require-builtin` answers the Node v24.18.0 internal modules that the vendored Loader, app-boot, and HMR read without `--expose-internals`: the cascaded ESM loader's `resolveSync` and `import` over the Worker loader, with Node's `ERR_MODULE_NOT_FOUND` and `ERR_PACKAGE_PATH_NOT_EXPORTED` codes, and an empty `loadCache`; and the CommonJS loader, package reader, `modules` binding, and resolve-cache members that HMR replaces, which refuse when called. `process.versions.node` reports `24.18.0`, so `ModuleLoader.fromInternal()` and the Loader's `internal` reach that cascaded loader. `node:path.win32.isAbsolute` and `node:util.inherits` follow Node; other `win32` members throw. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches; Node’s `global` alias references the same `globalThis` object for image-loaded packages. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. Lowered bodies read named and default imports through the required module object at each reference, so a module in an import cycle observes a binding once the exporting module initializes it; in a module with such imports, an assignment to an imported binding, a direct `eval`, and a declaration using the reserved `__dsh$` prefix fail the pack. VFS mutations drive `node:fs` callback, polling, and promise watchers, whose listeners run in the async context where the watcher was created rather than that of the writing code; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies `node:stream/promises` completion and pipeline helpers and the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. The maintained `string_decoder` package supplies `node:string_decoder`, retaining incomplete multibyte characters between chunks. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`. - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. -- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. +- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. The manifest's optional `links` list of relative URLs renders beside the start button; the PR preview workflow adds one for its snapshot diff page. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. Callbacks and timers registered under an explicit root context retain its empty stores, so they cannot inherit an unrelated transaction. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index b666c692d8..b09bc78a5b 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -31,7 +31,7 @@ kind: "package-library" - **懒加载归档**——manifest 按路径和大小登记 packer 移出基础镜像的每个页面 chunk,并给出相对镜像 URL 的归档名。存在性、stat 和目录列表立即作答;第一次异步读取(`fs.promises.readFile`、`fs.promises.open`、`fs.createReadStream`、`fs.promises.cp`)为所有等待中的读取方只拉取并解压一次该归档,按登记内容校验后挂载其文件,不发布 mutation。拉取失败时本次读取被拒绝,文件保持登记状态,下次读取会重新拉取。在此之前,对已登记文件的同步读取、写入、追加、截断、chmod、rename 和 link 会以 `ERR_DSH_VFS_DEFERRED` 失败,错误中写明归档名;unlink 和递归删除会移除登记,再次 seed 该路径会替换登记。归档名由内容摘要派生,拉取时只校验登记的路径和大小,不校验摘要。登记了懒加载归档的镜像必须以 URL 传入。 - **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node-addon-require-builtin` 应答 vendor Loader、app-boot 和 HMR 在没有 `--expose-internals` 时读取的 Node v24.18.0 internal 模块:cascaded ESM loader 的 `resolveSync` 和 `import` 经 Worker 加载器完成,失败时带 Node 的 `ERR_MODULE_NOT_FOUND` 与 `ERR_PACKAGE_PATH_NOT_EXPORTED` 错误码,`loadCache` 为空;HMR 会替换的 CommonJS loader、package reader、`modules` binding 与 resolve cache 成员被调用时拒绝。`process.versions.node` 报告 `24.18.0`,因此 `ModuleLoader.fromInternal()` 和 Loader 的 `internal` 拿到的是这个 cascaded loader。`node:path.win32.isAbsolute` 与 `node:util.inherits` 与 Node 一致,其余 `win32` 成员抛出。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支;镜像中加载的包通过 Node 的 `global` 别名访问同一个 `globalThis` 对象。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。降低后的模块体在每次引用具名导入与 default 导入时,都经所 require 的模块对象读取,因此循环导入中的模块能在导出方完成初始化后读到该绑定;在含此类导入的模块中,对导入绑定赋值、直接调用 `eval`、声明使用保留前缀 `__dsh$` 的名字,都会使 pack 失败。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher,监听回调运行在创建 watcher 时的异步上下文中,而不是写入方代码的上下文中;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供 `node:stream/promises` 的完成等待与管道方法,以及文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。维护中的 `string_decoder` 包提供 `node:string_decoder`,在数据块之间保留不完整的多字节字符。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。 - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 -- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 +- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。manifest 中可选的 `links` 列表只接受相对 URL,显示在开始按钮旁;PR 预览工作流为它的 snapshot diff 页面加了一条。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 在显式根上下文中登记的回调和定时器保留其空 store,避免继承无关事务。 diff --git a/packages/experimental/webworker-runtime/src/client/index.ts b/packages/experimental/webworker-runtime/src/client/index.ts index ab44c85d10..7366a56412 100644 --- a/packages/experimental/webworker-runtime/src/client/index.ts +++ b/packages/experimental/webworker-runtime/src/client/index.ts @@ -20,7 +20,7 @@ export { applyIndexInjections } from './apply-injections.ts' export { IMAGE_FILE_NAME } from '../image-layout.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from '../fixture-manifest.ts' /** Transport global the connection plugin reads instead of building an HTTP carrier. */ diff --git a/packages/experimental/webworker-runtime/src/client/source-chooser.ts b/packages/experimental/webworker-runtime/src/client/source-chooser.ts index 48d454eb94..95752bb84d 100644 --- a/packages/experimental/webworker-runtime/src/client/source-chooser.ts +++ b/packages/experimental/webworker-runtime/src/client/source-chooser.ts @@ -113,11 +113,23 @@ const CHOOSER_STYLE = ` font-size: 14px; line-height: 24px; } + [data-preview-source-footer] { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px 16px; + margin: 24px 0 0; + } + [data-preview-source-link] { + color: #61666b; + text-underline-offset: 3px; + } + [data-preview-source-link]:hover { color: #0f1115; } [data-preview-source-submit] { display: block; min-width: 120px; height: 36px; - margin: 24px 0 0 auto; + margin: 0 0 0 auto; padding: 0 14px; border: 0; border-radius: 18px; @@ -148,6 +160,8 @@ const CHOOSER_STYLE = ` [data-preview-source-option]:has(input:checked) { background: rgb(255 255 255 / 8%); } [data-preview-source-option]:has(input:checked) { border-color: rgb(255 255 255 / 12%); } [data-preview-source-option] input { accent-color: #f9fafb; } + [data-preview-source-link] { color: #cfd3d6; } + [data-preview-source-link]:hover { color: #f9fafb; } [data-preview-source-submit] { color: #0f1115; background: #f9fafb; } [data-preview-source-submit]:hover:not(:disabled) { background: #ebeef2; } [data-preview-source-submit]:focus-visible { outline-color: rgb(255 255 255 / 20%); } @@ -243,7 +257,10 @@ export async function choosePreviewSource(manifestUrl: URL): PromiseFilesystem source ${choices.map(choice => optionMarkup(choice, selected)).join('')} - +
+ ${manifest.links.map(link => `${escapeMarkup(link.label)}`).join('')} + +
` root.prepend(chooser) const form = chooser.querySelector('[data-preview-source-card]') diff --git a/packages/experimental/webworker-runtime/src/fixture-manifest.ts b/packages/experimental/webworker-runtime/src/fixture-manifest.ts index 7d2ecf2556..6d7804f727 100644 --- a/packages/experimental/webworker-runtime/src/fixture-manifest.ts +++ b/packages/experimental/webworker-runtime/src/fixture-manifest.ts @@ -14,12 +14,39 @@ export interface PreviewFixtureManifestEntry { readonly overlays: readonly string[] } +/** A page the source chooser links to, such as a report published beside the Preview. */ +export interface PreviewLink { + readonly label: string + /** URL resolved against the manifest URL; one that resolves to another origin is rejected. */ + readonly href: string +} + /** Complete built-in fixture catalog consumed before Worker startup. */ export interface PreviewFixtureManifest { readonly version: number /** Required default fixture id, or null when the chooser should default to an empty overlay. */ readonly defaultFixture: string | null readonly fixtures: readonly PreviewFixtureManifestEntry[] + /** Links shown on the source chooser; the parser reads an absent list as empty. */ + readonly links: readonly PreviewLink[] +} + +/** Resolving against this base shows whether an href could leave the manifest's origin. */ +const SAME_ORIGIN_PROBE = new URL('https://preview.invalid/') + +function parseLinks(value: unknown): PreviewLink[] { + if (value === undefined) return [] + if (!Array.isArray(value)) throw new Error('preview fixture manifest links must be an array') + return value.map((item) => { + const link = recordOf(item) + const label = link?.label + const href = link?.href + if (typeof label !== 'string' || label.length === 0 + || typeof href !== 'string' || href.length === 0 || new URL(href, SAME_ORIGIN_PROBE).origin !== SAME_ORIGIN_PROBE.origin) { + throw new Error('preview fixture manifest contains an invalid link') + } + return { label, href } + }) } function recordOf(value: unknown): Record | undefined { @@ -31,7 +58,7 @@ function recordOf(value: unknown): Record | undefined { /** * Validate the static fixture catalog before it controls Worker fetches. * @param value - Parsed JSON response. - * @returns A detached manifest with unique ids and non-empty overlay lists. + * @returns A detached manifest with unique ids, non-empty overlay lists, and relative links. */ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManifest { const record = recordOf(value) @@ -64,5 +91,5 @@ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManif if (defaultFixture !== null && (typeof defaultFixture !== 'string' || !ids.has(defaultFixture))) { throw new Error('preview fixture manifest defaultFixture does not name a fixture') } - return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures } + return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures, links: parseLinks(record.links) } } diff --git a/packages/experimental/webworker-runtime/src/index.ts b/packages/experimental/webworker-runtime/src/index.ts index c8d8907d3a..788120c22d 100644 --- a/packages/experimental/webworker-runtime/src/index.ts +++ b/packages/experimental/webworker-runtime/src/index.ts @@ -43,7 +43,7 @@ export { } from './image-manifest.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from './fixture-manifest.ts' export { loadVfsImage, loadVfsOverlay, MemoryVfs } from './storage/memory.ts' export { inflateImage, inflateImageStream } from './storage/image-gzip.ts' diff --git a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts index f636c32ebe..14ded4eea2 100644 --- a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts +++ b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts @@ -15,6 +15,7 @@ const MANIFEST: PreviewFixtureManifest = { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], } function setLocation(search = ''): void { @@ -108,6 +109,31 @@ describe('Preview source chooser', () => { expect(document.querySelector('[data-preview-source-style]')).toBeNull() }) + it('shows manifest links resolved against the manifest URL', async () => { + installManifest({ ...MANIFEST, links: [{ label: 'Snapshot ', href: '../snapshot-diff/' }] }) + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-link]')).not.toBeNull() + }) + const link = document.querySelector('[data-preview-source-link]') + expect([link?.textContent, link?.href]).toEqual(['Snapshot ', 'https://preview.test/snapshot-diff/']) + submitChooser() + await selected + }) + + it('shows no link when the manifest has none', async () => { + installManifest() + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-chooser]')).not.toBeNull() + }) + expect(document.querySelector('[data-preview-source-link]')).toBeNull() + submitChooser() + await selected + }) + it('selects the empty source when the manifest has no default', async () => { installManifest({ ...MANIFEST, defaultFixture: null }) diff --git a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts index 01b3d00e9a..804f0e7dbd 100644 --- a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts +++ b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts @@ -23,9 +23,20 @@ describe('Preview fixture manifest', () => { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], }) }) + it('accepts relative links', () => { + const links = [{ label: 'Snapshot changes', href: '../snapshot-diff/' }, { label: 'Root', href: '/report/' }] + expect(parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links }).links).toEqual(links) + }) + + it.each(['https://example.test/', 'javascript:alert(1)', '//example.test/', '\\\\example.test/', '', ' //evil.test/x', '/\t/evil.test/x', '\njavascript:alert(1)'])('rejects the link href %j', (href) => { + expect(() => parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'L', href }] })) + .toThrow(/invalid link/) + }) + it.each([ [{ version: 2, defaultFixture: null, fixtures: [] }, /must use version/], [{ version: 1, defaultFixture: 'missing', fixtures: [] }, /defaultFixture/], @@ -42,6 +53,8 @@ describe('Preview fixture manifest', () => { defaultFixture: 'none', fixtures: [{ id: 'none', label: 'None', description: 'Reserved.', overlays: ['none.tar.gz'] }], }, /invalid fixture entry/], + [{ version: 1, defaultFixture: null, fixtures: [], links: {} }, /links must be an array/], + [{ version: 1, defaultFixture: null, fixtures: [], links: [{ label: '', href: 'a/' }] }, /invalid link/], ])('rejects malformed catalogs', (value, error) => { expect(() => parsePreviewFixtureManifest(value)).toThrow(error) }) diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index bd21bc2c0a..b7c851c3eb 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -30,14 +30,15 @@ describe('PR preview workflow', () => { it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } - for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { + for (const name of ['Render the snapshot diff page', 'Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { expect(byName(name)?.['continue-on-error'], `${name} must warn instead of failing`).toBe(true) } const report = byName('Report preview publication failures') - expect(report?.if).toBe("steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") + expect(report?.if).toBe("steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'" + + " || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") expect(report?.run).toContain('::warning::') }) @@ -78,15 +79,19 @@ describe('PR preview workflow', () => { expect(verify.env?.CF_ACCESS_CLIENT_SECRET).toBe('${{ secrets.CF_ACCESS_CLIENT_SECRET }}') const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') - expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('printf \'%s\' "$body" | gh pr comment "$PR" --body-file -') expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.env?.SNAPSHOT_DIFF).toBe('${{ steps.snapshot-diff.outcome }}') + expect(comment.run).toContain('if [ "$SNAPSHOT_DIFF" = success ]') expect(comment.run).toContain('gh api -X PATCH') + expect(comment.run).toContain('select(.user.login == \\"github-actions[bot]\\"') }) it('renders the snapshot diff page into the upload against the base branch tip', () => { const steps = preview.steps.map(step => step.name) const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! - expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD' + + ' --out apps/web/dist/snapshot-diff/index.html --preview-manifest apps/web/dist/preview/fixtures.json') expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts index 5147ec6dd0..84ffd1dfff 100644 --- a/scripts/snapshot-diff-page.spec.ts +++ b/scripts/snapshot-diff-page.spec.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' -import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' - -const limits = { fileLines: 100, totalChars: 10_000 } +import { addPreviewLink, catalogFiles, groupDiffs, limitDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md index 1111111..2222222 100644 @@ -27,50 +25,80 @@ old mode 100644 new mode 100755 ` -const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] +const file = (path: string, hunks = '') => ({ path, hunks, binary: false, omitted: 0 }) describe('snapshot diff page', () => { it('splits git diff output into files with their hunks', () => { - expect(parseUnifiedDiff(diff, limits)).toEqual([ - { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, - { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + expect(parseUnifiedDiff(diff)).toEqual([ + file('snapshots/sdk/text-turn/system-prompt.expected.md', '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.'), + file('snapshots/web/ptc-round/session.jsonl', '@@ -1 +0,0 @@\n-{"type":"header"}'), + { ...file('snapshots/web/ptc-round/image.png'), binary: true }, + file('snapshots/web/present/workspace.expected/a b/说明.txt'), ]) - expect(parseUnifiedDiff('', limits)).toEqual([]) + expect(parseUnifiedDiff('')).toEqual([]) }) - it('rejects paths git still quotes', () => { - expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + it.each([ + ['a quoted path', 'diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n'], + ['unequal header paths', 'diff --git a/snapshots/x b/snapshots/y\n'], + ['a missing prefix', 'diff --git snapshots/x snapshots/x\n'], + ])('rejects a header with %s', (_, text) => { + expect(() => parseUnifiedDiff(text)).toThrow('unsupported git diff header') }) - it('truncates long files and drops hunks once the total budget is spent', () => { - const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` - const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) - expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) - expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) - expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + it('truncates long sections and drops sections past the byte budget of the escaped JSON', () => { + const lines = (count: number, line = '+x') => file(`f${count}`, ['@@', ...Array.from({ length: count - 1 }, () => line)].join('\n')) + const [long, fits, over] = limitDiffs([lines(150), lines(10), lines(10)], { fileLines: 100, totalBytes: 445 }) + expect([long?.hunks.split('\n').length, long?.omitted]).toEqual([100, 50]) + expect([fits?.hunks.split('\n').length, fits?.omitted]).toEqual([10, 0]) + expect([over?.hunks, over?.omitted]).toEqual(['', 10]) + // Quotes, `@@`, and nine lines of an escaped newline, `+`, and two six-byte \u003c escapes: 139 bytes. + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 138 })[0]?.omitted).toBe(10) + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 139 })[0]?.omitted).toBe(0) }) - it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { - const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) - expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ - ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => { + const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y'] + expect(groupDiffs([...paths, 'snapshots/web/b/x'].map(path => file(path)), catalog)).toEqual([ + { title: 'SDK blank Session catalog', paths: catalog }, + { title: 'snapshots', paths: ['snapshots/AGENTS.md'] }, + { title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] }, + { title: 'web/B', paths: ['snapshots/web/B/x'] }, + { title: 'web/b', paths: ['snapshots/web/b/a/y', 'snapshots/web/b/x'] }, ]) }) - it('lists a path once when a type change splits it into two sections', () => { - const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } - const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } - expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + it.each([ + ['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'], + ['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'], + ['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'], + ])('resolves catalog sidecars when the manifest %s', (_, text, prompt, schemas) => { + expect(catalogFiles(text)).toEqual({ + systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`, + toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`, + }) + }) + + it.each([ + ['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'], + ['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'], + ])('rejects %s', (_, text, message) => { + expect(() => catalogFiles(text)).toThrow(message) }) it('embeds the data so diff text cannot close the script element', () => { - const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + const files = [file('p', '+')] + const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') expect(page).not.toContain('') - const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + const data = / ')] - const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') + it('embeds the index so a path cannot close the script element', () => { + const files = [{ path: 'p', added: 1, removed: 0 }] + const groups = [{ title: 't', paths: ['p'] }] + const page = renderSnapshotDiffPage(files, groups, 'a → b') expect(page).not.toContain('') const data = /')) } - // An authenticated browser renders for the owner's shared browser Peer. - expect(renderedFor).toEqual([loaded.connection.browserPeer, loaded.connection.browserPeer, loaded.connection.browserPeer]) + // Default-token requests render for the Peer owned by the token provider. + const admission = loaded.connection.authentication.authenticate({ headers: { host: `127.0.0.1:${String(port)}`, cookie } }) + if ('rejection' in admission) throw new Error('token provider refused its issued Cookie') + expect(admission.peer).not.toBe(loaded.connection.browserPeer) + expect(renderedFor).toEqual([admission.peer, admission.peer, admission.peer, admission.peer]) offRows() expect(await request(port, '/', authenticated({ method: 'HEAD' }))).toEqual({ status: 200, @@ -230,10 +261,95 @@ describe('real Loader composition', () => { expect(() => server.registerFallback(() => {})).not.toThrow() }) + it('uses centralized HTTP admission while public files and in-process reads stay independent', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + let attempts = 0 + loaded.connection.authentication.register({ authenticate() { + attempts++ + return undefined + } }) + for (const path of ['/app.js', '/preview.html', '/missing.js', '/..%2f..%2foutside']) await request(loaded.webServer.port, path) + expect(attempts).toBe(0) + const inProcess = await loaded.webServer.readResource(new Request('http://reader.invalid/'), reader) + await inProcess.text() + expect(attempts).toBe(0) + expect((await request(loaded.webServer.port, '/')).status).toBe(401) + expect(attempts).toBe(1) + expect((await request(loaded.webServer.port, '/index.html', { method: 'HEAD' })).status).toBe(401) + expect(attempts).toBe(2) + }) + + it('renders each HTTP index for the Peer returned by page admission', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' }) + expect(reader).not.toBe(loaded.connection.browserPeer) + let attempts = 0 + const unregister = loaded.connection.authentication.register({ + authenticate(input) { + attempts++ + const value = input.headers instanceof Headers ? input.headers.get('x-reader') : input.headers['x-reader'] + return value === 'external' ? reader : undefined + }, + }) + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (rows, peer) => { + renderedFor.push(peer) + rows.push({ kind: 'global', name: '__READER__', value: peer === reader }) + }) + for (const path of ['/', '/index.html']) { + const response = await request(loaded.webServer.port, path, { headers: { 'x-reader': 'external' } }) + expect(response.status).toBe(200) + expect(response.body).toContain('globalThis["__READER__"] = true') + } + expect(renderedFor).toEqual([reader, reader]) + expect(attempts).toBe(2) + await unregister() + expect((await request(loaded.webServer.port, '/', { headers: { 'x-reader': 'external' } })).status).toBe(401) + }) + + it('reports unavailable authentication without rendering the index', async () => { + const loaded = await loadComposition() + loaded.connection.authentication.register({ authenticate() { throw new Error('provider unavailable') } }) + const rendered = vi.fn() + loaded.on('webserver/index-inject', rendered) + for (const path of ['/', '/index.html']) { + expect(await request(loaded.webServer.port, path)).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect(await request(loaded.webServer.port, path, { method: 'HEAD' })).toMatchObject({ status: 503, body: '' }) + } + expect(rendered).not.toHaveBeenCalled() + }) + + it.each(['request', 'peer'] as const)('does not inject an index after its %s ends during file reading', { timeout: 60_000 }, async (ended) => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + const controller = new AbortController() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + heldIndex.path = join(root!, 'dist', 'index.html') + heldIndex.entered = () => { entered.resolve(undefined) } + heldIndex.release = release.promise + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (_rows, peer) => { renderedFor.push(peer) }) + const result = loaded.webServer.readResource(new Request('http://reader.invalid/', { signal: controller.signal }), reader) + const outcome = result.then(() => 'served', () => 'cancelled') + try { + await entered.promise + if (ended === 'request') controller.abort() + else await reader.dispose() + release.resolve(undefined) + expect(await outcome).toBe('cancelled') + expect(renderedFor).toEqual([]) + } finally { + release.resolve(undefined) + await outcome + } + }) + it('answers in-process reads for the given Peer without browser authentication', { timeout: 60_000 }, async () => { const loaded = await loadComposition() const server = loaded.webServer - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = (path: string, init?: RequestInit) => server.readResource(new Request(`http://reader.invalid${path}`, init), reader) const renderedFor: Connection.PeerScope[] = [] loaded.on('webserver/index-inject', (rows, peer) => { @@ -283,7 +399,7 @@ describe('real Loader composition', () => { expect([revalidated.status, revalidated.headers.get('etag'), revalidated.headers.get('cache-control')]).toEqual([304, etag, 'no-cache']) expect(await revalidated.text()).toBe('') // An in-process read revalidates the same way. - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = await loaded.webServer.readResource(new Request(`${base}/app.js`, { headers: { 'if-none-match': etag } }), reader) expect(read.status).toBe(304) diff --git a/packages/host/open-in-app/README.i18n.yaml b/packages/host/open-in-app/README.i18n.yaml index 97f08b56d1..8b7437f949 100644 --- a/packages/host/open-in-app/README.i18n.yaml +++ b/packages/host/open-in-app/README.i18n.yaml @@ -9,14 +9,14 @@ en: 91ff0fbf5f0b95b9 zh: 13a18d1a9bc38da0 /deepseek-ai-dsh-host-open-in-app/summary: - en: 894ed6d5eec55b71 - zh: b94ae1411966f145 + en: f6922aa70b598d29 + zh: d03dafb50850fafc /deepseek-ai-dsh-host-open-in-app/table-of-contents: en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-host-open-in-app/use-this-package: - en: c1217da1d6bdfd36 - zh: cbb05caa1a7764d0 + en: b800b5c32358b04f + zh: b7df359af6cd4c47 /deepseek-ai-dsh-host-open-in-app/use-this-package/when-to-choose-it: en: fcf8f52b6cf1f0dd zh: aed2366ccd0f112a @@ -33,8 +33,8 @@ en: 558e741770080c93 zh: 80482d355dc89cae /deepseek-ai-dsh-host-open-in-app/understand-the-implementation: - en: 0ebb9f5dfb251f11 - zh: d60bd93d5b3e6fb9 + en: 2245b83097ae2e1b + zh: 306ec4b3edfa3e47 /deepseek-ai-dsh-host-open-in-app/further-exploration: en: d5b6ee9a195a810b zh: 7825d6182be37255 diff --git a/packages/host/open-in-app/README.md b/packages/host/open-in-app/README.md index d32d42b93a..df763084c7 100644 --- a/packages/host/open-in-app/README.md +++ b/packages/host/open-in-app/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require the deployment's browser authentication and host-origin trust checks. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. +Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require WebServer admission and an owner Peer; non-owner Peers receive 403 before application probing, icon access, or launch. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. ## Table of Contents @@ -25,7 +25,7 @@ Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in- ## Use this package -Mount the package in a composition that carries `webServer`, `connection`, and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. +Mount the package in a composition that carries `webServer` and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. ### When to choose it @@ -79,7 +79,7 @@ Linux desktop-entry fields and icons use the shared [native-command](../../util/ The package splits into a data table and three roles. [`src/catalog.ts`](src/catalog.ts) is the compile-time table: each entry's per-platform locator chain (`fixed`, `app`, `xcode`, `cli`, `file`, `scan`, `app-paths`, `install-record`, `github-desktop`, `desktop`) plus, on Linux, the desktop-entry id owning its icon. [`src/resolver.ts`](src/resolver.ts) resolves the table against this host: one pass yields a map of catalog id to verified launch (primary and optional fallback argv plus the icon source), sharing one batched Windows-registry read; argv launches spawn detached with a credential-scrubbed environment (`scrubbedParentEnv`) minus the Desktop Host's `ELECTRON_RUN_AS_NODE`, plus explicit adapter entries, and keep Windows GUI processes visible unless the adapter hides a CLI process that launches the GUI separately. `shell-open` launches (the file managers) run the OS shell's open verb through `dsh-native-command`'s path opener under the same watch window, and a spawn `ENOENT` is classified as `missing` so the routes can refresh a stale entry. [`src/icons.ts`](src/icons.ts) extracts icons per platform: `plutil`/`sips` over the resolved bundle on macOS, a generated PowerShell `ExtractAssociatedIcon` script over the resolved executable on Windows (positional `-File` args keep paths out of command-line parsing), and desktop-entry/hicolor/pixmaps filesystem lookup on Linux. -[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route asks the composition's `connection` service for a rejection first; the complete trust story — the Host/Origin fence and browser authentication — has one home in the [`src/index.ts`](src/index.ts) module comment. On top of that fence the open route validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. +[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route declares required WebServer admission and checks the supplied Peer's owner principal before accessing Host resources. The open route also validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. diff --git a/packages/host/open-in-app/README.zh.md b/packages/host/open-in-app/README.zh.md index d14624c00d..3d4858c610 100644 --- a/packages/host/open-in-app/README.zh.md +++ b/packages/host/open-in-app/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过部署的浏览器认证与主机来源信任检查。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 +将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过 WebServer 准入并持有 owner Peer;非 owner Peer 在应用探测、图标访问或启动前收到403。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包挂进携带 `webServer`、`connection` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 +把本包挂进携带 `webServer` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 ### 何时选择 @@ -79,7 +79,7 @@ Linux 桌面文件字段和图标使用共享的 [native-command](../../util/nat 本包拆为一张数据表与三个角色。[`src/catalog.ts`](src/catalog.ts) 是编译期表格:每个条目按平台的 locator 链(`fixed`、`app`、`xcode`、`cli`、`file`、`scan`、`app-paths`、`install-record`、`github-desktop`、`desktop`),以及 Linux 上拥有其图标的 desktop 条目 id。[`src/resolver.ts`](src/resolver.ts) 把表格解析到本机:一趟产出目录 id 到已验证启动的映射(主/回退 argv 加图标来源),共享一次批量的 Windows 注册表读取;argv 启动以清理过凭据的环境(`scrubbedParentEnv`)去掉 Desktop Host 的 `ELECTRON_RUN_AS_NODE` 后叠加适配器显式环境,再 detached 派生,Windows GUI 默认保持可见,只有负责另行打开 GUI 的 CLI 适配器会隐藏自己的进程。`shell-open` 启动(文件管理器)在同一看护窗口下经 `dsh-native-command` 的路径打开器执行 OS shell 的 open verb,spawn 的 `ENOENT` 被归类为 `missing`,让路由能刷新失效条目。[`src/icons.ts`](src/icons.ts) 按平台提取图标:macOS 在解析出的 bundle 上跑 `plutil`/`sips`,Windows 在解析出的可执行文件上跑生成的 PowerShell `ExtractAssociatedIcon` 脚本(`-File` 位置参数让路径不经过命令行解析),Linux 走 desktop 条目/hicolor/pixmaps 的文件系统查找。 -[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由都先向组合的 `connection` 服务询问是否拒绝;完整的信任叙述——Host/Origin 栅栏与浏览器认证——唯一的出处在 [`src/index.ts`](src/index.ts) 的模块注释。在该栅栏之上,open 路由在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 +[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由均声明 WebServer 认证准入,并在访问 Host 资源前检查传入 Peer 的 owner principal。open 路由还在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 diff --git a/packages/host/open-in-app/package.json b/packages/host/open-in-app/package.json index 256d6919a8..29ce84dcd0 100644 --- a/packages/host/open-in-app/package.json +++ b/packages/host/open-in-app/package.json @@ -52,6 +52,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-host-webserver": "workspace:*" + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" } } diff --git a/packages/host/open-in-app/src/index.ts b/packages/host/open-in-app/src/index.ts index 8e8da91ec4..13baf80bae 100644 --- a/packages/host/open-in-app/src/index.ts +++ b/packages/host/open-in-app/src/index.ts @@ -4,12 +4,8 @@ * launch endpoint the browser split button * (`@deepseek-ai/dsh-client-ui-open-in-app`) posts to. * - * Security has one home, here. Every route asks the composition's - * `connection` service for a rejection first (`requestRejection`): its - * Host/Origin fence defeats DNS rebinding and cross-site calls, and its - * browser authentication (the login-token cookie) gates every caller before - * any resolution result, icon, or launch is reachable. On top of that fence - * the open route validates its body at the wire: an `application/json` media + * WebServer admits requests before dispatch; these routes require an owner Peer. + * The open route validates its body at the wire: an `application/json` media * type, a 64 KiB ceiling, string `app`/`path` fields, a resolved-available * catalog id, and an absolute path naming an existing directory. * @@ -43,8 +39,8 @@ export type * from './shared.ts' /** Cordis function-plugin name. */ export const name = 'open-in-app' -/** The route carrier, the trust fence guarding every route, and the PATH resolver. */ -export const inject = ['webServer', 'connection', 'subprocess'] +/** The route carrier and the PATH resolver. */ +export const inject = ['webServer', 'subprocess'] /** Open-in-app host configuration. */ export interface Config { @@ -75,16 +71,6 @@ export const Config: z = z.object({ launchWatchMs: boundedMs(), }) -/** Trust surface consumed here; the browser-side connection package owns the full type. */ -interface OpenInAppConnection { - requestRejection(request: { readonly headers: IncomingMessage['headers'] }): 401 | 403 | undefined -} - -/** The composition's connection service (typed locally: its package is browser-side). */ -function connectionOf(ctx: Context): OpenInAppConnection { - return Reflect.get(ctx, 'connection') as OpenInAppConnection -} - /** Open-route request bodies are tiny JSON objects; anything larger is hostile. */ const MAX_BODY_BYTES = 64 * 1024 @@ -134,7 +120,7 @@ function parseOpenBody(text: string): { app: string; path: string } | null { return typeof app === 'string' && typeof path === 'string' ? { app, path } : null } -/** Register the apps, icon, and open routes behind the connection trust fence. */ +/** Register owner-only apps, icon, and open routes. */ export function apply(ctx: Context, config: Config): void { const ssh = launchedThroughSsh(launchEnvironmentOf(ctx)) /** Test-seam facts completed with the composition's PATH resolver. */ @@ -181,20 +167,15 @@ export function apply(ctx: Context, config: Config): void { map.set(app.id, fresh) return fresh } - /** Answer an untrusted/unauthenticated request; true when it was rejected. */ - const rejected = (req: IncomingMessage, res: ServerResponse): boolean => { - const rejection = connectionOf(ctx).requestRejection(req) - if (rejection === undefined) return false - res.statusCode = rejection - res.end() - return true - } - ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_APPS_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -205,9 +186,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'prefix', + auth: 'required', path: OPEN_IN_APP_ICON_PREFIX_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -240,9 +225,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_OPEN_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'POST') { sendMethodNotAllowed(res, 'POST') return diff --git a/packages/host/open-in-app/tests/host-routes.spec.ts b/packages/host/open-in-app/tests/host-routes.spec.ts index ff73819cc0..6327b3ff08 100644 --- a/packages/host/open-in-app/tests/host-routes.spec.ts +++ b/packages/host/open-in-app/tests/host-routes.spec.ts @@ -1,12 +1,11 @@ /** * Host routes over a real WebServer booted through the vendored Loader * (the REAL-composition requirement), asserting the HTTP surface: the - * connection trust fence, the one-pass catalog resolution the routes share, + * centralized admission, owner authorization, and one-pass catalog resolution, * icon serving with caching, the open route's wire validation, and the * stale-launcher (ENOENT) refresh. Host commands, launches, and PATH - * resolution are faked through the package `internals` seam; the connection - * service is a controllable stub (its real provider is the browser - * composition); the filesystem is real. + * resolution are faked through the package `internals` seam; admission returns + * a controllable Peer; the filesystem is real. */ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' @@ -18,7 +17,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import WebServer from '@deepseek-ai/dsh-host-webserver' +import WebServer, { type WebRoute } from '@deepseek-ai/dsh-host-webserver' import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentLayerInput, @@ -27,9 +26,15 @@ import * as OpenInApp from '../src/index.ts' import { internals } from '../src/internals.ts' import type { OpenInAppLauncher } from '../src/resolver.ts' +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + openInAppAuthorizationTest: { readonly kind: 'open-in-app-authorization-test' } + } +} + let root: string | undefined let context: Context | undefined -/** Answer the connection stub gives every route until a test changes it. */ +/** Central admission decision until a test changes it. */ const trust: { rejection: 401 | 403 | undefined } = { rejection: undefined } afterEach(async () => { @@ -48,7 +53,7 @@ function pathTable(entries: Record = {}): (name: string) => Prom } /** Boot webserver + open-in-app rows through the real Loader. */ -async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promise { +async function boot(layers: readonly LaunchEnvironmentLayerInput[] = [], access: 'owner' | 'restricted' = 'owner'): Promise { internals.catalog = { env: {}, ...internals.catalog } root = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-loader-')) const configPath = join(root, 'cordis.yml') @@ -68,7 +73,17 @@ async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promis context = new Context() context.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot(layers)) context.baseUrl = pathToFileURL(root).href + '/' - context.provide('connection', { requestRejection: () => trust.rejection } as never) + type Peer = NonNullable[2]> + const abort = new AbortController() + const peer: Peer = { + id: 'open-in-app-fixture' as Peer['id'], ctx: context, + principal: access === 'owner' ? { kind: 'owner' } : { kind: 'open-in-app-authorization-test' }, + signal: abort.signal, interactions: 'none', dispose: async () => { abort.abort() }, + } + context.effect(() => () => peer.dispose()) + context.on('webserver/authorize', () => trust.rejection === undefined + ? { kind: 'allow', peer } + : { kind: 'deny', status: trust.rejection }) // The plugin resolves PATH names through the composition's subprocess // capability; the not-found rejection is the provider's real signal. context.provide('subprocess', { @@ -172,7 +187,7 @@ describe('open-in-app host routes (real Loader composition)', () => { expect(Object.keys(OpenInApp).sort()).toEqual(['Config', 'apply', 'inject', 'name']) }) - it('answers the connection rejection on every route, before any resolution runs', async () => { + it('answers the admission rejection on every route, before any resolution runs', async () => { const run = vi.fn() internals.catalog = { platform: 'darwin', run, resolveExecutable: pathTable() } const base = await boot() @@ -188,6 +203,31 @@ describe('open-in-app host routes (real Loader composition)', () => { expect((await fetch(`${base}/open-in-app/apps`)).status).toBe(200) }) + it('refuses an authenticated non-owner before probing, reading icons, or launching', async () => { + const run = vi.fn() + const launch = vi.fn() + const resolveExecutable = vi.fn(pathTable()) + internals.catalog = { platform: 'darwin', run, launch, resolveExecutable } + const base = await boot([], 'restricted') + expect(context?.get('connection')).toBeUndefined() + for (const [path, options] of [ + ['/open-in-app/apps', {}], + ['/open-in-app/icon/finder', {}], + ['/open-in-app/open', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ app: 'finder', path: root }), + }], + ] as const) { + const response = await fetch(`${base}${path}`, options) + expect(response.status).toBe(403) + expect(response.headers.get('cache-control')).toBe('no-store') + await response.text() + } + expect(run).not.toHaveBeenCalled() + expect(resolveExecutable).not.toHaveBeenCalled() + expect(launch).not.toHaveBeenCalled() + }) + it('serves the resolved catalog, one cached icon, and launches from the same resolution', async () => { const launches: string[][] = [] const home = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-home-')) diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index 7a81b0a0db..ac210137e2 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/README.i18n.yaml @@ -24,11 +24,11 @@ en: 90352948bfdc1d99 zh: 35d148bf3bfcf76f /deepseek-ai-dsh-host-webserver/use-this-package/registering-routes: - en: 55b5f5751c46e0ee - zh: 6c609104f0798e01 + en: cf35827f67a2b78f + zh: f2259e857335d48f /deepseek-ai-dsh-host-webserver/use-this-package/the-fallback-seat: - en: 20e5a88f42ba38aa - zh: f20d2f4b3eba267a + en: 6e9a37ec076c8f50 + zh: 1e7c2291c6af9e61 /deepseek-ai-dsh-host-webserver/use-this-package/behavior-under-failure: en: 1bfff905b600f694 zh: 73f3b7704af686dc @@ -36,8 +36,8 @@ en: 42b15ac6321706aa zh: 4ed0861911abaf5d /deepseek-ai-dsh-host-webserver/understand-the-implementation/design-concept: - en: 88adbd5967b978d3 - zh: b4fabfd6f5df1b71 + en: 66e4cf637f553ddf + zh: 47d6d5ea8f7c3ac8 /deepseek-ai-dsh-host-webserver/understand-the-implementation/matching-and-lifecycle: en: 8589aba0cbaa1c76 zh: babf3b27b0cdb35e @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work: - en: 9aa6b8cf92d5b506 - zh: 55ee3f6ad1cace50 + en: ac86e691a0994600 + zh: 99d2409389c9aa12 /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work/dev-note: en: 245b35764295ba1e zh: a15b132b111bfef0 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 59313177e2..5288a1039b 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -58,13 +58,21 @@ Set `compression: 'gzip'` to wrap eligible socket-backed responses without chang ### Registering routes +WebServer events use the emitting WebServer as their Cordis subject. Ordinary listeners receive events only from the same `webServer` isolation; `{ global: true }` explicitly opts out. This applies to request handling, page injection, and entry-URL collection. Custom emitters must pass their WebServer instance as the subject too. + `register(route)` adds a named `exact` or `prefix` HTTP route, `registerUpgrade(route)` adds an upgrade route for an exact pathname, and both return a disposer that removes the registration. A duplicate path within either table throws — route patterns are a composition-level contract, so a collision is a misconfiguration. HTTP matching is exact over the whole table, then longest prefix, then the fallback; upgrades match exactly and unmatched connections are closed. -A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. Over HTTP only `GET` and `HEAD` reach it — any other method is answered 405 with `Allow: GET, HEAD` and its body is never read — and the request carries no Peer, the client's headers, and a URL that is the request target resolved against a placeholder origin; the client's authority stays only in the `host` header. The response is written back with backpressure and the gzip decision a handler's response gets; `HEAD` sends no body, and a client disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` returns the response the same URL would receive over HTTP, computed by the resource for `peer` (a `HEAD` read returns no body): it follows the HTTP match order, answers 404 when the path belongs to a handler or reaches a fallback that is unclaimed or a handler, answers 405 for a method other than `GET` or `HEAD`, and checks no cookie, Host, or Origin, so its caller admits the reader first. +A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. After admission, only `GET` and `HEAD` reach it; other methods receive 405 with `Allow: GET, HEAD`, without reading the body. The resource receives the admitted Peer, if any, and the client headers; its URL resolves the request target against a placeholder origin, leaving the client authority in `host`. Responses use backpressure and the same gzip handling as handlers; `HEAD` sends no body, and disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` dispatches in process with its explicitly admitted Peer: it checks no cookie, Host, or Origin, but a resolved `deny` returns 403. It follows HTTP match order, returns 404 for handlers or an unclaimed fallback, and 405 for non-GET/HEAD reads; HEAD reads return no body. + +HTTP requests pass through `webserver/request(request, response, next)` before route lookup. A listener owns the response or awaits `next()`; the request-error handler contains middleware failures. After matching, HTTP and upgrade routes resolve `auth`, either a fixed policy or a synchronous selector over request facts. `required` is the default and requires a live Peer; `anonymous` removes the credential requirement; `deny` returns 403 without dispatch. For other policies, synchronous `webserver/authorize(request, policy)` takes the first decision. Without a decision, `anonymous` allows and `required` returns 503. HTTP and upgrade admission refusals carry `Cache-Control: no-store`. Connection supplies source checks and ordered credential verification; its source checks also apply to anonymous routes. HTTP handlers receive `(req, res, peer?)`, upgrades `(req, socket, head, peer?)`, and resources keep their Peer parameter. In-process reads do not emit this event. + +Admitted upgrades pass through `webserver/upgrade(req, socket, head, peer, next)` before their registered protocol handler. The waterfall carries the already selected Peer, or `undefined` for anonymous admission; denied requests never enter it. A listener handles the Socket itself or awaits `next()` to delegate. WebServer awaits synchronous or asynchronous protocol handlers and contains rejected middleware or handlers by logging and destroying that Socket. Provider-specific Socket limits and credential cleanup belong to listeners, not to WebServer or Gateway. + +`webserver/entry-url(baseUrl, entries)` synchronously collects complete entry URLs for a supplied server base URL. Listeners append `{ label, url, open }` entries. WebApp emits it after readiness. WebApp owns ordered printing and the first eligible browser handoff. This event neither authenticates requests nor changes the listener or advertised-address configuration. ### The fallback seat -`registerFallback(handler)` or `registerFallback({ resource })` claims the one responder for every request no named route matches. A second registration throws; while no fallback is registered the server answers 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat and calls `renderIndex` on every index response it renders. +`registerFallback(handler)` or an object containing `handler` or `resource` and optional `auth` claims the one responder for unmatched requests. A bare handler still defaults to `required` admission. A second registration throws; an unclaimed seat returns 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat, selects authenticated index access and anonymous assets, and calls `renderIndex` for index responses. Index startup inputs are two layers, computed for the Peer the page speaks for. `collectIndexInjections(peer)` gathers a fresh injection table — one `webserver/index-inject` emit per call, passing `peer` to each subscriber, which pushes its current rows — and `renderIndex(html, peer)` renders those rows into the index.html body before applying the raw `tapIndex(transform)` transforms in registration order. A `script-preload` row renders an advisory classic-script preload link. Static deployments carry the same rows in their boot payload. `applyIndexTaps(html)` applies only the raw transforms; it is the escape hatch for markup no row expresses. @@ -82,7 +90,7 @@ A listen failure (for example EADDRINUSE) rejects plugin initialization with the ### Design concept -The package is a plain route registry whose only harness vocabulary is the Peer an index render speaks for: `WebServer` extends Cordis `Service` and holds three route tables plus the fallback slot, the raw index-tap list, and the `webserver/index-inject` event the index renderer gathers rows through. Index rendering composes two layers per response: `renderIndex` renders the fresh injection table, including advisory `script-preload` rows, into the body, then applies the raw taps in registration order; `applyIndexTaps` runs the taps alone. The upgrade handler owns the protocol handshake and connection contents; the webserver only delivers the raw socket and request. `host`, `port`, and `protocol` getters and `getOrigin()` expose composition-time facts other plugins adapt to (for example the directory-picker chooser), and an explicit `tls: null` normalizes to an unset listener, so `protocol` has a single source. +`WebServer` extends Cordis `Service` and owns matching, route admission, response delivery, and index rendering. Connection supplies source/credential decisions through an event rather than a WebServer dependency on a concrete authentication implementation. Index rendering gathers fresh `webserver/index-inject` rows, renders them, then applies raw taps. The upgrade handler owns protocol negotiation and connection contents after admission. Listener getters and `getOrigin()` expose configuration-derived transport facts; explicit `tls: null` means an HTTP listener. ### Matching and lifecycle @@ -129,7 +137,7 @@ None; this package neither assembles nor sends a provider request. These limits define where the server is intentionally minimal. They are current package constraints, not a task backlog. - **No certificate lifecycle** — `tls` serves the PEM files present at activation: the carrier never provisions, renews, or watches them, and it applies Node's default TLS policy. Replacing a certificate takes a reload. -- **No server-wide authentication or origin policy** — route owners such as `dsh-client-connection` enforce their own request policy. Binding a non-loopback address still exposes unprotected routes and static assets to that network. +- **Credential and source policy need an authorization listener** — the carrier enforces route declarations but verifies no credentials itself. Without a decision, authenticated routes return 503 and anonymous routes remain reachable; an active Connection listener applies source checks to both. - **Socket options are fixed** — config selects the bind host and port, while backlog and other socket settings remain internal until a deployment needs them. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index aa8cde6345..0fce2aac11 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -58,13 +58,21 @@ kind: "package-reference" ### 注册路由 +WebServer 事件以发起它的 WebServer 为 Cordis subject。普通监听器仅接收相同 `webServer` isolation 中的事件;`{ global: true }` 明确跳过此过滤。请求处理、页面注入和入口 URL 收集均遵循此规则。自定义发起者也必须把自己的 WebServer 实例作为 subject 传入。 + `register(route)` 添加具名的 `exact`/`prefix` HTTP route,`registerUpgrade(route)` 为精确 pathname 添加 upgrade route,两者返回的 disposer 都会移除注册。同一张表内的重复路径会抛错——route 模式是组合层约定,冲突即配置错误。HTTP 匹配先在整张表中匹配精确 route,再匹配最长前缀,最后交给回退;upgrade 只做精确匹配,未命中连接直接关闭。 -具名 route 可以用 `resource(request, peer?)` 代替 `handler`:一个把 Fetch `Request` 映射为 `Response` 的函数。经 HTTP 时只有 `GET` 与 `HEAD` 能到达它——其他方法得到带 `Allow: GET, HEAD` 的 405,请求 body 从不读取——请求不带 Peer,携带客户端的 header,URL 是把请求目标按一个占位 origin 解析得到的,客户端的 authority 只保留在 `host` 头里。响应按背压写回,gzip 的处理与 handler 的响应相同;`HEAD` 不发送 body,客户端断开会中止 `request.signal` 并取消 body。`readResource(request, peer)` 返回同一 URL 经 HTTP 会得到的响应,由 resource 按 `peer` 计算(`HEAD` 读取不返回 body):它遵循 HTTP 的匹配顺序;路径属于 handler、或落到未认领或 handler 形式的回退时返回 404;`GET`、`HEAD` 以外的方法返回 405;不检查 cookie、Host 或 Origin,因此调用方须先准入读者。 +具名路由可以使用 `resource(request, peer?)` 代替 `handler`,将 Fetch `Request` 映射为 `Response`。准入后仅 `GET` 与 `HEAD` 可到达 resource;其他方法返回带 `Allow: GET, HEAD` 的405,不读取正文。resource 接收准入 Peer(若有)与客户端请求头;URL 将请求目标按占位 origin 解析,客户端 authority 保留在 `host` 中。响应按背压及与 handler 相同的 gzip 规则发送;`HEAD` 不发送正文,断开会中止 `request.signal` 并取消正文。`readResource(request, peer)` 使用显式准入的 Peer 在进程内分发,不检查 Cookie、Host 或 Origin,但解析出的 `deny` 返回403。它遵循 HTTP 匹配顺序,对 handler 或未认领回退返回404,对非 GET/HEAD 读取返回405;HEAD 读取不返回正文。 + +HTTP 请求在路由查找前经过 `webserver/request(request, response, next)`。监听器拥有响应或等待 `next()`,请求错误处理器容纳中间件异常。匹配后,HTTP 与 upgrade 路由解析 `auth`,可为固定策略或读取请求事实的同步选择器。默认 `required` 要求存活 Peer;`anonymous` 免凭据;`deny` 不分发,直接返回403。其余策略通过同步 `webserver/authorize(request, policy)` 采用首个决策。无人决策时匿名放行,认证返回503。HTTP 与 upgrade 的准入拒绝响应均携带 `Cache-Control: no-store`。Connection 提供来源检查与有序凭据验证;来源检查同样适用于匿名路由。HTTP handler 接收 `(req, res, peer?)`,upgrade 接收 `(req, socket, head, peer?)`,resource 保留已有 Peer 参数。进程内读取不触发此事件。 + +已准入的 upgrade 在已注册协议 handler 前经过 `webserver/upgrade(req, socket, head, peer, next)`。waterfall 携带已选定的 Peer,匿名准入可为 `undefined`;被拒绝的请求不会进入。监听器自行处理 Socket,或等待 `next()` 委派。WebServer 等待同步或异步协议 handler,并在中间件或 handler 拒绝时记录日志、销毁该 Socket。Provider 专属 Socket 限制与凭据清理属于监听器,不属于 WebServer 或 Gateway。 + +`webserver/entry-url(baseUrl, entries)` 根据传入的服务器基地址同步收集完整入口 URL。监听器追加 `{ label, url, open }` 入口。WebApp 在就绪后触发该事件。WebApp 拥有按序打印与首个可自动打开入口的浏览器交接。该事件不认证请求,也不改变监听器或公告地址配置。 ### 回退席位 -`registerFallback(handler)` 或 `registerFallback({ resource })` 认领所有未被具名 route 命中的请求的唯一一个应答方。第二次注册会抛错;没有注册回退时服务器回答 404。在随附的 Web 组合中,[SPA dist 服务器](../frontend-static/README.zh.md)拥有该席位,并对其渲染的每个 index 响应调用 `renderIndex`。 +`registerFallback(handler)` 或含 `handler`/`resource` 及可选 `auth` 的对象认领未匹配请求的唯一应答方。裸 handler 同样默认采用 `required` 准入。第二次注册抛错,未认领席位返回404。随附 Web 组合由 [SPA dist 服务器](../frontend-static/README.zh.md)持有席位,选择 index 认证访问及静态资源匿名访问,并为 index 响应调用 `renderIndex`。 index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexInjections(peer)` 收集一张全新的注入表——每次调用发一次 `webserver/index-inject` 事件,把 `peer` 传给每个订阅方,订阅方推入其当前行——`renderIndex(html, peer)` 先把这些行渲染进 index.html 正文,再按注册顺序应用原始 `tapIndex(transform)` 转换。`script-preload` 行会渲染为 classic script 的提示性 preload 链接。静态部署会在启动 payload 中携带同一批行。`applyIndexTaps(html)` 只应用原始转换;它是任何行都无法表达的标记的逃生口。 @@ -82,7 +90,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI ### 设计理念 -本包是一个普通路由注册表,唯一的 harness 词汇是 index 渲染所代表的 Peer:`WebServer` 继承 Cordis `Service`,持有三张路由表、回退 slot、原始 index 转换列表,以及 `webserver/index-inject` 事件,index 渲染器经其收集行。index 渲染每次响应组合两层:`renderIndex` 先把包含提示性 `script-preload` 行的全新注入表渲染进正文,再按注册顺序应用原始转换;`applyIndexTaps` 只运行转换。upgrade handler 拥有协议握手与连接内容;webserver 只交付原始 socket 与 request。`host`、`port`、`protocol` getter 与 `getOrigin()` 暴露其他插件据以自适应的组合期事实(例如 directory-picker 选择器),而显式的 `tls: null` 会归一为未设置监听,使 `protocol` 只有一个来源。 +`WebServer` 继承 Cordis `Service`,拥有匹配、路由准入、响应交付与 index 渲染。Connection 通过事件提供来源/凭据决策,WebServer 不依赖具体认证实现。index 渲染收集新的 `webserver/index-inject` 行,渲染后执行原始转换。upgrade handler 在准入后拥有协议协商与连接内容。监听器 getter 与 `getOrigin()` 暴露配置决定的传输事实;显式 `tls: null` 表示 HTTP 监听器。 ### 匹配与生命周期 @@ -129,7 +137,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI 这些限制说明服务器在何处有意保持最小。它们是当前包约束,不是任务积压。 - **不管理证书生命周期**:`tls` 只提供激活时存在的 PEM 文件——载体从不申请、续期或监视它们,并采用 Node 默认的 TLS 策略。替换证书需要重新加载。 -- **不提供服务器级认证或来源策略**:`dsh-client-connection` 等 route owner 会实施自己的请求策略。绑定非回环地址仍会向该网络公开未受保护的 route 与静态资源。 +- **凭据与来源策略需要准入监听器**——载体执行路由声明,但不自行验证凭据。无人决策时,认证路由返回503,匿名路由仍可访问;活动 Connection 监听器对两者均执行来源检查。 - **Socket 选项固定不变**:配置只选择绑定宿主与端口;在具体部署产生需求前,backlog 和其他 socket 设置仍保持内部实现。 diff --git a/packages/host/webserver/src/index.ts b/packages/host/webserver/src/index.ts index 6d613e8a49..3ed162f3b4 100644 --- a/packages/host/webserver/src/index.ts +++ b/packages/host/webserver/src/index.ts @@ -7,6 +7,8 @@ * Route handlers retain direct response ownership; a route or the fallback may * instead give a resource, which maps a Fetch `Request` to a `Response` and * also answers in-process reads. + * WebServer events use the instance as their subject: ordinary listeners follow + * its webServer isolation, while explicitly global listeners receive every instance. */ import { readFile } from 'node:fs/promises' @@ -27,11 +29,55 @@ import { renderIndexInjections, type IndexInjection } from './injections.ts' export { renderIndexInjections } from './injections.ts' export type { IndexInjection, IndexInjectionPlacement } from './injections.ts' +/** One application entry URL contributed for startup printing or browser handoff. */ +export interface WebEntryUrl { + /** Output prefix, such as `dsh web`. */ + readonly label: string + /** Complete entry URL, including any credentials required by its provider. */ + readonly url: string + /** Whether this entry is eligible for the application's automatic browser handoff. */ + readonly open: boolean +} + declare module '@deepseek-ai/cordis' { interface Context { webServer: WebServer } interface Events { + /** + * Collect complete entry URLs for an advertised server address. + * @param baseUrl - advertised server base URL without provider credentials. + * @param entries - entries appended synchronously in listener order. + * @mode emit + */ + 'webserver/entry-url'(baseUrl: string, entries: WebEntryUrl[]): void + /** + * Admit a matched request synchronously; the first decision wins. + * @param request - headers, target, transport, and available cancellation state. + * @param policy - resolved route policy; deny never emits this event. + * @mode bail + */ + 'webserver/authorize'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined + /** + * Handle an HTTP request before named-route and fallback dispatch. + * @param request - original incoming HTTP request. + * @param response - response owned by the listener or its delegated handler. + * @param next - dispatch to the next listener or the matching route. + * @mode waterfall + */ + 'webserver/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise + /** + * Handle an admitted upgrade before its registered protocol handler. + * @param request - original upgrade request. + * @param socket - transport owned by the upgrade. + * @param head - bytes received after the HTTP headers. + * @param peer - authenticated identity, absent for anonymous admission. + * @param next - delegate to the next listener or protocol handler. + * @mode waterfall + */ + 'webserver/upgrade'( + request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, + ): Promise /** * Collect the structured index injection table for the page `peer` speaks * for. Emitted on every index render and every worker boot-payload @@ -45,6 +91,25 @@ declare module '@deepseek-ai/cordis' { } } +/** A route permits anonymous access, requires a live Peer, or refuses all access. */ +export type WebAuthPolicy = 'anonymous' | 'required' | 'deny' + +/** Authentication inputs shared by socket-backed and synthetic requests. */ +export interface WebAuthRequest { + headers: Headers | Readonly> + method?: string | undefined + url: URL + transport: 'http' | 'upgrade' + signal?: AbortSignal | undefined + socket?: { readonly destroyed: boolean } | undefined +} + +/** Fixed route policy or a synchronous policy selector. */ +export type WebAuthenticationRule = WebAuthPolicy | ((request: WebAuthRequest) => WebAuthPolicy) + +/** First authorization decision; authenticated access requires a live Peer. */ +export type WebAdmission = { kind: 'allow'; peer?: PeerScope } | { kind: 'deny'; status: 401 | 403 | 503 } + /** Route match kind: 'exact' matches the pathname verbatim; 'prefix' p matches p and p/. */ export type WebRouteKind = 'exact' | 'prefix' @@ -54,12 +119,14 @@ export interface WebRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ - handler: (req: IncomingMessage, res: ServerResponse) => void | Promise + handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** - * Answers one GET or HEAD request with a Fetch response. An HTTP request - * arrives without a Peer and carries the client's headers; an in-process + * Answers one GET or HEAD request with a Fetch response and its admitted Peer. + * Anonymous HTTP admission may omit the Peer; an in-process * {@link WebServer.readResource} read passes the Peer its caller admitted. */ export type WebResource = (request: Request, peer?: PeerScope) => Promise @@ -71,14 +138,21 @@ export interface WebResourceRoute { path: string /** Answers HTTP GET and HEAD requests and in-process reads. */ resource: WebResource + /** Defaults to required; in-process reads still enforce deny. */ + auth?: WebAuthenticationRule } +/** The unmatched-request responder; omitted auth requires authentication. */ +export type WebFallback = Pick | Pick + /** One exact-path HTTP upgrade registration. */ export interface WebUpgradeRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns protocol negotiation and the upgraded socket after dispatch. */ - handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void | Promise + handler: (req: IncomingMessage, socket: Duplex, head: Buffer, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** @@ -352,7 +426,8 @@ async function writeResponse(res: ServerResponse, response: Response, head: bool * initialization, and the boot process reports the failed fiber. Route * registration order does not affect requests because configured named routes * must be distinct, and a request no named route matches is answered 404 - * until the fallback owner registers. + * until the fallback owner registers. HTTP and upgrade admission refusals + * carry `Cache-Control: no-store`. */ export class WebServer extends Service { static Config: z = z.object({ @@ -388,7 +463,7 @@ export class WebServer extends Service { */ private readonly tlsConnections = new Set() private readonly indexTaps: ((html: string) => string)[] = [] - private fallback: WebRoute['handler'] | Pick | undefined + private fallback: WebFallback | undefined private server!: Server private listenedPort: number | undefined private readonly gzip: NodeMiddleware | undefined @@ -471,14 +546,14 @@ export class WebServer extends Service { * composition). One owner only — a second registration throws, because two * fallbacks cannot compose. * @param fallback - a handler owning the full response lifecycle of - * unmatched requests, or `{ resource }` answering them. + * unmatched requests, or an object declaring `handler` or `resource` and auth. * @returns the disposer releasing the seat. */ - registerFallback(fallback: WebRoute['handler'] | Pick): () => void { + registerFallback(fallback: WebRoute['handler'] | WebFallback): () => void { if (this.fallback !== undefined) { throw new Error('webserver: fallback already registered') } - this.fallback = fallback + this.fallback = typeof fallback === 'function' ? { handler: fallback } : fallback return () => { this.fallback = undefined } } @@ -488,6 +563,7 @@ export class WebServer extends Service { * path picks the responder by the HTTP match order — exact, longest prefix, * then the fallback — and only a resource answers. This method checks no * cookie, Host, or Origin: the caller admits the reader before reading. + * A resolved deny policy returns 403 even for an explicitly admitted Peer. * @param request - the read; its URL path selects the responder. * @param peer - the Peer the read speaks for, passed to the resource. * @returns the resource's response, without a body for HEAD as over HTTP; @@ -501,8 +577,12 @@ export class WebServer extends Service { if (request.method !== 'GET' && request.method !== 'HEAD') { return new Response(null, { status: 405, headers: { allow: RESOURCE_METHODS } }) } - const responder = this.responderFor(new URL(request.url).pathname) - if (typeof responder !== 'object' || !('resource' in responder)) return new Response(null, { status: 404 }) + const url = new URL(request.url) + const responder = this.responderFor(url.pathname) + if (responder === undefined || !('resource' in responder)) return new Response(null, { status: 404 }) + if (this.authPolicy(responder.auth, { headers: request.headers, method: request.method, url, transport: 'http', signal: request.signal }) === 'deny') { + return new Response(null, { status: 403 }) + } const response = await responder.resource(request, peer) if (request.method === 'GET') return response await response.body?.cancel() @@ -536,9 +616,34 @@ export class WebServer extends Service { res.end() return } - if (typeof responder === 'function') await responder(req, res) - else if ('resource' in responder) await this.serveResource(req, res, target, responder.resource) - else await responder.handler(req, res) + const abort = new AbortController() + const cleanup = (): void => { + res.off('close', onClose) + res.off('finish', cleanup) + } + const onClose = (): void => { + abort.abort() + cleanup() + } + res.once('close', onClose) + res.once('finish', cleanup) + try { + const request: WebAuthRequest = { + headers: req.headers, method: req.method, url: target, transport: 'http', + signal: abort.signal, socket: req.socket, + } + const admission = this.authorize(request, responder.auth) + if (abort.signal.aborted || request.socket?.destroyed) return + if (admission.kind === 'deny') { + res.writeHead(admission.status, { 'Cache-Control': 'no-store' }) + res.end(admission.status === 401 ? 'unauthorized' : admission.status === 503 ? 'authentication unavailable' : 'forbidden') + return + } + if ('resource' in responder) await this.serveResource(req, res, target, responder.resource, abort.signal, admission.peer) + else await responder.handler(req, res, admission.peer) + } finally { + if (res.writableEnded || abort.signal.aborted) cleanup() + } } // Last-resort guard: handle() rejecting would otherwise be an unhandled // rejection killing the process on one malformed request (bad %-escape, @@ -546,7 +651,8 @@ export class WebServer extends Service { // never a process exit. const listener = (req: IncomingMessage, res: ServerResponse): void => { const next = (): void => { - void handle(req, res).catch((err: unknown) => { + const dispatch = async (): Promise => { await this.ctx.waterfall(this, 'webserver/request', req, res, () => handle(req, res)) } + void dispatch().catch((err: unknown) => { this.ctx.logger.warn(err instanceof Error ? err : new Error(String(err))) if (res.headersSent) { res.destroy() @@ -592,9 +698,11 @@ export class WebServer extends Service { this.upgradedSockets.delete(socket) }) let route: WebUpgradeRoute | undefined + let target: URL try { /* v8 ignore next -- node:http always sets url on server requests. */ - route = this.upgrades.get(new URL(req.url ?? '/', 'http://x').pathname) + target = new URL(req.url ?? '/', 'http://x') + route = this.upgrades.get(target.pathname) } catch (error) { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() @@ -605,8 +713,26 @@ export class WebServer extends Service { return } this.upgradedSockets.add(socket) + const abort = new AbortController() + socket.once('close', () => { abort.abort() }) try { - Promise.resolve(route.handler(req, socket, head)).catch((error: unknown) => { + const admission = this.authorize({ + headers: req.headers, method: req.method, url: target, transport: 'upgrade', + signal: abort.signal, socket, + }, route.auth) + if (abort.signal.aborted || socket.destroyed) return + if (admission.kind === 'deny') { + const reason = { 401: 'Unauthorized', 403: 'Forbidden', 503: 'Service Unavailable' }[admission.status] + const body = reason.toLowerCase() + socket.end(`HTTP/1.1 ${String(admission.status)} ${reason}\r\nConnection: close\r\nCache-Control: no-store\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${String(Buffer.byteLength(body))}\r\n\r\n${body}`) + return + } + const dispatch = async (): Promise => { + await this.ctx.waterfall(this, 'webserver/upgrade', req, socket, head, admission.peer, async () => { + if (!socket.destroyed) await route.handler(req, socket, head, admission.peer) + }) + } + void dispatch().catch((error: unknown) => { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() }) @@ -647,10 +773,26 @@ export class WebServer extends Service { * The responder for one request path, shared by HTTP requests and * {@link readResource}: the matched named route, otherwise the fallback. */ - private responderFor(pathname: string): WebRoute | WebResourceRoute | WebRoute['handler'] | Pick | undefined { + private responderFor(pathname: string): WebFallback | undefined { return this.match(pathname) ?? this.fallback } + private authPolicy(auth: WebAuthenticationRule | undefined, request: WebAuthRequest): WebAuthPolicy { + return typeof auth === 'function' ? auth(request) : auth ?? 'required' + } + + private authorize(request: WebAuthRequest, auth: WebAuthenticationRule | undefined): WebAdmission { + const policy = this.authPolicy(auth, request) + if (policy === 'deny') return { kind: 'deny', status: 403 } + const admission: WebAdmission = this.ctx.bail(this, 'webserver/authorize', request, policy) + ?? (policy === 'anonymous' ? { kind: 'allow' } : { kind: 'deny', status: 503 }) + if (admission.kind === 'allow') { + if (policy === 'required' && admission.peer === undefined) return { kind: 'deny', status: 503 } + if (admission.peer?.signal.aborted) return { kind: 'deny', status: 401 } + } + return admission + } + /** Longest-prefix-wins over the prefix table after an exact-table miss. */ private match(pathname: string): WebRoute | WebResourceRoute | undefined { const exact = this.exact.get(pathname) @@ -666,13 +808,15 @@ export class WebServer extends Service { /** * Answer one HTTP exchange from a resource. Only GET and HEAD reach it; * any other method receives 405 and its request body is never read. The - * request becomes a Fetch `Request` without a Peer whose URL is the request + * request becomes a Fetch `Request` whose URL is the request * target resolved against a placeholder origin, as the match reads it; the * client's authority stays only in the `host` header. The connection * closing before this method ends the response aborts the request signal * and cancels the response body. */ - private async serveResource(req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource): Promise { + private async serveResource( + req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource, signal: AbortSignal, peer?: PeerScope, + ): Promise { if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: RESOURCE_METHODS }) res.end() @@ -682,24 +826,9 @@ export class WebServer extends Service { for (const [name, value] of Object.entries(req.headers)) { for (const item of typeof value === 'string' ? [value] : value ?? []) headers.append(name, item) } - const abort = new AbortController() - // An own flag, not `writableEnded`: the Web Worker tunnel marks an aborted - // response ended before it emits `close`. - let ended = false - const onClose = (): void => { - if (!ended) abort.abort() - } - res.on('close', onClose) - try { - const response = await resource(new Request(target, { method: req.method, headers, signal: abort.signal })) - await writeResponse(res, response, req.method === 'HEAD', abort.signal) - if (!abort.signal.aborted) { - ended = true - res.end() - } - } finally { - res.off('close', onClose) - } + const response = await resource(new Request(target, { method: req.method, headers, signal }), peer) + await writeResponse(res, response, req.method === 'HEAD', signal) + if (!signal.aborted) res.end() } /** @@ -724,7 +853,7 @@ export class WebServer extends Service { */ collectIndexInjections(peer: PeerScope): IndexInjection[] { const table: IndexInjection[] = [] - this.ctx.emit('webserver/index-inject', table, peer) + this.ctx.emit(this, 'webserver/index-inject', table, peer) return table } diff --git a/packages/host/webserver/tests/event-isolation.host.spec.ts b/packages/host/webserver/tests/event-isolation.host.spec.ts new file mode 100644 index 0000000000..5d7828d1fb --- /dev/null +++ b/packages/host/webserver/tests/event-isolation.host.spec.ts @@ -0,0 +1,88 @@ +/** WebServer request and page events follow each instance's service isolation. */ +import { once } from 'node:events' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { connect } from 'node:net' +import { Context } from '@deepseek-ai/cordis' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished } from 'vitest' +import WebServer from '../src/index.ts' + +it('filters HTTP, upgrade, and index listeners while retaining explicitly global listeners', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const isolated = ctx.isolate('webServer') + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + const servers = [ctx.webServer, isolated.webServer] + const calls: string[] = [] + ctx.on('webserver/request', async function (this: unknown, _req: IncomingMessage, _res: ServerResponse, next: () => Promise) { + expect(this).toBeInstanceOf(WebServer) + calls.push('global:request') + await next() + }, { global: true }) + ctx.on('webserver/authorize', () => { calls.push('global:authorize') }, { global: true }) + ctx.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push('global:upgrade') + await next() + }, { global: true }) + ctx.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: 'globalEntry', value: true }) + }, { global: true }) + + for (const [scope, label] of [[ctx, 'main'], [isolated, 'isolated']] as const) { + scope.on('webserver/request', async (_req, _res, next) => { + calls.push(`${label}:request`) + await next() + }) + scope.on('webserver/authorize', () => { + calls.push(`${label}:authorize`) + return { kind: 'allow' } + }) + scope.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push(`${label}:upgrade`) + await next() + }) + scope.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: label, value: true }) + }) + scope.effect(() => scope.webServer.register({ + kind: 'exact', path: '/probe', auth: 'anonymous', + handler(_req, res) { res.end(label) }, + })) + scope.effect(() => scope.webServer.registerUpgrade({ + path: '/socket', auth: 'anonymous', + handler(_req, socket) { + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + }, + })) + } + + for (const [index, label] of ['main', 'isolated'].entries()) { + const server = servers[index]! + calls.length = 0 + const response = await fetch(`${server.getOrigin()}/probe`) + expect(await response.text()).toBe(label) + expect(calls).toEqual(['global:request', `${label}:request`, 'global:authorize', `${label}:authorize`]) + + calls.length = 0 + const socket = connect(server.port!, '127.0.0.1') + const closed = new Promise((resolve) => { socket.once('close', () => { resolve() }) }) + onTestFinished(async () => { socket.destroy(); await closed }) + await once(socket, 'connect') + let output = '' + socket.setEncoding('utf8').on('data', (data: string) => { output += data }) + socket.write('GET /socket HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + await closed + expect(output).toContain('101 Switching Protocols') + expect(calls).toEqual(['global:authorize', `${label}:authorize`, 'global:upgrade', `${label}:upgrade`]) + + const peer: PeerScope = { + id: label as PeerScope['id'], ctx, principal: { kind: 'owner' }, interactions: 'none', + signal: new AbortController().signal, async dispose() {}, + } + expect(server.collectIndexInjections(peer)).toEqual([ + { kind: 'global', name: 'globalEntry', value: true }, + { kind: 'global', name: label, value: true }, + ]) + } +}) diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts index 783b0c86dc..0ebf4abec8 100644 --- a/packages/host/webserver/tests/webserver.spec.ts +++ b/packages/host/webserver/tests/webserver.spec.ts @@ -15,7 +15,7 @@ import { Agent, request as httpsRequest } from 'node:https' import { connect, createServer as createTcpServer, type AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import type { Duplex } from 'node:stream' +import { Duplex } from 'node:stream' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context, FiberState } from '@deepseek-ai/cordis' @@ -24,6 +24,7 @@ import Include from '@deepseek-ai/cordis-plugin-include' import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' import HttpServer, { bindUrlHost, isLoopbackHost, normalizeBindAddress, renderIndexInjections, type TlsConfig, type WebResource, type WebRoute, + type WebAuthRequest, } from '../src/index.ts' import { materializeTlsFixture, type TlsFixture } from './tls-fixture.ts' @@ -247,6 +248,279 @@ function tlsUpgrade(port: number | undefined, path: string, ca: string): Promise } describe('real Loader composition', () => { + it.each([401, 403, 503] as const)('marks HTTP and upgrade admission refusals %s as non-cacheable', async (status) => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.register({ kind: 'exact', path: '/private', handler }) + ctx.webServer.registerUpgrade({ path: '/private', handler }) + ctx.on('webserver/authorize', () => ({ kind: 'deny', status })) + + const response = await request(ctx.webServer.port, '/private') + expect(response.status).toBe(status) + expect(response.headers.get('cache-control')).toBe('no-store') + const upgraded = await rawExchange(ctx.webServer.port, + 'GET /private HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + expect(upgraded).toMatch(new RegExp(`^HTTP/1.1 ${String(status)} `, 'u')) + expect(upgraded).toContain('\r\nCache-Control: no-store\r\n') + expect(handler).not.toHaveBeenCalled() + }) + + it('authenticates matched HTTP routes once and forwards the admitted Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const abort = new AbortController() + const peer: PeerScope = { + id: 'route-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: abort.signal, + interactions: 'none', async dispose() { abort.abort() }, + } + const reached: (PeerScope | undefined)[] = [] + const handler: WebRoute['handler'] = (_req, res, admitted) => { reached.push(admitted); res.end('allowed') } + server.register({ kind: 'exact', path: '/private', handler }) + server.register({ kind: 'prefix', path: '/public', auth: 'anonymous', handler }) + server.register({ kind: 'exact', path: '/public/secret', auth: 'deny', handler }) + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect((await request(server.port, '/public')).status).toBe(200) + expect(reached).toEqual([undefined]) + const seen: WebAuthRequest[] = [] + const listener = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/authorize', (incoming, policy) => { + seen.push(incoming) + if (policy === 'anonymous') return { kind: 'allow' } + if (incoming.headers instanceof Headers || incoming.headers.authorization !== 'Bearer valid') return { kind: 'deny', status: 401 } + return { kind: 'allow', peer } + }) + } }) + await listener.await() + const later = vi.fn(() => ({ kind: 'deny' as const, status: 403 as const })) + const removeLater = ctx.on('webserver/authorize', later) + expect((await request(server.port, '/missing')).status).toBe(404) + expect(await request(server.port, '/public/secret')).toMatchObject({ status: 403, body: 'forbidden' }) + expect(seen).toHaveLength(0) + expect((await request(server.port, '/private')).status).toBe(401) + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(200) + expect(reached.at(-1)).toBe(peer) + expect(seen.at(-1)).toMatchObject({ method: 'GET', transport: 'http' }) + expect(seen.at(-1)?.url.pathname).toBe('/private') + expect(seen.at(-1)?.socket?.destroyed).toBe(false) + expect(later).not.toHaveBeenCalled() + await peer.dispose() + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(401) + await listener.dispose() + removeLater() + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + }) + + it('resolves selectors for resources and fallback while trusting explicit in-process Peers', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'resource-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const resource = vi.fn(async (_request: Request, admitted?: PeerScope) => { + expect(admitted).toBe(peer) + return new Response('resource') + }) + server.register({ kind: 'exact', path: '/resource', resource, auth: incoming => incoming.url.searchParams.has('deny') ? 'deny' : 'required' }) + const authorize = vi.fn(() => ({ kind: 'allow' as const, peer })) + ctx.on('webserver/authorize', authorize) + expect(await request(server.port, '/resource', { method: 'HEAD' })).toMatchObject({ status: 200, body: '' }) + expect(authorize).toHaveBeenCalledTimes(1) + expect(resource).toHaveBeenCalledTimes(1) + const direct = await server.readResource(new Request('http://reader.invalid/resource', { headers: { authorization: 'invalid' } }), peer) + expect(await direct.text()).toBe('resource') + expect(authorize).toHaveBeenCalledTimes(1) + expect((await server.readResource(new Request('http://reader.invalid/resource?deny'), peer)).status).toBe(403) + expect((await request(server.port, '/resource?deny', { method: 'HEAD' })).status).toBe(403) + expect(resource).toHaveBeenCalledTimes(2) + expect(authorize).toHaveBeenCalledTimes(1) + const release = server.registerFallback({ auth: incoming => incoming.url.pathname === '/blocked' ? 'deny' : 'required', resource }) + expect((await request(server.port, '/fallback')).body).toBe('resource') + expect((await request(server.port, '/blocked')).status).toBe(403) + release() + }) + + it('requires admission for bare fallback handlers and rejects an allow without a required Peer', async () => { + const ctx = await loadComposition() + const reached = vi.fn((_req, res) => { res.end('unexpected') }) + ctx.webServer.registerFallback(reached) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + const stop = ctx.on('webserver/authorize', () => ({ kind: 'allow' })) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + stop() + ctx.on('webserver/authorize', () => { throw new Error('authorization failed') }) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(400) + expect(reached).not.toHaveBeenCalled() + }) + + it('authorizes upgrade routes before dispatch and forwards their Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'upgrade-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const stages: string[] = [] + const removeMiddleware = ctx.on('webserver/upgrade', async (_request, _socket, _head, incomingPeer, next) => { + expect(incomingPeer).toBe(peer) + stages.push('before') + await next() + stages.push('after') + }) + let admitted: PeerScope | undefined + server.registerUpgrade({ path: '/private', handler(_req, socket, _head, incoming) { + admitted = incoming + stages.push('handler') + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + server.registerUpgrade({ path: '/denied', auth: 'deny', handler() { throw new Error('must not dispatch') } }) + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + expect(await exchange('/private')).toContain('503 Service Unavailable') + expect(await exchange('/denied')).toContain('403 Forbidden') + expect(await exchange('/missing')).toBe('') + const reject = ctx.on('webserver/authorize', () => ({ kind: 'deny', status: 401 })) + expect(await exchange('/private')).toContain('401 Unauthorized') + expect(stages).toEqual([]) + reject() + let incoming: WebAuthRequest | undefined + const allow = ctx.on('webserver/authorize', (request) => { incoming = request; return { kind: 'allow', peer } }) + expect(await exchange('/private?x=1')).toContain('101 Switching Protocols') + expect(admitted).toBe(peer) + expect(stages).toEqual(['before', 'handler', 'after']) + removeMiddleware() + const veto = ctx.on('webserver/upgrade', async (_req, socket) => { socket.end('HTTP/1.1 409 Conflict\r\n\r\n') }) + expect(await exchange('/private?x=1')).toContain('409 Conflict') + expect(stages).toEqual(['before', 'handler', 'after']) + veto() + expect(incoming?.url.search).toBe('?x=1') + expect(incoming?.transport).toBe('upgrade') + await vi.waitFor(() => { expect(incoming?.signal?.aborted).toBe(true) }) + allow() + ctx.on('webserver/authorize', () => { throw new Error('upgrade authorization failed') }) + expect(await exchange('/private')).toBe('') + }) + + it('propagates HTTP cancellation to authorization and the resource without reauthenticating', async () => { + const ctx = await loadComposition() + const cancelled = Promise.withResolvers() + let admissionSignal: AbortSignal | undefined + let resourceSignal: AbortSignal | undefined + ctx.on('webserver/authorize', (incoming) => { admissionSignal = incoming.signal; return { kind: 'allow' } }) + ctx.webServer.register({ kind: 'exact', path: '/stream', auth: 'anonymous', resource: async (incoming) => { + resourceSignal = incoming.signal + return new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode('ready')) }, + cancel() { cancelled.resolve(undefined) }, + })) + } }) + const abort = new AbortController() + const response = await fetch(`${ctx.webServer.getOrigin()}/stream`, { signal: abort.signal }) + await response.body!.getReader().read() + expect(admissionSignal?.aborted).toBe(false) + abort.abort() + await cancelled.promise + expect(admissionSignal?.aborted).toBe(true) + expect(resourceSignal?.aborted).toBe(true) + }) + + it('contains selector failures and never dispatches a synchronously closed request', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const handler = vi.fn((_req, res) => { res.end('unexpected') }) + server.register({ kind: 'exact', path: '/throws', auth() { throw new Error('selector failed') }, handler }) + expect((await request(server.port, '/throws')).status).toBe(400) + server.register({ kind: 'exact', path: '/closed', auth: 'anonymous', handler }) + let closeRequest = (): void => {} + ctx.on('webserver/request', async (req, _res, next) => { closeRequest = () => { req.socket.destroy() }; await next() }) + ctx.on('webserver/authorize', () => { closeRequest(); return { kind: 'allow' } }) + expect(await rawExchange(server.port, 'GET /closed HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')).toBe('') + expect(handler).not.toHaveBeenCalled() + }) + + it('dispatches anonymous upgrades without a provider and contains selector and handler failures', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + server.registerUpgrade({ path: '/public', auth: 'anonymous', handler(_req, socket, _head, peer) { + expect(peer).toBeUndefined() + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + expect(await exchange('/public')).toContain('101 Switching Protocols') + server.registerUpgrade({ path: '/selector', auth() { throw new Error('upgrade selector failed') }, handler() {} }) + server.registerUpgrade({ path: '/sync', auth: 'anonymous', handler() { throw new Error('sync upgrade failed') } }) + server.registerUpgrade({ path: '/async', auth: 'anonymous', async handler() { throw new Error('async upgrade failed') } }) + for (const path of ['/selector', '/sync', '/async']) expect(await exchange(path)).toBe('') + expect(await exchange('http://[')).toBe('') + }) + + it('does not dispatch upgrades destroyed during synchronous admission', async () => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.registerUpgrade({ path: '/closed', auth: 'anonymous', handler }) + const socket = new Duplex({ read() {}, write(_chunk, _encoding, callback) { callback() } }) + const closed = once(socket, 'close') + ctx.on('webserver/authorize', (incoming) => { + expect(incoming.socket).toBe(socket) + socket.destroy() + return { kind: 'allow' } + }) + const server = Reflect.get(ctx.webServer, 'server') as { emit(event: 'upgrade', req: object, socket: Duplex, head: Buffer): boolean } + server.emit('upgrade', { url: '/closed', method: 'GET', headers: {} }, socket, Buffer.alloc(0)) + await closed + expect(handler).not.toHaveBeenCalled() + }) + + it('runs HTTP middleware before dispatch and delegates only through next', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const calls: string[] = [] + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: async () => { + calls.push('resource') + return new Response('resource') + } }) + const middleware = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/request', async (req, res, next) => { + calls.push('before') + if (req.url === '/exchange') { + res.writeHead(303, { location: './', 'set-cookie': 'fixture=valid' }) + res.end() + return + } + await next() + calls.push('after') + }) + } }) + await middleware.await() + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['before', 'resource', 'after']) + calls.length = 0 + const response = await fetch(`http://127.0.0.1:${String(server.port)}/exchange`, { redirect: 'manual' }) + expect(response.status).toBe(303) + expect(response.headers.get('set-cookie')).toBe('fixture=valid') + await response.text() + expect(calls).toEqual(['before']) + calls.length = 0 + const peer = { principal: { kind: 'owner' } } as PeerScope + expect(await (await server.readResource(new Request('http://reader.invalid/resource'), peer)).text()).toBe('resource') + expect(calls).toEqual(['resource']) + await middleware.dispose() + calls.length = 0 + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['resource']) + }) + + it('contains synchronous middleware failures before reaching the route', async () => { + const ctx = await loadComposition() + let reached = false + ctx.webServer.register({ auth: 'anonymous', kind: 'exact', path: '/guarded', handler(_req, res) { + reached = true + res.end('unexpected') + } }) + ctx.on('webserver/request', () => { throw new Error('middleware failed') }) + expect((await request(ctx.webServer.port, '/guarded')).status).toBe(400) + expect(reached).toBe(false) + }) + it('accepts one concrete IP literal, keeping an IPv6 zone for listen', () => { for (const host of ['127.0.0.1', '10.1.2.3', '0.1.2.3', '::1', 'fd00::1', '::ffff:10.1.2.3', '::ffff:0.1.2.3', '0:0:0:0:0:0:0:1', 'fe80::1%lo', '::0.0.0.1', '::0.0.0.1%lo', '::127.0.0.1']) { expect(HttpServer.Config({ host, port: 0 }).host).toBe(host) @@ -346,7 +620,7 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, true) const server = loaded.webServer const body = 'compressible response '.repeat(8) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/text', handler: (_req, res) => { @@ -357,7 +631,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', handler: (_req, res) => { @@ -366,7 +640,7 @@ describe('real Loader composition', () => { res.end(body.slice(40)) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/small', handler: (_req, res) => { @@ -374,7 +648,7 @@ describe('real Loader composition', () => { res.end('small') }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/events', handler: (_req, res) => { @@ -382,7 +656,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/archive', handler: (_req, res) => { @@ -390,7 +664,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/range', handler: (_req, res) => { @@ -423,7 +697,7 @@ describe('real Loader composition', () => { .headers.get('content-encoding')).toBeNull() // A resource response passes through the same gzip decision as a handler's. - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-text', resource: () => Promise.resolve(new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } })), @@ -442,7 +716,7 @@ describe('real Loader composition', () => { process.on('warning', onWarning) try { const chunk = new TextEncoder().encode('compressible chunk '.repeat(64 * 1024 / 16)) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-large', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -480,9 +754,9 @@ describe('real Loader composition', () => { // Routing precedence: exact beats prefix, longest prefix wins, a prefix // route answers its own path, and routes own their method handling // (POST reaches a registered prefix; 405 is fallback-only semantics). - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) - server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) - server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' }) expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' }) expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' }) @@ -495,13 +769,13 @@ describe('real Loader composition', () => { expect((await request(port, '/no/such/route')).status).toBe(404) const untap = server.tapIndex(html => html.replace('', '')) expect(server.applyIndexTaps('')).toContain('__T__') - const releaseFallback = server.registerFallback((req, res) => { + const releaseFallback = server.registerFallback({ auth: 'anonymous', handler: (req, res) => { // Decode like a real static server would — a malformed %-escape throws // here, probing the webserver's per-request error containment. decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname) res.writeHead(200, { 'content-type': 'text/html' }) res.end(server.applyIndexTaps('shell')) - }) + } }) expect(() => server.registerFallback(() => {})).toThrow(/fallback already registered/) expect((await request(port, '/no/such/route')).body).toContain('__T__') untap() @@ -515,13 +789,13 @@ describe('real Loader composition', () => { // Duplicate (kind, path) is a misconfiguration and throws; the disposer // restores registrability (register/disposer symmetry). - expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} })) + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: () => {} })) .toThrow(/duplicate exact route/) - const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) + const disposeOnce = server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' }) disposeOnce() expect((await request(port, '/once')).body).toContain('shell') // back to the fallback owner - expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() // Releasing the seat restores the unclaimed 404 and registrability. releaseFallback() @@ -532,22 +806,22 @@ describe('real Loader composition', () => { // become registrable again after disposal. The accepted socket stays open // so the teardown assertion also covers upgraded-connection ownership. let upgradedServerClosed = false - const disposeUpgrade = server.registerUpgrade({ + const disposeUpgrade = server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradedServerClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })) + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })) .toThrow(/duplicate upgrade route/) const upgraded = await upgrade(port, '/events?stream=mux') disposeUpgrade() - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })).not.toThrow() + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })).not.toThrow() // The webserver contains raw-socket errors even before an upgrade handler // has installed its protocol implementation. - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/upgrade-error', handler: async (_req, socket) => { await Promise.resolve() @@ -592,7 +866,7 @@ describe('real Loader composition', () => { cookie: string | null peer: PeerScope | undefined } | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: (request, peer) => { @@ -627,7 +901,7 @@ describe('real Loader composition', () => { // The status and headers arrive before the first body chunk exists. const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/held', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -646,7 +920,7 @@ describe('real Loader composition', () => { // A streamed body reaches the client chunk by chunk: the first chunk is // readable while the second is still withheld. const second = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -668,7 +942,7 @@ describe('real Loader composition', () => { // HEAD writes the status and headers, sends no body, and cancels the body. const headCancelled = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/head', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -681,7 +955,7 @@ describe('real Loader composition', () => { // A client leaving mid-body aborts the request signal and cancels the body. const cancelled = Promise.withResolvers() let endlessSignal: AbortSignal | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/endless', resource: (request) => { @@ -701,7 +975,7 @@ describe('real Loader composition', () => { // Only GET and HEAD reach a resource; another method is 405 and its body is never read. let posted = false - server.register({ kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) const refused = await request(port, '/posted', { method: 'POST', body: 'payload' }) expect(refused).toMatchObject({ status: 405, body: '' }) expect(refused.headers.get('allow')).toBe('GET, HEAD') @@ -714,7 +988,7 @@ describe('real Loader composition', () => { expect(seen?.url).toBe('http://x/resource?q=2') expect(await rawExchange(port, 'GET /resource?q=3 HTTP/1.1\r\nHost: bad host\r\nConnection: close\r\n\r\n')).toMatch(/^HTTP\/1\.1 201/) expect([seen?.url, seen?.host]).toEqual(['http://x/resource?q=3', 'bad host']) - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) expect((await request(port, '/throws')).status).toBe(400) expect((await request(port, '/resource')).status).toBe(201) }) @@ -727,7 +1001,7 @@ describe('real Loader composition', () => { const server = loaded.webServer const cancelled = Promise.withResolvers() const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tunnel', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -775,10 +1049,10 @@ describe('real Loader composition', () => { res.writeHead(200) res.end(label) } - server.register({ kind: 'prefix', path: '/assets', resource: resource('assets') }) - server.register({ kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) - server.register({ kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) - server.register({ kind: 'prefix', path: '/api', handler: handler('API') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets', resource: resource('assets') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: handler('API') }) // Exact, then longest prefix: the same responder HTTP picks answers the // read, and the read passes its Peer to the resource. @@ -802,11 +1076,11 @@ describe('real Loader composition', () => { // The fallback seat answers a read only while it holds a resource. expect((await read('/elsewhere')).status).toBe(404) - const releaseHandler = server.registerFallback(handler('FALLBACK')) + const releaseHandler = server.registerFallback({ auth: 'anonymous', handler: handler('FALLBACK') }) expect((await read('/elsewhere')).status).toBe(404) expect((await request(port, '/elsewhere')).body).toBe('FALLBACK') releaseHandler() - server.registerFallback({ resource: resource('fallback') }) + server.registerFallback({ auth: 'anonymous', resource: resource('fallback') }) const fallback = await read('/elsewhere') expect(await fallback.text()).toBe('fallback:/elsewhere') expect(readersOf.at(-1)).toBe(peer) @@ -819,7 +1093,7 @@ describe('real Loader composition', () => { expect(readersOf).toHaveLength(calls) // A throwing resource rejects the read; over HTTP the same failure is 400. - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) await expect(read('/throws')).rejects.toThrow('resource failure') expect((await request(port, '/throws')).status).toBe(400) }) @@ -897,7 +1171,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('https:') expect(server.getOrigin()).toBe(`https://127.0.0.1:${String(server.port)}`) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tls', handler: (_req, res) => { @@ -923,7 +1197,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('http:') expect(server.getOrigin()).toBe(`http://127.0.0.1:${String(server.port)}`) - server.register({ kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) expect(await request(server.port, '/plain')).toMatchObject({ status: 200, body: 'PLAIN' }) await expect(tlsRequest(server.port, '/plain')).rejects.toThrow() }) @@ -994,14 +1268,14 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, false, '127.0.0.1', { certFile: fixture.certFile, keyFile: fixture.keyFile }) const server = loaded.webServer let upgradeClosed = false - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradeClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) const clients = new Map>() const clientErrors: Error[] = [] diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index da06785281..533a1f5765 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -286,6 +286,8 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| +| `@deepseek-ai/dsh-host-authentication-desktop` | yes | Desktop private-channel authentication provider | +| `@deepseek-ai/dsh-host-authentication-token` | yes | Default token authentication provider and HTTP cookie exchange | | `@deepseek-ai/dsh-host-directory-picker-auto` | no | Adaptive chooser of the directory-picker seam: resolves the host situation at boot and mounts the native or browse backend for the DeepSeek Harness web GUI host | | `@deepseek-ai/dsh-host-directory-picker-browse` | yes | In-app browsing backend of the directory-picker seam (listing/creation primitives over the host filesystem) | | `@deepseek-ai/dsh-host-directory-picker-native` | no | Native-OS-chooser backend of the directory-picker seam for the DeepSeek Harness web GUI host | diff --git a/packages/session-query/session-log-export/tests/archive.host.spec.ts b/packages/session-query/session-log-export/tests/archive.host.spec.ts index 61791185b3..46ea244bae 100644 --- a/packages/session-query/session-log-export/tests/archive.host.spec.ts +++ b/packages/session-query/session-log-export/tests/archive.host.spec.ts @@ -16,8 +16,7 @@ import type { SessionEvent, SessionHeader, SessionId, ToolResultMessage, UserMes import type { SessionLineageNode } from '@deepseek-ai/dsh-session-query' import { SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence' import type { SessionAccess, SessionHandle } from '@deepseek-ai/dsh-session-persistence' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import * as SessionLogExport from '../src/index.ts' declare module '@deepseek-ai/dsh-llm' { @@ -171,7 +170,8 @@ async function buildApi( } as never) } if (services.sessions !== undefined) ctx.provide('sessions', services.sessions as never) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin(SessionLogExport, { ...services.compressionLevel === undefined ? {} diff --git a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts index 86f15828fe..29e21fae67 100644 --- a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import type { MessageId } from '@deepseek-ai/dsh-llm' import type { SessionEvent, SessionHeader, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' @@ -89,7 +88,8 @@ async function mounted( ctx.provide('commands', { register: () => () => {} } as never) if (sessionQuery !== undefined) ctx.provide('sessionQuery', sessionQuery as never) if (persistence !== undefined) ctx.provide('sessionPersistence', persistence as SessionPersistence) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { diff --git a/packages/session-query/session-log-export/tests/route.host.spec.ts b/packages/session-query/session-log-export/tests/route.host.spec.ts index 5d793aec0e..eeff55888d 100644 --- a/packages/session-query/session-log-export/tests/route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence' @@ -52,7 +51,8 @@ async function mounted(withServices: boolean): Promise<{ readImage: async () => { throw new Error('fixture has no images') }, } as never) } - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { connection, dispose: () => fiber.dispose() } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a21a45066..0d91895e89 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -755,6 +755,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../packages/client/connection '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../packages/client/product-analytics @@ -785,6 +788,12 @@ importers: '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../packages/host/webserver '@deepseek-ai/dsh-official-bundles': specifier: workspace:* version: link:../../packages/util/official-bundles @@ -881,6 +890,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../packages/host/webserver @@ -900,6 +912,12 @@ importers: specifier: 3.1.1 version: 3.1.1 devDependencies: + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../packages/api/gateway + '@deepseek-ai/dsh-api-remote-access': + specifier: workspace:* + version: link:../../packages/api/remote-access '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand @@ -918,9 +936,18 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:* version: link:../../packages/session/session-persistence + '@deepseek-ai/dsh-typert-registry': + specifier: workspace:* + version: link:../../packages/typert/registry '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../packages/util/workspace-path + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 + ws: + specifier: ^8.21.3 + version: 8.21.3 apps/desktop-publisher: dependencies: @@ -3253,6 +3280,9 @@ importers: '@deepseek-ai/dsh-harness-dev-context': specifier: workspace:* version: link:../../context/harness-dev-context + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-directory-picker-auto': specifier: workspace:* version: link:../../host/directory-picker-auto @@ -3494,9 +3524,6 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand - '@deepseek-ai/dsh-credentials': - specifier: workspace:* - version: link:../../credentials/credentials '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery @@ -3510,6 +3537,12 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -8472,6 +8505,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials @@ -13357,6 +13393,52 @@ importers: specifier: workspace:* version: link:../../core/tools + packages/host/authentication-desktop: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + + packages/host/authentication-token: + dependencies: + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-credentials-local': + specifier: workspace:* + version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-frontend-static': + specifier: workspace:* + version: link:../frontend-static + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + packages/host/directory-picker: devDependencies: '@deepseek-ai/cordis': @@ -13450,6 +13532,9 @@ importers: '@deepseek-ai/dsh-credentials-local': specifier: workspace:* version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver @@ -13478,6 +13563,9 @@ importers: '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol packages/host/plugin-inventory: dependencies: diff --git a/scripts/cordis-walk.ts b/scripts/cordis-walk.ts index 3a38f0ca29..80aeed6f34 100644 --- a/scripts/cordis-walk.ts +++ b/scripts/cordis-walk.ts @@ -72,7 +72,8 @@ export function contextKeyMap(body: ts.ModuleBlock, sf: ts.SourceFile): Map { expect(events).toEqual(['second/changed']) }) - it('reads string-literal and identifier member names from an Events merge', () => { + it('reads string-literal and identifier service and event names', () => { const sf = ts.createSourceFile('x.ts', [ "declare module '@deepseek-ai/cordis' {", ' interface Events {', @@ -196,6 +196,8 @@ describe('cordis-walk scan reach', () => { ' }', ' interface Context {', ' thing: ThingService', + " 'connection.authentication': AuthenticationService", + ' "connection.other": OtherService', ' }', '}', '', @@ -206,6 +208,10 @@ describe('cordis-walk scan reach', () => { : null if (!body) throw new Error('fixture did not parse to a module block') expect(eventNameList(body, sf)).toEqual(['scope/list', 'plain']) - expect([...contextKeyMap(body, sf)]).toEqual([['thing', 'ThingService']]) + expect([...contextKeyMap(body, sf)]).toEqual([ + ['thing', 'ThingService'], + ['connection.authentication', 'AuthenticationService'], + ['connection.other', 'OtherService'], + ]) }) }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 5c3da61024..90526d7a80 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -59,6 +59,7 @@ export const SERVICE_PAGE: Record = { productTelemetry: 'product-telemetry.md', productAnalytics: 'product-telemetry.md', connection: 'web-server.md', + 'connection.authentication': 'web-server.md', pluginManager: 'boot.md', actionCards: 'boot.md', pluginRecommendations: 'boot.md', @@ -313,6 +314,8 @@ export const EVENT_WALK_EXEMPTIONS: Record = { * appear on more than one page. */ export const LINK_MAP: Readonly> = { + AuthenticationProvider: '../../packages/client/connection/README.md#browser-authentication-and-request-trust', + PeerId: 'typert.md', Principal: 'typert.md', PrincipalMap: 'typert.md', RemoteAccessResource: 'typert.md', @@ -947,6 +950,12 @@ export const LINK_MAP: Readonly> = { PermissionCatalog: 'permission-presets.md', PresetOption: 'permission-presets.md', PresetSpec: 'permission-presets.md', + WebEntryUrl: 'web-server.md', + WebAdmission: 'web-server.md', + WebAuthPolicy: 'web-server.md', + WebAuthRequest: 'web-server.md', + WebAuthenticationRule: 'web-server.md', + WebFallback: 'web-server.md', WebRoute: 'web-server.md', WebResourceRoute: 'web-server.md', IndexInjection: 'web-server.md', @@ -1008,6 +1017,7 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'Plugin', 'AbortSignal', 'Headers', + 'URL', 'AsyncIterable', 'Context', 'Error', @@ -1028,6 +1038,8 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'ReadonlySet', 'Request', 'Response', + 'Buffer', + 'Duplex', 'IncomingMessage', 'ServerResponse', 'ReturnType', @@ -1043,18 +1055,14 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { RecommendationDetails: 'packages/experimental/plugin-recommendations/README.md', ProductEvent: 'Desktop event fields are owned by packages/client/product-analytics/README.md and src/events.ts', ConnectionFetchHandler: 'shared Fetch dispatch is owned by packages/client/connection/src/rpc.ts', - ConnectionRequestRejection: 'transport rejection status is owned by packages/client/connection/src/rpc.ts', ConnectionTrustRequest: 'transport authentication input is owned by packages/client/connection/src/rpc.ts', PeerAdmission: 'Peer admission outcome is owned by packages/client/connection/src/rpc.ts', - ConnectionAdmission: 'physical socket admission and release are owned by packages/client/connection/src/rpc.ts', PeerScope: 'Peer scope contract is owned by packages/typert/protocol/src/types.ts', RemoteAccessPolicy: 'access policy contract is owned by packages/api/remote-access/README.md', RemoteAccessRequest: 'Gateway decision requests are owned by packages/api/remote-access/README.md', RemoteAccessDecision: 'Gateway decisions are owned by packages/api/remote-access/README.md', RemoteAccessFrame: 'access snapshot frames are owned by packages/api/remote-access/README.md', RemoteAccessBaseline: 'access snapshot frames are owned by packages/api/remote-access/README.md', - ConnectionIndexRequest: 'frontend authentication request is owned by packages/client/connection/src/rpc.ts', - ConnectionIndexResponse: 'frontend authentication response is owned by packages/client/connection/src/rpc.ts', Profile: 'resolved profile layers are owned by packages/boot/app-boot/README.md', PatchOptions: 'Include patch entries are owned by vendor/include (vendored upstream)', McpResourceProvider: 'scoped resource provider is owned by packages/mcp/mcp-resources/README.md', diff --git a/scripts/gen-doc-graphs.spec.ts b/scripts/gen-doc-graphs.spec.ts index 3274c79f12..9315e03b92 100644 --- a/scripts/gen-doc-graphs.spec.ts +++ b/scripts/gen-doc-graphs.spec.ts @@ -27,7 +27,15 @@ const FIXTURE: Record = { }, include: ['vendor/**/*.ts', 'packages/**/*.ts'], }), - 'vendor/cordis/src/context.ts': 'export class Context { private brand!: void }\n', + 'vendor/cordis/src/context.ts': [ + 'export class Context {', + ' private brand!: void', + ' bail(...args: unknown[]): void {}', + ' on(...args: unknown[]): void {}', + ' once(...args: unknown[]): void {}', + '}', + '', + ].join('\n'), 'vendor/cordis/src/events.ts': [ 'export class EventsService {', ' dispatch(type: string, args: unknown[]): unknown[] { return [type, args] }', @@ -63,6 +71,28 @@ const FIXTURE: Record = { 'packages/fix/pkgc/src/helper.ts': "function scriptFire(args: [string]): void { void gEvents.dispatch('emit', args) }\n", 'packages/fix/pkgc/src/caller.ts': "scriptFire(['pkgc/script-event'])\n", + 'packages/fix/bailtypes/src/receiver.ts': [ + "import { Context } from '../../../../vendor/cordis/src/context.ts'", + 'export declare const application: Context', + "export declare const event: 'bail/union-a' | 'bail/union-b'", + '', + ].join('\n'), + 'packages/fix/bailcalls/src/index.ts': [ + "import { application as receiver, event } from '../../bailtypes/src/receiver.ts'", + "receiver.bail('bail/direct')", + "receiver.bail({}, 'bail/scoped')", + 'receiver.bail(event)', + "receiver.on('bail/direct', () => {})", + "receiver.once('bail/scoped', () => {})", + 'declare const widened: string', + 'receiver.bail(widened)', + 'const ctx = { bail(...args: unknown[]): void {} }', + "ctx.bail('bail/unrelated')", + '// An untyped receiver cannot establish event API ownership.', + 'declare const untyped: any', + "untyped.bail('bail/untyped')", + '', + ].join('\n'), } const root = mkdtempSync(join(tmpdir(), 'gen-doc-graphs-')) @@ -99,6 +129,34 @@ describe('event relation call-site indexing', () => { }) }) +describe('type-aware bail dispatch', () => { + function collectBailRelations() { + return new EventRelationCollector(project, sources.filter(source => source.pkg === 'bailcalls')).collect() + } + + it.each(['bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b'])( + 'records %s from an imported Context receiver as a bail dispatcher', + (event) => { + expect(collectBailRelations().get(event)?.dispatchers).toEqual(new Map([ + ['bailcalls', new Set(['bail'])], + ])) + }, + ) + + it('keeps on and once registrations as listeners', () => { + const relations = collectBailRelations() + expect(relations.get('bail/direct')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/scoped')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/union-a')?.listeners.size).toBe(0) + }) + + it('excludes unrelated and untyped receivers and widened event names', () => { + expect([...collectBailRelations().keys()].sort()).toEqual([ + 'bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b', + ]) + }) +}) + describe('memoized filesystem probes', () => { function countingSystem(): { system: ts.System; calls: string[] } { const calls: string[] = [] diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 01d33a95e9..7078d12753 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -192,7 +192,16 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Authenticated browser transport', mode: 'core', consumers: ['api-gateway', 'host-frontend-static'], - note: 'Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams.', + note: 'Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams.', + }, + { + key: 'connection.authentication', + pkg: 'client-connection', + title: 'Connection authentication provider registry', + mode: 'seam', + implementations: ['host-authentication-token', 'host-authentication-desktop'], + consumers: ['client-connection'], + note: 'Tries scope-owned credential verifiers in registration order and returns the first live Peer; transport source policy and business authorization stay with their consumers.', }, { key: 'forge', @@ -1178,7 +1187,7 @@ type CallSiteIndex = Map> = { + 'packages/host/authentication-desktop': { category: 'optional', reason: 'Mounted by the private Desktop Host with its parent-process credential, outside default Web profiles.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/browser-use/browser-use': { category: 'optional', reason: 'Service definition used by explicitly selected browser providers.' }, 'packages/computer-use/computer-use': { category: 'optional', reason: 'Service definition used by explicitly selected computer providers.' }, diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 2a19069258..6a626d8973 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -69,6 +69,8 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/experimental/voice-input-bundle': { kind: 'none', reason: 'Composes dictation and preparation plugins without adding any model-facing contribution.' }, 'packages/telemetry/otel': { kind: 'none', reason: 'The service delivers caller-selected records without changing model context.' }, 'packages/host/product-telemetry-otel': { kind: 'none', reason: 'The plugin exports explicit analytics records without contributing model context.' }, + 'packages/host/authentication-token': { kind: 'none', reason: 'Launch-token exchange and Cookie verification authenticate HTTP callers without contributing model input.' }, + 'packages/host/authentication-desktop': { kind: 'none', reason: 'Private Desktop credential verification authenticates HTTP callers without contributing model input.' }, 'packages/api/terminal-controller': { kind: 'indirect', reason: 'Working-directory recovery owns directory context; user terminal screens never enter model requests.' }, 'packages/client/ui-sidebar-terminal': { kind: 'none', reason: 'The browser renders user terminal screens without exposing them to the model.' }, 'packages/ssh/ssh-helper-runtime': { kind: 'none', reason: 'The private executable carrier registers no model-facing content; its providers and consumers own operation results.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index d14d434d5c..f7e5269ec6 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -251,6 +251,10 @@ "@deepseek-ai/dsh-host-open-in-app/shared": ["./packages/host/open-in-app/src/shared.ts"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], "@deepseek-ai/dsh-host-frontend-static": ["./packages/host/frontend-static/src"], + "@deepseek-ai/dsh-host-authentication-desktop": ["./packages/host/authentication-desktop/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-desktop/src/*": ["./packages/host/authentication-desktop/src/*"], + "@deepseek-ai/dsh-host-authentication-token": ["./packages/host/authentication-token/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-token/src/*": ["./packages/host/authentication-token/src/*"], "@deepseek-ai/dsh-plugin-manager": ["./packages/boot/plugin-manager/src"], "@deepseek-ai/dsh-plugin-manager/diagnostic": ["./packages/boot/plugin-manager/src/diagnostic.ts"], "@deepseek-ai/dsh-plugin-manager/types": ["./packages/boot/plugin-manager/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index d77b87c35e..faa4315244 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -597,6 +597,8 @@ { "path": "./packages/host/directory-picker-browse" }, { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/host/frontend-static" }, + { "path": "./packages/host/authentication-token" }, + { "path": "./packages/host/authentication-desktop" }, { "path": "./packages/host/open-in-app" }, { "path": "./packages/host/plugin-inventory" }, { "path": "./packages/boot/plugin-manager" }, From 695f640063cf3d348da278e65be05e0a40b4a6e9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:11:54 +0800 Subject: [PATCH 396/396] Merge pull request #8133 from deepseek-harness/discuss-client-iframe refactor(client): add client module js realm (with module manifest and style operation) --- ...7-23-client-plugin-loading-model.i18n.yaml | 16 +- .../2026-07-23-client-plugin-loading-model.md | 10 +- ...26-07-23-client-plugin-loading-model.zh.md | 10 +- ...ient-shells-and-dynamic-packages.i18n.yaml | 4 +- ...8-15-client-shells-and-dynamic-packages.md | 6 +- ...5-client-shells-and-dynamic-packages.zh.md | 6 +- ...026-11-05-client-module-metadata.i18n.yaml | 19 + .../2026-11-05-client-module-metadata.md | 33 ++ .../2026-11-05-client-module-metadata.zh.md | 33 ++ apps/web/package.json | 3 + apps/web/tests/assembled-boot.ts | 3 + apps/web/tests/built-boot.expected.e2e.ts | 4 +- apps/web/tests/client-plugin-live.e2e.ts | 6 + .../tests/default-product-isolation.e2e.ts | 25 +- .../plugins/fixture-live-client/client.js | 13 +- apps/web/tests/navigation-panes.e2e.ts | 25 +- apps/web/tests/preview-boot.e2e.ts | 3 +- apps/web/tests/shell-command-details.e2e.ts | 4 +- .../web/tests/source-static-modules.client.ts | 41 ++ apps/web/tests/terminal-command-browser.ts | 8 +- apps/web/tests/window-drag-coverage.e2e.ts | 2 +- apps/web/vite.config.ts | 7 +- docs/config-catalog.md | 2 + docs/config-catalog.zh.md | 2 + docs/module-graph.md | 4 + docs/module-graph.zh.md | 4 + docs/subsystems/web-client.i18n.yaml | 4 +- docs/subsystems/web-client.md | 2 + docs/subsystems/web-client.zh.md | 2 + .../client-module-metadata/guide.i18n.yaml | 16 + .../client-module-metadata/guide.md | 29 ++ .../client-module-metadata/guide.zh.md | 29 ++ packages/client/AGENTS.md | 2 +- packages/client/modules/README.i18n.yaml | 21 +- packages/client/modules/README.md | 13 +- packages/client/modules/README.zh.md | 12 +- packages/client/modules/package.json | 3 +- packages/client/modules/src/client/entries.ts | 8 +- .../modules/src/client/entry-lifecycle.ts | 11 - packages/client/modules/src/client/index.ts | 2 +- .../client/modules/src/client/main-realm.ts | 46 ++ .../client/modules/src/client/manifest.ts | 84 ++-- packages/client/modules/src/client/system.ts | 217 +++++---- .../tests/document-module.client.spec.ts | 248 ++++++++++ .../modules/tests/entries.client.spec.ts | 225 +++++++-- .../modules/tests/loader.client.spec.ts | 213 ++++++--- .../modules/tests/main-realm.client.spec.ts | 91 ++++ .../modules/tests/node-half.client.spec.ts | 10 +- packages/client/modules/tsconfig.json | 1 + .../script-realm-iframe/README.i18n.yaml | 37 ++ packages/client/script-realm-iframe/README.md | 58 +++ .../client/script-realm-iframe/README.zh.md | 58 +++ .../client/script-realm-iframe/locale/de.json | 5 + .../client/script-realm-iframe/locale/en.json | 5 + .../client/script-realm-iframe/locale/es.json | 5 + .../client/script-realm-iframe/locale/fr.json | 5 + .../client/script-realm-iframe/locale/ja.json | 5 + .../client/script-realm-iframe/locale/pt.json | 5 + .../client/script-realm-iframe/locale/ru.json | 5 + .../client/script-realm-iframe/locale/zh.json | 5 + .../client/script-realm-iframe/package.json | 56 +++ .../script-realm-iframe/src/client/iframe.ts | 169 +++++++ .../script-realm-iframe/src/client/index.ts | 16 + .../client/script-realm-iframe/src/index.ts | 4 + .../tests/execution.client.spec.ts | 204 ++++++++ .../tests/realm.client.spec.ts | 33 ++ .../client/script-realm-iframe/tsconfig.json | 18 + .../script-realm-iframe/tsdown.config.ts | 3 + packages/client/script-realm/README.i18n.yaml | 37 ++ packages/client/script-realm/README.md | 58 +++ packages/client/script-realm/README.zh.md | 58 +++ packages/client/script-realm/locale/de.json | 5 + packages/client/script-realm/locale/en.json | 5 + packages/client/script-realm/locale/es.json | 5 + packages/client/script-realm/locale/fr.json | 5 + packages/client/script-realm/locale/ja.json | 5 + packages/client/script-realm/locale/pt.json | 5 + packages/client/script-realm/locale/ru.json | 5 + packages/client/script-realm/locale/zh.json | 5 + packages/client/script-realm/package.json | 55 +++ .../client/script-realm/src/client/index.ts | 80 ++++ .../client/script-realm/src/client/types.ts | 48 ++ packages/client/script-realm/src/index.ts | 2 + .../script-realm/tests/realm.client.spec.ts | 80 ++++ packages/client/script-realm/tsconfig.json | 18 + packages/client/script-realm/tsdown.config.ts | 3 + packages/client/tsdown.client.ts | 351 +++++++++++--- packages/client/ui-dockkit/README.i18n.yaml | 4 +- packages/client/ui-dockkit/README.md | 2 +- packages/client/ui-dockkit/README.zh.md | 2 +- .../ui-dockkit/src/components/TabLayout.tsx | 3 +- .../ui-dockkit/src/components/TabPanel.tsx | 2 +- packages/client/ui-layout/README.i18n.yaml | 4 +- packages/client/ui-layout/README.md | 2 +- packages/client/ui-layout/README.zh.md | 2 +- packages/client/ui-layout/src/client/index.ts | 1 + .../ui-layout/src/client/theme-presenter.ts | 20 +- .../tests/theme-presenter.client.spec.ts | 71 ++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../ui-primitives/src/TerminalBlock.tsx | 8 +- packages/client/ui-renderer/README.i18n.yaml | 12 +- packages/client/ui-renderer/README.md | 7 +- packages/client/ui-renderer/README.zh.md | 7 +- packages/client/ui-renderer/package.json | 5 +- .../client/ui-renderer/src/client/index.ts | 49 +- .../client/ui-renderer/src/client/renderer.ts | 115 +++++ .../src/client/styles/document-styles.ts | 189 ++++++++ .../tests/module-styles.client.spec.ts | 447 ++++++++++++++++++ .../tests/ui-renderer.client.spec.tsx | 213 ++++++++- packages/client/ui-renderer/tsconfig.json | 6 + packages/client/ui-theme/src/client/styles.ts | 41 +- .../tests/client-styles.client.spec.ts | 28 +- .../tests/client-bundle.client.spec.ts | 32 +- packages/client/web/README.i18n.yaml | 8 +- packages/client/web/README.md | 8 +- packages/client/web/README.zh.md | 8 +- packages/client/web/package.json | 1 + packages/client/web/src/boot.ts | 26 +- packages/client/web/src/platform.ts | 7 + packages/client/web/src/seed.ts | 63 +-- .../web/tests/boot-client.client.spec.ts | 4 +- packages/client/web/tests/boot.client.spec.ts | 5 + .../web/tests/source-static-modules.client.ts | 41 ++ packages/client/web/tsconfig.json | 1 + packages/client/web/tsdown.config.ts | 4 +- .../liveshare/tests/viewer-page.client.ts | 3 + .../skills/dsh-doc/references/packages.md | 2 + .../client-runtime/src/assembly/modules.ts | 2 +- .../assembly-bundle-roster.client.spec.ts | 4 +- .../tests/assembly-roster.client.spec.ts | 5 +- .../package-manifest/src/client-module.ts | 42 ++ packages/util/package-manifest/src/index.ts | 10 + pnpm-lock.yaml | 39 ++ scripts/browser-bundled-externals.spec.ts | 51 ++ scripts/browser-bundled-externals.ts | 3 +- scripts/client-bundle-css.spec.ts | 80 +++- scripts/client-bundle-purity.spec.ts | 189 +++++++- scripts/gen-cordis-catalog.ts | 1 + scripts/product-package-policy.ts | 2 + scripts/verify-client-packages.spec.ts | 28 ++ scripts/verify-client-packages.ts | 5 +- .../verify-package-readme-model-experience.ts | 2 + tsconfig.base.json | 4 + tsconfig.client.json | 2 + 146 files changed, 4410 insertions(+), 628 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md create mode 100644 .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md create mode 100644 apps/web/tests/source-static-modules.client.ts create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.zh.md create mode 100644 packages/client/modules/src/client/main-realm.ts create mode 100644 packages/client/modules/tests/document-module.client.spec.ts create mode 100644 packages/client/modules/tests/main-realm.client.spec.ts create mode 100644 packages/client/script-realm-iframe/README.i18n.yaml create mode 100644 packages/client/script-realm-iframe/README.md create mode 100644 packages/client/script-realm-iframe/README.zh.md create mode 100644 packages/client/script-realm-iframe/locale/de.json create mode 100644 packages/client/script-realm-iframe/locale/en.json create mode 100644 packages/client/script-realm-iframe/locale/es.json create mode 100644 packages/client/script-realm-iframe/locale/fr.json create mode 100644 packages/client/script-realm-iframe/locale/ja.json create mode 100644 packages/client/script-realm-iframe/locale/pt.json create mode 100644 packages/client/script-realm-iframe/locale/ru.json create mode 100644 packages/client/script-realm-iframe/locale/zh.json create mode 100644 packages/client/script-realm-iframe/package.json create mode 100644 packages/client/script-realm-iframe/src/client/iframe.ts create mode 100644 packages/client/script-realm-iframe/src/client/index.ts create mode 100644 packages/client/script-realm-iframe/src/index.ts create mode 100644 packages/client/script-realm-iframe/tests/execution.client.spec.ts create mode 100644 packages/client/script-realm-iframe/tests/realm.client.spec.ts create mode 100644 packages/client/script-realm-iframe/tsconfig.json create mode 100644 packages/client/script-realm-iframe/tsdown.config.ts create mode 100644 packages/client/script-realm/README.i18n.yaml create mode 100644 packages/client/script-realm/README.md create mode 100644 packages/client/script-realm/README.zh.md create mode 100644 packages/client/script-realm/locale/de.json create mode 100644 packages/client/script-realm/locale/en.json create mode 100644 packages/client/script-realm/locale/es.json create mode 100644 packages/client/script-realm/locale/fr.json create mode 100644 packages/client/script-realm/locale/ja.json create mode 100644 packages/client/script-realm/locale/pt.json create mode 100644 packages/client/script-realm/locale/ru.json create mode 100644 packages/client/script-realm/locale/zh.json create mode 100644 packages/client/script-realm/package.json create mode 100644 packages/client/script-realm/src/client/index.ts create mode 100644 packages/client/script-realm/src/client/types.ts create mode 100644 packages/client/script-realm/src/index.ts create mode 100644 packages/client/script-realm/tests/realm.client.spec.ts create mode 100644 packages/client/script-realm/tsconfig.json create mode 100644 packages/client/script-realm/tsdown.config.ts create mode 100644 packages/client/ui-renderer/src/client/renderer.ts create mode 100644 packages/client/ui-renderer/src/client/styles/document-styles.ts create mode 100644 packages/client/ui-renderer/tests/module-styles.client.spec.ts create mode 100644 packages/client/web/tests/source-static-modules.client.ts create mode 100644 packages/util/package-manifest/src/client-module.ts diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index a41dd3bd98..f29cf535f2 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -15,20 +15,20 @@ en: 6af228b03e5e533f zh: 276a522af6be5d7a /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor: - en: 575aad62490f32e9 - zh: a6c18eb63965fc1e + en: 5f5daec51b20db77 + zh: e4d6f78fc1b4b835 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps: en: 0a4240d88cca240a zh: 8f5f1527caf571cd /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end: - en: dd05aa1ee608c414 - zh: 2863ced0086e3122 + en: 1f7db6ecfc0b0831 + zh: f6bf37dc921a7d40 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation: - en: 37e2fa1fe5cb2b95 - zh: 80e513db87709cb4 + en: ab9577214d7b2f2b + zh: fc8f10fd8c90b34b /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles: - en: c1fdcb3e6f074a7a - zh: b08c7b1ff25acb09 + en: e6a0bee3d31cd2c6 + zh: 7f7384c5d1a74751 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership: en: 94ca0d09e6fd1e3a zh: d5949a2bdec795ba diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 15c0a39295..bc24420a59 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -34,7 +34,7 @@ The web kernel remains framework-free and imports no dynamic package value. Modu The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientModuleSystem`) takes the module-system seat that Node's internal ESM loader holds host-side; the same vendored `@cordisjs/plugin-loader` keeps the governance seat on both sides. The line between them in one sentence: **the module system owns module identity and bytes — how code arrives, registers, and becomes an exports; the Loader owns plugin lifecycle — when a plugin mounts, what it waits for, and how it is torn down.** -`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. Every module body side effect, CSS injection included, lives inside the factory closure and runs at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owned `