From bf8d8494bac1db26c130065829508b2208d22bfe Mon Sep 17 00:00:00 2001 From: yudshj Date: Tue, 27 Oct 2026 13:43:39 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix(ui-user-questions):=20=E5=A4=9A?= =?UTF-8?q?=E9=80=89=E9=A2=98=E9=A2=84=E9=80=89=E6=89=80=E6=9C=89=E6=8E=A8?= =?UTF-8?q?=E8=8D=90=E9=80=89=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/ui-user-questions/README.i18n.yaml | 4 +-- packages/client/ui-user-questions/README.md | 2 +- .../client/ui-user-questions/README.zh.md | 2 +- .../src/client/QuestionComposer.tsx | 15 ++++++---- .../user-questions-composer.client.spec.tsx | 30 +++++++++++++++++++ 5 files changed, 43 insertions(+), 10 deletions(-) diff --git a/packages/client/ui-user-questions/README.i18n.yaml b/packages/client/ui-user-questions/README.i18n.yaml index ae89cb24b4..dbf890074c 100644 --- a/packages/client/ui-user-questions/README.i18n.yaml +++ b/packages/client/ui-user-questions/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-user-questions/use-this-package: - en: 8d3815c19858ac85 - zh: 94fc905fa202d334 + en: 56368ea7909468c0 + zh: b212ffa1f0fda6a5 /deepseek-ai-dsh-client-ui-user-questions/use-this-package/answering: en: 8900fbf9cbd72083 zh: 67a951d58a029a58 diff --git a/packages/client/ui-user-questions/README.md b/packages/client/ui-user-questions/README.md index 205b8732b4..e510b510c0 100644 --- a/packages/client/ui-user-questions/README.md +++ b/packages/client/ui-user-questions/README.md @@ -25,7 +25,7 @@ The Web client shows an agent's question beside the chat input. Users choose opt ## Use this package -When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. A first choice marked “Recommended” starts selected, but remains an unsubmitted draft and does not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing). +When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. A single-select question’s first choice marked “Recommended” starts selected, as does every marked choice of a multi-select question; but remains an unsubmitted draft and does not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing). ### Answering diff --git a/packages/client/ui-user-questions/README.zh.md b/packages/client/ui-user-questions/README.zh.md index 122b6e9c26..40b309155b 100644 --- a/packages/client/ui-user-questions/README.zh.md +++ b/packages/client/ui-user-questions/README.zh.md @@ -25,7 +25,7 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户 ## 使用本包 -当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。首个带推荐标记的选项会预先选中,但仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。 +当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。单选题中首个带推荐标记的选项、多选题中所有带推荐标记的选项会预先选中,但仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。 ### 作答 diff --git a/packages/client/ui-user-questions/src/client/QuestionComposer.tsx b/packages/client/ui-user-questions/src/client/QuestionComposer.tsx index 0baf6e54c5..a24372c990 100644 --- a/packages/client/ui-user-questions/src/client/QuestionComposer.tsx +++ b/packages/client/ui-user-questions/src/client/QuestionComposer.tsx @@ -49,10 +49,14 @@ export function parseRecommendedLabel(label: string): { label: string; recommend : { label, recommended: false } } -/** Only a marked first choice is an implicit draft; the user still submits it. */ -function recommendedFirstOption(question: PendingQuestion['questions'][number]): string | undefined { - const label = question.options?.[0]?.label - return label !== undefined && parseRecommendedLabel(label).recommended ? label : undefined +/** + * Implicit draft selection the user still submits: every marked choice of a + * multi-select question, or a marked first choice of a single-select question. + */ +function recommendedOptions(question: PendingQuestion['questions'][number]): string[] { + const labels = (question.options ?? []).map(option => option.label) + const candidates = question.multiSelect === true ? labels : labels.slice(0, 1) + return candidates.filter(label => parseRecommendedLabel(label).recommended) } /** Accept persisted progress only when it still describes this question batch. */ @@ -182,9 +186,8 @@ function QuestionFlow({ pending, t, useStore, useQuestionCard, actions }: Questi return questions.map((item) => { const answer = recorded.get(item.id) const custom = answer?.custom ?? '' - const recommended = review === undefined ? recommendedFirstOption(item) : undefined return { - selected: answer === undefined && recommended !== undefined ? [recommended] : [...answer?.selected ?? []], + selected: answer !== undefined ? [...answer.selected] : review === undefined ? recommendedOptions(item) : [], custom, // A recorded answer with no selection and no custom text was skipped. skipped: answer !== undefined && answer.selected.length === 0 && custom === '', diff --git a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx index 4b46adcbd0..90cfaecbea 100644 --- a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx @@ -240,6 +240,36 @@ describe('QuestionComposer', () => { } }) + it('starts every recommended choice of a multi-select question selected', () => { + const { carrier, answer } = wait([{ + id: 'checks', question: 'Which checks?', multiSelect: true, + options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types(推荐)' }], + }]) + render() + expect(screen.getByRole('checkbox', { name: /Unit/ }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('checkbox', { name: /Lint/ }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('checkbox', { name: /Types/ }).getAttribute('aria-checked')).toBe('true') + + fireEvent.keyDown(screen.getByRole('checkbox', { name: /Lint/ }), { key: 'Enter' }) + expect(answer).toHaveBeenCalledWith(answerBatch([ + { id: 'checks', selected: ['Unit (Recommended)', 'Types(推荐)'] }, + ])) + }) + + it('starts only a recommended first choice of a single-select question selected', () => { + const { carrier } = wait([ + { id: 'first', question: 'First?', options: [{ label: 'A (Recommended)' }, { label: 'B (Recommended)' }] }, + { id: 'later', question: 'Later?', options: [{ label: 'C' }, { label: 'D (Recommended)' }] }, + ]) + render() + expect(screen.getByRole('radio', { name: /A/ }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('radio', { name: /B/ }).getAttribute('aria-checked')).toBe('false') + + fireEvent.click(screen.getByLabelText('下一题')) + expect(screen.getByRole('radio', { name: /C/ }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('radio', { name: /D/ }).getAttribute('aria-checked')).toBe('false') + }) + it('treats Enter on an unselected option as submit, without selecting it', () => { const { carrier, answer } = wait([{ id: 'mode', question: 'Which mode?', options: [{ label: 'Alpha' }, { label: 'Beta' }], From 07c3c10d2c6247173baa2f4b2e87b62d0ea5e82b Mon Sep 17 00:00:00 2001 From: yudshj Date: Tue, 27 Oct 2026 13:47:34 +0800 Subject: [PATCH 2/7] =?UTF-8?q?test(ui-user-questions):=20=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E5=A4=9A=E9=80=89=E9=A2=84=E9=80=89=E7=9A=84=E8=AE=A1?= =?UTF-8?q?=E6=97=B6=E4=B8=8E=E5=9B=9E=E7=9C=8B=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/ui-user-questions/README.i18n.yaml | 4 +- packages/client/ui-user-questions/README.md | 2 +- .../client/ui-user-questions/README.zh.md | 2 +- .../user-questions-composer.client.spec.tsx | 60 ++++++++++++++++--- 4 files changed, 56 insertions(+), 12 deletions(-) diff --git a/packages/client/ui-user-questions/README.i18n.yaml b/packages/client/ui-user-questions/README.i18n.yaml index dbf890074c..4177fb0a50 100644 --- a/packages/client/ui-user-questions/README.i18n.yaml +++ b/packages/client/ui-user-questions/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-user-questions/use-this-package: - en: 56368ea7909468c0 - zh: b212ffa1f0fda6a5 + en: f63c46f9fc2edb1f + zh: 82ad1b2e56a61a52 /deepseek-ai-dsh-client-ui-user-questions/use-this-package/answering: en: 8900fbf9cbd72083 zh: 67a951d58a029a58 diff --git a/packages/client/ui-user-questions/README.md b/packages/client/ui-user-questions/README.md index e510b510c0..5effc083a8 100644 --- a/packages/client/ui-user-questions/README.md +++ b/packages/client/ui-user-questions/README.md @@ -25,7 +25,7 @@ The Web client shows an agent's question beside the chat input. Users choose opt ## Use this package -When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. A single-select question’s first choice marked “Recommended” starts selected, as does every marked choice of a multi-select question; but remains an unsubmitted draft and does not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing). +When the agent asks a question, the attached card temporarily occupies the composer seat: answer each question, navigate with the pager, or skip it. When a single-select question’s first choice is marked “Recommended”, it starts selected; in a multi-select question, every marked choice starts selected. These preselections remain unsubmitted drafts and do not pause a timed countdown. Clicking a single-select choice advances immediately. Enter on a focused option attempts to submit the batch without selecting that option; missing answers return to the first incomplete question. Enter in a text answer continues the flow, while Shift+Enter breaks a line instead (during IME composition Enter only confirms the input candidate without advancing). ### Answering diff --git a/packages/client/ui-user-questions/README.zh.md b/packages/client/ui-user-questions/README.zh.md index 40b309155b..ad9149c648 100644 --- a/packages/client/ui-user-questions/README.zh.md +++ b/packages/client/ui-user-questions/README.zh.md @@ -25,7 +25,7 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户 ## 使用本包 -当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。单选题中首个带推荐标记的选项、多选题中所有带推荐标记的选项会预先选中,但仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。 +当 agent 提问时,附着式卡片会暂时占用编辑器位置:回答每个问题、用翻页器导航,或跳过它。单选题的第一个选项带推荐标记时会预先选中;多选题中所有带推荐标记的选项都会预先选中。这些预选仍只是未提交的草稿,不会暂停计时倒计时。点击单选选项会立即前进。聚焦选项时按 Enter 会尝试提交整组答案,不会选中该选项;若有缺失答案,则回到第一道未完成的问题。文本答案中的 Enter 会继续流程,Shift+Enter 则换行(IME 组合输入期间按 Enter 只会确认输入候选,不会前进)。 ### 作答 diff --git a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx index 90cfaecbea..bdb8ce927a 100644 --- a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx @@ -246,28 +246,50 @@ describe('QuestionComposer', () => { options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types(推荐)' }], }]) render() - expect(screen.getByRole('checkbox', { name: /Unit/ }).getAttribute('aria-checked')).toBe('true') - expect(screen.getByRole('checkbox', { name: /Lint/ }).getAttribute('aria-checked')).toBe('false') - expect(screen.getByRole('checkbox', { name: /Types/ }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('checkbox', { name: 'Lint' }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('true') - fireEvent.keyDown(screen.getByRole('checkbox', { name: /Lint/ }), { key: 'Enter' }) + fireEvent.keyDown(screen.getByRole('checkbox', { name: 'Lint' }), { key: 'Enter' }) expect(answer).toHaveBeenCalledWith(answerBatch([ { id: 'checks', selected: ['Unit (Recommended)', 'Types(推荐)'] }, ])) }) + it('keeps several recommended multi-select defaults without pausing a timed wait', () => { + const { carrier } = wait([ + { + id: 'checks', question: 'Which checks?', multiSelect: true, + options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types (Recommended)' }], + }, + { id: 'note', question: 'Anything else?' }, + ], Date.now() + 30_000) + try { + const view = render() + fireEvent.click(screen.getByLabelText('下一题')) + view.unmount() + render() + expect(carrier.snapshot().countdown?.running).toBe(true) + fireEvent.click(screen.getByLabelText('上一题')) + expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('true') + } finally { + carrier.timeout() + } + }) + it('starts only a recommended first choice of a single-select question selected', () => { const { carrier } = wait([ { id: 'first', question: 'First?', options: [{ label: 'A (Recommended)' }, { label: 'B (Recommended)' }] }, { id: 'later', question: 'Later?', options: [{ label: 'C' }, { label: 'D (Recommended)' }] }, ]) render() - expect(screen.getByRole('radio', { name: /A/ }).getAttribute('aria-checked')).toBe('true') - expect(screen.getByRole('radio', { name: /B/ }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('radio', { name: 'A' }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('radio', { name: 'B' }).getAttribute('aria-checked')).toBe('false') fireEvent.click(screen.getByLabelText('下一题')) - expect(screen.getByRole('radio', { name: /C/ }).getAttribute('aria-checked')).toBe('false') - expect(screen.getByRole('radio', { name: /D/ }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('radio', { name: 'C' }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('radio', { name: 'D' }).getAttribute('aria-checked')).toBe('false') }) it('treats Enter on an unselected option as submit, without selecting it', () => { @@ -1023,6 +1045,28 @@ describe('review card', () => { expect(screen.queryByPlaceholderText('输入你的答案')).toBeNull() }) + it('shows recorded multi-select answers without restoring recommended defaults', () => { + const questions: PendingQuestion['questions'] = [ + { + id: 'checks', question: 'Which checks?', multiSelect: true, + options: [{ label: 'Unit (Recommended)' }, { label: 'Lint' }, { label: 'Types (Recommended)' }], + }, + { + id: 'unrecorded', question: 'Which targets?', multiSelect: true, + options: [{ label: 'Web (Recommended)' }, { label: 'Desktop' }], + }, + ] + const carrier = new PendingQuestion(SID, questions, ToolCallId(REVIEWED_CALL), undefined, [{ id: 'checks', selected: ['Lint'] }]) + carrier.attachSeat({ hide: vi.fn() }) + render() + + expect(screen.getByRole('checkbox', { name: 'Unit' }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('checkbox', { name: 'Lint' }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('checkbox', { name: 'Types' }).getAttribute('aria-checked')).toBe('false') + fireEvent.click(screen.getByLabelText('下一题')) + expect(screen.getByRole('checkbox', { name: 'Web' }).getAttribute('aria-checked')).toBe('false') + }) + it('reads the record back instead of a draft the live card left under the same key', () => { kit.actions.replace(PendingQuestion.keyOf(SID, REVIEWED_CALL), { index: 2, From 185eb56a2b54a40d839c60ad4086a2c007b44e46 Mon Sep 17 00:00:00 2001 From: yudshj Date: Tue, 27 Oct 2026 14:31:56 +0800 Subject: [PATCH 3/7] =?UTF-8?q?test(web):=20=E6=96=B0=E5=A2=9E=E5=A4=9A?= =?UTF-8?q?=E9=80=89=E9=A2=98=E5=A4=9A=E6=8E=A8=E8=8D=90=E9=A1=B9=E9=A2=84?= =?UTF-8?q?=E9=80=89=E7=9A=84=20Web=20snapshot=20=E5=9C=BA=E6=99=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../question-composer-recommended.e2e.ts | 92 +++++++++++++++++++ apps/web/tsconfig.json | 1 + .../session.v4.jsonl | 23 +++++ .../snapshot.yml | 7 ++ .../ui.expected.md | 16 ++++ tsconfig.host.json | 1 + 6 files changed, 140 insertions(+) create mode 100644 apps/web/tests/question-composer-recommended.e2e.ts create mode 100644 snapshots/web/question-composer-recommended/session.v4.jsonl create mode 100644 snapshots/web/question-composer-recommended/snapshot.yml create mode 100644 snapshots/web/question-composer-recommended/ui.expected.md diff --git a/apps/web/tests/question-composer-recommended.e2e.ts b/apps/web/tests/question-composer-recommended.e2e.ts new file mode 100644 index 0000000000..96ebc2c15a --- /dev/null +++ b/apps/web/tests/question-composer-recommended.e2e.ts @@ -0,0 +1,92 @@ +/** A multi-select question opens with every option marked as recommended already chosen, wherever it sits in the list. */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { + connectFreshWorkspace, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, +} from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/question-composer-recommended', import.meta.url)) +const FIXTURE = join(SNAPSHOT_DIR, 'session.v4.jsonl') +const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md') +const MODE = webSnapshotMode() + +const PROMPT = 'Use the ask_user_question tool to ask me exactly one multi-select question with id "checks", question "Which checks should run before merging?", header "Checks", and three options in this order: label "Unit tests (Recommended)", label "Full e2e suite", and label "Type check (Recommended)". Set multi_select to true. After I answer, reply with the single word DONE and stop.' + +describe('web e2e: recommended multi-select options', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + const sessionEvents: SessionEvent[] = [] + let hostClock: ReturnType | undefined + + beforeAll(async () => { + if (MODE !== 'record') hostClock = pinHostClock() + scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15, compareReplaySession: true }) + scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + if (MODE !== 'record') await pinBrowserClock(page) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + }, 120_000) + + afterAll(async () => { + try { + await browser?.close() + } finally { + try { await scaffold?.close() } + finally { hostClock?.mockRestore() } + } + }) + + it('preselects every recommended option and submits them unchanged', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-question-recommended')) + if (MODE !== 'record') { + expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) + } + const input = page.locator('[data-composer-input]').first() + await input.waitFor({ timeout: 10_000 }) + const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000) + await input.fill(PROMPT) + await input.press('Enter') + + const composer = page.locator('[data-question-key]') + await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 }) + await composer.getByRole('heading', { name: 'Which checks should run before merging?' }).waitFor({ timeout: 10_000 }) + const checked = await composer.getByRole('checkbox').evaluateAll(nodes => + nodes.map(node => node.getAttribute('aria-checked'))) + expect(checked).toEqual(['true', 'false', 'true']) + if (MODE !== 'record') { + const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd) + await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) + } + + await composer.getByRole('button', { name: 'Submit', exact: true }).click() + const sessionId = await settled + if (MODE === 'record') { + await recordFixture(scaffold, sessionId, FIXTURE) + return + } + const answerText = sessionEvents.filter(event => event.type === 'tool/result') + .flatMap(event => event.data.message.content.filter(item => item.type === 'text').map(item => item.text)) + .at(-1) + expect(JSON.parse(answerText ?? '')).toEqual({ + answers: [{ id: 'checks', selected: ['Unit tests (Recommended)', 'Type check (Recommended)'] }], + }) + await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['session.v4.jsonl', 'ui.expected.md']) + }, 200_000) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index e9df1e11f1..3de8b1fb68 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -67,6 +67,7 @@ "tests/subagent-fork-schedule.snapshot.ts", "tests/live-interactions.e2e.ts", "tests/question-composer.e2e.ts", + "tests/question-composer-recommended.e2e.ts", "tests/question-ptc.e2e.ts", "tests/approval-composer.e2e.ts", "tests/ptc-escalation.e2e.ts", diff --git a/snapshots/web/question-composer-recommended/session.v4.jsonl b/snapshots/web/question-composer-recommended/session.v4.jsonl new file mode 100644 index 0000000000..e04da5e1c8 --- /dev/null +++ b/snapshots/web/question-composer-recommended/session.v4.jsonl @@ -0,0 +1,23 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1788240617068,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the ask_user_question tool to ask me exactly one multi-select question with id \"checks\", question \"Which checks should run before merging?\", header \"Checks\", and three options in this order: label \"Unit tests (Recommended)\", label \"Full e2e suite\", and label \"Type check (Recommended)\". Set multi_select to true. After I answer, reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"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":"Use the ask_user_question tool to ask me exactly one multi-select question with id \"checks\", question \"Which checks should run before merging?\", header \"Checks\", and three options in this order: label \"Unit tests (Recommended)\", label \"Full e2e suite\", and label \"Type check (Recommended)\". Set multi_select to true. After I answer, reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} +{"type":"session/title","data":{"title":"Use the ask_user_question tool to","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants a multi-select question with two recommended options. Let me ask it."},{"type":"tool-call","id":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":113,"outputTokens":80,"cacheReadTokens":4096,"reasoningTokens":16},"stream":[{"type":"chunk","time":1790389322730,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389322746,"index":0,"dt":[],"texts":["The user wants a multi-select question with two recommended options. Let me ask it."]},{"type":"chunk","time":1790389322762,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790389322778,"index":1,"dt":[16],"id":"call_00_RecommendedChecks0001","name":"ask_user_question","args":["","{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"]},{"type":"chunk","time":1790389322810,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants a multi-select question with two recommended options. Let me ask it."}}},{"type":"chunk","time":1790389322826,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}}},{"type":"chunk","time":1790389322842,"chunk":{"type":"usage","usage":{"inputTokens":113,"outputTokens":80,"cacheReadTokens":4096,"reasoningTokens":16}}},{"type":"chunk","time":1790389322858,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_RecommendedChecks0001","name":"ask_user_question","arguments":"{\"questions\": [{\"id\": \"checks\", \"question\": \"Which checks should run before merging?\", \"header\": \"Checks\", \"multi_select\": true, \"options\": [{\"label\": \"Unit tests (Recommended)\"}, {\"label\": \"Full e2e suite\"}, {\"label\": \"Type check (Recommended)\"}]}]}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_RecommendedChecks0001"},"toolCallId":"call_00_RecommendedChecks0001","content":[{"type":"text","text":"{\"answers\":[{\"id\":\"checks\",\"selected\":[\"Unit tests (Recommended)\",\"Type check (Recommended)\"]}]}"}],"isError":false,"id":"{{message:6}}"}},"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":"reasoning","text":"The user kept both recommended checks. I should reply DONE and stop."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":220,"outputTokens":18,"cacheReadTokens":4096,"reasoningTokens":14},"stream":[{"type":"chunk","time":1790389325337,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389325353,"index":0,"dt":[],"texts":["The user kept both recommended checks. I should reply DONE and stop."]},{"type":"chunk","time":1790389325369,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389325385,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790389325401,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user kept both recommended checks. I should reply DONE and stop."}}},{"type":"chunk","time":1790389325417,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790389325433,"chunk":{"type":"usage","usage":{"inputTokens":220,"outputTokens":18,"cacheReadTokens":4096,"reasoningTokens":14}}},{"type":"chunk","time":1790389325449,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/question-composer-recommended/snapshot.yml b/snapshots/web/question-composer-recommended/snapshot.yml new file mode 100644 index 0000000000..fb27eeca81 --- /dev/null +++ b/snapshots/web/question-composer-recommended/snapshot.yml @@ -0,0 +1,7 @@ +version: 1 +scenario: question-composer-recommended +profile: web +composition: web-default +recording: authored +header: + class: web-default diff --git a/snapshots/web/question-composer-recommended/ui.expected.md b/snapshots/web/question-composer-recommended/ui.expected.md new file mode 100644 index 0000000000..cd65682b26 --- /dev/null +++ b/snapshots/web/question-composer-recommended/ui.expected.md @@ -0,0 +1,16 @@ +- region "Which checks should run before merging?": + - text: Checks + - button "Collapse the question card" [expanded] + - button "Dismiss all questions" + - heading "Which checks should run before merging?" [level=2] + - group: + - checkbox "Unit tests" [checked]: Unit tests Recommended + - checkbox "Full e2e suite" + - checkbox "Type check" [checked]: Type check Recommended + - textbox "Type your answer" + - button "Previous question" [disabled] + - text: 1 / 1 + - button "Next question" [disabled] + - status + - button "Skip" + - button "Submit" diff --git a/tsconfig.host.json b/tsconfig.host.json index fa98ab87dd..7b0f9bec4b 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -62,6 +62,7 @@ "apps/web/tests/subagent-fork-schedule.snapshot.ts", "apps/web/tests/live-interactions.e2e.ts", "apps/web/tests/question-composer.e2e.ts", + "apps/web/tests/question-composer-recommended.e2e.ts", "apps/web/tests/question-ptc.e2e.ts", "apps/web/tests/approval-composer.e2e.ts", "apps/web/tests/plan-control-row.e2e.ts", From 4f851948a57d862c49c136db9d77f35b38445434 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 27 Oct 2026 15:42:21 +0800 Subject: [PATCH 4/7] perf(web): minify dynamic client bundles --- packages/client/modules/README.i18n.yaml | 4 +- packages/client/modules/README.md | 2 + packages/client/modules/README.zh.md | 2 + packages/client/tsdown.client.ts | 16 +- ...ment-preview-license-bundle.client.spec.ts | 12 +- .../tests/bundle-split.client.spec.ts | 14 +- .../webworker-packer/README.i18n.yaml | 4 +- .../experimental/webworker-packer/README.md | 2 +- .../webworker-packer/README.zh.md | 2 +- .../experimental/webworker-packer/src/pack.ts | 6 +- .../tests/lazy-chunks.spec.ts | 22 +++ scripts/client-bundle-css.spec.ts | 28 ++- scripts/client-bundle-purity.spec.ts | 184 +++++++++++++++++- 13 files changed, 265 insertions(+), 33 deletions(-) diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index eb264da002..30c512d5c4 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -36,8 +36,8 @@ en: 1778b5a63ecde5e8 zh: 537b4f8c755af8ad /deepseek-ai-dsh-client-modules/use-this-package/build-requirements: - en: b6a4d3b901c89efe - zh: 615b5f3eec41f281 + en: 3fb8bab648cc58d1 + zh: 064667ba7b45839e /deepseek-ai-dsh-client-modules/understand-the-implementation: en: 7ab11d2c2bdc6eaa zh: 54c3c9091cf59711 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 6048a73939..262298ece6 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -58,6 +58,8 @@ The shell seeds a frozen module table ([`PLATFORM_MODULES`](../web/README.md#the The host serves built client bundles, so `pnpm run build` must have produced each `lib/client.js` before launch; a missing bundle fails activation loudly with one build instruction and a package/path list. Source launch maps host imports to TypeScript source but still consumes the built client export. The package accepts no plugin config of its own. +The shared Client preset minifies browser factories and lazy chunks unless `NODE_ENV=development`. Minification preserves the function and class names produced by bundling, legal comments, full package license banners, and source maps with original source content. Development output remains unminified; Host and Node Client output use separate presets. + ----- diff --git a/packages/client/modules/README.zh.md b/packages/client/modules/README.zh.md index 1d97be97de..086d0810eb 100644 --- a/packages/client/modules/README.zh.md +++ b/packages/client/modules/README.zh.md @@ -59,6 +59,8 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启 宿主提供的是已构建的客户端 bundle,因此启动前 `pnpm run build` 必须已产出每个 `lib/client.js`;缺失 bundle 会明确导致激活失败,并给出一条构建说明及包/路径列表。源码启动会把宿主侧导入映射到 TypeScript 源码,但仍消费这一构建后的客户端导出。本包自身不接受任何插件配置。 +除 `NODE_ENV=development` 外,共享 Client 预设会压缩浏览器 factory 和懒加载 chunk。压缩会保留打包生成的函数名和类名、法律声明注释、完整的包许可证声明,以及包含原始源码内容的 source map。开发产物保持未压缩;Host 和 Node Client 产物使用各自的预设。 + ----- diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index ca7bbc4154..a82d7b3a5c 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -120,6 +120,8 @@ function browserSourcePath(source: string, sourcemapPath: string): string { * the package without lib/index.js and the host Loader cannot import its node * half. The Client build consumes `lib/types` and chains those tsc maps, with * original source content, into the standalone plugin map. + * Browser factories and lazy chunks are minified unless NODE_ENV is development; + * minification retains bundled function/class names and legal notices. * @param packageDir - the package's own directory, normally the config's * `import.meta.dirname`. Its `package.json` name is the plugin id stamped into * the __ModuleLoader__.load handoff and onto the injected style tags, and the @@ -790,6 +792,12 @@ function clientConfig( outDir: 'lib', format: 'cjs', platform: 'browser', + minify: process.env.NODE_ENV === 'development' ? false : { + // Cordis uses function/class names for plugin and callback labels. + compress: { keepNames: { function: true, class: true } }, + mangle: { keepNames: true }, + codegen: { legalComments: 'inline' }, + }, // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing. dts: false, // Plugin code is fetched outside Vite's module graph, so its own bundle @@ -927,11 +935,9 @@ function clientConfig( isolation.sourcePath(source, mapPath) return browserSourcePath(source, mapPath) }, - banner: (chunk) => { - const registration = `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}factory: (require) => {` - const prefix = clientBanner?.(chunk.fileName) - return prefix === undefined ? registration : `${prefix}\n${registration}` - }, + banner: chunk => `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}factory: (require) => {`, + // Full license notices may include ordinary comments that minification removes. + postBanner: chunk => clientBanner?.(chunk.fileName) ?? '', footer: 'return module.exports; } });', intro: 'var module = { exports: {} }; var exports = module.exports;', }, diff --git a/packages/client/ui-sidebar-documentpreview/tests/document-preview-license-bundle.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/document-preview-license-bundle.client.spec.ts index d42317f4b8..3a854e57a5 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/document-preview-license-bundle.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/document-preview-license-bundle.client.spec.ts @@ -10,6 +10,7 @@ import { describe, expect, it } from 'vitest' const packageRoot = resolve(import.meta.dirname, '..') const bundlePath = join(packageRoot, 'lib/client.js') const pdfChunkPath = join(packageRoot, 'lib/client.pdf.js') +const syncChunkCall = /(? { const client = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.js'], packageRoot, task.timeout) const pdf = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.pdf.js'], packageRoot, task.timeout) - expect([...client.matchAll(/require\.async\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1])) + expect([...client.matchAll(/\.async\s*\(\s*(["'`])(\.\/client[^"'`/]*\.js)\1\s*\)/gu)].map(match => match[2])) .toEqual(['./client.frontmatter-fields.js', './client.pdf.js', './client.excel.js']) - expect(client).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u) - expect([...pdf.matchAll(/require\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1])) - .toEqual([]) + expect(client).not.toMatch(syncChunkCall) + expect(pdf).not.toMatch(syncChunkCall) expect(client).not.toContain('//! Bundled PDF.js license notices') expect(client).not.toContain('/pdfjs-dist/') expect(pdf).toContain('//! Bundled PDF.js license notices') const excel = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.excel.js'], packageRoot, task.timeout) - expect(excel).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u) + expect(excel).not.toMatch(syncChunkCall) expect(client).not.toContain('FortuneSheet') expect(excel).toContain('//! Bundled spreadsheet license notices') expect(excel).toContain('Copyright (c) 2022 Suzhou Ruilisi Technology Co., Ltd') @@ -78,7 +78,7 @@ describe('published document preview licenses', () => { expect(excel).toContain(license.split('\n').map(line => `// ${line}`).join('\n')) } const frontmatter = run('tar', ['-xOf', resolve(packageRoot, packed.filename), 'package/lib/client.frontmatter-fields.js'], packageRoot, task.timeout) - expect(frontmatter).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u) + expect(frontmatter).not.toMatch(syncChunkCall) let frontmatterInitialized = false runInNewContext(frontmatter, { window: { __ModuleLoader__: { load: (registration: { factory: (resolve: (specifier: string) => unknown) => { FrontmatterFields: unknown } diff --git a/packages/client/ui-sidebar-terminal/tests/bundle-split.client.spec.ts b/packages/client/ui-sidebar-terminal/tests/bundle-split.client.spec.ts index c42abde2e6..aa9d9df1f6 100644 --- a/packages/client/ui-sidebar-terminal/tests/bundle-split.client.spec.ts +++ b/packages/client/ui-sidebar-terminal/tests/bundle-split.client.spec.ts @@ -5,18 +5,20 @@ import { describe, expect, it } from 'vitest' const packageRoot = resolve(import.meta.dirname, '..') const entryPath = join(packageRoot, 'lib/client.js') const terminalPath = join(packageRoot, 'lib/client.terminal.js') +const syncChunkCall = /(? { it.skipIf(!existsSync(entryPath))('keeps xterm outside the startup bundle', () => { expect(existsSync(terminalPath)).toBe(true) const entry = readFileSync(entryPath, 'utf8') const terminal = readFileSync(terminalPath, 'utf8') - expect([...entry.matchAll(/require\.async\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1])) + expect([...entry.matchAll(/\.async\s*\(\s*(["'`])(\.\/client[^"'`/]*\.js)\1\s*\)/gu)].map(match => match[2])) .toEqual(['./client.terminal.js']) - expect(entry).not.toMatch(/\brequire\("\.\/client[^"/]*\.js"\)/u) - expect([...terminal.matchAll(/require\("(\.\/client[^"/]*\.js)"\)/gu)].map(match => match[1])) - .toEqual([]) - expect(entry).not.toContain('/@xterm+xterm@') - expect(terminal).toContain('/@xterm+xterm@') + expect(entry).not.toMatch(syncChunkCall) + expect(terminal).not.toMatch(syncChunkCall) + const entryMap = JSON.parse(readFileSync(`${entryPath}.map`, 'utf8')) as { sources: string[] } + const terminalMap = JSON.parse(readFileSync(`${terminalPath}.map`, 'utf8')) as { sources: string[] } + expect(entryMap.sources.some(source => source.includes('/@xterm/xterm/'))).toBe(false) + expect(terminalMap.sources.some(source => source.includes('/@xterm/xterm/'))).toBe(true) }) }) diff --git a/packages/experimental/webworker-packer/README.i18n.yaml b/packages/experimental/webworker-packer/README.i18n.yaml index 3604dcd3db..cf9f1bc879 100644 --- a/packages/experimental/webworker-packer/README.i18n.yaml +++ b/packages/experimental/webworker-packer/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-packer/use-this-package: - en: 6a4ec925ea6681f5 - zh: 4af12d1d3de38dbd + en: 2c7aff0894ebf4fa + zh: cce7ca3aa5eeac33 /deepseek-ai-dsh-experimental-webworker-packer/model-experience: en: e16b355530dadc1c zh: 8488e03b253b7b33 diff --git a/packages/experimental/webworker-packer/README.md b/packages/experimental/webworker-packer/README.md index 1e6c3289f7..04d1587963 100644 --- a/packages/experimental/webworker-packer/README.md +++ b/packages/experimental/webworker-packer/README.md @@ -32,7 +32,7 @@ The pack is a three-layer standard stack: 1. **Roster** — the shipped profile template's bundles and every bundle in `OPTIONAL_BUNDLES` from [`dsh-official-bundles`](../../util/official-bundles/README.md), each resolved from the CLI manifest as the launcher resolves it, plus every package their patch files name (insert lists and grouped rows included), plus the rows of every config tree the CLI declares in its `package.json` `dsh.configTrees`, materialized as a Node-style dependency closure. External peer edges never bind the worker; workspace peers stay on the chain. The CLI manifest itself enters the image alone at `node_modules/@deepseek-ai/dsh/package.json`, as the worker's bundle resolution anchor; the manifest records its name and the profile. 2. **Publish view** — each workspace or vendored package contributes its built npm slice (`files` through picomatch) without source or workspace `dist/`. External packages retain published JavaScript under both `src/` and `dist/` because their `main` or `exports` may point there; only generic test, map, declaration, and archive exclusions apply. 3. **Reachability sweep** — the runtime loader's own resolution walks from every non-wildcard workspace runtime export plus the worker assembly's seeds (`IMAGE_ENTRY_SEEDS`), lowering each reached module to the wrapper contract at pack time. Declaration-only condition trees do not seed the sweep; runtime requests for those exports still fail. The transform reports statically named imports, re-exports, and dynamic imports; calls through `require`; and module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named import from `node:module` or `module`, including an import alias. Page assets (`lib/client.js` behind `./client` exports) ship verbatim; an unresolvable request from our own code fails the pack, third-party ones are tolerated to fail loud at require time. -4. **Lazy chunks** — every page chunk a page asset requests as a literal `require.async("./client..js")`, the only form the dynamic Client build emits, leaves the base image unless a `./client` export names it. Each becomes its own deterministic archive named `lazy/.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack. +4. **Lazy chunks** — every page chunk requested through the Client factory's injected loader `.async` method with a literal `./client..js` path leaves the base image unless a `./client` export names it. The scanner accepts the production build's renamed loader variable and single, double, or backtick quotes. Each chunk becomes its own deterministic archive named `lazy/.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack. `repository.ts` owns the repo-shaped inputs (workspace scan of `vendor/`, `packages/`, `native/system/packages/`, and `apps/`; the profile roster through the shipped templates and optional-bundle list of `dsh-official-bundles` and app-boot's bundle patch readers; the CLI manifest as the installation; the home patch, which sets the runtime's `PLATFORM_ENTRY_CONFIG` fields over each named row's config composed from the template's bundle layers); `pack.ts` owns none of them, so the same library packs a different tree by being called differently. The native scan makes the Landlock entry package an ordinary published-view dependency while its executable remains a Worker platform implementation. The CLI is `dsh-pack-vfs-image --out [--profile web]`; it writes the lazy archives beside the base image, and `apps/web`'s `build:preview` runs it after the preview shell build. diff --git a/packages/experimental/webworker-packer/README.zh.md b/packages/experimental/webworker-packer/README.zh.md index fc760a4f65..832d47c8cd 100644 --- a/packages/experimental/webworker-packer/README.zh.md +++ b/packages/experimental/webworker-packer/README.zh.md @@ -32,7 +32,7 @@ VFS 镜像打包器:把一份随附 profile 的 bundle 和安装提供的 opti 1. **Roster**——随附 profile 模板的 bundle 和 [`dsh-official-bundles`](../../util/official-bundles/README.zh.md) `OPTIONAL_BUNDLES` 中的每个 bundle(各自按启动器的方式从 CLI manifest 解析),加上它们 patch 文件点名的每个包(含 insert 列表与分组行),再加上 CLI(命令行界面)在 `package.json` `dsh.configTrees` 里声明的每棵配置树的行,按 Node 式依赖闭包物化。外部 peer 边绝不会绑定到 worker,workspace peer 保留在链上。CLI manifest 本身单独进入镜像,位于 `node_modules/@deepseek-ai/dsh/package.json`,作为 worker 解析 bundle 的锚点;manifest 记录它的名称和 profile。 2. **发布视图**——每个 workspace 或 vendored 包贡献其构建后的 npm 切片(`files` 走 picomatch),不带源码和 workspace `dist/`。外部包的 `main` 或 `exports` 可能指向 `src/` 或 `dist/`,因此两处发布 JavaScript 都会保留,只应用通用的测试、map、声明与归档排除规则。 3. **可达性 sweep**——用运行时加载器自己的解析, 从全部不含通配符的 workspace 运行时导出加 worker 装配种子 (`IMAGE_ENTRY_SEEDS`) 出发, 打包时把每个可达模块转换为符合包装层约定的形式. 仅含类型声明的条件树不作为扫描入口; 运行时代码请求这些导出仍会失败. 该转换会报告名称可静态确定的 import、re-export 与动态 import、经 `require` 发起的调用, 以及通过 `node:module` 或 `module` 具名导入 (含导入别名) 在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用. 页面资产 (`./client` 导出背后的 `lib/client.js`) 原样直发; 自家代码的不可解析请求会让打包失败, 第三方不可解析请求则允许延后到 require 时明确失败. -4. **懒加载 chunk**——页面资产以字面量 `require.async("./client..js")`(动态 Client 构建产出的唯一形式)请求的每个页面 chunk,除非被 `./client` 导出点名,否则移出基础镜像。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。 +4. **懒加载 chunk**——通过注入 Client factory 的 loader 的 `.async` 方法以字面量 `./client..js` 路径请求的每个页面 chunk,除非被 `./client` 导出点名,否则移出基础镜像。扫描器支持生产构建中改名后的 loader 变量,以及单引号、双引号或反引号。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。 `repository.ts` 拥有仓库形态输入(`vendor/`、`packages/`、`native/system/packages/` 与 `apps/` 的 workspace 扫描;经 `dsh-official-bundles` 的随附模板、optional bundle 列表和 app-boot 的 bundle patch 读取器得出 profile roster;以 CLI manifest 作为安装清单;home patch 在模板各 bundle 层合成出的行配置之上设置运行时 `PLATFORM_ENTRY_CONFIG` 字段);`pack.ts` 一概不拥有,同一库换参即可打另一棵树。Native 扫描使 Landlock 入口包成为普通发布视图依赖,其可执行文件仍由 Worker 平台实现。CLI 为 `dsh-pack-vfs-image --out [--profile web]`;它把懒加载归档写在基础镜像旁,`apps/web` 的 `build:preview` 在预览壳构建后运行它。 diff --git a/packages/experimental/webworker-packer/src/pack.ts b/packages/experimental/webworker-packer/src/pack.ts index fd394d2d51..269aedf7e9 100644 --- a/packages/experimental/webworker-packer/src/pack.ts +++ b/packages/experimental/webworker-packer/src/pack.ts @@ -580,10 +580,10 @@ function materialize( } /** - * Request form the dynamic Client build emits for a package-local chunk: a - * literal `require.async("./client..js")`, served by the Host on demand. + * Dynamic Client factories request package-local chunks through `.async` with + * a literal path. Minification can rename `require` and change the quote style. */ -const CHUNK_REQUEST = /\brequire\.async\(\s*(["'])(\.\/client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\1\s*\)/g +const CHUNK_REQUEST = /[A-Za-z_$][\w$]*\.async\(\s*(["'`])(\.\/client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\1\s*\)/g /** * Image paths every materialized package's `./client` export names, under any diff --git a/packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts b/packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts index d910d9768f..07f04c436d 100644 --- a/packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts +++ b/packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts @@ -86,6 +86,28 @@ it('refuses a chunk request whose file the package does not publish', (test) => expect(() => packVfsImage(options)).toThrow(/client\.browser\.js requests chunk "\.\/client\.missing\.js"/) }) +it.for(['published', 'missing'] as const)('handles %s chunks with renamed loaders and backtick paths', (publication, test) => { + const options = fixture(test, { + ...CHUNKS, + 'client.browser.js': 'module.exports=e=>({load:()=>e.async(`./client.pdf.js`)})', + 'client.pdf.js': 'module.exports=t=>({worker:()=>t.async(`./client.pdf-worker.js`)})', + }) + if (publication === 'missing') { + rmSync(join(options.resolveFrom, 'lib/client.pdf-worker.js')) + expect(() => packVfsImage(options)).toThrow(/client\.pdf\.js requests chunk "\.\/client\.pdf-worker\.js"/) + } else { + const result = packVfsImage(options) + expect(Object.keys(result.files)).toContain(`${PREFIX}/client.browser.js`) + expect(Object.keys(result.files)).toContain(`${PREFIX}/client.orphan.js`) + expect(Object.keys(result.files)).not.toContain(`${PREFIX}/client.pdf.js`) + expect(Object.keys(result.files)).not.toContain(`${PREFIX}/client.pdf-worker.js`) + expect(result.lazyArchives.map(archive => archive.files)).toEqual([ + [`${PREFIX}/client.pdf-worker.js`], + [`${PREFIX}/client.pdf.js`], + ]) + } +}) + it('keeps a ./client export target in the base image even when a chunk requests it', (test) => { const result = packVfsImage(fixture(test, { 'client.browser.js': 'module.exports = { load: () => require.async("./client.pdf.js") }', diff --git a/scripts/client-bundle-css.spec.ts b/scripts/client-bundle-css.spec.ts index 3703a36225..1290ff475d 100644 --- a/scripts/client-bundle-css.spec.ts +++ b/scripts/client-bundle-css.spec.ts @@ -259,10 +259,30 @@ describe('client bundle package asset imports', () => { write: false, clean: false, exports: false, report: false, logLevel: 'silent', }) const output = builds.flatMap(bundle => bundle.chunks).find(chunk => chunk.type === 'chunk' && chunk.fileName === 'client.js') - const code = output?.type === 'chunk' ? output.code : '' - expect(code).toContain(`require.asset(${JSON.stringify(WHALE_URL)})`) - expect(code).not.toContain('__dshPackageAsset_') - expect(code).toContain('"__dshPackageAsset("') + if (output?.type !== 'chunk') throw new Error('asset fixture client output missing') + type AssetRequire = ((specifier: string) => never) & { asset(reference: string): string } + const requests: string[] = [] + const require: AssetRequire = Object.assign((specifier: string): never => { + throw new Error(`Unexpected synchronous module request: ${specifier}`) + }, { + asset(reference: string): string { + requests.push(reference) + return `resolved:${reference}` + }, + }) + const registrations: { id: string; factory(require: AssetRequire): { url: string; text: string } }[] = [] + runInNewContext(output.code, { window: { __ModuleLoader__: { load(value: typeof registrations[number]) { + registrations.push(value) + } } } }) + expect(registrations).toHaveLength(1) + const registration = registrations[0] + if (registration === undefined) throw new Error('asset fixture factory registration missing') + expect(registration.id).toBe(PACKAGE_NAME) + expect(requests).toEqual([]) + const exports = registration.factory(require) + expect(exports.url).toBe(`resolved:${WHALE_URL}`) + expect(exports.text).toBe('__dshPackageAsset(') + expect(requests).toEqual([WHALE_URL]) } finally { for (const bundle of builds) await bundle[Symbol.asyncDispose]() } diff --git a/scripts/client-bundle-purity.spec.ts b/scripts/client-bundle-purity.spec.ts index d23402b3eb..91b80ad71f 100644 --- a/scripts/client-bundle-purity.spec.ts +++ b/scripts/client-bundle-purity.spec.ts @@ -6,6 +6,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node: import { tmpdir } from 'node:os' import { dirname, join, relative } from 'node:path' import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' import { build, type Rolldown, type TsdownBundle, type UserConfig } from 'tsdown' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { clientBundle, requestedExternals, staticLinked } from '../packages/client/tsdown.client.ts' @@ -120,6 +121,24 @@ function dynamicImportFixture(prefix: string): string { return root } +interface ClientFactoryRegistration { + id: string + chunk?: string + factory(require: Require): Value +} + +function registerClientFactory(code: string): ClientFactoryRegistration { + const registrations: ClientFactoryRegistration[] = [] + runInNewContext(code, { window: { __ModuleLoader__: { load(value: ClientFactoryRegistration) { + registrations.push(value) + } } } }) + expect(registrations).toHaveLength(1) + const registration = registrations[0] + if (registration === undefined) throw new Error('client factory registration missing') + expect(registration.id).toBe(REQUESTING_PACKAGE) + return registration +} + describe('client bundle dynamic imports', () => { it('keeps a dual Client browser chunk disjoint from its Node output', async () => { const root = dynamicImportFixture('dsh-dual-client-chunk-') @@ -155,15 +174,174 @@ describe('client bundle dynamic imports', () => { write: false, clean: false, exports: false, report: false, logLevel: 'silent', }) const chunks = builds.flatMap(bundle => bundle.chunks).filter(chunk => chunk.type === 'chunk') - const output = chunks.find(chunk => chunk.fileName === 'client.js')?.code - expect(output).toContain('require.async("./client.terminal.js")') - expect(output).not.toContain('Promise.resolve().then(() => require("./client.terminal.js"))') + const entry = chunks.find(chunk => chunk.fileName === 'client.js') + const terminal = chunks.find(chunk => chunk.fileName === 'client.terminal.js') + if (entry === undefined || terminal === undefined) throw new Error('dynamic import fixture outputs missing') + type Terminal = { marker: string } + type Require = ((specifier: string) => never) & { async(specifier: string): Promise } + const requests: string[] = [] + const require: Require = Object.assign((specifier: string): never => { + throw new Error(`Unexpected synchronous module request: ${specifier}`) + }, { + async(specifier: string): Promise { + requests.push(specifier) + expect(specifier).toBe('./client.terminal.js') + const registration = registerClientFactory(terminal.code) + expect(registration.chunk).toBe('client.terminal.js') + return Promise.resolve(registration.factory(require)) + }, + }) + const registration = registerClientFactory<{ load(): Promise }, Require>(entry.code) + expect(registration.chunk).toBeUndefined() + const exports = registration.factory(require) + expect(requests).toEqual([]) + await expect(exports.load()).resolves.toEqual({ marker: 'terminal' }) + expect(requests).toEqual(['./client.terminal.js']) } finally { for (const bundle of builds) await bundle[Symbol.asyncDispose]() } }) }) +interface CompressionFixtureDetails { + describeScore(value: number): string +} + +interface CompressionFixtureEntry { + calculateScore(values: readonly number[]): number + activate(): number + incrementScore(value: number): number + decrementScore(value: number): number + FixtureAccumulator: { new (seed: number): { total(values: readonly number[]): number }; readonly name: string } + loadDetails(): Promise +} + +type CompressionFixtureRequire = ((specifier: string) => never) & { + async(specifier: string): Promise +} + +describe('production client bundle compression', () => { + it('keeps executable exports, lazy chunks, names, notices and maps while compressing production only', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-client-compression-')) + onTestFinished(() => { rmSync(root, { recursive: true, force: true }) }) + const directory = join(root, 'lib/types/client') + mkdirSync(directory, { recursive: true }) + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: REQUESTING_PACKAGE, type: 'module' })) + // Every long local contributes to a runtime result; comments and dead branches cannot earn the byte reduction. + const terms = Array.from({ length: 24 }, (_, index) => `intermediateContributionForInputPosition${index}`) + const entrySource = [ + '/*! @license Fixture arithmetic license */', + 'export function calculateScore(values) {', + ...terms.map((name, index) => ` const ${name} = values[${index}] * ${index + 1} + ${index + 2};`), + ` return ${terms.join(' + ')};`, + '}', + 'export class FixtureAccumulator {', + ' constructor(seed) { this.seed = seed; }', + ' total(values) { return this.seed + calculateScore(values); }', + '}', + 'export const activate = () => 7;', + 'export { collisionLabel as incrementScore } from "./increment.js";', + 'export { collisionLabel as decrementScore } from "./decrement.js";', + 'export function loadDetails() { return import("./details.js"); }', + '', + ].join('\n') + const detailSource = [ + '/*! @license Fixture detail license */', + 'export function describeScore(value) {', + ' const descriptiveScorePrefix = "score";', + ' return descriptiveScorePrefix + ":" + value;', + '}', + '', + ].join('\n') + writeFileSync(join(directory, 'index.js'), entrySource) + writeFileSync(join(directory, 'details.js'), detailSource) + writeFileSync(join(directory, 'increment.js'), 'export function collisionLabel(value) { return value + 1; }\n') + writeFileSync(join(directory, 'decrement.js'), 'export function collisionLabel(value) { return value - 1; }\n') + + const namesByMode = new Map() + for (const mode of ['production', 'development'] as const) { + const previousNodeEnv = process.env.NODE_ENV + const noticeBody = '// Copyright Fixture Authors\n// Permission is granted to use this fixture.' + let config: UserConfig | undefined + try { + process.env.NODE_ENV = mode + config = clientBundle(root, ['lib/types/index.js'], { + clientBanner: fileName => `//! Fixture banner for ${fileName}\n${noticeBody}`, + })({ env: { DSH_BUILD_FACE: 'client' } }).find(candidate => candidate.platform === 'browser') + } finally { + if (previousNodeEnv === undefined) delete process.env.NODE_ENV + else process.env.NODE_ENV = previousNodeEnv + } + if (config === undefined) throw new Error('client config missing') + + const builds = await build({ + ...config, cwd: root, config: false, tsconfig: false, + write: false, clean: false, exports: false, report: false, logLevel: 'silent', + }) + try { + const chunks = builds.flatMap(bundle => bundle.chunks).filter(chunk => chunk.type === 'chunk') + expect(chunks.map(chunk => chunk.fileName).sort()).toEqual(['client.details.js', 'client.js']) + const entry = chunks.find(chunk => chunk.fileName === 'client.js') + const details = chunks.find(chunk => chunk.fileName === 'client.details.js') + if (entry === undefined || details === undefined) throw new Error('client fixture outputs missing') + + const requests: string[] = [] + const require: CompressionFixtureRequire = Object.assign((specifier: string): never => { + throw new Error(`Unexpected synchronous module request: ${specifier}`) + }, { + async(specifier: string): Promise { + requests.push(specifier) + expect(specifier).toBe('./client.details.js') + const registration = registerClientFactory(details.code) + expect(registration.chunk).toBe('client.details.js') + return Promise.resolve(registration.factory(require)) + }, + }) + const registration = registerClientFactory(entry.code) + expect(registration.chunk).toBeUndefined() + const exports = registration.factory(require) + const values = Array.from({ length: terms.length }, (_, index) => index * 3 - 7) + const expected = values.reduce((sum, value, index) => sum + value * (index + 1) + index + 2, 0) + expect(exports.calculateScore(values)).toBe(expected) + expect(new exports.FixtureAccumulator(9).total(values)).toBe(expected + 9) + expect(exports.incrementScore(expected)).toBe(expected + 1) + expect(exports.decrementScore(expected)).toBe(expected - 1) + expect(exports.calculateScore.name).toBe('calculateScore') + expect(exports.activate()).toBe(7) + expect(exports.activate.name).toBe('activate') + expect(exports.FixtureAccumulator.name).toBe('FixtureAccumulator') + namesByMode.set(mode, [exports.incrementScore.name, exports.decrementScore.name]) + expect(requests).toEqual([]) + const loaded = await exports.loadDetails() + expect(requests).toEqual(['./client.details.js']) + expect(loaded.describeScore(expected)).toBe(`score:${expected}`) + expect(loaded.describeScore.name).toBe('describeScore') + + for (const [chunk, source, notice] of [ + [entry, entrySource, 'Fixture arithmetic license'], + [details, detailSource, 'Fixture detail license'], + ] as const) { + expect(chunk.code).toContain(`@license ${notice}`) + expect(chunk.code).toContain(`//! Fixture banner for ${chunk.fileName}\n${noticeBody}`) + expect(chunk.map?.sourcesContent).toContain(source) + expect(chunk.map?.mappings.length).toBeGreaterThan(0) + } + if (mode === 'production') { + // These ceilings include the executable factory, loader call, legal notices and source-map reference. + expect(Buffer.byteLength(entry.code)).toBeLessThanOrEqual(1600) + expect(Buffer.byteLength(details.code)).toBeLessThanOrEqual(600) + } else { + expect(entry.code).toContain('intermediateContributionForInputPosition0') + } + } finally { + for (const bundle of builds) await bundle[Symbol.asyncDispose]() + } + } + // Minification preserves the bundler's names, including any static-module name collision suffixes. + expect(namesByMode.get('production')).toEqual(namesByMode.get('development')) + }) +}) + function clientSourceMapPath(packagePath: string): string { return fileURLToPath(new URL(`../packages/${packagePath}/lib/client.js.map`, import.meta.url)) } From fcca5408411d661c7273e7348a23a68352de2dcd Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 27 Oct 2026 17:50:22 +0800 Subject: [PATCH 5/7] refactor(session): unify runtime projection reads (#7347) * refactor(session): bind runtime projection reads to one session * refactor(session): expose session-bound readers on projection handles --------- Co-authored-by: _Kerman --- .../skills/dsh-session-projection/SKILL.md | 2 + docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- docs/subsystems/session-projection.i18n.yaml | 4 +- docs/subsystems/session-projection.md | 9 ++ docs/subsystems/session-projection.zh.md | 9 ++ packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 15 ++- packages/core/agent-loop/src/index.ts | 9 +- .../agent-loop/tests/request-freeze.spec.ts | 4 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../session-projection/README.i18n.yaml | 7 +- packages/session/session-projection/README.md | 15 +++ .../session/session-projection/README.zh.md | 15 +++ .../session/session-projection/src/index.ts | 11 +- .../tests/registration-reader.spec.ts | 106 +++++++++++++++++- .../tests/registration.type-test.ts | 6 + 20 files changed, 205 insertions(+), 25 deletions(-) diff --git a/.agents/skills/dsh-session-projection/SKILL.md b/.agents/skills/dsh-session-projection/SKILL.md index 90d483f4ac..f2820d7454 100644 --- a/.agents/skills/dsh-session-projection/SKILL.md +++ b/.agents/skills/dsh-session-projection/SKILL.md @@ -13,6 +13,8 @@ Keep recoverable session facts in Projection and expose them through their ownin 2. Do not expose projection definitions or handles as production read APIs. Keep the ready handle private; consumers use the owning service's domain methods. A handle is a process-local reader, recreated during activation. Require `sessionProjections` when the service depends on it; optional registration is only for optional contributions. Do not hide a missing required dependency with another recovery path. + A runtime that needs several projected states receives one typed object of callbacks created with `handle.readerFor(session)`. Add properties instead of a constructor parameter or feature-specific reader for each state. Each callback has type `() => S`; single-purpose collaborators receive it directly. These host-state readers are separate from wire snapshots and live Cordis Context; they own no registration, disposal, cache or I/O. Registration, Session preparation and handle lifetimes stay with their owners. Rule 9 defines synchronous API compatibility. + 3. State recovery through `init` and `apply` is synchronous and deterministic. Do not perform I/O or trigger Cordis hooks, models, or tools. Runtime hooks own those effects. Replay must not repeat them. Return the same state reference for unrelated events. Keep views synchronous and preserve their references when visible values do not change. 4. Persist JSON state that its schema accepts. Follow the README's state-version and checkpoint-watermark rules. Restoring a checkpoint and replaying its suffix must match full replay. Change the version when state fields or recovery semantics change. diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index c8543cdc36..72dc6b08a6 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -27,8 +27,8 @@ en: 1a79a70b62c04cdb zh: c86d765e21430405 /deepseek-harness-architecture/session-log: - en: 8a7f19b95d426c99 - zh: d5bb0538404e20ea + en: b3b63d8fe7cab9fe + zh: 3703fcf30b1639d0 /deepseek-harness-architecture/capability-seams: en: a5bc20c3f2a1b370 zh: 91773a281410b2f4 diff --git a/docs/architecture.md b/docs/architecture.md index e6bede8d0e..e3f5cd24a3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -127,7 +127,7 @@ Session consumers know only the current logical format. Header-only `stat` and ` **Model-visible means logged.** Every model request must be reconstructable from the log. New model-visible inputs require session events. Plugins changing existing message content register [pure message projections](subsystems/session.md#plugin-owned-message-projections); detached readers supply the same definitions explicitly. Tool changes are capability-independent; [Session tool history](../packages/core/session/README.md) supplies provider declarations. -**Projection seam.** `dsh-session-projection` owns `ctx.sessionProjections`: registered units fold committed events incrementally, and carriers batch cropped client views with `snapshot()`. Domain services await registration during activation, retain private handles, and expose business methods for other plugins. Releasing registration removes global participation; retained handles continue folding Session events. `AgentRegistry` owns turn and step state and exposes `turnBoundaryOf(session)` ([registration lifecycle](../packages/session/session-projection/README.md)). `AgentLoop` owns `modelSelection` and constructs each Agent’s `model` instance alongside its inbox. +**Projection seam.** `dsh-session-projection` owns `ctx.sessionProjections`: registered units fold committed events; carriers read selected client views through `snapshot()`. Domain services await registration, retain private handles, and expose business methods ([registration lifecycle](../packages/session/session-projection/README.md)). `AgentRegistry` exposes turn and step state through `turnBoundaryOf(session)`. `AgentLoop` owns `modelSelection` and inbox state ([loop lifecycle](../packages/core/agent-loop/README.md)). [Working directories](subsystems/working-directory.md) supply user context and execution paths without changing original project identity, sandbox write roots, or existing process directories. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 8863c8047c..4ab73a419d 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -131,7 +131,7 @@ Session 消费方只了解当前逻辑格式。仅 header 的 `stat` 与 `list` **模型可见即已记录。** 每个模型请求都必须能从日志重建。新增模型可见输入需要会话事件。修改现有消息内容的插件注册[纯消息投影](subsystems/session.zh.md#plugin-owned-message-projections),独立读取器显式传入相同的处理器。 工具变更不依赖能力;[Session 工具历史](../packages/core/session/README.zh.md)提供提供方声明。 -**投影 seam。** `dsh-session-projection` 提供 `ctx.sessionProjections`:已注册单元增量折叠已提交事件,载体通过 `snapshot()` 批量取得裁剪后的客户端视图。领域服务在激活时等待注册完成,在内部保留句柄,并向其他插件提供业务方法。释放注册会移除全局参与关系;已有句柄仍可继续折叠 Session 事件。`AgentRegistry` 持有轮次和步骤状态,并提供 `turnBoundaryOf(session)`([注册生命周期](../packages/session/session-projection/README.zh.md))。 `AgentLoop` 持有 `modelSelection`,并与 inbox 一起构建每个 Agent 的 `model` 实例。 +**投影 seam。** `dsh-session-projection` 提供 `ctx.sessionProjections`:已注册单元折叠已提交事件,载体通过 `snapshot()` 读取选定的客户端视图。领域服务等待注册完成,在内部保留句柄,并提供业务方法([注册生命周期](../packages/session/session-projection/README.zh.md))。`AgentRegistry` 通过 `turnBoundaryOf(session)` 提供轮次和步骤状态。`AgentLoop` 持有 `modelSelection` 和 inbox 状态([Loop 生命周期](../packages/core/agent-loop/README.zh.md))。 [工作目录](subsystems/working-directory.zh.md) 提供用户上下文和执行路径,不改变原始项目标识、沙箱写入根目录或已有进程目录。 diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index 29991cd13f..b38666ddb4 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/session-projection.md /session-projections: - en: 45e5f8cb8ca18d6b - zh: 4ecfad40ec9e221c + en: b2789f5257a935c5 + zh: 12d430a9cd454592 /session-projections/the-unit: en: d48814d3ab0e997f zh: d0337d8eba097a63 diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index e56896f455..cee8103ef0 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -18,6 +18,13 @@ interface ProjectionHandle { * @returns the projection state at the Session's current cursor. */ stateOf(session: Session): S + /** + * Create a reader for one exact Session without reading state or preparing it. + * The reader retains this unit after unregistration and owns no disposal. + * @param session - Session whose committed events the bound reader folds. + * @returns a synchronous callback with the same state and failures as `stateOf(session)`. + */ + readerFor(session: Session): () => S /** * Unregister from global drives and snapshots without invalidating this reader. * @returns a promise that resolves when this registration is released. @@ -28,6 +35,8 @@ interface ProjectionHandle { The [compatibility rules](../../packages/session/session-projection/README.md#deprecated-plugin-compatibility) define legacy disposal, keyed reads, and their once-per-key deprecation warnings. +`ProjectionHandle.readerFor(session)` returns a `() => S` callback for one exact Session. Calling it reads the original unit and preserves borrowed state, readiness requirements and synchronous failures. Owners can compose several readers in a typed object; domain services keep them private. See [binding several states](../../packages/session/session-projection/README.md#bind-several-states-to-one-session). + ## The unit `ProjectionDefinition` carries each unit's host state type locally; registration infers `S` from `stateSchema` and returns `ProjectionHandle`. Only client-visible keys merge into `SessionProjectionMap`, which types their whole values. A `wire` block makes a unit client-visible, and rendering belongs to the slot system, never this layer: diff --git a/docs/subsystems/session-projection.zh.md b/docs/subsystems/session-projection.zh.md index da53b76a7e..6e076a18a3 100644 --- a/docs/subsystems/session-projection.zh.md +++ b/docs/subsystems/session-projection.zh.md @@ -18,6 +18,13 @@ interface ProjectionHandle { * @returns the projection state at the Session's current cursor. */ stateOf(session: Session): S + /** + * Create a reader for one exact Session without reading state or preparing it. + * The reader retains this unit after unregistration and owns no disposal. + * @param session - Session whose committed events the bound reader folds. + * @returns a synchronous callback with the same state and failures as `stateOf(session)`. + */ + readerFor(session: Session): () => S /** * Unregister from global drives and snapshots without invalidating this reader. * @returns a promise that resolves when this registration is released. @@ -28,6 +35,8 @@ interface ProjectionHandle { [兼容规则](../../packages/session/session-projection/README.zh.md#deprecated-plugin-compatibility)规定旧释放操作、按键读取及其每个键一次的弃用警告。 +`ProjectionHandle.readerFor(session)` 为一个确切的 Session 返回 `() => S` 回调。调用它会读取原有单元,保留借用状态、就绪要求和同步失败。所有者可将多个读取函数组合成一个类型化对象;领域服务将它们保留在内部。参见[绑定多个状态](../../packages/session/session-projection/README.zh.md#bind-several-states-to-one-session)。 + ## 投影单元 `ProjectionDefinition` 在各单元内部携带宿主状态类型;注册从 `stateSchema` 推导 `S`,并返回 `ProjectionHandle`。只有客户端可见的 key 合并到 `SessionProjectionMap`,由它约束对应的全量值。`wire` 块使单元对客户端可见,渲染归 slot 体系管,永远不归本层: diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 33c53afffa..12a118bc5e 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: ec2bf804bd1a5439 zh: 316e767507e859ef /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: 25be2920f1de4f6f - zh: 279c60a6e1b1767a + en: eaaed8cc22640221 + zh: 557e2e67888ef7f6 /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: 3b48a480036bd5df zh: 28cea2036b0dccee diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 28b862ff9d..6db520d9b5 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. A caller creating a runtime child sets `options.parentAgent`; the caller Context separately owns the transaction and live handle. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -The loop awaits inbox and turn-boundary registration before publishing its factory and passes those handles into synchronous Agent construction. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. +The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. ### Persistence integration diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index f872d4289e..d44f26a867 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。创建运行时子 Agent 的调用方设置 `options.parentAgent`;调用方 Context 则单独拥有事务和存活句柄。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -loop 在发布工厂前等待 inbox 与轮次边界注册完成,并将句柄传入 Agent 的同步构造过程。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 +loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 ### 持久化集成 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 03c4c0c2bf..c4daa50c47 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -42,6 +42,14 @@ import { RuntimeContextProjection } from './runtime-context.ts' import { AssistantStreamAttempt } from './assistant-stream.ts' import { SystemPromptProjection } from './runtime-context.ts' +/** Projected facts consumed by this driver; registration stays with the factory. */ +interface LoopProjections { + /** Current model selection, including pending changes. */ + readonly modelSelection: () => ModelSelectionProjectionState + /** Current queued and claimed input. */ + readonly inbox: () => InboxState +} + type Phase = | { kind: 'idle'; lastTurn: number } | { @@ -131,16 +139,15 @@ export class ReactLoopAgent implements Agent { public readonly id: SessionId, public readonly options: AgentOptions, public readonly session: Session, - readModel: () => ModelSelectionProjectionState, - readInbox: () => InboxState, + projections: LoopProjections, lastTurn: number, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx - this.model = new AgentModel(readModel, session, options) - this.inbox = new ReactLoopInbox(readInbox, session, this.dispatch) + this.model = new AgentModel(projections.modelSelection, session, options) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index cb5007c28f..381ef6e93a 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -553,8 +553,6 @@ export class AgentLoop extends Service implements AgentFactory { } } const untrack = this.ownership.track(dispose) - const modelProjectionHandle = this.modelProjectionHandle - const inboxProjectionHandle = this.inboxProjectionHandle try { assertAgentOptions(agentOptions) ownerCtx.fiber.assertActive() @@ -567,11 +565,14 @@ export class AgentLoop extends Service implements AgentFactory { : new Error(`agent "${id}" creation aborted`, { cause: callerSignal.reason }) } const lastTurn = loopCtx.agents.turnBoundaryOf(session).lastTurn + const projections = { + modelSelection: this.modelProjectionHandle.readerFor(session), + inbox: this.inboxProjectionHandle.readerFor(session), + } unfollowOwner = ownerCtx.effect(function* () { const created = machine = new ReactLoopAgent( loopCtx, id, agentOptions, session, - () => modelProjectionHandle.stateOf(session), - () => inboxProjectionHandle.stateOf(session), + projections, lastTurn, ) machineReady.resolve() diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index 276e007d27..8ed1c4d138 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -79,7 +79,7 @@ describe('loop-owned request freezing', () => { const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition) const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition) const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - () => model.stateOf(session), () => inbox.stateOf(session), ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) cleanups.push(async () => { agent.cancel({ kind: 'disposed' }) await agent.whenIdle() @@ -129,7 +129,7 @@ describe('loop-owned request freezing', () => { expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1) expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1) const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - () => model.stateOf(session), () => inbox.stateOf(session), ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) cleanups.push(async () => { resumed.cancel({ kind: 'disposed' }) await resumed.whenIdle() diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 48aaec1093..ff2978a2b9 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -7382,7 +7382,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ProjectionHandle', - declaration: 'export interface ProjectionHandle {\n stateOf(session: Session): S;\n dispose(): Promise;\n}', + declaration: 'export interface ProjectionHandle {\n stateOf(session: Session): S;\n readerFor(session: Session): () => S;\n dispose(): Promise;\n}', }, { name: 'ProjectionKeySelection', diff --git a/packages/session/session-projection/README.i18n.yaml b/packages/session/session-projection/README.i18n.yaml index b3988ff592..7b4fd598e0 100644 --- a/packages/session/session-projection/README.i18n.yaml +++ b/packages/session/session-projection/README.i18n.yaml @@ -24,8 +24,11 @@ en: 09758d1475fad86e zh: 473637cb34aebe72 /deepseek-ai-dsh-session-projection/use-this-package/register-and-read: - en: 976fb019501a941b - zh: e15038a7205337c3 + en: f64bc8038aecfcae + zh: fb5fb0999468fac0 +/deepseek-ai-dsh-session-projection/use-this-package/bind-several-states-to-one-session: + en: dac4ea4d67ce057d + zh: 1cf3e5c7af5a5203 /deepseek-ai-dsh-session-projection/use-this-package/deprecated-plugin-compatibility: en: eed1ad9d62755251 zh: 88a07c787528009a diff --git a/packages/session/session-projection/README.md b/packages/session/session-projection/README.md index 3c597534ed..6882d93515 100644 --- a/packages/session/session-projection/README.md +++ b/packages/session/session-projection/README.md @@ -63,6 +63,21 @@ const state = todoProjectionHandle.stateOf(session) const { asOfSeq, values } = ctx.sessionProjections.snapshot(session) ``` + +### Bind several states to one Session + +Call `handle.readerFor(session)` on an awaited registration handle to obtain a `() => S` callback. Calling it reads the current state without a Session argument. An owner composing several states passes a typed object of these callbacks to its runtime. New states add properties instead of constructor arguments; ordinary plugins still use domain-service methods. + +```text +const projections = { + todo: todoProjectionHandle.readerFor(session), + goal: goalProjectionHandle.readerFor(session), +} +const todo = projections.todo() +``` + +Each reader captures the exact Session and delegates to the original handle's `stateOf(session)`, preserving readiness requirements, null and undefined values, state references, and synchronous failures. Creating a reader does not read state, prepare the Session, perform storage I/O, or create a state cache. Readers own no registration or disposal. The original handle keeps its disposal responsibility; a reader keeps reading the original unit after deregistration or version replacement. One handle can create readers for several Sessions independently. Registration and Session preparation remain the owner's responsibility; client snapshots remain separate. + A domain that owns projected state declares `sessionProjections` as a Cordis service dependency and keeps its handle private. Consumers inject that domain service and use its methods, such as `ctx.agents.turnBoundaryOf(session)`, without importing definitions or retaining projection readers. Optional contributors may register under `ctx.inject(['sessionProjections'], …)`. Carriers use `ctx.get('sessionProjections')` and omit their block or frames when the registry is absent. diff --git a/packages/session/session-projection/README.zh.md b/packages/session/session-projection/README.zh.md index 80362008ef..a3398965f6 100644 --- a/packages/session/session-projection/README.zh.md +++ b/packages/session/session-projection/README.zh.md @@ -63,6 +63,21 @@ const state = todoProjectionHandle.stateOf(session) const { asOfSeq, values } = ctx.sessionProjections.snapshot(session) ``` + +### 将多个状态绑定到一个 Session + +对已等待注册完成的句柄调用 `handle.readerFor(session)`,即可得到 `() => S` 回调。调用它时无需 Session 参数即可读取当前状态。组合多个状态的所有者将这些回调放入一个类型化对象,交给运行时。新增状态只增加属性,不增加构造参数;普通插件仍通过领域服务的方法读取。 + +```text +const projections = { + todo: todoProjectionHandle.readerFor(session), + goal: goalProjectionHandle.readerFor(session), +} +const todo = projections.todo() +``` + +每个读取函数保存确切的 Session,并将读取委托给原句柄的 `stateOf(session)`,保留就绪要求、null 和 undefined 值、状态引用及同步失败。创建读取函数不读取状态、不准备 Session、不执行存储 I/O,也不创建状态缓存。读取函数不拥有注册或释放职责。原句柄仍负责释放;注销或版本替换后,读取函数仍读取原有单元。同一句柄可为多个 Session 独立创建读取函数。注册和 Session 准备仍由原所有者完成;客户端快照保持独立。 + 持有投影状态的领域将 `sessionProjections` 声明为 Cordis 服务依赖,并在内部保留句柄。消费方注入该领域服务并使用其方法,例如 `ctx.agents.turnBoundaryOf(session)`,无需导入定义或保留投影读取句柄。可选贡献方可以在 `ctx.inject(['sessionProjections'], …)` 下注册。载体使用 `ctx.get('sessionProjections')`,注册表缺席时省略自己的块或帧。 diff --git a/packages/session/session-projection/src/index.ts b/packages/session/session-projection/src/index.ts index 54f874a51b..63342e374b 100644 --- a/packages/session/session-projection/src/index.ts +++ b/packages/session/session-projection/src/index.ts @@ -56,6 +56,13 @@ export interface ProjectionHandle { * @returns the projection state at the Session's current cursor. */ stateOf(session: Session): S + /** + * Create a reader for one exact Session without reading state or preparing it. + * The reader retains this unit after unregistration and owns no disposal. + * @param session - Session whose committed events the bound reader folds. + * @returns a synchronous callback with the same state and failures as `stateOf(session)`. + */ + readerFor(session: Session): () => S /** * Unregister from global drives and snapshots without invalidating this reader. * @returns a promise that resolves when this registration is released. @@ -400,14 +407,16 @@ export class SessionProjectionRegistry extends Service { // Observe disposal during the asynchronous registration handoff before exposing a reader. await Promise.resolve() this.ctx.fiber.assertActive() - return { + const handle: ProjectionHandle = { async dispose() { await dispose() }, stateOf: (session) => { return this.cellFor(registration, session).state as S }, + readerFor: session => () => handle.stateOf(session), } + return handle } /** diff --git a/packages/session/session-projection/tests/registration-reader.spec.ts b/packages/session/session-projection/tests/registration-reader.spec.ts index e2a82746e8..939a6f1a1d 100644 --- a/packages/session/session-projection/tests/registration-reader.spec.ts +++ b/packages/session/session-projection/tests/registration-reader.spec.ts @@ -3,7 +3,7 @@ import { Context } from '@deepseek-ai/cordis' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' -import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { describe, expect, expectTypeOf, it, onTestFinished, vi } from 'vitest' import { z } from 'zod' declare module '@deepseek-ai/dsh-session-projection/types' { @@ -32,10 +32,113 @@ async function setup() { } describe('retained projection readers', () => { + it('binds typed host states to the exact Session without reading unrelated units', async () => { + const { ctx, owner, session } = await setup() + const unrelatedInit = vi.fn(() => 0) + const unrelatedApply = vi.fn((state: number) => state) + await ctx.sessionProjections.register({ + key: 'test/bound-unrelated', stateSchema: z.number(), stateVersion: 1, + init: unrelatedInit, apply: unrelatedApply, + }) + const countInit = vi.fn(definition.init) + const countApply = vi.fn(definition.apply) + const count = await owner.ctx.sessionProjections.register({ ...definition, init: countInit, apply: countApply }) + const hostInit = vi.fn((): { turn: number } | null => null) + const hostApply = vi.fn((state: { turn: number } | null, event: Parameters['apply']>[1]) => ( + event.type === 'turn/start' ? { turn: event.data.turn } : state + )) + const host = await owner.ctx.sessionProjections.register({ + key: 'test/bound-host', stateSchema: z.object({ turn: z.number() }).nullable(), stateVersion: 1, + init: hostInit, apply: hostApply, + }) + const initialized = { count: countInit.mock.calls.length, host: hostInit.mock.calls.length, unrelated: unrelatedInit.mock.calls.length } + const applied = { count: countApply.mock.calls.length, host: hostApply.mock.calls.length, unrelated: unrelatedApply.mock.calls.length } + const reader = { count: count.readerFor(session), host: host.readerFor(session) } + expect({ + count: countInit.mock.calls.length, host: hostInit.mock.calls.length, unrelated: unrelatedInit.mock.calls.length, + }).toEqual(initialized) + expect({ + count: countApply.mock.calls.length, host: hostApply.mock.calls.length, unrelated: unrelatedApply.mock.calls.length, + }).toEqual(applied) + const initialCount = reader.count() + expectTypeOf(initialCount).toEqualTypeOf() + expect(initialCount).toBe(0) + const initialHost = reader.host() + expectTypeOf(initialHost).toEqualTypeOf<{ turn: number } | null>() + expect(initialHost).toBeNull() + expect(unrelatedInit).toHaveBeenCalledTimes(initialized.unrelated) + expect(unrelatedApply).toHaveBeenCalledTimes(applied.unrelated) + + const other = ctx.sessions.create() + const otherReader = count.readerFor(other) + other.append('turn/start', { turn: 1 }) + expect(otherReader()).toBe(1) + expect(reader.count()).toBe(0) + session.append('turn/start', { turn: 2 }) + expect(reader.count()).toBe(1) + expect(reader.host()).toEqual({ turn: 2 }) + expect(reader.host()).toBe(host.stateOf(session)) + const read = reader.host + expect(read()).toBe(host.stateOf(session)) + }) + + it('retains the bound unit after owner disposal and version replacement', async () => { + const { ctx, owner, session } = await setup() + const original = await owner.ctx.sessionProjections.register(definition) + const reader = original.readerFor(session) + await owner.dispose() + expect(ctx.sessionProjections.checkpoint(session)).toEqual({}) + const replacement = await ctx.sessionProjections.register({ ...definition, stateVersion: 2, apply: state => state + 10 }) + const changed = vi.fn() + ctx.sessionProjections.onChanged(changed) + session.append('turn/start', { turn: 1 }) + expect(reader()).toBe(1) + expect(original.readerFor(session)()).toBe(1) + expect(replacement.stateOf(session)).toBe(10) + expect(ctx.sessionProjections.snapshot(session).values).toEqual({ 'test/reader': 10 }) + expect(changed).toHaveBeenCalledOnce() + expect(ctx.sessionProjections.checkpoint(session)['test/reader']?.ver).toBe(2) + }) + + it('does not read during binding and preserves the original synchronous failure', async () => { + const { owner, session } = await setup() + const failure = new Error('host state cannot initialize') + const init = vi.fn((): number => { throw failure }) + const broken = await owner.ctx.sessionProjections.register({ + key: 'test/bound-failure', stateSchema: z.number(), stateVersion: 1, + init, apply: state => state, + }) + const initialized = init.mock.calls.length + const reader = broken.readerFor(session) + expect(init).toHaveBeenCalledTimes(initialized) + let caught: unknown + try { + reader() + } catch (error) { + caught = error + } + expect(caught).toBe(failure) + }) + + it('preserves undefined state without substituting a value', async () => { + const { owner, session } = await setup() + const handle = await owner.ctx.sessionProjections.register({ + key: 'test/bound-undefined', stateSchema: z.number().optional(), stateVersion: 1, + init: () => undefined, + apply: (state, event) => event.type === 'turn/start' ? event.data.turn : state, + }) + const read = handle.readerFor(session) + expectTypeOf(read()).toEqualTypeOf() + expect(read()).toBeUndefined() + session.append('turn/start', { turn: 1 }) + expect(read()).toBe(1) + }) + it.each(['handle', 'fiber'] as const)('reads new events after %s disposal without rejoining snapshots or notifications', async (release) => { const { ctx, owner, session } = await setup() const apply = vi.fn(definition.apply) const handle = await owner.ctx.sessionProjections.register({ ...definition, apply }) + const read = handle.readerFor(session) const changed = vi.fn() ctx.sessionProjections.onChanged(changed) expect(handle.stateOf(session)).toBe(0) @@ -47,6 +150,7 @@ describe('retained projection readers', () => { session.append('turn/start', { turn: 2 }) expect(apply).toHaveBeenCalledTimes(1) expect(handle.stateOf(session)).toBe(2) + expect(read()).toBe(2) expect(apply).toHaveBeenCalledTimes(2) expect(changed).toHaveBeenCalledOnce() expect(ctx.sessionProjections.snapshot(session).values).toEqual({}) diff --git a/packages/session/session-projection/tests/registration.type-test.ts b/packages/session/session-projection/tests/registration.type-test.ts index dc9cadce3b..5cdb37099a 100644 --- a/packages/session/session-projection/tests/registration.type-test.ts +++ b/packages/session/session-projection/tests/registration.type-test.ts @@ -28,6 +28,11 @@ export async function checkProjectionRegistrationTypes(registry: SessionProjecti const host = await registry.register(counter) expectTypeOf(host).toEqualTypeOf>() expectTypeOf(host.stateOf(session)).toEqualTypeOf() + const read = host.readerFor(session) + expectTypeOf(read).toEqualTypeOf<() => number>() + expectTypeOf(read()).toEqualTypeOf() + // @ts-expect-error -- a bound reader cannot be retargeted at read time. + read(session) const nullable = await registry.register({ key: 'type-test/nullable', @@ -40,6 +45,7 @@ export async function checkProjectionRegistrationTypes(registry: SessionProjecti }, }) expectTypeOf(nullable.stateOf(session)).toEqualTypeOf() + expectTypeOf(nullable.readerFor(session)()).toEqualTypeOf() const visible = { ...counter, From 0bfa572080ec1395e1ee700b5e7a48d9c52473c7 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Tue, 27 Oct 2026 17:55:51 +0800 Subject: [PATCH 6/7] test(web): retain minified bundles in real-host smoke coverage --- apps/web/tests/smoke-real.e2e.ts | 35 ++++++------------- packages/client/AGENTS.md | 2 +- packages/client/modules/README.i18n.yaml | 8 ++--- packages/client/modules/README.md | 4 +-- packages/client/modules/README.zh.md | 4 +-- .../experimental/webworker-packer/src/pack.ts | 4 +-- .../webworker-runtime/src/image-manifest.ts | 2 +- scripts/client-bundle-purity.spec.ts | 24 +++++++++++-- 8 files changed, 43 insertions(+), 40 deletions(-) diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index a980c2d02d..0bbaa2c1d3 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -17,7 +17,7 @@ import type { ChildProcess } from 'node:child_process' import { spawn } from 'node:child_process' import { randomUUID } from 'node:crypto' -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { createRequire, SourceMap } from 'node:module' import { tmpdir } from 'node:os' @@ -27,7 +27,7 @@ import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import WebSocket from 'ws' -import { REPO_ROOT, connectFreshWorkspace, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts' +import { REPO_ROOT, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts' const WEB_SURFACE_PROMPT = fileURLToPath(new URL('./expected/web-runtime-context/web-surface-prompt.expected.md', import.meta.url)) /** Framed user text that marks the auxiliary title request's own messages. */ @@ -284,31 +284,18 @@ async function screen(page: Page, name: string): Promise { /** First column track (px string) of the frame grid. */ async function firstTrack(page: Page): Promise { - return (await page.locator('[class*="frame"]').evaluate( + return (await page.locator('[class*="frame"]').first().evaluate( el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]! } /** Last column track (details) as a number of pixels. */ async function detailsTrack(page: Page): Promise { - const cols = await page.locator('[class*="frame"]').evaluate( + const cols = await page.locator('[class*="frame"]').first().evaluate( el => getComputedStyle(el).gridTemplateColumns) return Number(cols.split(' ').pop()!.replace('px', '')) } -// Readiness gate: `dsh web` serves every production manifest plugin; until every UI -// plugin's client bundle exists and exports apply, the loader fail-louds and -// the frame never appears. -const UI_PLUGIN_DIRS = [ - 'connection', 'ui-theme', 'locale', 'ui-layout', 'ui-renderer', 'ui-session', 'ui-sidebar', - 'ui-settings', 'ui-settings-general', 'ui-settings-models', 'ui-conversation', 'ui-approval', 'ui-chat', - 'ui-model-selection', 'ui-user-questions', 'ui-trajectory', '../session-query/session-log-export', -] const ROUND_DONE_MARKER = 'WEB_ROUND_DONE' -const notReady = UI_PLUGIN_DIRS.filter((dir) => { - const bundle = join(REPO_ROOT, 'packages/client', dir, 'lib/client.js') - return !existsSync(bundle) || !readFileSync(bundle, 'utf8').includes('exports.apply') -}) -if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`) describe('dsh web keyless CLI smoke', () => { it('serves a usable app from three immutable plugin batches', async () => { @@ -686,7 +673,7 @@ describe('dsh web keyless CLI smoke', () => { }) }) -describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke (real host, real key)', () => { +describe.skipIf(!process.env.DEEPSEEK_API_KEY)('web smoke (real host, real key)', () => { let child: ChildProcess let sessionsDir: string let baseUrl: string @@ -730,6 +717,9 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke page = await newEnglishPage(browser) page.on('pageerror', e => pageErrors.push(String(e))) await page.goto(baseUrl, { waitUntil: 'load' }) + const welcome = page.getByRole('dialog', { name: 'Preview Notice' }) + await welcome.getByRole('button', { name: 'Continue' }).click() + await welcome.waitFor({ state: 'detached' }) }, 120_000) afterAll(async () => { @@ -747,18 +737,13 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke onTestFailed(() => saveFailureShot(page, 'w5-cold-start')) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) expect(await page.locator('text=Failed to load plugins').count()).toBe(0) - const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns) + const template = await page.locator('[class*="frame"]').first().evaluate(el => getComputedStyle(el).gridTemplateColumns) expect(template.split(' ').length).toBe(3) await screen(page, '01-cold-start') }) it('empty-state first send completes a real model round', async () => { onTestFailed(() => saveFailureShot(page, 'w5-first-round')) - // This scenario spawns its own server against a fresh $DSH_HOME with the - // DeepSeek credential inherited from the environment, so no onboarding - // step mounts and the page is immediately interactive. - // Fresh world: connect a Workspace so the composer starts live. - await connectFreshWorkspace(page, sessionsDir) const input = page.locator('[data-composer-input]').first() await input.waitFor({ timeout: 10_000 }) const productTitle = await page.title() @@ -839,7 +824,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke it('sidebar drag widens the column and resets across reload', async () => { onTestFailed(() => saveFailureShot(page, 'w5-drag')) const before = await firstTrack(page) - const handle = page.locator('[class*="handle"]').first() + const handle = page.locator('[data-side="sidebar"]') const box = await handle.boundingBox() expect(box).not.toBeNull() await page.mouse.move(box!.x + box!.width / 2, box!.y + 300) diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 85d5d69354..80d9702f14 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -85,7 +85,7 @@ A dynamic browser half either carries a module privately or requests the shared 3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request. 4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. 5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. -6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset emits `require.async("./client..js")`; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support. +6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset calls the factory loader's `.async` method with a literal `./client..js` path; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support. ### The module graph sits below cordis DI diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index 30c512d5c4..258d5971f7 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -24,8 +24,8 @@ en: 529af1eb8bf1acf2 zh: 7d891a5dfa90c625 /deepseek-ai-dsh-client-modules/use-this-package/what-the-browser-loads: - en: 1383d68472b3c057 - zh: 94dd7d9abbdbccf3 + en: 3c372e9d65e294a8 + zh: 00f82efab7071258 /deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition: en: 45740a56e931d094 zh: fa44cf77c86019af @@ -36,8 +36,8 @@ en: 1778b5a63ecde5e8 zh: 537b4f8c755af8ad /deepseek-ai-dsh-client-modules/use-this-package/build-requirements: - en: 3fb8bab648cc58d1 - zh: 064667ba7b45839e + en: 15aa99a9df72e51e + zh: 3324596fb5d3588d /deepseek-ai-dsh-client-modules/understand-the-implementation: en: 7ab11d2c2bdc6eaa zh: 54c3c9091cf59711 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 262298ece6..10af92132b 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -40,7 +40,7 @@ The same `/plugins` route serves the images a client package publishes through i ### What the browser loads -The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client..js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `