From 712292efa8c7fde6be77c540c5dbe20a278dd9c6 Mon Sep 17 00:00:00 2001 From: Kaige-Gao <102539609+Kaige-Gao@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:46:28 +0800 Subject: [PATCH 1/9] feat(client): add file references from context menus --- apps/web/tests/context-menus.e2e.ts | 2 + apps/web/tests/markdown-file-links.e2e.ts | 51 +++++- apps/web/tests/reference-composer.e2e.ts | 91 ++++++++++ .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/contract/input.ts | 7 + .../src/client/input/facade.ts | 4 +- packages/client/ui-reference/README.i18n.yaml | 4 +- packages/client/ui-reference/README.md | 2 + packages/client/ui-reference/README.zh.md | 2 + .../ui-reference/src/client/context-menu.ts | 58 ++++++ .../client/ui-reference/src/client/index.ts | 2 + .../client/ui-reference/src/client/locales.ts | 16 ++ .../tests/context-menu.client.spec.ts | 167 ++++++++++++++++++ .../src/client/slot-catalog.ts | 3 +- .../add-to-chat.expected.md | 11 ++ 17 files changed, 416 insertions(+), 12 deletions(-) create mode 100644 packages/client/ui-reference/src/client/context-menu.ts create mode 100644 packages/client/ui-reference/tests/context-menu.client.spec.ts create mode 100644 snapshots/web/markdown-file-links/add-to-chat.expected.md diff --git a/apps/web/tests/context-menus.e2e.ts b/apps/web/tests/context-menus.e2e.ts index b5035f449a..e880d9e25b 100644 --- a/apps/web/tests/context-menus.e2e.ts +++ b/apps/web/tests/context-menus.e2e.ts @@ -217,6 +217,8 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s', await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).waitFor() await page.keyboard.press('End') expect(await page.getByRole('menuitem', { name: 'Save as…', exact: true }).count()).toBe(0) + expect(await page.getByRole('menuitem', { name: 'Add to chat', exact: true }).evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('ArrowUp') expect(await page.getByRole('menuitem', { name: 'Download', exact: true }).evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('ArrowUp') expect(await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).evaluate(element => element === document.activeElement)).toBe(true) diff --git a/apps/web/tests/markdown-file-links.e2e.ts b/apps/web/tests/markdown-file-links.e2e.ts index 4354a018f6..0d4475372d 100644 --- a/apps/web/tests/markdown-file-links.e2e.ts +++ b/apps/web/tests/markdown-file-links.e2e.ts @@ -11,9 +11,9 @@ import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import type {} from '@deepseek-ai/dsh-session-title' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, - launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, + launchWebScaffold, readPersistedEvents, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links', import.meta.url)) const MODE = webSnapshotMode() @@ -161,7 +161,52 @@ describe('web e2e: Markdown file links', () => { expect(page.url()).toBe(beforeUrl) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) - await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'links.expected.md', 'preview.expected.md']) + }) + + it('adds a recorded line-labeled file to the draft without its line suffix or a new turn', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-markdown-file-add-to-chat')) + const sessionId = brandString('markdown-file-links') + const beforeEvents = await readPersistedEvents(scaffold, sessionId) + const beforeMessages = await page.locator('[data-chat-flow-kind="user"]').count() + const input = page.locator('[data-composer-input]').first() + const draft = 'Review this file next: ' + await writeComposerDraft(page, input, draft) + await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).click({ button: 'right' }) + const menu = page.getByRole('menu') + const action = menu.getByRole('menuitem', { name: 'Add to chat', exact: true }) + await action.waitFor() + expect(await menu.getByRole('menuitem').last().textContent()).toBe('Add to chat') + const menuAria = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + await action.click() + await menu.waitFor({ state: 'hidden' }) + await expect.poll(() => input.evaluate(node => node === document.activeElement)).toBe(true) + await expect.poll(() => input.textContent()).toBe(`${draft}example.txt `) + const chip = input.locator('[data-composer-chip]') + expect(await chip.count()).toBe(1) + expect(await chip.textContent()).toBe('example.txt') + expect(await chip.locator('svg').count()).toBe(1) + const composerAria = await captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'add-to-chat.expected.md'), + `## File menu\n\n${menuAria}\n\n## Composer\n\n${composerAria}`, MODE) + + await page.keyboard.press('ControlOrMeta+A') + const copied = await input.evaluate((node) => { + const clipboardData = new DataTransfer() + node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true })) + return clipboardData.getData('text/plain') + }) + const path = join(scaffold.workspaceCwd, 'src/example.txt') + expect(copied).toBe(`${draft}@${path} `) + expect(copied).not.toContain(':24') + expect(copied).not.toContain('#L24') + expect(await page.locator('[data-chat-flow-kind="user"]').count()).toBe(beforeMessages) + expect(await readPersistedEvents(scaffold, sessionId)).toEqual(beforeEvents) + await writeComposerDraft(page, input, '') + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, [ + 'session.v3.jsonl', 'links.expected.md', 'preview.expected.md', 'add-to-chat.expected.md', + ]) }) it('replays colon line suffixes as locations and shares tabs with fragment links', async () => { diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index ec02751e46..57fd1c946d 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -165,6 +165,7 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through // stays out of the menu golden. await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested'), { recursive: true }) await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'leaf.txt'), 'leaf fixture\n') + await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'space name.txt'), 'space fixture\n') await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) @@ -429,4 +430,94 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, ['menu.expected.md', 'order.expected.md']) }) + + it('adds a sidebar file after retained selection without sending and undoes it as one edit', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-add-to-chat')) + const group = page.getByRole('treeitem', { name: /Ungrouped/ }) + await group.waitFor({ timeout: 15_000 }) + if (await group.getAttribute('aria-expanded') !== 'true') await group.click() + await page.locator(`[data-row-key="session:${TARGET_SESSION_ID}"]`).click() + await page.locator('[data-chat-flow-kind="user"]').filter({ hasText: 'Research notes' }).waitFor() + const input = page.locator('[data-composer-input]').first() + const suggestions = page.getByRole('listbox', { name: 'Trigger suggestions' }) + const directory = join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested') + const file = join(directory, 'space name.txt') + const sessionId = brandString(TARGET_SESSION_ID) + const beforeEvents = await readPersistedEvents(scaffold, sessionId) + const beforeMessages = await page.locator('[data-chat-flow-kind="user"]').count() + + // An absolute query compares the same resource spelling as the sidebar. + await replaceReferenceQuery(page, input, `@"${directory}/`) + const option = suggestions.getByRole('option', { name: /^space name\.txt/ }) + await option.waitFor({ timeout: 15_000 }) + await option.click() + const chip = input.locator('[data-composer-chip]') + await expect.poll(() => chip.textContent()).toBe('space name.txt') + const pickerAppearance = await chip.evaluate(node => ({ + source: node.getAttribute('data-composer-chip'), + label: node.textContent, + icons: node.querySelectorAll('svg').length, + })) + await page.keyboard.press('ControlOrMeta+A') + // A page-local clipboard avoids interference with parallel browser workers. + const pickerClipboard = await input.evaluate((node) => { + const clipboardData = new DataTransfer() + node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true })) + return clipboardData.getData('text/plain') + }) + expect(pickerClipboard).toBe(`@"${file}" `) + await writeComposerDraft(page, input, '') + + const column = page.locator('[data-rightbar-col]') + await page.locator('[data-sidebar-right-expand]').click() + await column.locator('[data-sidebar-right-guide-entry="files"]').click() + const navigator = column.locator('[data-files-navigator]:visible') + await navigator.waitFor() + for (const name of ['workspace', 'folderx', 'nested']) { + const folder = navigator.getByRole('button', { name, exact: true }) + await folder.waitFor() + if (await folder.getAttribute('aria-expanded') !== 'true') await folder.click() + } + const row = navigator.getByRole('button', { name: 'space name.txt', exact: true }) + await row.waitFor() + const draft = 'Review selected, then finish.' + await writeComposerDraft(page, input, draft) + await page.keyboard.press('ControlOrMeta+A') + await page.keyboard.press('ArrowLeft') + for (let i = 0; i < 'Review '.length; i++) await page.keyboard.press('ArrowRight') + for (let i = 0; i < 'selected'.length; i++) await page.keyboard.press('Shift+ArrowRight') + expect(await page.evaluate(() => window.getSelection()?.toString())).toBe('selected') + + await row.click({ button: 'right' }) + const menu = page.getByRole('menu') + const action = menu.getByRole('menuitem', { name: 'Add to chat', exact: true }) + await action.waitFor() + expect(await menu.getByRole('menuitem').last().textContent()).toBe('Add to chat') + expect(await action.isEnabled()).toBe(true) + await action.click() + await menu.waitFor({ state: 'hidden' }) + await expect.poll(() => input.evaluate(node => node === document.activeElement)).toBe(true) + await expect.poll(() => input.textContent()).toBe('Review selected space name.txt , then finish.') + expect(await chip.evaluate(node => ({ + source: node.getAttribute('data-composer-chip'), + label: node.textContent, + icons: node.querySelectorAll('svg').length, + }))).toEqual(pickerAppearance) + await page.keyboard.press('ControlOrMeta+A') + const menuClipboard = await input.evaluate((node) => { + const clipboardData = new DataTransfer() + node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true })) + return clipboardData.getData('text/plain') + }) + expect(menuClipboard).toBe(`Review selected ${pickerClipboard}, then finish.`) + + await page.keyboard.press('ControlOrMeta+Z') + await expect.poll(() => input.textContent()).toBe(draft) + expect(await chip.count()).toBe(0) + expect(await input.evaluate(node => node === document.activeElement)).toBe(true) + expect(await page.locator('[data-chat-flow-kind="user"]').count()).toBe(beforeMessages) + expect(await readPersistedEvents(scaffold, sessionId)).toEqual(beforeEvents) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) }) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 83044eef74..8610723688 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: dcbdef97e4532896 - zh: 23d6840c89f66bab + en: add85894c192e327 + zh: b27a5d47b6a390e0 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 24077e4a55..0bf9196817 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addFiles` inserts references after the retained selection in one undo step without replacing selected text; it refuses edits after disposal or during submission. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index a2d6b994cb..0a8ca621a2 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addFiles` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字;输入模型释放后或提交期间拒绝编辑。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 3d8ebd6d6a..e1a9c0cf6e 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -195,6 +195,13 @@ export interface SessionInput extends InputTarget { setDraft(text: string): void /** Append ordered browser-owned attachment ids; busy admission phases refuse. */ addAttachments(ids: readonly DraftAttachmentId[]): boolean + /** + * Insert file references after the retained selection without replacing text, and append attachment ids. + * @param references - validated reference chips in source order. + * @param ids - browser-owned attachment ids; empty for reference-only insertion. + * @returns false after disposal, while submission is locked, or when insertion is refused. + */ + addFiles(references: readonly ReferenceInsert[], ids: readonly DraftAttachmentId[]): boolean /** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */ removeAttachment(id: DraftAttachmentId): boolean /** Drop ids whose browser-owned objects no longer exist. */ diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 1fd208b6f7..c24f40b4f6 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -344,10 +344,10 @@ export class SessionInputShell implements SessionInput { * Add validated file references and attachment ids while admission is editable. * @param references - reference chips in source order. * @param ids - newly allocated attachment ids. - * @returns false when admission is locked or the editor refuses the insertion. + * @returns false after disposal, when admission is locked, or when the editor refuses insertion. */ addFiles(references: readonly ReferenceInsert[], ids: readonly DraftAttachmentId[]): boolean { - if (frozen(this.snapshot.phase)) return false + if (this.disposed || frozen(this.snapshot.phase)) return false if (!this.draftEditor.insertFileReferences(references)) return false this.attachmentIds = [...this.attachmentIds, ...ids] this.publish() diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index 2386cfb242..8c7cbebdd2 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -18,8 +18,8 @@ en: 779a9a534eaad38b zh: 3dd159a2c35702d6 /deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts: - en: 0b41c33743e5b422 - zh: 551896094c03f57e + en: 817aa123e8033ff7 + zh: 19e6593b61e8b5b7 /deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior: en: 386bbd9dc0a2c322 zh: 3014a367157532b7 diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index 1647f5b162..ed3c545b1d 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -33,6 +33,8 @@ A file closes completion as an atomic inline reference displayed with a file gly A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`. +The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited or the path cannot use the mention grammar. + ### Failure behavior One unavailable or failed candidate domain yields no rows for that domain while the other still lists. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn. diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index 9b16dd48d7..ba9a3d24a6 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -33,6 +33,8 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。 +共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。Session 不可编辑或路径无法用 mention 语法表示时,此入口不可用。 + ### 失败行为 某个候选领域不可用或失败时,该领域不产生任何行,另一领域仍正常列出。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。 diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts new file mode 100644 index 0000000000..8bad653ddd --- /dev/null +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -0,0 +1,58 @@ +/** File references contributed to the shared file menu. */ +import type { Context } from '@deepseek-ai/cordis' +import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { formatFileMention } from '@deepseek-ai/dsh-file-reference/grammar' +import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' +import type { ReferenceKey } from './locales.ts' + +/** + * Add the captured file to its Session draft without submitting or replacing selected text. + * @param ctx - reference plugin's menu and conversation dependencies. + * @param t - localized labels and failure feedback. + */ +export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => string): void { + ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({ + name: 'contextMenu.icon', key: 'reference.addToChat', + }, IconPlusOutlineRegular)) + const targetInput = ({ sessionId }: ContextMenuTargetMap['file']) => { + const binding = ctx.sessions.binding(sessionId) + if (binding === undefined) return undefined + const input = ctx.conversation.input.for(binding.ctx) + const blocks = ctx.conversation.blocks.storeFor(sessionId) + const editable = (): boolean => { + if (ctx.sessions.binding(sessionId) !== binding) return false + const state = binding.session.getSnapshot() + const phase = input.state.getSnapshot().phase + return !state.removed && (state.subagent === null || state.subagent.address.mode === 'continuable') + && blocks.getSnapshot() === undefined && (phase === 'plain' || phase === 'claimed') + } + return { binding, input, blocks, editable } + } + ctx.effect(() => ctx.contextMenus.register({ + id: 'reference.file', target: 'file', order: 300, + observe: (target) => { + const current = targetInput(target) + return current === undefined ? [] : [current.binding.session, current.input.state, current.blocks] + }, + resolve: (target) => { + const current = targetInput(target) + const path = resolveWorkspacePath(ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd, target.path) + const mention = formatFileMention({ path, kind: 'file' }, false) + return [{ + id: 'addToChat', label: t('menu.addToChat'), icon: { key: 'reference.addToChat' }, separatorBefore: true, + disabled: mention === undefined || current === undefined || !current.editable(), + failureLabel: t('menu.addToChatFailed'), + run: () => { + if (mention === undefined || current === undefined || !current.editable() + || !current.input.addFiles([{ + source: 'reference', ref: mention, label: path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1), + appearance: 'file', clipboardText: mention, + }], [])) throw new Error('File reference insertion unavailable') + current.input.focus() + }, + }] + }, + }), 'ui-reference: file context menu') +} diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index ab66cffa5e..142589a52f 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -34,6 +34,7 @@ import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference/typ import type { SessionReferenceMentionCandidate } from '@deepseek-ai/dsh-session-reference/types' import { abbreviateHomePath, fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import { en, ja, es, fr, de, ru, pt, NS, zh, type ReferenceKey } from './locales.ts' +import { registerReferenceMenu } from './context-menu.ts' declare module '@deepseek-ai/dsh-api-session-controller/client' { interface SessionReferenceSourceMap { @@ -55,6 +56,7 @@ export const inject = [ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-reference: dictionaries') const t = ctx.locale.bind(NS) + ctx.inject(['contextMenus', 'conversation'], (menuCtx) => { registerReferenceMenu(menuCtx, t) }) const sessions = ctx.get('sessions') as ISessions ctx.uiConversation.userText.register(fileReferenceRule) ctx.uiConversation.userText.register(folderReferenceRule) diff --git a/packages/client/ui-reference/src/client/locales.ts b/packages/client/ui-reference/src/client/locales.ts index a742c82eca..e4b4ad2f76 100644 --- a/packages/client/ui-reference/src/client/locales.ts +++ b/packages/client/ui-reference/src/client/locales.ts @@ -13,6 +13,8 @@ export const NS = 'reference' * bucketing they name is the one shared {@link relativeTime} in ui-primitives. */ export const zh = { + 'menu.addToChat': '添加到对话', + 'menu.addToChatFailed': '无法添加文件,请返回对话后重试', 'section.files': '文件与文件夹', 'section.subagents': '子智能体', 'section.sessions': '对话', @@ -42,6 +44,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** English dictionary, checked complete against the zh key set. */ export const en = { + 'menu.addToChat': 'Add to chat', + 'menu.addToChatFailed': 'Couldn’t add file. Return to the chat and try again.', 'section.files': 'Files & folders', 'section.subagents': 'Subagents', 'section.sessions': 'Sessions', @@ -61,6 +65,8 @@ export const en = { /** Japanese copy, checked against the English keys. */ export const ja = { + 'menu.addToChat': 'チャットに追加', + 'menu.addToChatFailed': 'ファイルを追加できませんでした。チャットに戻って再試行してください。', 'section.files': 'ファイルとフォルダ', 'section.subagents': 'サブエージェント', 'section.sessions': 'セッション', @@ -80,6 +86,8 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { + 'menu.addToChat': 'Añadir al chat', + 'menu.addToChatFailed': 'No se pudo añadir el archivo. Vuelve al chat e inténtalo de nuevo.', 'section.files': 'Archivos y carpetas', 'section.subagents': 'Subagentes', 'section.sessions': 'Sesiones', @@ -99,6 +107,8 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { + 'menu.addToChat': 'Ajouter au chat', + 'menu.addToChatFailed': 'Impossible d’ajouter le fichier. Revenez au chat et réessayez.', 'section.files': 'Fichiers et dossiers', 'section.subagents': 'Sous-agents', 'section.sessions': 'Séances', @@ -118,6 +128,8 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { + 'menu.addToChat': 'Zum Chat hinzufügen', + 'menu.addToChatFailed': 'Datei konnte nicht hinzugefügt werden. Kehren Sie zum Chat zurück und versuchen Sie es erneut.', 'section.files': 'Dateien und Ordner', 'section.subagents': 'Subagenten', 'section.sessions': 'Sitzungen', @@ -137,6 +149,8 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { + 'menu.addToChat': 'Добавить в чат', + 'menu.addToChatFailed': 'Не удалось добавить файл. Вернитесь в чат и повторите попытку.', 'section.files': 'Файлы и папки', 'section.subagents': 'Субагенты', 'section.sessions': 'Сессии', @@ -156,6 +170,8 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { + 'menu.addToChat': 'Adicionar ao chat', + 'menu.addToChatFailed': 'Não foi possível adicionar o arquivo. Volte ao chat e tente novamente.', 'section.files': 'Arquivos e pastas', 'section.subagents': 'Subagentes', 'section.sessions': 'Sessões', diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts new file mode 100644 index 0000000000..1ad5986881 --- /dev/null +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -0,0 +1,167 @@ +// @vitest-environment jsdom +/** Shared file menus insert references through the Session's real draft editor. */ +import { expect, it, onTestFinished, vi } from 'vitest' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' +import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts' +import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import { registerReferenceMenu } from '../src/client/context-menu.ts' +import { en, zh } from '../src/client/locales.ts' + +const id = 'target' as SessionId +const actionId = 'reference.file/addToChat' + +async function bench() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + await runtime.declare({ 'contextMenu.icon': { kind: 'keyed', scope: 'root', inline: true } }) + await runtime.sessions.add({ id, summary: { cwd: '/workspace' } }) + const owner = runtime.sessions.retain(id) + onTestFinished(() => { owner.release() }) + const binding = runtime.sessions.binding(id)! + const sink = vi.fn(async () => ({ kind: 'success' as const })) + const shell = new SessionInputShell({ + actx: binding.ctx, defaultSink: sink, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + }) + onTestFinished(() => { shell.dispose() }) + const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {}) + const blocks = new ComposerBlockRegistry() + const resolveInput = vi.fn(() => shell) + runtime.ctx.provide('conversation', { input: { for: resolveInput }, blocks }) + const failed = vi.fn() + const menus = new MenuRegistry(failed) + onTestFinished(() => { menus.dispose() }) + runtime.ctx.provide('contextMenus', { register: menus.register.bind(menus) }) + const fiber = runtime.ctx.plugin({ + inject: ['slots', 'sessions', 'conversation', 'contextMenus'], + apply: (ctx) => { registerReferenceMenu(ctx, key => en[key]) }, + }) + await fiber.await() + const menu = async (value: Partial = {}) => { + const result = menus.resolve({ kind: 'file', value: { sessionId: id, path: 'docs/a b.md', ...value } }) + onTestFinished(() => { result.dispose() }) + await result.ready + return result + } + return { runtime, owner, binding, shell, sink, focus, blocks, resolveInput, failed, menus, fiber, menu } +} + +it('appends the final action after other providers and inserts the captured file without sending', async () => { + const b = await bench() + const ready = Promise.withResolvers() + b.menus.register({ id: 'open', target: 'file', order: 100, resolve: async () => { + await ready.promise + return [{ id: 'preview', label: 'Preview' }] + } }) + b.menus.register({ id: 'save', target: 'file', order: 200, resolve: () => [{ id: 'download', label: 'Download' }] }) + b.shell.setDraft('Review this') + const pending = b.menu({ line: 24 }) + ready.resolve(undefined) + const menu = await pending + expect(menu.source.getSnapshot().map(row => row.label)).toEqual(['Preview', 'Download', en['menu.addToChat']]) + expect(menu.source.getSnapshot().at(-1)).toMatchObject({ separatorBefore: true, disabled: false }) + menu.select(actionId) + expect(b.resolveInput).toHaveBeenCalledWith(b.binding.ctx) + expect(b.shell.snapshot.draft).toBe('Review this @"/workspace/docs/a b.md" ') + expect(b.shell.snapshot.occurrences).toMatchObject([{ + source: 'reference', ref: '@"/workspace/docs/a b.md"', label: 'a b.md', appearance: 'file', + }]) + expect(b.shell.snapshot.attachmentIds).toEqual([]) + expect(b.focus).toHaveBeenCalledOnce() + expect(b.sink).not.toHaveBeenCalled() + expect(b.failed).not.toHaveBeenCalled() +}) + +it.each(['bad"name.txt', 'bad\nname.txt'])('disables paths outside the mention grammar: %j', async (path) => { + const b = await bench() + const menu = await b.menu({ path }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('') + expect(b.focus).not.toHaveBeenCalled() +}) + +it('disables an unretained Session and never opens it or targets another draft', async () => { + const b = await bench() + const menu = await b.menu({ sessionId: 'absent' as SessionId }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect(b.resolveInput).not.toHaveBeenCalled() + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('') +}) + +it('tracks composer blocks and rejects a stale Session binding at execution', async () => { + const b = await bench() + const menu = await b.menu() + b.blocks.set(id, { reason: 'Unavailable' }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + b.blocks.set(id, undefined) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + b.owner.release() + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.focus).not.toHaveBeenCalled() +}) + +it('disables removed and one-shot Sessions but permits continuable Sessions', async () => { + const b = await bench() + const menu = await b.menu() + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { + state.removed = false + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } } + }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } } + }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) +}) + +it('tracks submission locks without treating a running turn as an editing lock', async () => { + const b = await bench() + const pending = Promise.withResolvers<{ kind: 'success' }>() + b.sink.mockImplementation(() => pending.promise) + const menu = await b.menu() + await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.running = true }) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + b.shell.setDraft('Sending') + b.shell.submit() + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + pending.resolve({ kind: 'success' }) + await vi.waitFor(() => { expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) }) +}) + +it('reports insertion refusal without focusing or sending', async () => { + const b = await bench() + vi.spyOn(b.shell, 'addFiles').mockReturnValue(false) + const menu = await b.menu() + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.focus).not.toHaveBeenCalled() + expect(b.sink).not.toHaveBeenCalled() +}) + +it('withdraws open menu actions and their icon on plugin disposal', async () => { + const b = await bench() + const menu = await b.menu() + expect(b.runtime.ctx.slots.entries('contextMenu.icon').map(row => row.options.key)).toEqual(['reference.addToChat']) + await b.fiber.dispose() + expect(menu.source.getSnapshot()).toEqual([]) + expect(b.runtime.ctx.slots.entries('contextMenu.icon')).toEqual([]) + menu.select(actionId) + expect(b.focus).not.toHaveBeenCalled() + expect(zh['menu.addToChat']).toBe('添加到对话') +}) + +it('refuses direct file insertion after the draft editor is disposed', async () => { + const b = await bench() + b.shell.setDraft('Keep this') + b.shell.dispose() + expect(b.shell.addFiles([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }], [])).toBe(false) + expect(b.shell.snapshot.draft).toBe('Keep this') +}) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index c878484faf..0db2be70b1 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -157,7 +157,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', ], - keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: open-in-app.application, sidebar.close', + keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: open-in-app.application, reference.addToChat, sidebar.close', hookContext: '', slotInject: '', declaredBy: 'an entry in \'shell.overlay\' (client-ui-context-menu), so it exists while that entry is mounted', @@ -165,6 +165,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'client-ui-file-actions Icon', 'client-ui-open-in-app Icon', 'client-ui-open-in-app ContextMenuApplicationIcon key \'open-in-app.application\'', + 'client-ui-reference IconPlusOutlineRegular key \'reference.addToChat\'', 'client-ui-sidebar-right IconCloseOutlineRegular key \'sidebar.close\'', 'client-ui-workspace Icon', 'session-log-export Icon', diff --git a/snapshots/web/markdown-file-links/add-to-chat.expected.md b/snapshots/web/markdown-file-links/add-to-chat.expected.md new file mode 100644 index 0000000000..06882f5e2c --- /dev/null +++ b/snapshots/web/markdown-file-links/add-to-chat.expected.md @@ -0,0 +1,11 @@ +## File menu + +- menu: + - menuitem "Download" + - separator + - menuitem "Add to chat" + +## Composer + +- textbox "Message or run a task, / commands, @ files or sessions": + - paragraph: "Review this file next: example.txt" From 3749375caf8df68c4cee2a9cfeb99d0285b8afbb Mon Sep 17 00:00:00 2001 From: Kaige-Gao <102539609+Kaige-Gao@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:21:36 +0800 Subject: [PATCH 2/9] test(web): await committed selection before file menu action --- apps/web/tests/reference-composer.e2e.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index 57fd1c946d..7011225503 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -443,7 +443,8 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through const directory = join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested') const file = join(directory, 'space name.txt') const sessionId = brandString(TARGET_SESSION_ID) - const beforeEvents = await readPersistedEvents(scaffold, sessionId) + const beforeEvents = (await readPersistedEvents(scaffold, sessionId)) + .filter(event => event.type === 'user/message' || event.type.startsWith('turn/')) const beforeMessages = await page.locator('[data-chat-flow-kind="user"]').count() // An absolute query compares the same resource spelling as the sidebar. @@ -487,6 +488,12 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through for (let i = 0; i < 'Review '.length; i++) await page.keyboard.press('ArrowRight') for (let i = 0; i < 'selected'.length; i++) await page.keyboard.press('Shift+ArrowRight') expect(await page.evaluate(() => window.getSelection()?.toString())).toBe('selected') + // Copy observes the editor's committed selection, not only the native range. + await expect.poll(() => input.evaluate((node) => { + const clipboardData = new DataTransfer() + node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true })) + return clipboardData.getData('text/plain') + })).toBe('selected') await row.click({ button: 'right' }) const menu = page.getByRole('menu') @@ -516,7 +523,8 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through expect(await chip.count()).toBe(0) expect(await input.evaluate(node => node === document.activeElement)).toBe(true) expect(await page.locator('[data-chat-flow-kind="user"]').count()).toBe(beforeMessages) - expect(await readPersistedEvents(scaffold, sessionId)).toEqual(beforeEvents) + expect((await readPersistedEvents(scaffold, sessionId)) + .filter(event => event.type === 'user/message' || event.type.startsWith('turn/'))).toEqual(beforeEvents) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) From 4430bb0ccfaf31f7761c30e39b5a60131998ca2d Mon Sep 17 00:00:00 2001 From: Kaige-Gao <102539609+Kaige-Gao@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:55:19 +0800 Subject: [PATCH 3/9] fix(client): refresh file reference menus on locale changes --- .../src/client/contract/input.ts | 12 +++--- packages/client/ui-reference/README.i18n.yaml | 4 +- packages/client/ui-reference/README.md | 2 +- packages/client/ui-reference/README.zh.md | 2 +- .../ui-reference/src/client/context-menu.ts | 6 +-- .../tests/context-menu.client.spec.ts | 37 +++++++++++++++++-- 6 files changed, 47 insertions(+), 16 deletions(-) diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index e1a9c0cf6e..c2362f438e 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -1,10 +1,10 @@ /** - * Frozen input-machine contract. Types - * only. Three-tier visibility: business packages see InputState via the - * InputZone currency; the scoped input events carry the mutation verbs; the - * conversation wiring layer alone sees the full SessionInput. The draft text - * and its reference chips live in the shell's Lexical editor; the machine - * here is the submit plane (phase, claim, attempt) alone. + * Input-machine types and Session-addressed draft operations. Business packages + * read InputState through InputZone and use scoped input events for guarded + * mutations. Conversation wiring and direct draft consumers resolve SessionInput + * through conversation.input.for(), including file insertion through addFiles. + * Draft text and reference chips live in the shell's Lexical editor; the machine + * here owns submission state (phase, claim, attempt). */ import type { Context } from '@deepseek-ai/cordis' import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index 8c7cbebdd2..229d0d9363 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -18,8 +18,8 @@ en: 779a9a534eaad38b zh: 3dd159a2c35702d6 /deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts: - en: 817aa123e8033ff7 - zh: 19e6593b61e8b5b7 + en: 27ca6ef7a0fbe913 + zh: aa413e010a563593 /deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior: en: 386bbd9dc0a2c322 zh: 3014a367157532b7 diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index ed3c545b1d..96f4cc47e5 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -33,7 +33,7 @@ A file closes completion as an atomic inline reference displayed with a file gly A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`. -The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited or the path cannot use the mention grammar. +The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited or the path cannot use the mention grammar. An open menu updates its label and failure feedback when the interface language changes. ### Failure behavior diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index ba9a3d24a6..b08b9164fe 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -33,7 +33,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。 -共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。Session 不可编辑或路径无法用 mention 语法表示时,此入口不可用。 +共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。Session 不可编辑或路径无法用 mention 语法表示时,此入口不可用。切换界面语言时,已打开菜单的标题和失败提示随之更新。 ### 失败行为 diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts index 8bad653ddd..2786d3de9d 100644 --- a/packages/client/ui-reference/src/client/context-menu.ts +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -4,7 +4,7 @@ import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-me import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { formatFileMention } from '@deepseek-ai/dsh-file-reference/grammar' -import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' +import { resolveWorkspacePath, workspaceTitleOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ReferenceKey } from './locales.ts' /** @@ -34,7 +34,7 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st id: 'reference.file', target: 'file', order: 300, observe: (target) => { const current = targetInput(target) - return current === undefined ? [] : [current.binding.session, current.input.state, current.blocks] + return current === undefined ? [ctx.locale] : [ctx.locale, current.binding.session, current.input.state, current.blocks] }, resolve: (target) => { const current = targetInput(target) @@ -47,7 +47,7 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st run: () => { if (mention === undefined || current === undefined || !current.editable() || !current.input.addFiles([{ - source: 'reference', ref: mention, label: path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1), + source: 'reference', ref: mention, label: workspaceTitleOf(path), appearance: 'file', clipboardText: mention, }], [])) throw new Error('File reference insertion unavailable') current.input.focus() diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts index 1ad5986881..5530747b41 100644 --- a/packages/client/ui-reference/tests/context-menu.client.spec.ts +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -5,6 +5,7 @@ import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts' import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { registerReferenceMenu } from '../src/client/context-menu.ts' @@ -16,6 +17,10 @@ const actionId = 'reference.file/addToChat' async function bench() { const runtime = await SlotTestRuntime.create() onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + runtime.ctx.provide('locale', locale) + runtime.ctx.effect(() => locale.register('reference', { en, zh })) + locale.setLocale('en') await runtime.declare({ 'contextMenu.icon': { kind: 'keyed', scope: 'root', inline: true } }) await runtime.sessions.add({ id, summary: { cwd: '/workspace' } }) const owner = runtime.sessions.retain(id) @@ -36,8 +41,8 @@ async function bench() { onTestFinished(() => { menus.dispose() }) runtime.ctx.provide('contextMenus', { register: menus.register.bind(menus) }) const fiber = runtime.ctx.plugin({ - inject: ['slots', 'sessions', 'conversation', 'contextMenus'], - apply: (ctx) => { registerReferenceMenu(ctx, key => en[key]) }, + inject: ['slots', 'sessions', 'conversation', 'contextMenus', 'locale'], + apply: (ctx) => { registerReferenceMenu(ctx, locale.bind('reference')) }, }) await fiber.await() const menu = async (value: Partial = {}) => { @@ -46,7 +51,7 @@ async function bench() { await result.ready return result } - return { runtime, owner, binding, shell, sink, focus, blocks, resolveInput, failed, menus, fiber, menu } + return { runtime, locale, owner, binding, shell, sink, focus, blocks, resolveInput, failed, menus, fiber, menu } } it('appends the final action after other providers and inserts the captured file without sending', async () => { @@ -158,6 +163,32 @@ it('withdraws open menu actions and their icon on plugin disposal', async () => expect(zh['menu.addToChat']).toBe('添加到对话') }) +it('refreshes open labels and failure feedback when the locale changes', async () => { + const b = await bench() + const menu = await b.menu() + const unavailable = await b.menu({ sessionId: 'absent' as SessionId }) + expect(menu.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat']) + expect(unavailable.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat']) + b.locale.setLocale('zh') + expect(menu.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) + expect(unavailable.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) + vi.spyOn(b.shell, 'addFiles').mockReturnValue(false) + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(zh['menu.addToChatFailed']) + await b.fiber.dispose() + b.locale.setLocale('en') + expect(unavailable.source.getSnapshot()).toEqual([]) +}) + +it.each(['/work/a b.md', 'C:\\work\\a b.md', '\\\\server\\share\\a b.md', '/work/a b.md/'])( + 'uses the final nonempty path segment as the reference label: %j', async (path) => { + const b = await bench() + const menu = await b.menu({ path }) + menu.select(actionId) + expect(b.shell.snapshot.occurrences).toMatchObject([{ label: 'a b.md', ref: `@"${path}"` }]) + }, +) + it('refuses direct file insertion after the draft editor is disposed', async () => { const b = await bench() b.shell.setDraft('Keep this') From def0a656884948055aa99a458f203757bd1e4580 Mon Sep 17 00:00:00 2001 From: Kaige-Gao <102539609+Kaige-Gao@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:23:56 +0800 Subject: [PATCH 4/9] test(web): select draft word with a native pointer gesture --- apps/web/tests/reference-composer.e2e.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index 7011225503..0fbf92a6a6 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -483,10 +483,16 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through await row.waitFor() const draft = 'Review selected, then finish.' await writeComposerDraft(page, input, draft) - await page.keyboard.press('ControlOrMeta+A') - await page.keyboard.press('ArrowLeft') - for (let i = 0; i < 'Review '.length; i++) await page.keyboard.press('ArrowRight') - for (let i = 0; i < 'selected'.length; i++) await page.keyboard.press('Shift+ArrowRight') + const word = await input.evaluate((node) => { + const text = document.createTreeWalker(node, NodeFilter.SHOW_TEXT).nextNode() + if (text === null) throw new Error('Composer draft has no text') + const range = document.createRange() + range.setStart(text, 'Review '.length) + range.setEnd(text, 'Review selected'.length) + const rect = range.getBoundingClientRect() + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 } + }) + await page.mouse.dblclick(word.x, word.y) expect(await page.evaluate(() => window.getSelection()?.toString())).toBe('selected') // Copy observes the editor's committed selection, not only the native range. await expect.poll(() => input.evaluate((node) => { From d22af04fbb6cebf3fe0de61644392c6526707cd7 Mon Sep 17 00:00:00 2001 From: zhc Date: Tue, 17 Nov 2026 14:25:38 +0800 Subject: [PATCH 5/9] refactor(client): expose reference insertion through SessionInput Replace the public SessionInput.addFiles with addReferences, keeping the attachment-carrying addFiles as a SessionInputShell method for drop and paste. Conversation now owns the Session and composer-block editability rule as an observable referenceInsertionAllowed, shared with quote insertion, so the file context menu no longer duplicates it. --- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/contract/input.ts | 14 ++- .../src/client/input/draft-editability.ts | 32 ++++++ .../src/client/input/facade.ts | 28 ++++- .../ui-conversation/src/client/input/hub.ts | 8 +- .../tests/quote-composer.client.spec.tsx | 11 +- .../tests/reference-insertion.client.spec.ts | 101 ++++++++++++++++++ .../ui-reference/src/client/context-menu.ts | 18 ++-- .../tests/context-menu.client.spec.ts | 16 +-- 11 files changed, 195 insertions(+), 41 deletions(-) create mode 100644 packages/client/ui-conversation/src/client/input/draft-editability.ts create mode 100644 packages/client/ui-conversation/tests/reference-insertion.client.spec.ts diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index ec4ed26da1..195c125d27 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 41474b736046dcfa - zh: ab3428752c222c89 + en: e89d6f5735f863ba + zh: 1e4d9a2d25f145e5 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index d73df2c962..f557a076be 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addFiles` inserts references after the retained selection in one undo step without replacing selected text; it refuses edits after disposal or during submission. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.referenceInsertionAllowed` is the observable precondition: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set; quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index f5b94d6f29..385339044c 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addFiles` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字;输入模型释放后或提交期间拒绝编辑。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.referenceInsertionAllowed` 是可订阅的前置条件:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false;引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index c2362f438e..36ead1e534 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -2,7 +2,7 @@ * Input-machine types and Session-addressed draft operations. Business packages * read InputState through InputZone and use scoped input events for guarded * mutations. Conversation wiring and direct draft consumers resolve SessionInput - * through conversation.input.for(), including file insertion through addFiles. + * through conversation.input.for(), including reference insertion through addReferences. * Draft text and reference chips live in the shell's Lexical editor; the machine * here owns submission state (phase, claim, attempt). */ @@ -196,12 +196,16 @@ export interface SessionInput extends InputTarget { /** Append ordered browser-owned attachment ids; busy admission phases refuse. */ addAttachments(ids: readonly DraftAttachmentId[]): boolean /** - * Insert file references after the retained selection without replacing text, and append attachment ids. + * Insert file references after the retained selection in one undo step without replacing text. * @param references - validated reference chips in source order. - * @param ids - browser-owned attachment ids; empty for reference-only insertion. - * @returns false after disposal, while submission is locked, or when insertion is refused. + * @returns false while {@link referenceInsertionAllowed} is false or when the editor refuses insertion. */ - addFiles(references: readonly ReferenceInsert[], ids: readonly DraftAttachmentId[]): boolean + addReferences(references: readonly ReferenceInsert[]): boolean + /** + * Whether {@link addReferences} can edit the draft: false after disposal, during submission, + * for removed or non-continuable subagent Sessions, and while a composer block is set. + */ + readonly referenceInsertionAllowed: ObservableSnapshot /** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */ removeAttachment(id: DraftAttachmentId): boolean /** Drop ids whose browser-owned objects no longer exist. */ diff --git a/packages/client/ui-conversation/src/client/input/draft-editability.ts b/packages/client/ui-conversation/src/client/input/draft-editability.ts new file mode 100644 index 0000000000..6ec12db350 --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/draft-editability.ts @@ -0,0 +1,32 @@ +/** Session conditions under which features outside the composer may edit a Session draft. */ +import type { SessionFace } from '@deepseek-ai/dsh-api-session-controller/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { ComposerBlock } from '../contract/composer-blocks.ts' + +/** + * Observe whether a Session accepts draft insertions from outside the composer. + * Removed Sessions, non-continuable subagent Sessions, and composer blocks refuse. + * @param session - live Session face. + * @param blocks - resolves the Session's composer-block store at each read and subscription. + * @returns a boolean snapshot that notifies on Session and composer-block changes. + */ +export function sessionDraftEditable( + session: SessionFace, + blocks: () => ObservableSnapshot, +): ObservableSnapshot { + return { + getSnapshot: () => { + const state = session.getSnapshot() + return !state.removed && (state.subagent === null || state.subagent.address.mode === 'continuable') + && blocks().getSnapshot() === undefined + }, + subscribe: (fn) => { + const offSession = session.subscribe(fn) + const offBlocks = blocks().subscribe(fn) + return () => { + offSession() + offBlocks() + } + }, + } +} diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index c24f40b4f6..fc6057c7d1 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -71,8 +71,8 @@ export interface SessionInputDeps { signal: AbortSignal, accept: () => void, ): Promise - /** Live Session and composer-block policy for transcript insertion. */ - quoteInsertionAllowed?: () => boolean + /** Live Session and composer-block policy for quote and reference insertion; absent permits both. */ + sessionEditable?: ObservableSnapshot | undefined /** Current localized quote removal copy. */ quoteRemoveLabel?: () => string /** Command-plane attachment plumbing (the hub owns the conversation face and the copy). */ @@ -138,6 +138,18 @@ const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() export class SessionInputShell implements SessionInput { /** Published editor projection + submit-plane state + queue overlay (the InputZone currency source). */ readonly state: SnapshotStore + /** @inheritdoc */ + readonly referenceInsertionAllowed: ObservableSnapshot = { + getSnapshot: () => !this.disposed && !frozen(this.snapshot.phase) && this.deps.sessionEditable?.getSnapshot() !== false, + subscribe: (fn) => { + const offState = this.state.subscribe(fn) + const offSession = this.deps.sessionEditable?.subscribe(fn) + return () => { + offState() + offSession?.() + } + }, + } /** Latest surfaced notice (null after clear); the bar renders errors as banners and information inline. */ readonly notices: SnapshotStore = createSnapshotStore(null) /** The shell-owned editor (text + chip truth); the composer binds its contenteditable to it. */ @@ -242,7 +254,7 @@ export class SessionInputShell implements SessionInput { * @returns whether the editable draft accepted the quote. */ insertQuote(text: string, summary?: QuoteSummary): boolean { - if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.quoteInsertionAllowed?.() === false || text.trim() === '') return false + if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.sessionEditable?.getSnapshot() === false || text.trim() === '') return false const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary) if (inserted) this.focus() return inserted @@ -342,6 +354,7 @@ export class SessionInputShell implements SessionInput { /** * Add validated file references and attachment ids while admission is editable. + * Drop and paste use this wiring-layer method; other packages use {@link addReferences}. * @param references - reference chips in source order. * @param ids - newly allocated attachment ids. * @returns false after disposal, when admission is locked, or when the editor refuses insertion. @@ -354,6 +367,15 @@ export class SessionInputShell implements SessionInput { return true } + /** + * @param references - validated reference chips in source order. + * @returns whether the draft accepted the references. + */ + addReferences(references: readonly ReferenceInsert[]): boolean { + if (!this.referenceInsertionAllowed.getSnapshot()) return false + return this.addFiles(references, []) + } + /** * Remove one attachment id from this draft. Busy admission phases refuse, like * {@link addAttachments}: a removal landing while a send serializes would diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 8944d91981..5e30c77f1b 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -25,6 +25,7 @@ import type { ComposerBlocks } from '../contract/composer-blocks.ts' import type { InputSubmitMode } from '../contract/composer-submission.ts' import type { PopupDismissFace } from './facade.ts' import { SessionInputShell } from './facade.ts' +import { sessionDraftEditable } from './draft-editability.ts' import { reportMessageSubmission } from './submission-analytics.ts' import { readConversationDraft } from '../stores.ts' @@ -157,12 +158,7 @@ export class InputHub implements SessionInputResolver { inbox: session.projections.faceOf('inbox') as ObservableSnapshot, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), - quoteInsertionAllowed: () => { - const state = session.getSnapshot() - return !state.removed && (state.subagent === null - || state.subagent.address.mode === 'continuable') - && this.conversation().blocks.storeFor(session.sessionId).getSnapshot() === undefined - }, + sessionEditable: sessionDraftEditable(session, () => this.conversation().blocks.storeFor(session.sessionId)), steerQueue: () => { void this.steerQueue(session, shell) }, commandAttachments: { serialize: async (ids) => { diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index 8582f67e55..f4c683812c 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { fireEvent, render } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import { KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, UNDO_COMMAND, $getRoot, $getSelection, $isRangeSelection, $nodesOfType, @@ -16,7 +17,7 @@ import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' const quote = 'selected source text' -function bench(quoteInsertionAllowed?: () => boolean) { +function bench(sessionEditable?: ObservableSnapshot) { const sink = vi.fn(() => Promise.resolve({ kind: 'success' })) const shell = new SessionInputShell({ actx: {} as Context, @@ -27,7 +28,7 @@ function bench(quoteInsertionAllowed?: () => boolean) { unsupportedNotice: () => 'unsupported', }, quoteRemoveLabel: () => 'Remove quote', - ...(quoteInsertionAllowed === undefined ? {} : { quoteInsertionAllowed }), + ...(sessionEditable === undefined ? {} : { sessionEditable }), }) return { shell, sink } } @@ -38,13 +39,13 @@ function quoteKeys(shell: SessionInputShell): string[] { describe('QuoteNode composer lifecycle', () => { it('preserves the draft when its Session cannot accept an inserted quote', () => { - let allowed = false - const { shell } = bench(() => allowed) + const allowed = createSnapshotStore(false) + const { shell } = bench(allowed) shell.setDraft('base ') const before = shell.draftSnapshot expect(shell.insertQuote(quote)).toBe(false) expect(shell.draftSnapshot).toBe(before) - allowed = true + allowed.set(true) expect(shell.insertQuote(quote)).toBe(true) }) diff --git a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts new file mode 100644 index 0000000000..2aa99d2b1d --- /dev/null +++ b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts @@ -0,0 +1,101 @@ +// @vitest-environment jsdom +/** Reference insertion from outside the composer follows Session, submission, and disposal state. */ +import { expect, it, onTestFinished, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts' +import type { SubmitOutcome } from '../src/client/contract/input.ts' +import { SessionInputShell } from '../src/client/input/facade.ts' +import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' +import { sessionDraftEditable } from '../src/client/input/draft-editability.ts' + +const reference: ReferenceInsert = { + source: 'reference', ref: '@"/work/a b.md"', label: 'a b.md', appearance: 'file', clipboardText: '@"/work/a b.md"', +} + +function bench(sessionEditable?: ObservableSnapshot) { + const pending = Promise.withResolvers() + const sink = vi.fn(() => pending.promise) + const shell = new SessionInputShell({ + actx: {} as Context, + defaultSink: sink, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + ...(sessionEditable === undefined ? {} : { sessionEditable }), + }) + onTestFinished(() => { shell.dispose() }) + return { shell, sink, pending } +} + +it('inserts references without attachments and locks while a submission owns the draft', async () => { + const { shell, pending } = bench() + const changed = vi.fn() + const unsubscribe = shell.referenceInsertionAllowed.subscribe(changed) + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) + shell.setDraft('Review') + expect(shell.addReferences([reference])).toBe(true) + expect(shell.snapshot.draft).toBe('Review @"/work/a b.md" ') + expect(shell.snapshot.attachmentIds).toEqual([]) + changed.mockClear() + shell.submit() + expect(changed).toHaveBeenCalled() + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + pending.resolve({ kind: 'success' }) + await vi.waitFor(() => { expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) }) + unsubscribe() +}) + +it('follows the Session policy and refuses after disposal', () => { + const editable = createSnapshotStore(false) + const { shell } = bench(editable) + const changed = vi.fn() + const unsubscribe = shell.referenceInsertionAllowed.subscribe(changed) + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + expect(shell.snapshot.draft).toBe('') + editable.set(true) + expect(changed).toHaveBeenCalledOnce() + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) + unsubscribe() + editable.set(false) + expect(changed).toHaveBeenCalledOnce() + editable.set(true) + shell.dispose() + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) +}) + +it('derives Session editability from removal, subagent mode, and composer blocks', async () => { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const id = 'target' as SessionId + await runtime.sessions.add({ id, summary: { cwd: '/workspace' } }) + const owner = runtime.sessions.retain(id) + onTestFinished(() => { owner.release() }) + const blocks = new ComposerBlockRegistry() + const editable = sessionDraftEditable(runtime.sessions.binding(id)!.session, () => blocks.storeFor(id)) + const changed = vi.fn() + const unsubscribe = editable.subscribe(changed) + expect(editable.getSnapshot()).toBe(true) + blocks.set(id, { reason: 'Unavailable' }) + expect(changed).toHaveBeenCalled() + expect(editable.getSnapshot()).toBe(false) + blocks.set(id, undefined) + await runtime.sessions.updateSessionSnapshot(id, (state) => { + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } } + }) + expect(editable.getSnapshot()).toBe(false) + await runtime.sessions.updateSessionSnapshot(id, (state) => { + state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } } + }) + expect(editable.getSnapshot()).toBe(true) + await runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true }) + expect(editable.getSnapshot()).toBe(false) + unsubscribe() + changed.mockClear() + blocks.set(id, { reason: 'Unavailable' }) + await runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = false }) + expect(changed).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts index 2786d3de9d..3d01a6864b 100644 --- a/packages/client/ui-reference/src/client/context-menu.ts +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -20,21 +20,15 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st const binding = ctx.sessions.binding(sessionId) if (binding === undefined) return undefined const input = ctx.conversation.input.for(binding.ctx) - const blocks = ctx.conversation.blocks.storeFor(sessionId) - const editable = (): boolean => { - if (ctx.sessions.binding(sessionId) !== binding) return false - const state = binding.session.getSnapshot() - const phase = input.state.getSnapshot().phase - return !state.removed && (state.subagent === null || state.subagent.address.mode === 'continuable') - && blocks.getSnapshot() === undefined && (phase === 'plain' || phase === 'claimed') - } - return { binding, input, blocks, editable } + // A released or replaced binding must not receive the reference captured for its predecessor. + const editable = (): boolean => ctx.sessions.binding(sessionId) === binding && input.referenceInsertionAllowed.getSnapshot() + return { input, editable } } ctx.effect(() => ctx.contextMenus.register({ id: 'reference.file', target: 'file', order: 300, observe: (target) => { const current = targetInput(target) - return current === undefined ? [ctx.locale] : [ctx.locale, current.binding.session, current.input.state, current.blocks] + return current === undefined ? [ctx.locale] : [ctx.locale, current.input.referenceInsertionAllowed] }, resolve: (target) => { const current = targetInput(target) @@ -46,10 +40,10 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st failureLabel: t('menu.addToChatFailed'), run: () => { if (mention === undefined || current === undefined || !current.editable() - || !current.input.addFiles([{ + || !current.input.addReferences([{ source: 'reference', ref: mention, label: workspaceTitleOf(path), appearance: 'file', clipboardText: mention, - }], [])) throw new Error('File reference insertion unavailable') + }])) throw new Error('File reference insertion unavailable') current.input.focus() }, }] diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts index 5530747b41..e9d45290de 100644 --- a/packages/client/ui-reference/tests/context-menu.client.spec.ts +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -5,6 +5,7 @@ import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts' import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts' +import { sessionDraftEditable } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/draft-editability.ts' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -27,15 +28,16 @@ async function bench() { onTestFinished(() => { owner.release() }) const binding = runtime.sessions.binding(id)! const sink = vi.fn(async () => ({ kind: 'success' as const })) + const blocks = new ComposerBlockRegistry() const shell = new SessionInputShell({ actx: binding.ctx, defaultSink: sink, commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, + sessionEditable: sessionDraftEditable(binding.session, () => blocks.storeFor(id)), }) onTestFinished(() => { shell.dispose() }) const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {}) - const blocks = new ComposerBlockRegistry() const resolveInput = vi.fn(() => shell) - runtime.ctx.provide('conversation', { input: { for: resolveInput }, blocks }) + runtime.ctx.provide('conversation', { input: { for: resolveInput } }) const failed = vi.fn() const menus = new MenuRegistry(failed) onTestFinished(() => { menus.dispose() }) @@ -143,7 +145,7 @@ it('tracks submission locks without treating a running turn as an editing lock', it('reports insertion refusal without focusing or sending', async () => { const b = await bench() - vi.spyOn(b.shell, 'addFiles').mockReturnValue(false) + vi.spyOn(b.shell, 'addReferences').mockReturnValue(false) const menu = await b.menu() menu.select(actionId) expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) @@ -172,7 +174,7 @@ it('refreshes open labels and failure feedback when the locale changes', async ( b.locale.setLocale('zh') expect(menu.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) expect(unavailable.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat']) - vi.spyOn(b.shell, 'addFiles').mockReturnValue(false) + vi.spyOn(b.shell, 'addReferences').mockReturnValue(false) menu.select(actionId) expect(b.failed).toHaveBeenCalledWith(zh['menu.addToChatFailed']) await b.fiber.dispose() @@ -189,10 +191,12 @@ it.each(['/work/a b.md', 'C:\\work\\a b.md', '\\\\server\\share\\a b.md', '/work }, ) -it('refuses direct file insertion after the draft editor is disposed', async () => { +it('disables the action and refuses direct insertion after the draft editor is disposed', async () => { const b = await bench() + const menu = await b.menu() b.shell.setDraft('Keep this') b.shell.dispose() - expect(b.shell.addFiles([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }], [])).toBe(false) + expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect(b.shell.addReferences([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }])).toBe(false) expect(b.shell.snapshot.draft).toBe('Keep this') }) From 91d9eb61adc83b0767c710ce4e4c24b4c8097237 Mon Sep 17 00:00:00 2001 From: zhc Date: Tue, 17 Nov 2026 17:21:20 +0800 Subject: [PATCH 6/9] refactor(client): keep draft insertion policy inside the input facade SessionInputShell now receives the Session and composer-block sources directly and evaluates removal, subagent mode, and blocks in one private check shared by quote insertion and referenceInsertionAllowed. The separate draft-editability helper is removed. --- .../src/client/input/draft-editability.ts | 32 ------- .../src/client/input/facade.ts | 24 ++++-- .../ui-conversation/src/client/input/hub.ts | 4 +- .../tests/quote-composer.client.spec.tsx | 11 +-- .../tests/reference-insertion.client.spec.ts | 86 +++++++++---------- .../tests/context-menu.client.spec.ts | 4 +- 6 files changed, 70 insertions(+), 91 deletions(-) delete mode 100644 packages/client/ui-conversation/src/client/input/draft-editability.ts diff --git a/packages/client/ui-conversation/src/client/input/draft-editability.ts b/packages/client/ui-conversation/src/client/input/draft-editability.ts deleted file mode 100644 index 6ec12db350..0000000000 --- a/packages/client/ui-conversation/src/client/input/draft-editability.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** Session conditions under which features outside the composer may edit a Session draft. */ -import type { SessionFace } from '@deepseek-ai/dsh-api-session-controller/client' -import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { ComposerBlock } from '../contract/composer-blocks.ts' - -/** - * Observe whether a Session accepts draft insertions from outside the composer. - * Removed Sessions, non-continuable subagent Sessions, and composer blocks refuse. - * @param session - live Session face. - * @param blocks - resolves the Session's composer-block store at each read and subscription. - * @returns a boolean snapshot that notifies on Session and composer-block changes. - */ -export function sessionDraftEditable( - session: SessionFace, - blocks: () => ObservableSnapshot, -): ObservableSnapshot { - return { - getSnapshot: () => { - const state = session.getSnapshot() - return !state.removed && (state.subagent === null || state.subagent.address.mode === 'continuable') - && blocks().getSnapshot() === undefined - }, - subscribe: (fn) => { - const offSession = session.subscribe(fn) - const offBlocks = blocks().subscribe(fn) - return () => { - offSession() - offBlocks() - } - }, - } -} diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index fc6057c7d1..1388a7caff 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -10,6 +10,7 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' @@ -24,6 +25,7 @@ import type { ArbitrateKey, ArbitrateOutcome, ComposerKeyboard, DraftInput, DraftSnapshot, ReferenceInsert, TokenSpan, } from '../contract/draft-editor.ts' import type { InputSubmitMode, MessageSubmission, MessageSubmissionState } from '../contract/composer-submission.ts' +import type { ComposerBlock } from '../contract/composer-blocks.ts' import { serializeDraftPrompt } from './prompt.ts' import { SubmitMachine } from './machine.ts' import { resolveDraftInput, snapshotDraft } from '../draft.ts' @@ -71,8 +73,10 @@ export interface SessionInputDeps { signal: AbortSignal, accept: () => void, ): Promise - /** Live Session and composer-block policy for quote and reference insertion; absent permits both. */ - sessionEditable?: ObservableSnapshot | undefined + /** Live Session whose removal and subagent mode gate quote and reference insertion; absent permits both. */ + session?: ObservableSnapshot> | undefined + /** The Session's composer block, resolved at each read and subscription; absent means never blocked. */ + composerBlock?: (() => ObservableSnapshot) | undefined /** Current localized quote removal copy. */ quoteRemoveLabel?: () => string /** Command-plane attachment plumbing (the hub owns the conversation face and the copy). */ @@ -140,13 +144,15 @@ export class SessionInputShell implements SessionInput { readonly state: SnapshotStore /** @inheritdoc */ readonly referenceInsertionAllowed: ObservableSnapshot = { - getSnapshot: () => !this.disposed && !frozen(this.snapshot.phase) && this.deps.sessionEditable?.getSnapshot() !== false, + getSnapshot: () => !this.disposed && !frozen(this.snapshot.phase) && this.sessionAcceptsInsertion(), subscribe: (fn) => { const offState = this.state.subscribe(fn) - const offSession = this.deps.sessionEditable?.subscribe(fn) + const offSession = this.deps.session?.subscribe(fn) + const offBlock = this.deps.composerBlock?.().subscribe(fn) return () => { offState() offSession?.() + offBlock?.() } }, } @@ -254,7 +260,7 @@ export class SessionInputShell implements SessionInput { * @returns whether the editable draft accepted the quote. */ insertQuote(text: string, summary?: QuoteSummary): boolean { - if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.sessionEditable?.getSnapshot() === false || text.trim() === '') return false + if (this.disposed || this.snapshot.phase !== 'plain' || !this.sessionAcceptsInsertion() || text.trim() === '') return false const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary) if (inserted) this.focus() return inserted @@ -343,6 +349,14 @@ export class SessionInputShell implements SessionInput { return this.disposed || frozen(this.core.state.phase) } + /** Whether the Session lets features outside the composer insert quotes or references. */ + private sessionAcceptsInsertion(): boolean { + const session = this.deps.session?.getSnapshot() + if (session !== undefined && (session.removed + || (session.subagent !== null && session.subagent.address.mode !== 'continuable'))) return false + return this.deps.composerBlock?.().getSnapshot() === undefined + } + /** Append ordered attachment ids unless an admission transaction is locked. */ addAttachments(ids: readonly DraftAttachmentId[]): boolean { if (frozen(this.snapshot.phase)) return false diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 5e30c77f1b..904fb327ea 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -25,7 +25,6 @@ import type { ComposerBlocks } from '../contract/composer-blocks.ts' import type { InputSubmitMode } from '../contract/composer-submission.ts' import type { PopupDismissFace } from './facade.ts' import { SessionInputShell } from './facade.ts' -import { sessionDraftEditable } from './draft-editability.ts' import { reportMessageSubmission } from './submission-analytics.ts' import { readConversationDraft } from '../stores.ts' @@ -158,7 +157,8 @@ export class InputHub implements SessionInputResolver { inbox: session.projections.faceOf('inbox') as ObservableSnapshot, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), - sessionEditable: sessionDraftEditable(session, () => this.conversation().blocks.storeFor(session.sessionId)), + session, + composerBlock: () => this.conversation().blocks.storeFor(session.sessionId), steerQueue: () => { void this.steerQueue(session, shell) }, commandAttachments: { serialize: async (ids) => { diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index f4c683812c..f37e7c75d1 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest' import { fireEvent, render } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' import { KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, UNDO_COMMAND, $getRoot, $getSelection, $isRangeSelection, $nodesOfType, @@ -17,7 +18,7 @@ import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' const quote = 'selected source text' -function bench(sessionEditable?: ObservableSnapshot) { +function bench(composerBlock?: () => ObservableSnapshot) { const sink = vi.fn(() => Promise.resolve({ kind: 'success' })) const shell = new SessionInputShell({ actx: {} as Context, @@ -28,7 +29,7 @@ function bench(sessionEditable?: ObservableSnapshot) { unsupportedNotice: () => 'unsupported', }, quoteRemoveLabel: () => 'Remove quote', - ...(sessionEditable === undefined ? {} : { sessionEditable }), + ...(composerBlock === undefined ? {} : { composerBlock }), }) return { shell, sink } } @@ -39,13 +40,13 @@ function quoteKeys(shell: SessionInputShell): string[] { describe('QuoteNode composer lifecycle', () => { it('preserves the draft when its Session cannot accept an inserted quote', () => { - const allowed = createSnapshotStore(false) - const { shell } = bench(allowed) + const block = createSnapshotStore({ reason: 'Unavailable' }) + const { shell } = bench(() => block) shell.setDraft('base ') const before = shell.draftSnapshot expect(shell.insertQuote(quote)).toBe(false) expect(shell.draftSnapshot).toBe(before) - allowed.set(true) + block.set(undefined) expect(shell.insertQuote(quote)).toBe(true) }) diff --git a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts index 2aa99d2b1d..753530ae91 100644 --- a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts +++ b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts @@ -2,32 +2,40 @@ /** Reference insertion from outside the composer follows Session, submission, and disposal state. */ import { expect, it, onTestFinished, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' -import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts' import type { SubmitOutcome } from '../src/client/contract/input.ts' import { SessionInputShell } from '../src/client/input/facade.ts' -import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' -import { sessionDraftEditable } from '../src/client/input/draft-editability.ts' const reference: ReferenceInsert = { source: 'reference', ref: '@"/work/a b.md"', label: 'a b.md', appearance: 'file', clipboardText: '@"/work/a b.md"', } -function bench(sessionEditable?: ObservableSnapshot) { +type SessionGate = Pick + +function bench(sources: { session?: SessionGate } = {}) { const pending = Promise.withResolvers() const sink = vi.fn(() => pending.promise) + const session = createSnapshotStore(sources.session ?? { removed: false, subagent: null }) + const block = createSnapshotStore(undefined) const shell = new SessionInputShell({ actx: {} as Context, defaultSink: sink, commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, - ...(sessionEditable === undefined ? {} : { sessionEditable }), + session, + composerBlock: () => block, }) onTestFinished(() => { shell.dispose() }) - return { shell, sink, pending } + return { shell, sink, pending, session, block } } +const child = (mode: 'one-shot' | 'continuable'): SessionGate['subagent'] => ({ + address: { parentSessionId: 'parent' as SessionId, childSessionId: 'child' as SessionId, mode }, +}) + it('inserts references without attachments and locks while a submission owns the draft', async () => { const { shell, pending } = bench() const changed = vi.fn() @@ -47,55 +55,43 @@ it('inserts references without attachments and locks while a submission owns the unsubscribe() }) -it('follows the Session policy and refuses after disposal', () => { - const editable = createSnapshotStore(false) - const { shell } = bench(editable) +it('follows Session removal, subagent mode, and composer blocks', () => { + const { shell, session, block } = bench({ session: { removed: true, subagent: null } }) const changed = vi.fn() const unsubscribe = shell.referenceInsertionAllowed.subscribe(changed) expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) expect(shell.addReferences([reference])).toBe(false) expect(shell.snapshot.draft).toBe('') - editable.set(true) + session.set({ removed: false, subagent: child('one-shot') }) expect(changed).toHaveBeenCalledOnce() + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + session.set({ removed: false, subagent: child('continuable') }) expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) + block.set({ reason: 'Unavailable' }) + expect(changed).toHaveBeenCalledTimes(3) + expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + block.set(undefined) + expect(shell.addReferences([reference])).toBe(true) unsubscribe() - editable.set(false) - expect(changed).toHaveBeenCalledOnce() - editable.set(true) + changed.mockClear() + session.set({ removed: true, subagent: null }) + block.set({ reason: 'Unavailable' }) + expect(changed).not.toHaveBeenCalled() +}) + +it('refuses after disposal and permits insertion without Session sources', () => { + const { shell } = bench() shell.dispose() expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) expect(shell.addReferences([reference])).toBe(false) -}) - -it('derives Session editability from removal, subagent mode, and composer blocks', async () => { - const runtime = await SlotTestRuntime.create() - onTestFinished(() => runtime.dispose()) - const id = 'target' as SessionId - await runtime.sessions.add({ id, summary: { cwd: '/workspace' } }) - const owner = runtime.sessions.retain(id) - onTestFinished(() => { owner.release() }) - const blocks = new ComposerBlockRegistry() - const editable = sessionDraftEditable(runtime.sessions.binding(id)!.session, () => blocks.storeFor(id)) - const changed = vi.fn() - const unsubscribe = editable.subscribe(changed) - expect(editable.getSnapshot()).toBe(true) - blocks.set(id, { reason: 'Unavailable' }) - expect(changed).toHaveBeenCalled() - expect(editable.getSnapshot()).toBe(false) - blocks.set(id, undefined) - await runtime.sessions.updateSessionSnapshot(id, (state) => { - state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } } + const bare = new SessionInputShell({ + actx: {} as Context, + defaultSink: async () => ({ kind: 'success' }), + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, }) - expect(editable.getSnapshot()).toBe(false) - await runtime.sessions.updateSessionSnapshot(id, (state) => { - state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } } - }) - expect(editable.getSnapshot()).toBe(true) - await runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true }) - expect(editable.getSnapshot()).toBe(false) + onTestFinished(() => { bare.dispose() }) + const unsubscribe = bare.referenceInsertionAllowed.subscribe(() => {}) + expect(bare.referenceInsertionAllowed.getSnapshot()).toBe(true) + expect(bare.addReferences([reference])).toBe(true) unsubscribe() - changed.mockClear() - blocks.set(id, { reason: 'Unavailable' }) - await runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = false }) - expect(changed).not.toHaveBeenCalled() }) diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts index e9d45290de..a45a5120c4 100644 --- a/packages/client/ui-reference/tests/context-menu.client.spec.ts +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -5,7 +5,6 @@ import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts' import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts' -import { sessionDraftEditable } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/draft-editability.ts' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -32,7 +31,8 @@ async function bench() { const shell = new SessionInputShell({ actx: binding.ctx, defaultSink: sink, commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, - sessionEditable: sessionDraftEditable(binding.session, () => blocks.storeFor(id)), + session: binding.session, + composerBlock: () => blocks.storeFor(id), }) onTestFinished(() => { shell.dispose() }) const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {}) From f0774ff2d1ba20f7f44d5b6d475a18a008495764 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:22:54 +0800 Subject: [PATCH 7/9] ci: compute the pre-merge merge with merge-tree in a separate process The pre-merge step fetches blobless history, so a missing blob is fetched from origin on demand. Within one `git merge` process, Git's cache of loose-object directories does not see the merged blobs the merge writes; the checkout prefetch then asks origin for those blobs, origin refuses the whole request with "not our ref", and the step reported a clean pull request as unmergeable. The step now computes the merged tree with `git merge-tree --write-tree`, commits it with `git commit-tree`, and checks it out in a separate process, and reports conflicts apart from other merge failures. Fixes #8655 --- .github/workflows/pr-check-on-head-branch.yml | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-check-on-head-branch.yml b/.github/workflows/pr-check-on-head-branch.yml index 7882c35d5b..f2d36b10af 100644 --- a/.github/workflows/pr-check-on-head-branch.yml +++ b/.github/workflows/pr-check-on-head-branch.yml @@ -87,8 +87,26 @@ jobs: if ! git merge-base "$HEAD_SHA" "$BASE_SHA" >/dev/null; then stop "the pull request shares no commit with $BASE_SHA within 150 commits of history, so nothing was merged or compiled; merge master into it and push, then this check runs again" fi - git -c user.name=pr-check -c user.email=pr-check@users.noreply.github.com merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA" || - stop "the pull request cannot merge $BASE_SHA; merge master into it and push, then this check runs again" + # The blobless history makes Git fetch missing blobs from origin on demand. Within one process, Git's cache of + # loose-object directories does not see the merged blobs it writes, so a single `git merge` asks origin for + # them while it checks out the result, and origin, which has never seen them, refuses the whole fetch. + # The merge is computed by `git merge-tree` and checked out by a separate process, which rereads the + # directories. + set +e + merge_output=$(git merge-tree --write-tree "$HEAD_SHA" "$BASE_SHA") + merge_status=$? + set -e + if [ "$merge_status" -eq 1 ]; then + echo "$merge_output" + stop "the pull request conflicts with $BASE_SHA; merge master into it and push, then this check runs again" + fi + if [ "$merge_status" -ne 0 ]; then + stop "git merge-tree could not merge $BASE_SHA (exit $merge_status), so nothing was compiled" + fi + merge_commit=$(git -c user.name=pr-check -c user.email=pr-check@users.noreply.github.com commit-tree "${merge_output%%$'\n'*}" -p "$HEAD_SHA" -p "$BASE_SHA" -m "Merge $BASE_SHA into $HEAD_SHA") || + stop "the merged tree of $BASE_SHA could not be committed, so nothing was compiled" + git checkout --quiet --detach "$merge_commit" || + stop "the merged tree of $BASE_SHA could not be checked out, so nothing was compiled" echo "merged=true" >> "$GITHUB_OUTPUT" - uses: pnpm/action-setup@v5.0.0 From 4f6e5d307591e54a89da5d1c6accf33c5191cfbb Mon Sep 17 00:00:00 2001 From: zhc Date: Tue, 17 Nov 2026 18:54:57 +0800 Subject: [PATCH 8/9] refactor(client): read reference insertion availability when the menu opens Replace the observable SessionInput.referenceInsertionAllowed with canInsertReferences(), a read that addReferences rechecks before editing. The file context menu now observes only the locale; a draft that becomes uneditable while the menu stays open reports failure on selection. The input facade reads Session and composer-block facts through plain functions, matching the quote-insertion dependency. --- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/contract/input.ts | 10 +-- .../src/client/input/facade.ts | 33 ++++------ .../ui-conversation/src/client/input/hub.ts | 4 +- .../tests/quote-composer.client.spec.tsx | 7 +- .../tests/reference-insertion.client.spec.ts | 64 ++++++++----------- packages/client/ui-reference/README.i18n.yaml | 4 +- packages/client/ui-reference/README.md | 2 +- packages/client/ui-reference/README.zh.md | 2 +- .../ui-reference/src/client/context-menu.ts | 8 +-- .../tests/context-menu.client.spec.ts | 46 +++++++------ 13 files changed, 87 insertions(+), 101 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 35fab76785..57dadf9476 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 1fbe587ec56d4622 - zh: 2b4b8400daabcc18 + en: f3f66b6795db8807 + zh: 07d092bcac4b99a2 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index e1e598ce54..b3891bdbc8 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.referenceInsertionAllowed` is the observable precondition: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set; quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.canInsertReferences()` reads the current precondition without notifying changes: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set, and `addReferences` rechecks it. Quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 74066fe810..94642ac167 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.referenceInsertionAllowed` 是可订阅的前置条件:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false;引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.canInsertReferences()` 读取当前的前置条件,不通知变化:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false,`addReferences` 执行时会再次检查。引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 36ead1e534..b93838c26f 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -198,14 +198,16 @@ export interface SessionInput extends InputTarget { /** * Insert file references after the retained selection in one undo step without replacing text. * @param references - validated reference chips in source order. - * @returns false while {@link referenceInsertionAllowed} is false or when the editor refuses insertion. + * @returns false while {@link canInsertReferences} is false or when the editor refuses insertion. */ addReferences(references: readonly ReferenceInsert[]): boolean /** - * Whether {@link addReferences} can edit the draft: false after disposal, during submission, - * for removed or non-continuable subagent Sessions, and while a composer block is set. + * Read whether {@link addReferences} can currently edit the draft. Callers read it when they + * present the operation; the answer does not notify changes, and addReferences rechecks it. + * @returns false after disposal, during submission, for removed or non-continuable subagent Sessions, + * and while a composer block is set. */ - readonly referenceInsertionAllowed: ObservableSnapshot + canInsertReferences(): boolean /** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */ removeAttachment(id: DraftAttachmentId): boolean /** Drop ids whose browser-owned objects no longer exist. */ diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 1388a7caff..393c88944c 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -73,10 +73,10 @@ export interface SessionInputDeps { signal: AbortSignal, accept: () => void, ): Promise - /** Live Session whose removal and subagent mode gate quote and reference insertion; absent permits both. */ - session?: ObservableSnapshot> | undefined - /** The Session's composer block, resolved at each read and subscription; absent means never blocked. */ - composerBlock?: (() => ObservableSnapshot) | undefined + /** Read the Session facts whose removal and subagent mode gate quote and reference insertion; absent permits both. */ + session?: (() => Pick) | undefined + /** Read the Session's current composer block; absent means never blocked. */ + composerBlock?: (() => ComposerBlock | undefined) | undefined /** Current localized quote removal copy. */ quoteRemoveLabel?: () => string /** Command-plane attachment plumbing (the hub owns the conversation face and the copy). */ @@ -142,20 +142,6 @@ const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() export class SessionInputShell implements SessionInput { /** Published editor projection + submit-plane state + queue overlay (the InputZone currency source). */ readonly state: SnapshotStore - /** @inheritdoc */ - readonly referenceInsertionAllowed: ObservableSnapshot = { - getSnapshot: () => !this.disposed && !frozen(this.snapshot.phase) && this.sessionAcceptsInsertion(), - subscribe: (fn) => { - const offState = this.state.subscribe(fn) - const offSession = this.deps.session?.subscribe(fn) - const offBlock = this.deps.composerBlock?.().subscribe(fn) - return () => { - offState() - offSession?.() - offBlock?.() - } - }, - } /** Latest surfaced notice (null after clear); the bar renders errors as banners and information inline. */ readonly notices: SnapshotStore = createSnapshotStore(null) /** The shell-owned editor (text + chip truth); the composer binds its contenteditable to it. */ @@ -351,10 +337,10 @@ export class SessionInputShell implements SessionInput { /** Whether the Session lets features outside the composer insert quotes or references. */ private sessionAcceptsInsertion(): boolean { - const session = this.deps.session?.getSnapshot() + const session = this.deps.session?.() if (session !== undefined && (session.removed || (session.subagent !== null && session.subagent.address.mode !== 'continuable'))) return false - return this.deps.composerBlock?.().getSnapshot() === undefined + return this.deps.composerBlock?.() === undefined } /** Append ordered attachment ids unless an admission transaction is locked. */ @@ -386,10 +372,15 @@ export class SessionInputShell implements SessionInput { * @returns whether the draft accepted the references. */ addReferences(references: readonly ReferenceInsert[]): boolean { - if (!this.referenceInsertionAllowed.getSnapshot()) return false + if (!this.canInsertReferences()) return false return this.addFiles(references, []) } + /** @inheritdoc */ + canInsertReferences(): boolean { + return !this.disposed && !frozen(this.snapshot.phase) && this.sessionAcceptsInsertion() + } + /** * Remove one attachment id from this draft. Busy admission phases refuse, like * {@link addAttachments}: a removal landing while a send serializes would diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 904fb327ea..7844495e2e 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -157,8 +157,8 @@ export class InputHub implements SessionInputResolver { inbox: session.projections.faceOf('inbox') as ObservableSnapshot, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), - session, - composerBlock: () => this.conversation().blocks.storeFor(session.sessionId), + session: () => session.getSnapshot(), + composerBlock: () => this.conversation().blocks.storeFor(session.sessionId).getSnapshot(), steerQueue: () => { void this.steerQueue(session, shell) }, commandAttachments: { serialize: async (ids) => { diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index f37e7c75d1..2235dae9bb 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { fireEvent, render } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' -import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' import { KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, UNDO_COMMAND, @@ -18,7 +17,7 @@ import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' const quote = 'selected source text' -function bench(composerBlock?: () => ObservableSnapshot) { +function bench(composerBlock?: () => ComposerBlock | undefined) { const sink = vi.fn(() => Promise.resolve({ kind: 'success' })) const shell = new SessionInputShell({ actx: {} as Context, @@ -40,13 +39,13 @@ function quoteKeys(shell: SessionInputShell): string[] { describe('QuoteNode composer lifecycle', () => { it('preserves the draft when its Session cannot accept an inserted quote', () => { - const block = createSnapshotStore({ reason: 'Unavailable' }) + let block: ComposerBlock | undefined = { reason: 'Unavailable' } const { shell } = bench(() => block) shell.setDraft('base ') const before = shell.draftSnapshot expect(shell.insertQuote(quote)).toBe(false) expect(shell.draftSnapshot).toBe(before) - block.set(undefined) + block = undefined expect(shell.insertQuote(quote)).toBe(true) }) diff --git a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts index 753530ae91..c35507a9d5 100644 --- a/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts +++ b/packages/client/ui-conversation/tests/reference-insertion.client.spec.ts @@ -4,7 +4,6 @@ import { expect, it, onTestFinished, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts' import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts' import type { SubmitOutcome } from '../src/client/contract/input.ts' @@ -16,73 +15,62 @@ const reference: ReferenceInsert = { type SessionGate = Pick -function bench(sources: { session?: SessionGate } = {}) { +function bench() { const pending = Promise.withResolvers() const sink = vi.fn(() => pending.promise) - const session = createSnapshotStore(sources.session ?? { removed: false, subagent: null }) - const block = createSnapshotStore(undefined) + const sources: { session: SessionGate; block: ComposerBlock | undefined } = { + session: { removed: false, subagent: null }, block: undefined, + } const shell = new SessionInputShell({ actx: {} as Context, defaultSink: sink, commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, - session, - composerBlock: () => block, + session: () => sources.session, + composerBlock: () => sources.block, }) onTestFinished(() => { shell.dispose() }) - return { shell, sink, pending, session, block } + return { shell, sink, pending, sources } } const child = (mode: 'one-shot' | 'continuable'): SessionGate['subagent'] => ({ address: { parentSessionId: 'parent' as SessionId, childSessionId: 'child' as SessionId, mode }, }) -it('inserts references without attachments and locks while a submission owns the draft', async () => { +it('inserts references without attachments and refuses while a submission owns the draft', async () => { const { shell, pending } = bench() - const changed = vi.fn() - const unsubscribe = shell.referenceInsertionAllowed.subscribe(changed) - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) + expect(shell.canInsertReferences()).toBe(true) shell.setDraft('Review') expect(shell.addReferences([reference])).toBe(true) expect(shell.snapshot.draft).toBe('Review @"/work/a b.md" ') expect(shell.snapshot.attachmentIds).toEqual([]) - changed.mockClear() shell.submit() - expect(changed).toHaveBeenCalled() - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + expect(shell.canInsertReferences()).toBe(false) expect(shell.addReferences([reference])).toBe(false) pending.resolve({ kind: 'success' }) - await vi.waitFor(() => { expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) }) - unsubscribe() + await vi.waitFor(() => { expect(shell.canInsertReferences()).toBe(true) }) }) -it('follows Session removal, subagent mode, and composer blocks', () => { - const { shell, session, block } = bench({ session: { removed: true, subagent: null } }) - const changed = vi.fn() - const unsubscribe = shell.referenceInsertionAllowed.subscribe(changed) - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) +it('reads Session removal, subagent mode, and composer blocks at each call', () => { + const { shell, sources } = bench() + sources.session = { removed: true, subagent: null } + expect(shell.canInsertReferences()).toBe(false) expect(shell.addReferences([reference])).toBe(false) expect(shell.snapshot.draft).toBe('') - session.set({ removed: false, subagent: child('one-shot') }) - expect(changed).toHaveBeenCalledOnce() - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) - session.set({ removed: false, subagent: child('continuable') }) - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(true) - block.set({ reason: 'Unavailable' }) - expect(changed).toHaveBeenCalledTimes(3) - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) - block.set(undefined) + sources.session = { removed: false, subagent: child('one-shot') } + expect(shell.canInsertReferences()).toBe(false) + sources.session = { removed: false, subagent: child('continuable') } + expect(shell.canInsertReferences()).toBe(true) + sources.block = { reason: 'Unavailable' } + expect(shell.canInsertReferences()).toBe(false) + expect(shell.addReferences([reference])).toBe(false) + sources.block = undefined expect(shell.addReferences([reference])).toBe(true) - unsubscribe() - changed.mockClear() - session.set({ removed: true, subagent: null }) - block.set({ reason: 'Unavailable' }) - expect(changed).not.toHaveBeenCalled() }) it('refuses after disposal and permits insertion without Session sources', () => { const { shell } = bench() shell.dispose() - expect(shell.referenceInsertionAllowed.getSnapshot()).toBe(false) + expect(shell.canInsertReferences()).toBe(false) expect(shell.addReferences([reference])).toBe(false) const bare = new SessionInputShell({ actx: {} as Context, @@ -90,8 +78,6 @@ it('refuses after disposal and permits insertion without Session sources', () => commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, }) onTestFinished(() => { bare.dispose() }) - const unsubscribe = bare.referenceInsertionAllowed.subscribe(() => {}) - expect(bare.referenceInsertionAllowed.getSnapshot()).toBe(true) + expect(bare.canInsertReferences()).toBe(true) expect(bare.addReferences([reference])).toBe(true) - unsubscribe() }) diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index 6ebc380001..8d66300915 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -18,8 +18,8 @@ en: 779a9a534eaad38b zh: 3dd159a2c35702d6 /deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts: - en: 27ca6ef7a0fbe913 - zh: aa413e010a563593 + en: 43b5324fb871a3d1 + zh: 3d101edc38b60d39 /deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions: en: 87c27115eae5a660 zh: a9a20431928072ec diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index 3f8ff4ff8d..5b1e3c9eca 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -33,7 +33,7 @@ A file closes completion as an atomic inline reference displayed with a file gly A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`. -The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited or the path cannot use the mention grammar. An open menu updates its label and failure feedback when the interface language changes. +The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited at the moment the menu opens or the path cannot use the mention grammar; a draft that becomes uneditable while the menu stays open makes the action report failure instead of inserting. An open menu updates its label and failure feedback when the interface language changes. ### Sent file and folder mentions diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index 24098027be..2dbbc7b76d 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -33,7 +33,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。 -共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。Session 不可编辑或路径无法用 mention 语法表示时,此入口不可用。切换界面语言时,已打开菜单的标题和失败提示随之更新。 +共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。打开菜单时 Session 不可编辑,或路径无法用 mention 语法表示时,此入口不可用;菜单打开期间草稿变为不可编辑时,点击会提示失败而不插入。切换界面语言时,已打开菜单的标题和失败提示随之更新。 ### 已发送的文件与目录引用 diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts index 3d01a6864b..7e13b3d876 100644 --- a/packages/client/ui-reference/src/client/context-menu.ts +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -21,15 +21,13 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st if (binding === undefined) return undefined const input = ctx.conversation.input.for(binding.ctx) // A released or replaced binding must not receive the reference captured for its predecessor. - const editable = (): boolean => ctx.sessions.binding(sessionId) === binding && input.referenceInsertionAllowed.getSnapshot() + const editable = (): boolean => ctx.sessions.binding(sessionId) === binding && input.canInsertReferences() return { input, editable } } ctx.effect(() => ctx.contextMenus.register({ id: 'reference.file', target: 'file', order: 300, - observe: (target) => { - const current = targetInput(target) - return current === undefined ? [ctx.locale] : [ctx.locale, current.input.referenceInsertionAllowed] - }, + // Draft editability is read when the menu opens; run rechecks it before inserting. + observe: () => [ctx.locale], resolve: (target) => { const current = targetInput(target) const path = resolveWorkspacePath(ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd, target.path) diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts index a45a5120c4..aa67881729 100644 --- a/packages/client/ui-reference/tests/context-menu.client.spec.ts +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -31,8 +31,8 @@ async function bench() { const shell = new SessionInputShell({ actx: binding.ctx, defaultSink: sink, commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token }, - session: binding.session, - composerBlock: () => blocks.storeFor(id), + session: () => binding.session.getSnapshot(), + composerBlock: () => blocks.storeFor(id).getSnapshot(), }) onTestFinished(() => { shell.dispose() }) const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {}) @@ -100,13 +100,25 @@ it('disables an unretained Session and never opens it or targets another draft', expect(b.shell.snapshot.draft).toBe('') }) -it('tracks composer blocks and rejects a stale Session binding at execution', async () => { +it('reads composer blocks when the menu opens and rechecks them at execution', async () => { + const b = await bench() + b.blocks.set(id, { reason: 'Unavailable' }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) + b.blocks.set(id, undefined) + const menu = await b.menu() + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + b.blocks.set(id, { reason: 'Unavailable' }) + // An open menu keeps the state read when it opened; execution refuses the stale action. + expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + menu.select(actionId) + expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) + expect(b.shell.snapshot.draft).toBe('') + expect(b.focus).not.toHaveBeenCalled() +}) + +it('rejects a stale Session binding at execution', async () => { const b = await bench() const menu = await b.menu() - b.blocks.set(id, { reason: 'Unavailable' }) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) - b.blocks.set(id, undefined) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) b.owner.release() menu.select(actionId) expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed']) @@ -115,32 +127,31 @@ it('tracks composer blocks and rejects a stale Session binding at execution', as it('disables removed and one-shot Sessions but permits continuable Sessions', async () => { const b = await bench() - const menu = await b.menu() await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true }) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = false state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } } }) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } } }) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) }) -it('tracks submission locks without treating a running turn as an editing lock', async () => { +it('disables the action while a submission owns the draft but not while a turn runs', async () => { const b = await bench() const pending = Promise.withResolvers<{ kind: 'success' }>() b.sink.mockImplementation(() => pending.promise) - const menu = await b.menu() await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.running = true }) - expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) b.shell.setDraft('Sending') b.shell.submit() - expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) pending.resolve({ kind: 'success' }) - await vi.waitFor(() => { expect(menu.source.getSnapshot()[0]?.disabled).toBe(false) }) + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false) }) it('reports insertion refusal without focusing or sending', async () => { @@ -193,10 +204,9 @@ it.each(['/work/a b.md', 'C:\\work\\a b.md', '\\\\server\\share\\a b.md', '/work it('disables the action and refuses direct insertion after the draft editor is disposed', async () => { const b = await bench() - const menu = await b.menu() b.shell.setDraft('Keep this') b.shell.dispose() - expect(menu.source.getSnapshot()[0]?.disabled).toBe(true) + expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true) expect(b.shell.addReferences([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }])).toBe(false) expect(b.shell.snapshot.draft).toBe('Keep this') }) From b1e7c5895316331d322d54e42dbecf063359437d Mon Sep 17 00:00:00 2001 From: Turtle 2099 Date: Tue, 17 Nov 2026 19:40:45 +0800 Subject: [PATCH 9/9] Merge pull request #8643 from deepseek-harness/turtle/fix-discussion-13531-d4b7fadf9b60 fix(tool-fs): copy read and glob meta text off the input string --- .../conversation-and-session.i18n.yaml | 3 + .../conversation-and-session.md | 20 +++++ .../conversation-and-session.zh.md | 20 +++++ .../fs/tool-fs-search/src/presentation.ts | 11 ++- .../tests/presentation-retention.spec.ts | 37 ++++++++++ packages/fs/tool-fs/src/read-render.ts | 46 ++++++++---- .../tests/read-render-retention.spec.ts | 73 +++++++++++++++++++ packages/fs/tool-fs/tests/read-render.spec.ts | 15 ++++ 8 files changed, 210 insertions(+), 15 deletions(-) create mode 100644 packages/fs/tool-fs-search/tests/presentation-retention.spec.ts create mode 100644 packages/fs/tool-fs/tests/read-render-retention.spec.ts diff --git a/docs/defensive-patterns/conversation-and-session.i18n.yaml b/docs/defensive-patterns/conversation-and-session.i18n.yaml index d8d0fcc6ae..0de6555a49 100644 --- a/docs/defensive-patterns/conversation-and-session.i18n.yaml +++ b/docs/defensive-patterns/conversation-and-session.i18n.yaml @@ -14,6 +14,9 @@ /conversation-and-session-rules/retention-follows-one-lifecycle-rule: en: fcb40a31d0881e84 zh: 779bc49cce81651e +/conversation-and-session-rules/retained-excerpts-do-not-keep-their-source-string-alive: + en: 6834b8020ee324b5 + zh: 10e76904d1470cec /conversation-and-session-rules/node-computation-is-incremental-and-streaming-publication-is-batched: en: 315c7ac2186d0721 zh: 06bb4e072b242fe1 diff --git a/docs/defensive-patterns/conversation-and-session.md b/docs/defensive-patterns/conversation-and-session.md index c8fe7af265..f8e4d74daa 100644 --- a/docs/defensive-patterns/conversation-and-session.md +++ b/docs/defensive-patterns/conversation-and-session.md @@ -125,6 +125,26 @@ export function reclaimIdle(): void { Nobody can count who still uses the Session, and the next state added to the Session escapes the enumeration and is never reclaimed. +## Retained excerpts do not keep their source string alive + +Session events, tool result `meta`, and other values kept for a Session's lifetime copy any excerpt taken from a large transient string, such as decoded file text or command output. In V8, a `slice`, `substring`, `split` piece, or regular-expression capture of 13 or more characters can reference its whole parent string, a concatenation references its parts, and `Session.append` copies objects but not string storage. A 200-character line kept in `meta` can therefore keep a 16 MB file in memory until the Session closes. + +- Judged condition: can a retained string be an excerpt of a larger string that would otherwise be garbage? The excerpt is copied with `Buffer.from(text, 'utf16le').toString('utf16le')` before it is retained, and a test drops a heap-allocated source, forces garbage collection, and checks that heap usage does not grow with the source size. +- Boundary: the rule applies to excerpts that outlive the operation. It does not apply when the source itself is retained or when the value comes from `JSON.parse`, `TextDecoder`, or `Buffer#toString`. `String()`, `slice(0)`, `trim()`, `'' + text`, and `join` can return the input string itself and are not copies. +- Ownership: the code that takes the excerpt copies it; the Session does not copy strings on append. + +The `read` tool copies a returned line once when it was built from a slice: + +```ts ignore-check +const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer +``` + +Keeping the slice keeps the decoded file: + +```ts ignore-check +const line = lineBuffer // may be a slice of the whole decoded file +``` + ## Node computation is incremental and streaming publication is batched A new node computation states its complexity, and high-frequency streaming chunks never publish immediately and never recompute in full. A per-chunk full rebuild published at once puts the whole node collection on the frame budget, and the transcript stalls behind the stream. The append-path cost — with `D` registered Definitions, `D` matches and one constant-time Context-key lookup — and the publication vocabulary (`none`, `animation-frame`, `immediate`) are owned by [conversation.md](../subsystems/conversation.md#definition-and-typed-chat-payload). diff --git a/docs/defensive-patterns/conversation-and-session.zh.md b/docs/defensive-patterns/conversation-and-session.zh.md index b1281c6b5d..be3696f759 100644 --- a/docs/defensive-patterns/conversation-and-session.zh.md +++ b/docs/defensive-patterns/conversation-and-session.zh.md @@ -125,6 +125,26 @@ export function reclaimIdle(): void { 没有人能数清谁仍在使用该 Session,下一个新增的 Session 状态也会漏出枚举、永远不被回收。 +## 保留的摘录不会让来源字符串常驻内存 + +Session 事件、工具结果的 `meta`,以及其他在 Session 生命周期内保留的值,若取自大型临时字符串(例如解码后的文件文本或命令输出)的摘录,都要先复制该摘录。在 V8 中,长度不少于 13 个字符的 `slice`、`substring`、`split` 片段或正则表达式捕获可能引用整个父字符串,拼接结果会引用其各个组成部分,而 `Session.append` 复制对象,不复制字符串存储。因此,`meta` 中保留的一行 200 个字符的文本可能让一个 16 MB 的文件一直留在内存中,直到 Session 关闭。 + +- 判定条件:被保留的字符串是否可能是某个更大字符串的摘录,而该更大字符串本应被垃圾回收?摘录在保留之前用 `Buffer.from(text, 'utf16le').toString('utf16le')` 复制;测试丢弃一个分配在堆上的来源字符串、强制垃圾回收,并检查堆内存用量不随来源大小增长。 +- 边界:该规则适用于存活时间超过本次操作的摘录。来源本身被保留,或值来自 `JSON.parse`、`TextDecoder` 或 `Buffer#toString` 时,该规则不适用。`String()`、`slice(0)`、`trim()`、`'' + text` 和 `join` 可能返回输入字符串本身,不算复制。 +- 归口:截取摘录的代码负责复制;Session 在 append 时不复制字符串。 + +返回行由 slice 拼成时,`read` 工具把它复制一次: + +```ts ignore-check +const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer +``` + +保留 slice 会把解码后的文件一并保留: + +```ts ignore-check +const line = lineBuffer // may be a slice of the whole decoded file +``` + ## 节点计算是增量的,流式发布是合批的 新增节点计算要说明其复杂度;高频流式 chunk 绝不立即发布、也不做全量计算。每个 chunk 全量重算并立即发布,等于把整个节点集合压进帧预算,转写区便会堵在流后面。追加速路径的开销——在 `D` 个已注册 Definition 下执行 `D` 次匹配与一次常量级 Context key 查找——以及发布节拍取值(`none`、`animation-frame`、`immediate`)归 [conversation.zh.md](../subsystems/conversation.zh.md#definition-and-typed-chat-payload)。 diff --git a/packages/fs/tool-fs-search/src/presentation.ts b/packages/fs/tool-fs-search/src/presentation.ts index 5597c74378..e943795eb6 100644 --- a/packages/fs/tool-fs-search/src/presentation.ts +++ b/packages/fs/tool-fs-search/src/presentation.ts @@ -137,11 +137,18 @@ export function grepSearchMeta(retained: RetainedPage, maxMetaBytes: return capMetaBytes(meta, maxMetaBytes) } +// Glob paths are V8 substrings of ripgrep's whole stdout, and the Session keeps `meta` for its +// lifetime. A UTF-16LE round trip copies each path so the stdout string can be garbage-collected. +function detachText(text: string): string { + return Buffer.from(text, 'utf16le').toString('utf16le') +} + /** * Project the retained `glob` paths into {@link SearchMeta} for the search card. * Consumes the same {@link RetainedItems} the model-facing render consumes (inline * path cap already applied), reports `total` (every discovered path) and - * `truncated`, then bounds the serialized meta to `maxMetaBytes`. + * `truncated`, then bounds the serialized meta to `maxMetaBytes`. Returned paths hold no reference + * to the strings in `retained`. * * @param retained - the retention outcome over every discovered path (capped). * @param maxMetaBytes - the serialized-meta byte budget. @@ -150,7 +157,7 @@ export function grepSearchMeta(retained: RetainedPage, maxMetaBytes: export function globSearchMeta(retained: RetainedPage, maxMetaBytes: number): SearchMeta { const meta: SearchMeta = { shape: 'paths', - paths: retained.items, + paths: retained.items.map(detachText), truncated: retained.truncated, total: retained.seen, } diff --git a/packages/fs/tool-fs-search/tests/presentation-retention.spec.ts b/packages/fs/tool-fs-search/tests/presentation-retention.spec.ts new file mode 100644 index 0000000000..58848efe9e --- /dev/null +++ b/packages/fs/tool-fs-search/tests/presentation-retention.spec.ts @@ -0,0 +1,37 @@ +/** + * Memory retention of `glob` search metadata: paths split from a large ripgrep stdout string must + * not keep that string alive once the Session holds only the metadata. The case forces full + * garbage collection and checks that heap usage returns near its baseline. + */ + +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import { expect, it } from 'vitest' +import { globSearchMeta } from '../src/presentation.ts' +import type { SearchMeta } from '../src/presentation.ts' + +setFlagsFromString('--expose-gc') +const collect = runInNewContext('gc') as () => void + +const STDOUT_CHARS = 32 * 1024 * 1024 + +function fullGc(): void { + collect() + collect() +} + +function metaFromLargeStdout(): SearchMeta { + const line = `src/${'nested/'.repeat(20)}file.ts\n` + const stdout = line.repeat(Math.ceil(STDOUT_CHARS / line.length)) + const paths = stdout.split('\n', 3) + return globSearchMeta({ items: paths, truncated: true, seen: paths.length }, 1_000_000) +} + +it('globSearchMeta drops the stdout string behind its paths', () => { + fullGc() + const before = process.memoryUsage().heapUsed + const meta = metaFromLargeStdout() + fullGc() + expect(process.memoryUsage().heapUsed - before).toBeLessThan(STDOUT_CHARS / 4) + expect(meta).toMatchObject({ shape: 'paths', paths: Array.from({ length: 3 }, () => `src/${'nested/'.repeat(20)}file.ts`) }) +}) diff --git a/packages/fs/tool-fs/src/read-render.ts b/packages/fs/tool-fs/src/read-render.ts index 13a849f011..28ab9782d9 100644 --- a/packages/fs/tool-fs/src/read-render.ts +++ b/packages/fs/tool-fs/src/read-render.ts @@ -29,7 +29,7 @@ export interface ReadWindow { export interface FileTextLine { /** 1-based line number in the file. */ number: number - /** Line text without its trailing newline. */ + /** Line text without its trailing newline; from {@link buildWindow}, it references no string larger than one input chunk. */ text: string } @@ -74,9 +74,14 @@ function lineByteSize(line: string, currentLineCount: number): number { return Buffer.byteLength(line, 'utf8') + (currentLineCount > 0 ? 1 : 0) } +function wantsNextLine(acc: WindowAccumulator, request: ReadWindow): boolean { + return !acc.truncatedByBytes && acc.totalLines + 1 >= request.offset && acc.lines.length < request.limit +} + function consumeLine(acc: WindowAccumulator, rawLine: string, request: ReadWindow): void { + const wanted = wantsNextLine(acc, request) acc.totalLines += 1 - if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return + if (!wanted) return const text = truncateLine(rawLine, request.maxLineLength) const bytes = lineByteSize(text, acc.lines.length) @@ -103,7 +108,8 @@ function finish(acc: WindowAccumulator, request: ReadWindow, displayPath: string * Build one window from streamed or whole-file chunks, enforcing line and byte caps while still * scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is * past EOF. - * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning. + * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning. A kept line + * that is a whole chunk is returned as that chunk, so a chunk must not be a substring of a larger string. * @param request - the resolved window; the caller has already applied its defaults and caps. * @param displayPath - the caller-facing path used in the offset-out-of-range error. * @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag. @@ -114,32 +120,46 @@ export async function buildWindow( displayPath: string, ): Promise { const acc = newAccumulator() - // One char past the truncation point is enough to prove a line overflows. - const lineBufferCap = request.maxLineLength + 1 + // Two chars past the truncation point still prove a line overflows after a trailing `\r` is stripped. + const lineBufferCap = request.maxLineLength + 2 let lineBuffer = '' + let lineHasText = false + let lineHasSlice = false - function appendToLineBuffer(segment: string): void { - if (lineBuffer.length >= lineBufferCap) return - lineBuffer += segment - if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap) + // Only lines the window still wants are collected, up to the truncation point. + function appendToLineBuffer(chunk: string, start: number, end: number): void { + const stop = Math.min(end, start + lineBufferCap - lineBuffer.length) + if (stop <= start || !wantsNextLine(acc, request)) return + if (start === 0 && stop === chunk.length) { + lineBuffer += chunk + } else { + lineBuffer += chunk.slice(start, stop) + lineHasSlice = true + } } function flushLine(): void { - consumeLine(acc, stripCarriageReturn(lineBuffer), request) + // A slice keeps its whole chunk alive, and kept lines outlive the read, so a line built from a + // slice is copied once; a UTF-16LE round trip keeps lone surrogates. + const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer + consumeLine(acc, stripCarriageReturn(line), request) lineBuffer = '' + lineHasSlice = false } for await (const chunk of chunks) { let startPos = 0 let newlinePos: number while ((newlinePos = chunk.indexOf('\n', startPos)) !== -1) { - appendToLineBuffer(chunk.slice(startPos, newlinePos)) + appendToLineBuffer(chunk, startPos, newlinePos) flushLine() + lineHasText = false startPos = newlinePos + 1 } - appendToLineBuffer(chunk.slice(startPos)) + appendToLineBuffer(chunk, startPos, chunk.length) + if (startPos < chunk.length) lineHasText = true } - if (lineBuffer.length > 0) flushLine() + if (lineHasText) flushLine() return finish(acc, request, displayPath) } diff --git a/packages/fs/tool-fs/tests/read-render-retention.spec.ts b/packages/fs/tool-fs/tests/read-render-retention.spec.ts new file mode 100644 index 0000000000..f3610846c6 --- /dev/null +++ b/packages/fs/tool-fs/tests/read-render-retention.spec.ts @@ -0,0 +1,73 @@ +/** + * Memory retention of returned read lines: a short retained line must not keep the decoded input + * string alive after the caller drops it. Each case scans a large input string, keeps only + * the returned window, forces full garbage collection, and checks that heap usage returns near its + * baseline instead of staying at the input size. The input is allocated on the V8 heap because Node + * frees external string memory asynchronously, which makes `memoryUsage().external` unstable here. + * The cases cover whole-file and streamed input, lines that span chunks, and truncated lines. + */ + +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import { describe, expect, it } from 'vitest' +import { buildWindow, READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from '../src/read-render.ts' +import type { FileTextLine } from '../src/read-render.ts' + +setFlagsFromString('--expose-gc') +const collect = runInNewContext('gc') as () => void + +const INPUT_CHARS = 32 * 1024 * 1024 +const RETAINED_LIMIT = INPUT_CHARS / 4 + +function fullGc(): void { + collect() + collect() +} + +function largeText(line: string): string { + return `${line}\r\n`.repeat(Math.ceil(INPUT_CHARS / (line.length + 2))) +} + +/** Measure the heap still held after `buildWindow` scans a large input and only its lines are kept. */ +async function measure( + line: string, + chunking: 'whole' | 'stream' | 'mid-line', + maxLineLength: number, +): Promise<{ bytes: number; lines: FileTextLine[] }> { + async function* chunks(): AsyncIterable { + const input = largeText(line) + if (chunking === 'whole') { + yield input + return + } + let at = 0 + if (chunking === 'mid-line') { + // Chunk boundaries fall inside lines 2-4, so each kept line joins two chunks. + for (const end of [1, 2, 3].map(index => index * (line.length + 2) + 100)) { + yield input.slice(at, end) + at = end + } + } + for (; at < input.length; at += 1024 * 1024) yield input.slice(at, at + 1024 * 1024) + } + fullGc() + const before = process.memoryUsage().heapUsed + const window = await buildWindow(chunks(), { offset: 2, limit: 3, maxLineLength, maxBytes: READ_MAX_BYTES }, 'f') + fullGc() + return { bytes: process.memoryUsage().heapUsed - before, lines: window.lines } +} + +describe('buildWindow retention', () => { + it.each([ + ['whole-file ASCII lines', 'a'.repeat(200), 'whole', READ_MAX_LINE_LENGTH], + ['whole-file two-byte lines', '中'.repeat(200), 'whole', READ_MAX_LINE_LENGTH], + ['streamed lines', 'c'.repeat(200), 'stream', READ_MAX_LINE_LENGTH], + ['lines that span chunks', 'd'.repeat(200), 'mid-line', READ_MAX_LINE_LENGTH], + ['truncated lines', 'e'.repeat(5000), 'whole', 100], + ] as const)('drops the decoded input behind %s', async (_name, line, chunking, maxLineLength) => { + const { bytes, lines } = await measure(line, chunking, maxLineLength) + const text = line.length > maxLineLength ? `${line.slice(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line + expect(lines).toEqual([2, 3, 4].map(number => ({ number, text }))) + expect(bytes).toBeLessThan(RETAINED_LIMIT) + }) +}) diff --git a/packages/fs/tool-fs/tests/read-render.spec.ts b/packages/fs/tool-fs/tests/read-render.spec.ts index df93824393..3bf8d8414d 100644 --- a/packages/fs/tool-fs/tests/read-render.spec.ts +++ b/packages/fs/tool-fs/tests/read-render.spec.ts @@ -84,6 +84,21 @@ describe('buildWindow', () => { expect(result.lines[0]?.text).toBe('abcde... (line truncated to 5 chars)') }) + it('truncates a long line whose lone \\r falls right after the truncation point', async () => { + const result = await buildWindow(whole('abcde\rXYZ\nnext'), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f') + expect(result.lines[0]?.text).toBe('abcde... (line truncated to 5 chars)') + }) + + it('keeps a CRLF line of exactly maxLineLength chars whole', async () => { + const result = await buildWindow(chunked('abcde\r\nnext', 3), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f') + expect(result.lines).toEqual([{ number: 1, text: 'abcde' }, { number: 2, text: 'next' }]) + }) + + it('keeps the lone high surrogate left by truncating inside a surrogate pair', async () => { + const result = await buildWindow(whole('abcd😀z'), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f') + expect(result.lines[0]?.text).toBe('abcd\uD83D... (line truncated to 5 chars)') + }) + it('caps output at a custom maxBytes', async () => { const result = await buildWindow(whole('aaaa\nbbbb\ncccc'), { offset: 1, limit: 10, maxLineLength: 2000, maxBytes: 9 }, 'f') expect(result.lines.map(l => l.text)).toEqual(['aaaa', 'bbbb'])