diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml index 68269e8997..93432e3ee9 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml @@ -15,8 +15,8 @@ en: 7f33895364a9f5cc zh: f1c79ea15f5c151e /agent-note-initial-draft-content-and-structured-reference-restoration/decision/classes-and-methods: - en: e57394545d9d93ff - zh: 5ab142e661750b82 + en: 9039c6bf700da3cf + zh: 2808757aed8615b3 /agent-note-initial-draft-content-and-structured-reference-restoration/decision/data-flow: en: dd57e639e9328f1d zh: 5e16cb2e3a73597c diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md index cbb15cc56a..24355ccf35 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md @@ -37,7 +37,7 @@ The existing `dsh.conversation.` key remains. Readers accept both leg | `SessionInputShell.refreshLexiconSubscription()` / `DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` owns the Session-scope `inject` callback that connects the lexicon after caching the shell, reconnects when the service arrives or is replaced, and unsubscribes on disposal. Both connection and catalog updates rescan the current editor without writing old text back; `setDraft` does not establish the subscription | | `ConversationStoreState` / `createConversationStore` | Support structured input and legacy strings in draft storage, keeping View state and the original key | | `DefaultConversationViews` | Remove restoration and prefill effects, retaining persistence binding and unbinding. Initial saving reads the owner's current snapshot, never text captured during render | -| The existing `selectWorkspace` callback in `apply.ts` | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | +| The cross-Workspace draft move (`moveDraft` in `apply.ts`) | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | There is no new draft service, storage key, general task framework, or Session creation entry point. SlotRenderer, Host Session logs, command execution, and file-discovery RPCs are unchanged. `InputActions` remains the shared input-action entry; components receive no separate content-initialization callback. diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md index 12d4e4731a..8a3a964e95 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md @@ -37,7 +37,7 @@ Status: implemented | `SessionInputShell.refreshLexiconSubscription()`/`DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` 拥有 Session scope 的 `inject` 回调,在缓存输入对象后连接词典,服务到达或替换时重接,销毁时退订。连接和词典更新都会重扫当前 editor,不覆盖旧文本;`setDraft` 不负责建立订阅 | | `ConversationStoreState`/`createConversationStore` | draft 支持兼容旧字符串的结构化输入,View 状态及原 key 保持 | | `DefaultConversationViews` | 删除恢复/预填 effect;保留持久化回调的绑定和解绑。初始保存只能读取 owner 的当前快照,不能把 render 时的旧文字写回 | -| `apply.ts` 中现有 `selectWorkspace` 回调 | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | +| 跨工作区的草稿移动(`apply.ts` 中的 `moveDraft`) | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | 不新增草稿服务、存储 key、通用任务框架或另一套 Session 创建入口;不改 SlotRenderer、Host Session 日志、命令执行和文件发现 RPC。`InputActions` 保留统一输入操作入口,组件不单独注入另一条内容初始化回调。 diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index b414ed28b1..578e4e9188 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: 27f5c34d34e96053 - zh: 2a7c1b04eb3b0505 + en: 1ef2a3b18c8cd023 + zh: f646e719c1397894 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 3017d5264d..cd71641498 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -106,7 +106,7 @@ A claimed command is one atomic chip at the start of the draft, and the claim la Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft content, including structured references, and attachments move in its synchronous preparation callback only while that request is current and no submission is in flight; later navigation, owner disposal, or a submission in flight leaves the original draft in its Session. -The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. An embedded occurrence may also pass `onWorkspaceSession`: it receives the blank Session of a Workspace the Hero's picker chose, retains it, and shows it, and the draft moves to that Session without it opening as the main Session. The handover runs in one synchronous step once the Workspace connects, and only for the latest pick of an occurrence that is still mounted, so a pick that connects after another pick or after the owner left changes nothing; the Session the draft leaves stays retained through the step, so the owner may release it there. A pick whose Workspace cannot connect shows a transient notice over the conversation and keeps the draft. An embedded occurrence may also pass `headline`, which replaces the Hero headline and preview badge. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. +The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. Every occurrence passes `onWorkspaceSelected`, which decides what a Workspace picked in the Hero does. It receives the Workspace and an `adopt` function, resolves that Workspace's blank Session, shows it in place of the Session shown before, and calls `adopt` with it in the same step while it retains both Sessions; `adopt` moves the draft. The main occurrence opens the blank as the main Session, and an embedded owner may show it itself. A pick the owner no longer wants resolves without calling `adopt`; a failed pick rejects, its owner reports the failure, and the Hero returns to the Workspace it showed. An embedded occurrence may also pass `headline`, which replaces the Hero headline and preview badge. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident header keeps the blank-Session 40px row on every platform, so the Hero input card sits at the same height before and after a Workspace is bound; on macOS desktop that row is also the window drag row. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. When the title and actions do not fit, the title area clips them and fades its trailing edge before the utilities, which stay fully visible and clickable; overlays in the title and actions slots portal to stay outside that clip. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index b93b5dbf03..38cf1e48f6 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -106,7 +106,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿内容(包括结构化引用)和附件仅在该请求仍为当前请求、且没有在途提交时,通过它的同步准备回调搬移;后续导航、所有者释放或在途提交都会把原草稿留在它的 Session 中。 -本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。嵌入式 occurrence 还可以传入 `onWorkspaceSession`:它接收 Hero 选择器所选工作区的空白 Session,由它保留并显示该 Session;草稿随之移过去,该 Session 不作为主 Session 打开。工作区连接完成后,交接在一个同步步骤内完成,并且只对仍挂载的 occurrence 的最后一次选择进行,因此在另一次选择之后、或 owner 离开之后才连接完成的选择不改变任何状态;草稿所在的 Session 在这一步期间保持保留,owner 可以在其中释放它。工作区无法连接时,在对话上方显示短暂提示,草稿保持不动。嵌入式 occurrence 也可以传入 `headline`,用来替换 Hero 的标题与预览徽标。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 +本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。每个 occurrence 都传入 `onWorkspaceSelected`,由它决定在 Hero 中选择工作区后做什么。它接收工作区和一个 `adopt` 函数:解析该工作区的空白 Session,用它替换此前显示的 Session,并在同一步、仍保留两个 Session 时以它调用 `adopt`;`adopt` 负责移动草稿。主 occurrence 把这个空白 Session 打开为主 Session,嵌入方可以自己显示它。属主不再需要的选择在不调用 `adopt` 的情况下完成;失败的选择会 reject,由属主报告失败,Hero 回到此前显示的工作区。嵌入式 occurrence 也可以传入 `headline`,用来替换 Hero 的标题与预览徽标。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻 header 在所有平台都保留与 blank Session 相同的 40px 行,因此绑定 Workspace 前后 Hero 输入卡片的高度位置不变;在 macOS 桌面上,这一行同时是窗口拖拽行。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。标题与 actions 放不下时,标题区域会裁剪它们,并在 utilities 之前渐隐其末端;utilities 始终完整可见且可点击;标题与 actions slot 中的浮层通过 portal 渲染,不受该裁剪影响。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 73ca3ddb64..2ed062b42f 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -22,7 +22,7 @@ import { sessionReferenceRule } from './user-text/session-reference-rule.ts' import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' import type { - ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, + ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationShellInjected, ConversationSessionInjected, DraftFileUploads, UserTextInjected, } from './contract/slots.ts' import type { InputNotice } from './contract/input.ts' @@ -112,10 +112,9 @@ function hostPathBridge(): HostPathBridge | undefined { interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( - workspaceId: Parameters[0], + workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise - connectWorkspace(workspaceId: Parameters[0]): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -330,6 +329,10 @@ export function apply(ctx: Context, config: SyncedConfig): v }, }) + const shellInjected: ConversationShellInjected = { + openWorkspace: (workspaceId, adopt) => workspaceNavigation.openWorkspace(workspaceId, adopt), + } + const registerConversationRoot = () => slots.register({ name: 'main.conversation', children: { @@ -360,46 +363,31 @@ export function apply(ctx: Context, config: SyncedConfig): v hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), }, - selectWorkspace: (workspaceId, report) => { - const moveDraft = (nextId: SessionId): void => { - if (sessionId !== undefined && nextId !== sessionId) { - const from = inputHub.shell(sessionId) - // A draft with a submission in flight stays with the Session that is admitting it. - if (from.snapshot.phase !== 'plain' && from.snapshot.phase !== 'claimed') return - const draft = from.draftSnapshot - const attachmentIds = from.snapshot.attachmentIds - const next = inputHub.shell(nextId) - if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) { - const binding = sessions.binding(nextId) - if (binding === undefined) { - throw new Error(`ui-conversation: session "${nextId}" resolved no binding`) - } - // The same rule as intake: only an ordinary Session stages image uploads. - const ordinary = binding.session.getSnapshot().subagent === null - concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary) - if (draft.text !== '') { - next.setDraft(draft) - from.setDraft('') - } - if (attachmentIds.length > 0) { - for (const id of attachmentIds) from.removeAttachment(id) - } + moveDraft: (nextId) => { + if (sessionId !== undefined && nextId !== sessionId) { + const from = inputHub.shell(sessionId) + // A draft with a submission in flight stays with the Session that is admitting it. + if (from.snapshot.phase !== 'plain' && from.snapshot.phase !== 'claimed') return + const draft = from.draftSnapshot + const attachmentIds = from.snapshot.attachmentIds + const next = inputHub.shell(nextId) + if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) { + const binding = sessions.binding(nextId) + if (binding === undefined) { + throw new Error(`ui-conversation: session "${nextId}" resolved no binding`) + } + // The same rule as intake: only an ordinary Session stages image uploads. + const ordinary = binding.session.getSnapshot().subagent === null + concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary) + if (draft.text !== '') { + next.setDraft(draft) + from.setDraft('') + } + if (attachmentIds.length > 0) { + for (const id of attachmentIds) from.removeAttachment(id) } } } - if (report === undefined) return workspaceNavigation.openWorkspace(workspaceId, moveDraft) - return workspaceNavigation.connectWorkspace(workspaceId).then((nextId) => { - // No await from here on, so nothing interleaves with the handover. The Session the draft leaves stays - // retained through it: `report` may release its own reference when it switches to `nextId`. - const source = sessionId === undefined || sessions.binding(sessionId) === undefined - ? undefined - : sessions.retain(sessionId, { source: 'controllerOperation' }) - try { - if (report(nextId)) moveDraft(nextId) - } finally { - source?.release() - } - }) }, }), }, ConversationContent) @@ -596,7 +584,7 @@ export function apply(ctx: Context, config: SyncedConfig): v yield slots.register({ name: 'main', key: 'conversation', - children: { 'main.conversation': { kind: 'single', scope: 'session-maybe' } }, + children: { 'main.conversation': { kind: 'single', scope: 'session-maybe', inject: shellInjected } }, }, ConversationPanel) yield registerConversationRoot() yield registerConversationContent() diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 3d6f0e1943..4efcee6601 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -226,7 +226,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { keyProps: { [Id in UserTextId]: { node: UserTextNode } } } /** Conversation shell beneath its root-scoped main-panel entry. */ - 'main.conversation': { kind: 'single'; scope: 'session-maybe' } + 'main.conversation': { kind: 'single'; scope: 'session-maybe'; inject: ConversationShellInjected } /** Strict per-Session Conversation body. */ 'conversation.session': { kind: 'single' @@ -466,16 +466,32 @@ export interface ConvViewOwnerProps { /** Base props of one target-owned Conversation View entry. */ export type ConvViewProps = PropsRuntime<'conversation.view'> -/** Business callbacks injected into the resident Conversation shell. */ +/** + * Moves the draft of the Session a Hero shows to the Session that replaces it. The occurrence owner calls it at most + * once per pick, synchronously with the step that shows the new Session, while it still retains both Sessions. + */ +export type WorkspaceSessionAdopter = (sessionId: SessionId) => void + +/** + * Handles a Workspace the Hero's picker chose: resolves that Workspace's blank Session, shows it in place of the + * Session shown before, and calls `adopt` with it in the same step. A pick the owner no longer wants resolves + * without calling `adopt`; a pick that failed rejects, and the owner reports the failure. + */ +export type WorkspaceSelectedHandler = (workspaceId: WorkspaceId, adopt: WorkspaceSessionAdopter) => Promise + +/** Business callbacks injected into the main Conversation shell. */ +export interface ConversationShellInjected { + /** Open the Workspace's blank Session as the main Session. */ + openWorkspace: WorkspaceSelectedHandler +} + +/** Business callbacks injected into the shared Conversation content. */ export interface ConversationInjected { /** - * Connect a blank Session in the selected Workspace and move the draft to it. Without `report` it opens as the main - * Session. With `report`, the connected Session is offered to it in one synchronous step: `report` returns whether - * the pick is still wanted and, when it is, retains the Session before it returns; the Session the draft comes from - * stays retained until the draft has moved, so `report` may release it. A declined pick changes nothing. A failed - * connection rejects; with `report`, the caller shows the failure. + * Move this occurrence's draft text and attachments to another Session. Both Sessions must be retained; a draft + * with a submission in flight stays where it is. */ - selectWorkspace: (workspaceId: WorkspaceId, report?: (sessionId: SessionId) => boolean) => Promise + moveDraft: WorkspaceSessionAdopter /** Session-addressed composer block source, or the stable absent source. */ hooks: { composerBlock: ObservableSnapshot } } @@ -689,15 +705,8 @@ export interface ConversationContentInputProps { variant: 'main' | 'embedded' phase: 'settling' | 'hero' | 'active' hero: boolean - /** - * Receives the blank Session of a Workspace the Hero's picker chose instead of that blank opening as the main - * Session; an embedded occurrence that sets it shows the reported Session itself. It is called only for the latest - * pick, and only while the occurrence still shows the Session the pick started from; a pick that completes later - * changes nothing. It must retain the reported Session before it returns and may release the one shown before: - * the draft moves to the reported Session once it returns. A pick whose Workspace cannot connect shows a transient - * notice and keeps the draft where it is. - */ - onWorkspaceSession?: ((sessionId: SessionId) => void) | undefined + /** What a Workspace picked in the Hero does in this occurrence; the main occurrence opens it as the main Session. */ + onWorkspaceSelected: WorkspaceSelectedHandler /** Text the blank-session Hero shows instead of its default headline and preview badge. */ headline?: string | undefined } diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index b2ce918f76..2aa335183b 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -86,7 +86,7 @@ export type { ComposerBarInjected, ComposerBarOwnerProps, ComposerBarProps, ComposerChainProps, ConversationHeaderActionOwnerProps, ConversationHeaderCornerOwnerProps, ConversationHeaderLineageOwnerProps, ConversationContentInputProps, ConversationContentProps, - ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, + ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, ConversationShellInjected, ConversationSessionInjected, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps, ConversationWidthControlsInputProps, ConversationWidthControlsProps, @@ -94,6 +94,7 @@ export type { HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputZone, MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, UseConversationViews, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 5886d86f25..2186b0e80c 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -393,7 +393,6 @@ export const zh = { 'queue.steer': '插话发送', 'queue.steer.unavailable': '仅运行中可插话发送', 'error.sessionInUse': '当前会话已被占用,可能是其他正在运行的 DSH 导致的(如其他 dsh web、桌面端),请退出其他正在运行的 DSH 后重试。', - 'error.workspaceConnectFailed': '没能打开这个工作区:{message}', 'queue.editFailed': '编辑失败:这条消息可能已经开始发送。', 'queue.removeFailed': '删除失败:这条消息可能已经开始发送。', 'queue.steerFailed': '插话发送失败,请重试。', @@ -801,7 +800,6 @@ export const en = { 'queue.steer': 'Steer queued message', 'queue.steer.unavailable': 'Steering is available only while the agent is running', 'error.sessionInUse': 'This session is already in use, possibly by another running DSH instance (such as dsh web or the desktop app). Quit other running DSH instances and try again.', - 'error.workspaceConnectFailed': "Couldn't open this workspace: {message}", 'queue.editFailed': 'Edit failed: this message may have already started sending.', 'queue.removeFailed': 'Removal failed: this message may have already started sending.', 'queue.steerFailed': 'Steering failed. Try again.', @@ -1208,7 +1206,6 @@ export const ja = { 'queue.steer': 'キュー内のメッセージを実行中の指示に追加', 'queue.steer.unavailable': '指示の変更はエージェントの実行中のみ利用できます', 'error.sessionInUse': 'このセッションはすでに使用中です。別の実行中のDSHインスタンス(dsh webやデスクトップアプリなど)が使用している可能性があります。他のDSHインスタンスを終了して再試行してください。', - 'error.workspaceConnectFailed': 'このワークスペースを開けませんでした:{message}', 'queue.editFailed': '編集に失敗しました。このメッセージはすでに送信が開始されている可能性があります。', 'queue.removeFailed': '削除に失敗しました。このメッセージはすでに送信が開始されている可能性があります。', 'queue.steerFailed': '指示の変更に失敗しました。再試行してください。', @@ -1608,7 +1605,6 @@ export const es = { 'queue.steer': 'Redirigir mensaje en cola', 'queue.steer.unavailable': 'La dirección solo está disponible mientras el agente está en ejecución', 'error.sessionInUse': 'Esta sesión ya está en uso, posiblemente por otra instancia de DSH en ejecución (como la web dsh o la aplicación de escritorio). Salga de otras instancias de DSH en ejecución y vuelva a intentarlo.', - 'error.workspaceConnectFailed': 'No se pudo abrir este espacio de trabajo: {message}', 'queue.editFailed': 'Error de edición: es posible que este mensaje ya haya comenzado a enviarse.', 'queue.removeFailed': 'Error al eliminar: es posible que este mensaje ya haya comenzado a enviarse.', 'queue.steerFailed': 'La dirección falló. Intentar otra vez.', @@ -2015,7 +2011,6 @@ export const fr = { 'queue.steer': 'Guider avec le message en attente', 'queue.steer.unavailable': "Le pilotage est disponible uniquement lorsque l'agent est en cours d'exécution", 'error.sessionInUse': "Cette session est déjà utilisée, éventuellement par une autre instance DSH en cours d'exécution (telle que le Web dsh ou l'application de bureau). Quittez les autres instances DSH en cours d'exécution et réessayez.", - 'error.workspaceConnectFailed': "Impossible d'ouvrir cet espace de travail : {message}", 'queue.editFailed': "Échec de la modification : l'envoi de ce message a peut-être déjà commencé.", 'queue.removeFailed': "Échec de la suppression : l'envoi de ce message a peut-être déjà commencé.", 'queue.steerFailed': 'La direction a échoué. Essayer à nouveau.', @@ -2422,7 +2417,6 @@ export const de = { 'queue.steer': 'Mit vorgemerkter Nachricht lenken', 'queue.steer.unavailable': 'Die Steuerung ist nur verfügbar, während der Agent ausgeführt wird', 'error.sessionInUse': 'Diese Sitzung wird bereits verwendet, möglicherweise von einer anderen laufenden DSH-Instanz (z. B. dsh Web oder der Desktop-App). Beenden Sie andere laufende DSH-Instanzen und versuchen Sie es erneut.', - 'error.workspaceConnectFailed': 'Dieser Arbeitsbereich konnte nicht geöffnet werden: {message}', 'queue.editFailed': 'Bearbeitung fehlgeschlagen: Der Versand dieser Nachricht wurde möglicherweise bereits gestartet.', 'queue.removeFailed': 'Fehler beim Entfernen: Der Versand dieser Nachricht wurde möglicherweise bereits gestartet.', 'queue.steerFailed': 'Lenkung versagt. Versuchen Sie es erneut.', @@ -2829,7 +2823,6 @@ export const ru = { 'queue.steer': 'Направить сообщение из очереди', 'queue.steer.unavailable': 'Управление доступно только во время работы агента.', 'error.sessionInUse': 'Этот сеанс уже используется, возможно, другим работающим экземпляром DSH (например, веб-сайтом dsh или настольным приложением). Закройте другие работающие экземпляры DSH и повторите попытку.', - 'error.workspaceConnectFailed': 'Не удалось открыть это рабочее пространство: {message}', 'queue.editFailed': 'Не удалось изменить: возможно, это сообщение уже начало отправляться.', 'queue.removeFailed': 'Удаление не удалось: возможно, это сообщение уже начало отправляться.', 'queue.steerFailed': 'Рулевое управление не удалось. Попробуйте еще раз.', @@ -3236,7 +3229,6 @@ export const pt = { 'queue.steer': 'Orientar com mensagem da fila', 'queue.steer.unavailable': 'A direção está disponível apenas enquanto o agente está em execução', 'error.sessionInUse': 'Esta sessão já está em uso, possivelmente por outra instância DSH em execução (como dsh web ou aplicativo de desktop). Saia de outras instâncias DSH em execução e tente novamente.', - 'error.workspaceConnectFailed': 'Não foi possível abrir este espaço de trabalho: {message}', 'queue.editFailed': 'Falha na edição: esta mensagem pode já ter começado a ser enviada.', 'queue.removeFailed': 'Falha na remoção: esta mensagem pode já ter começado a ser enviada.', 'queue.steerFailed': 'A direção falhou. Tente novamente.', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 236c1761cf..17ab15294e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -1,6 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' -import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import { workspaceDisplayTitle } from '@deepseek-ai/dsh-api-workspace-controller/default-workspace' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' @@ -24,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + moveDraft, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -41,15 +40,6 @@ export function ConversationContent(props: ConversationContentProps) { const [pickerOpen, setPickerOpen] = useState(false) const [pendingWorkspaceId, setPendingWorkspaceId] = useState() - // An embedded pick is handed to its owner only while it is the latest pick of a mounted occurrence. The content - // remounts for another Session, so a mounted occurrence still shows the Session the pick started from. - const mounted = useRef(false) - const pickSeq = useRef(0) - useEffect(() => { - mounted.current = true - return () => { mounted.current = false } - }, []) - const [pickFailure, setPickFailure] = useState<{ readonly seq: number; readonly text: string } | null>(null) const pickerAnchor = useRef(null) // Publishes the two live measurements floating View chrome reads off the @@ -133,19 +123,8 @@ export function ConversationContent(props: ConversationContentProps) { onPick: (workspaceId) => { setPickerOpen(false) setPendingWorkspaceId(workspaceId) - const handOver = props.onWorkspaceSession - pickSeq.current += 1 - const seq = pickSeq.current - const latest = (): boolean => mounted.current && seq === pickSeq.current - void selectWorkspace(workspaceId, handOver === undefined ? undefined : (nextId) => { - if (!latest()) return false - handOver(nextId) - return true - }).catch((error: unknown) => { + void props.onWorkspaceSelected(workspaceId, moveDraft).catch(() => { setPendingWorkspaceId(current => current === workspaceId ? undefined : current) - // Workspace navigation reports a failed pick of the main occurrence; an embedded one reports its own. - if (handOver === undefined || !latest()) return - setPickFailure({ seq, text: t('error.workspaceConnectFailed', { message: error instanceof Error ? error.message : String(error) }) }) }) }, onClose: () => { setPickerOpen(false) }, @@ -185,10 +164,6 @@ export function ConversationContent(props: ConversationContentProps) { const composerBar = (
- {pickFailure !== null && ( - } anchor={body} - onDone={() => { setPickFailure(null) }} /> - )} {hero && } {hero && heroWorkspaceRow} {zone !== undefined && renderSlot('conversation.input.dock', zone)} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx index dc82d99775..ef0f2ad583 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx @@ -11,7 +11,7 @@ const CONTENT_SLOTS = { widthControls: ConversationWidthControls } * @returns the unchanged root, Header, content, and width-control subtree. */ export function ConversationMainPanel(props: ConversationSlotProps) { - const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot } = props + const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot, openWorkspace } = props const session = useSession(s => s) const conversation = useConversation(s => s) const shellPhase = session === undefined || conversation === undefined @@ -41,6 +41,7 @@ export function ConversationMainPanel(props: ConversationSlotProps) { variant: 'main', phase, hero, + onWorkspaceSelected: openWorkspace, }, { slots: CONTENT_SLOTS, })} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 2fde1f24e9..5c11102f96 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -18,7 +18,7 @@ import { } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionBehaviorOverrides } from '@deepseek-ai/dsh-client-test-runtime' import { - apply, inject, type ComposerBarInjected, type ConversationInjected, + apply, inject, type ComposerBarInjected, type ConversationInjected, type ConversationShellInjected, type ConversationSessionHeaderInjected, type ConversationSessionInjected, type ViewTab, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -97,7 +97,6 @@ async function bench(renderQuote = false) { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, - connectWorkspace: async () => await connectWorkspace(), openSession, } as never) const sessionFake = sessionFakeFor() @@ -142,6 +141,11 @@ async function bench(renderQuote = false) { sessionId: SessionId | undefined, ) => ConversationInjected)(id) } + /** Pick a Workspace as the main occurrence does: the shell opens it and adopts the draft of the Session shown. */ + const selectWorkspace = (id: SessionId | undefined, workspaceId: WorkspaceId): Promise => { + const shell = runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + return shell.inject.openWorkspace(workspaceId, residentApi(id).moveDraft) + } const headerApi = (id: SessionId) => { const entry = entryOf('conversation.session.header') const instance = runtime.storeOf('conversation.session.header', references.get(id)) as ConversationInstance @@ -162,7 +166,7 @@ async function bench(renderQuote = false) { const viewSource = (id: SessionId): ObservableSnapshot => conversationApi(id).injected.hooks.conversationViews return { - runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, + runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, selectWorkspace, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, } } @@ -667,7 +671,6 @@ describe('Conversation inject API', () => { it('moves a draft only when Workspace navigation changes Session', async () => { const b = await bench() - const resident = b.residentApi(ROOT) const { state, actions } = b.inputApi(ROOT) actions.setDraft('carry me') expect(b.composerApi(ROOT).addFiles?.([ @@ -676,7 +679,7 @@ describe('Conversation inject API', () => { await vi.waitFor(() => { expect(b.rootUpload).toHaveBeenCalledOnce() }) b.connectWorkspace.mockResolvedValueOnce(ROOT) - await resident.selectWorkspace('workspace-1' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-1' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) expect(state.getSnapshot().draft).toBe('carry me') @@ -691,7 +694,7 @@ describe('Conversation inject API', () => { b.uploads.set(other, targetUpload) await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await resident.selectWorkspace('workspace-2' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-2' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(state.getSnapshot().draft).toBe('') expect(b.inputApi(other).state.getSnapshot().draft).toBe('carry me') @@ -700,98 +703,6 @@ describe('Conversation inject API', () => { await b.runtime.dispose() }) - it('reports the blank of a picked Workspace to an embedding owner, which retains it, and moves the draft without opening it', async () => { - const b = await bench() - const resident = b.residentApi(ROOT) - b.inputApi(ROOT).actions.setDraft('review this') - const other = 'other-2' as SessionId - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValueOnce(other) - const held: SessionReference[] = [] - const report = vi.fn((id: SessionId) => { - held.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - return true - }) - await resident.selectWorkspace('workspace-3' as WorkspaceId, report) - expect(report).toHaveBeenCalledWith(other) - expect(b.opened).not.toHaveBeenCalledWith(other) - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('') - expect(b.inputApi(other).state.getSnapshot().draft).toBe('review this') - for (const reference of held) reference.release() - await b.runtime.dispose() - }) - - it('moves the draft although the owner releases the Session it showed before while it takes the picked blank', async () => { - const b = await bench() - const source = 'handover-source' as SessionId - const target = 'handover-target' as SessionId - await b.runtime.sessions.add({ id: source, session: {} }) - await b.runtime.sessions.add({ id: target, session: {} }) - const shown = b.runtime.sessions.retain(source, { source: 'mainView' }) - b.inputApi(source).actions.setDraft('carry over') - b.connectWorkspace.mockResolvedValueOnce(target) - const taken: SessionReference[] = [] - await b.residentApi(source).selectWorkspace('workspace-5' as WorkspaceId, (id) => { - taken.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - shown.release() - return true - }) - expect(b.inputApi(target).state.getSnapshot().draft).toBe('carry over') - // The handover's own hold on the source ended with it. - expect(b.runtime.sessions.binding(source)).toBeUndefined() - for (const reference of taken) reference.release() - await b.runtime.dispose() - }) - - it('changes nothing when the owner declines the picked blank', async () => { - const b = await bench() - b.inputApi(ROOT).actions.setDraft('stay here') - const other = 'declined-target' as SessionId - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValueOnce(other) - const report = vi.fn((_id: SessionId) => false) - await b.residentApi(ROOT).selectWorkspace('workspace-6' as WorkspaceId, report) - expect(report).toHaveBeenCalledWith(other) - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('stay here') - expect(b.runtime.sessions.binding(other)).toBeUndefined() - expect(b.opened).not.toHaveBeenCalledWith(other) - await b.runtime.dispose() - }) - - it('offers the picked blank without retaining a source when no Session, or one no longer retained, started the pick', async () => { - const b = await bench() - const gone = 'released-source' as SessionId - const other = 'late-target' as SessionId - await b.runtime.sessions.add({ id: gone, session: {} }) - await b.runtime.sessions.add({ id: other, session: {} }) - b.connectWorkspace.mockResolvedValue(other) - const declined = vi.fn((_id: SessionId) => false) - await b.residentApi(gone).selectWorkspace('workspace-7' as WorkspaceId, declined) - expect(declined).toHaveBeenCalledWith(other) - expect(b.runtime.sessions.binding(gone)).toBeUndefined() - - const taken: SessionReference[] = [] - await b.residentApi(undefined).selectWorkspace('workspace-7' as WorkspaceId, (id) => { - taken.push(b.runtime.sessions.retain(id, { source: 'mainView' })) - return true - }) - expect(taken.map(reference => reference.sessionId)).toEqual([other]) - expect(b.opened).not.toHaveBeenCalledWith(other) - for (const reference of taken) reference.release() - await b.runtime.dispose() - }) - - it('rejects an embedded pick whose Workspace cannot connect without offering a Session', async () => { - const b = await bench() - b.inputApi(ROOT).actions.setDraft('kept') - b.connectWorkspace.mockRejectedValueOnce(new Error('preset missing')) - const report = vi.fn((_id: SessionId) => true) - await expect(b.residentApi(ROOT).selectWorkspace('workspace-8' as WorkspaceId, report)).rejects.toThrow('preset missing') - expect(report).not.toHaveBeenCalled() - expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('kept') - await b.runtime.dispose() - }) - it('leaves a draft whose message is still being sent with its Session', async () => { const b = await bench() const pending = Promise.withResolvers>>() @@ -804,7 +715,7 @@ describe('Conversation inject API', () => { const other = 'sending-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-sending' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-sending' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(b.inputApi(other).state.getSnapshot().draft).toBe('') expect(state.getSnapshot().draft).toBe('in flight') @@ -825,7 +736,7 @@ describe('Conversation inject API', () => { const other = 'structured-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-structured' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-structured' as WorkspaceId) expect(b.inputApi(other).state.getSnapshot().draft).toBe(draft.text) expect(b.inputApi(other).state.getSnapshot().occurrences).toMatchObject(draft.references) expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('') @@ -836,12 +747,12 @@ describe('Conversation inject API', () => { it('supports no-Session navigation and propagates Workspace connection failure', async () => { const b = await bench() b.connectWorkspace.mockResolvedValueOnce(ROOT) - await b.residentApi(undefined).selectWorkspace('workspace-0' as WorkspaceId) + await b.selectWorkspace(undefined, 'workspace-0' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) const opens = b.opened.mock.calls.length b.connectWorkspace.mockRejectedValueOnce(new Error('offline')) - await expect(b.residentApi(ROOT).selectWorkspace('workspace-4' as WorkspaceId)) + await expect(b.selectWorkspace(ROOT, 'workspace-4' as WorkspaceId)) .rejects.toThrow('offline') expect(b.opened).toHaveBeenCalledTimes(opens) await b.runtime.dispose() diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index 907b6ec015..5a0adbffb0 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -8,7 +8,7 @@ import { import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { apply, inject, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { apply, inject, type ConversationShellInjected, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' usePinnedBrowserLanguages('zh-CN') @@ -103,8 +103,9 @@ describe('target-neutral Conversation apply wiring', () => { b.runtime.renderRoot() expect(b.runtime.slots.entries('main').map(row => row.options.key)).toEqual(['conversation']) expect(b.runtime.slots.entries('main.conversation')).toHaveLength(1) - expect(b.runtime.slots.spec('main.conversation')) - .toEqual({ kind: 'single', scope: 'session-maybe' }) + const shell = b.runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + expect(shell.inject.openWorkspace).toBeTypeOf('function') + expect(shell).toEqual({ kind: 'single', scope: 'session-maybe', inject: shell.inject }) expect(b.runtime.factoryOf('conversation.content').slots) .toMatchObject({ views: { scope: 'session' } }) expect(b.runtime.slots.entries('conversation.session')).toHaveLength(1) diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 9fce5385e0..41c2c9ea9a 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { GlobalStandardProps, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createContext, useContext, type ReactNode } from 'react' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import type { Context } from '@deepseek-ai/cordis' @@ -32,6 +32,7 @@ import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import type { ComposerBarOwnerProps, ConversationContentInputProps, ConversationContentProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, ConversationHeaderLineageOwnerProps, ConversationSessionHeaderSlotProps, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, } from '../src/client/contract/slots.ts' @@ -124,7 +125,7 @@ function sessionSnapshotOf(overrides: Partial = {}): SessionSna function mount( snapshot: SessionSnapshot, workspaceRows: WorkspaceView[] = [{ ...workspace('one'), sessionIds: [SID] }], - retargetWorkspace = vi.fn(async (_workspaceId: WorkspaceId) => {}), + retargetWorkspace = vi.fn(async () => {}), options: { /** Explicit undefined exercises the shell before a Session is selected. */ sessionId?: SessionId | undefined @@ -148,8 +149,6 @@ function mount( entryActions?: boolean /** Isolate header capability checks from the composer's required layout observers. */ headerOnly?: boolean - /** Inputs an embedding owner adds to the content occurrence. */ - contentInput?: Pick } = {}, ) { const sessionId = 'sessionId' in options ? options.sessionId : SID @@ -353,6 +352,7 @@ function mount( : (opts?.fallback ?? null) )) as ConversationContentProps['renderSlotChain'] const SessionProvider: ConversationContentProps['SessionProvider'] = ({ children }) => children + const moveDraft = vi.fn() const renderFactorySlot = ((_name: string, input: ConversationContentInputProps, factoryOptions?: { slots?: Record ReactNode> }) => { @@ -379,7 +379,7 @@ function mount( renderSlot, renderSlotChain, renderFactorySlot, - selectWorkspace: retargetWorkspace, + moveDraft, t, } const useFactorySlot = ((name: string, fallback: (props: never) => ReactNode) => ( @@ -387,7 +387,7 @@ function mount( )) as ConversationContentProps['useFactorySlot'] return ( - + ) }) as ConversationSlotProps['renderFactorySlot'] @@ -395,6 +395,7 @@ function mount( usePanelInfo: selector => selector({ activePanelId: null }), sessionId, SessionProvider, + openWorkspace: retargetWorkspace, useSession: sessionId === undefined ? () => undefined : useSession, useConversation: sessionId === undefined ? () => undefined : useConversation, useSessions: bindSnapshotSelector(sessions), @@ -411,7 +412,8 @@ function mount( const props: ConversationSlotProps = { ...runtimeProps, renderSlot, renderFactorySlot } const view = render() return { - view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, open, + view, store, wiring, sink, retargetWorkspace, moveDraft, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, + open, pickerOwner: () => pickerOwner, frameOwner: () => frameOwners.at(-1), setPinned, @@ -620,7 +622,7 @@ describe('ConversationRoot resident composer', () => { const owner = b.pickerOwner() as { open: boolean; onPick(id: WorkspaceId): void } expect(owner.open).toBe(true) act(() => { owner.onPick(wid('second')) }) - expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), undefined) + expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.getByText('Selected Folder')).toBeTruthy() }) @@ -901,7 +903,7 @@ describe('ConversationRoot resident composer', () => { }) it('rolls the pending workspace label back when switching fails', async () => { - const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) + const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) const b = mount( sessionSnapshotOf({ blank: true }), [ @@ -913,87 +915,9 @@ describe('ConversationRoot resident composer', () => { fireEvent.click(b.view.getByRole('button', { name: '选择工作区' })) const owner = b.pickerOwner() as { onPick(id: WorkspaceId): void } await act(async () => { owner.onPick(wid('second')); await Promise.resolve() }) - expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), undefined) + expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.queryByText('Selected Folder')).toBeNull() expect(b.view.getByText('one')).toBeTruthy() - // Workspace navigation reports this failure; the content adds no notice of its own. - expect(screen.queryByText(/没能打开这个工作区/)).toBeNull() - }) - - describe('embedded Workspace pick', () => { - /** One pick in flight: the handover the content gave `selectWorkspace`, and how the connection settles. */ - interface Pick { - readonly handOver: ((sessionId: SessionId) => boolean) | undefined - readonly fail: (error: unknown) => void - } - - /** Mount a blank embedded occurrence whose picks settle when the test says. */ - function embedded() { - const picks: Pick[] = [] - const selectWorkspace = vi.fn((_workspaceId: WorkspaceId, handOver?: (sessionId: SessionId) => boolean) => - new Promise((_resolve, reject) => { picks.push({ handOver, fail: reject }) })) - const owner = vi.fn<(sessionId: SessionId) => void>() - const b = mount( - sessionSnapshotOf({ blank: true }), - [ - { ...workspace('one'), sessionIds: [SID] }, - { ...workspace('second'), title: 'Second Folder' }, - { ...workspace('third'), title: 'Third Folder' }, - ], - selectWorkspace, - { contentInput: { onWorkspaceSession: owner } }, - ) - const pick = (id: string): void => { - act(() => { (b.pickerOwner() as { onPick(id: WorkspaceId): void }).onPick(wid(id)) }) - } - return { b, picks, owner, pick } - } - - it('hands only the latest pick to the owner', () => { - const { picks, owner, pick } = embedded() - pick('second') - pick('third') - expect(picks[0]?.handOver?.(sid('second-blank'))).toBe(false) - expect(owner).not.toHaveBeenCalled() - expect(picks[1]?.handOver?.(sid('third-blank'))).toBe(true) - expect(owner.mock.calls).toEqual([[sid('third-blank')]]) - }) - - it('declines a pick that connects after the occurrence unmounted', () => { - const { b, picks, owner, pick } = embedded() - pick('second') - b.view.unmount() - expect(picks[0]?.handOver?.(sid('second-blank'))).toBe(false) - expect(owner).not.toHaveBeenCalled() - }) - - it('shows why the latest pick failed for a while and returns to the Workspace it showed', async () => { - vi.useFakeTimers() - onTestFinished(() => { vi.useRealTimers() }) - const { b, picks, pick } = embedded() - pick('second') - expect(b.view.getByText('Second Folder')).toBeTruthy() - await act(async () => { picks[0]?.fail(new Error('preset missing')); await Promise.resolve() }) - expect(screen.getByText('没能打开这个工作区:preset missing')).toBeTruthy() - expect(b.view.queryByText('Second Folder')).toBeNull() - expect(b.view.getByText('one')).toBeTruthy() - - pick('third') - await act(async () => { picks[1]?.fail('offline'); await Promise.resolve() }) - expect(screen.queryByText('没能打开这个工作区:preset missing')).toBeNull() - expect(screen.getByText('没能打开这个工作区:offline')).toBeTruthy() - act(() => { vi.advanceTimersByTime(5_000) }) - expect(screen.queryByText('没能打开这个工作区:offline')).toBeNull() - }) - - it('reports no failure for a pick that another pick replaced', async () => { - const { b, picks, pick } = embedded() - pick('second') - pick('third') - await act(async () => { picks[0]?.fail(new Error('too late')); await Promise.resolve() }) - expect(screen.queryByText(/没能打开这个工作区/)).toBeNull() - expect(b.view.getByText('Third Folder')).toBeTruthy() - }) }) it('blank session keeps the interactive picker chip (workspace switchable until the first message)', () => { diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 855eca71ba..0666bc24d6 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: 77677cfa89b26de8 - zh: 83909430c95f3a6b + en: e912edfd1406cc33 + zh: da0a59a27fb4a65c /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: en: da87d582146106c4 zh: f640b3a3fcc11209 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index e1a6e31218..f64c1a7b2c 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -27,7 +27,7 @@ Browse local subagent conversations and external tasks in the Session panel's Su The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. Each subagent breadcrumb title is a switcher over its parent's direct catalog that marks the title's Session as current; root Sessions have no switcher. The [Session panel](../ui-session-panel/README.md#contribute-a-section) section `subagents` (order 200, titled “Subagents”) lists the current Session's direct catalog, in root and child conversations alike, when the catalog has entries or a read has failed. Showing the section reads nothing; expanding a branch prepares that branch. An absent or empty catalog hides the section and its title unless a footer contribution is available and the Session's enabled `agentTeam` projection has nondeleted shared tasks or a task-record error. Enabling Team mode alone does not show an empty section. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. Either action closes the panel's overlay or the switcher menu that holds the row. -This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. +This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. A Workspace picked in a blank child's Hero opens that Workspace's blank Session as the main Session and moves the draft to it, as the main Conversation does. The section's title control (`conversation.session.panel.section.actions`, key `subagents`) shows direct-member progress: completed, in progress, not running, and external counts in that order, with zero counts omitted and the separator matching the input task list. External tasks never count as running or completed. The section lists running subagents first, the most recently started first, and then the others, the most recently updated first. It shows five rows and then the Session panel's fold control, “Show {count} more”, which shows the rest and then reads “Show less”; the list folds only when that holds back two rows or more, the choice holds for the Session, also after the panel is hidden and shown again, and an expanded branch's own rows all show. The section hides with its title while the Session has no subagents and no failed catalog read. While direct subagents run and the panel does not show, a blue dot on the panel toggle (`conversation.session.panel.indicator`) says so and names their number for assistive technology; external tasks do not count. The Session panel scrolls the section; the tree has no nested scrolling. The breadcrumb switcher menu is 360px wide with 6px outer padding, constrained to fit the layout viewport, and only the menu scrolls. In WebKit-compatible browsers, its native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index eaf55b25f9..4a794b4476 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" 会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。每个 subagent 面包屑标题都是覆盖其父会话直接目录的切换器,并把该标题对应的 Session 标为当前项;根 Session 没有切换器。[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `subagents`(order 200,标题为“子智能体”)在根会话和子会话中都列出当前 Session 的直接目录,前提是目录有子项或读取失败。显示分栏不读取任何内容;展开分支时准备该分支。目录缺席或为空时,分栏连同标题一起隐藏,除非存在可用的 footer 扩展,且 Session 已开启的 `agentTeam` 投影含有未删除的共享任务或任务记录错误。仅开启 Team 模式不会显示空分栏。选择任意深度的本地 child,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。两种操作都会关闭面板浮层或该行所在的切换器菜单。 -本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 +本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。在空白 child 的 Hero 中选择工作区时,与主 Conversation 一样,把该工作区的空白 Session 打开为主 Session,并把草稿移过去。 分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 diff --git a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx index 6d9c3fcbb5..8461e307ca 100644 --- a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx +++ b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx @@ -4,7 +4,7 @@ import type { ISessions, SessionReference, } from '@deepseek-ai/dsh-api-session-controller/client' import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client' -import type { ConversationViewsProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ConversationViewsProps, WorkspaceSelectedHandler } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SidebarRightTabDefinition } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { PropsRenderFactories, PropsRenderSlots, PropsRuntime, TranslateNS, @@ -39,7 +39,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session-scoped Conversation occurrence hosted by one Sidebar chat tab. */ - 'sidebar.chat.conversation': { kind: 'single'; scope: 'session' } + 'sidebar.chat.conversation': { kind: 'single'; scope: 'session'; inject: SidebarChatInjected } } } @@ -117,6 +117,12 @@ function subagentChatResourceProvider(sessions: ISessions): ResourceProvider<'su } } +/** Navigation injected into the child-Session Conversation host. */ +export interface SidebarChatInjected { + /** Open the Workspace's blank Session as the main Session. */ + readonly openWorkspace: WorkspaceSelectedHandler +} + /** Fixed Chat selection used by an embedded Conversation occurrence. */ export function FixedChatConversationView(props: ConversationViewsProps) { return <>{props.renderSlot('conversation.session', { view: 'chat' })} @@ -127,7 +133,7 @@ export type ConversationSlotPanelProps = PropsRuntime<'sidebar.chat.conversation /** Render the shared Conversation content for one explicitly provided child Session. */ export function ConversationSlotPanel({ - sessionId, useSession, useConversation, useSessions, renderFactorySlot, + sessionId, useSession, useConversation, useSessions, renderFactorySlot, openWorkspace, }: ConversationSlotPanelProps) { const session = useSession(value => value) const conversation = useConversation(value => value) @@ -139,7 +145,7 @@ export function ConversationSlotPanel({ const settling = (shellPhase === 'blank' && session.openState === 'loading' && summaryBlank !== true) const hero = shellPhase === 'blank' && (session.openState === 'open' || summaryBlank === true) const phase = settling ? 'settling' : hero ? 'hero' : 'active' - return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero }, { + return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero, onWorkspaceSelected: openWorkspace }, { slots: { views: FixedChatConversationView }, }) } @@ -188,10 +194,13 @@ export function registerSidebarChat(ctx: Context, t: TranslateNS): vo : ctx.sessions.list.getSnapshot().byId[child]?.projectionValues?.subagent?.label ?? child }, } satisfies SidebarRightTabDefinition), 'ui-subagent: Sidebar chat type') + const chatInjected: SidebarChatInjected = { + openWorkspace: (workspaceId, adopt) => ctx.uiWorkspace.openWorkspace(workspaceId, adopt), + } ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: SUBAGENT_CHAT_ID, - children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session' } }, + children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session', inject: chatInjected } }, }, SidebarChatTab)), 'ui-subagent: Sidebar chat body') ctx.effect(() => ctx.slots.inject('sidebar.chat.conversation', () => ctx.slots.register({ name: 'sidebar.chat.conversation', diff --git a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx index f7417ea910..76981b4522 100644 --- a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx +++ b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx @@ -85,6 +85,7 @@ describe('Sidebar chat registration', () => { let provider: ResourceProvider<'subagentchat'> | undefined let definition: SidebarRightTabDefinition | undefined const registrations: { options: Record; component: unknown }[] = [] + const openWorkspace = vi.fn(() => Promise.resolve()) const ctx = { sessions: { retain, refreshProjections, list } as unknown as ISessions, resources: { register: (value: ResourceProvider<'subagentchat'>) => { provider = value; return () => {} } }, @@ -99,7 +100,7 @@ describe('Sidebar chat registration', () => { effect: (install: () => unknown) => { install(); return () => {} }, } as unknown as Context - registerSidebarChat(ctx, (key: string) => key === 'sidebar.chat' ? 'Chat' : key) + registerSidebarChat(Object.assign(ctx, { uiWorkspace: { openWorkspace } }), (key: string) => key === 'sidebar.chat' ? 'Chat' : key) expect(definition?.id).toBe(SUBAGENT_CHAT_ID) expect(definition?.kind).toBe('subagentchat') @@ -112,6 +113,13 @@ describe('Sidebar chat registration', () => { 'sidebar.right.pane.tab', 'sidebar.chat.conversation', ]) + // A Workspace picked in the child's Hero opens as the main Session, as it does in the main Conversation. + const children = registrations[0]?.options.children as { + 'sidebar.chat.conversation': { inject: { openWorkspace: (workspaceId: string, adopt: () => void) => Promise } } + } + const adopt = vi.fn() + await children['sidebar.chat.conversation'].inject.openWorkspace('workspace-1', adopt) + expect(openWorkspace).toHaveBeenCalledWith('workspace-1', adopt) const controller = new AbortController() const stream = provider!.open(subagentChatAddress(ADDRESS), { signal: controller.signal })[Symbol.asyncIterator]() @@ -204,6 +212,7 @@ describe('Sidebar chat components', () => { ])('derives the $name embedded phase and fixes the local view to Chat', ({ session: patch, summaryBlank, expected }) => { const snapshot = { ...sessionSnapshot(CHILD), ...patch } as SessionSnapshot const renderFactorySlot = vi.fn(() => null) + const openWorkspace = vi.fn() render( unknown) => select(snapshot), @@ -212,10 +221,10 @@ describe('Sidebar chat components', () => { ids: [], byId: { [CHILD]: { blank: summaryBlank } }, phase: 'ready', projectionsBySession: {}, jobsBySession: {}, } as unknown as SessionListState), renderFactorySlot, - } as unknown as Parameters[0])} />) + } as unknown as Parameters[0])} openWorkspace={openWorkspace} />) expect(renderFactorySlot).toHaveBeenCalledWith( 'conversation.content', - { variant: 'embedded', ...expected }, + { variant: 'embedded', ...expected, onWorkspaceSelected: openWorkspace }, { slots: { views: FixedChatConversationView } }, ) }) 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 777480c1ef..22c3e0832c 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -3322,7 +3322,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], keyDomain: '', hookContext: '', - slotInject: '', + slotInject: 'ConversationShellInjected', declaredBy: 'an entry in \'main\' (client-ui-conversation), so it exists while that entry is mounted', occupants: [ 'client-ui-conversation ConversationRoot', @@ -4829,7 +4829,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], keyDomain: '', hookContext: '', - slotInject: '', + slotInject: 'SidebarChatInjected', declaredBy: 'an entry in \'sidebar.right.pane.tab\' (client-ui-subagent), so it exists while that entry is mounted', occupants: [ 'client-ui-subagent ConversationSlotPanel',