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') })