From e71df56b1a2b6511bc7184a58c6a6142e934bed9 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 14:59:15 +0800 Subject: [PATCH 01/11] feat(workspace): create the default workspace on first send --- ...ession-scope-and-provide-channel.i18n.yaml | 4 +- ...lient-session-scope-and-provide-channel.md | 8 +- ...nt-session-scope-and-provide-channel.zh.md | 8 +- .../2026-09-20-default-workspace.i18n.yaml | 6 + .../feature/2026-09-20-default-workspace.md | 32 ++++ .../2026-09-20-default-workspace.zh.md | 32 ++++ apps/web/tests/default-workspace.e2e.ts | 122 +++++++++++++++ .../default-workspace/failure.expected.md | 6 + apps/web/tests/scaffold.ts | 2 + apps/web/tests/support.ts | 23 +-- apps/web/tsconfig.json | 1 + docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 19 ++- docs/config-catalog.zh.md | 19 ++- docs/subsystems/workspace.i18n.yaml | 4 +- docs/subsystems/workspace.md | 23 +++ docs/subsystems/workspace.zh.md | 23 +++ .../api/workspace-controller/README.i18n.yaml | 4 +- packages/api/workspace-controller/README.md | 12 ++ .../api/workspace-controller/README.zh.md | 12 ++ .../api/workspace-controller/package.json | 2 + .../workspace-controller/src/client/index.ts | 2 +- .../workspace-controller/src/client/model.ts | 13 ++ .../src/client/service.ts | 15 +- .../src/default-directory.ts | 79 ++++++++++ .../api/workspace-controller/src/index.ts | 53 ++++++- .../api/workspace-controller/src/types.ts | 8 + .../tests/default-directory.host.spec.ts | 48 ++++++ .../tests/model.client.spec.ts | 17 +++ .../tests/remote/workspace.client.ts | 1 + .../tests/transport.client.spec.ts | 5 + .../tests/workspace-controller.host.spec.ts | 48 +++++- .../workspace-controller/tsconfig.host.json | 5 +- .../client/ui-agent-preset/README.i18n.yaml | 4 +- packages/client/ui-agent-preset/README.md | 2 + packages/client/ui-agent-preset/README.zh.md | 2 + .../ui-agent-preset/src/client/index.ts | 8 + .../ui-agent-preset/src/client/seat-store.ts | 13 +- .../tests/apply.client.spec.ts | 33 +++- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 6 +- packages/client/ui-conversation/README.zh.md | 6 +- .../ui-conversation/src/client/apply.ts | 41 +++-- .../src/client/contract/input.ts | 6 + .../src/client/contract/slots.ts | 13 +- .../ui-conversation/src/client/index.ts | 8 + .../src/client/input/facade.ts | 4 +- .../src/client/input/first-draft.ts | 79 ++++++++++ .../ui-conversation/src/client/locales.ts | 8 + .../client/skeleton/ConversationContent.tsx | 40 +++-- .../src/client/skeleton/ConversationRoot.tsx | 5 +- .../src/client/skeleton/InputBar.tsx | 81 ++++------ .../tests/apply-inject.client.spec.tsx | 52 ++++++- .../tests/assembly-surfaces.client.spec.tsx | 24 ++- .../tests/first-draft.client.spec.ts | 141 +++++++++++++++++ .../tests/input-bar.client.spec.tsx | 1 + .../tests/input-matrix.client.spec.tsx | 1 + .../tests/input-scenarios.client.spec.tsx | 1 + .../tests/skeleton.client.spec.tsx | 16 ++ packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 + packages/client/ui-workspace/README.zh.md | 2 + .../ui-workspace/src/client/navigation.ts | 33 +++- .../tests/workspaces-service.client.spec.ts | 40 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 16 ++ .../client-runtime/src/workspaces.ts | 15 +- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 13 +- packages/workspace/workspace/README.zh.md | 13 +- packages/workspace/workspace/src/index.ts | 41 ++++- packages/workspace/workspace/src/spec.ts | 2 + .../workspace/tests/workspace.spec.ts | 144 +++++++++++++++++- pnpm-lock.yaml | 6 + scripts/gen-cordis-catalog.ts | 2 + snapshots/web/default-workspace/snapshot.yml | 9 ++ .../web/default-workspace/ui.expected.md | 26 ++++ tsconfig.host.json | 1 + 77 files changed, 1472 insertions(+), 160 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.md create mode 100644 .agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md create mode 100644 apps/web/tests/default-workspace.e2e.ts create mode 100644 apps/web/tests/expected/default-workspace/failure.expected.md create mode 100644 packages/api/workspace-controller/src/default-directory.ts create mode 100644 packages/api/workspace-controller/tests/default-directory.host.spec.ts create mode 100644 packages/client/ui-conversation/src/client/input/first-draft.ts create mode 100644 packages/client/ui-conversation/tests/first-draft.client.spec.ts create mode 100644 snapshots/web/default-workspace/snapshot.yml create mode 100644 snapshots/web/default-workspace/ui.expected.md diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml index e891710dea..2e242505c5 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md -2026-07-25-web-client-session-scope-and-provide-channel.md: 990a9b6eef862a7ac4a549358beae7f9081eaa0b -2026-07-25-web-client-session-scope-and-provide-channel.zh.md: 5c90611fab36611766bb407138c4f0c8a6b3a01b +2026-07-25-web-client-session-scope-and-provide-channel.md: e2541836edc18755c2e49d30a10b44d2d3a7bcc3 +2026-07-25-web-client-session-scope-and-provide-channel.zh.md: fd082cc74974a22a69a67cbf657693911aea8f99 diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md index 990a9b6eef..e2541836ed 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md @@ -26,8 +26,8 @@ The reference-owned lifetime and Provider targeting now follow [Client Session r Host-side `session.create(workspaceId)` produces Session + Agent + cwd in one piece (an atomic bundle, never split); the client side is the mirror of that birth — the instant a session row enters the list mirror, the client mints its Agent scope (actx + provide + the full input surface mounted): - Session identity is the host's true form from birth: the sessionId arrives via the `session.create` response / the `host/session-added` frame, and every client-side address (the scope tag, slot store keys, RPC addressing) uses that same id. -- The materialization moment = the instant the user picks a Workspace (cwd settled): the client calls `session.create({workspaceId})` on the spot and receives the complete entity. -- "New Session with no workspace picked" is a **pure view state** (a navigation position) corresponding to no session/scope entity; until the pick, the composer is locked whole (no slash, no plain text). +- A manual Workspace pick or successful [first-use default preparation](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. +- "New Session with no workspace picked" has no Session or scope entity. The composer retains a local text draft; Session-scoped slash commands become available after connection. - A "blank session" is just an ordinary materialized session whose log is still empty; to every Agent-scope plugin on the host (goal/plan/skill/…) it is indistinguishable from any session, so slash/plan are all naturally live. ### Agent scope: the actx is the sole session carrier in the client-side cordis world @@ -95,7 +95,7 @@ Slot scope is the closed set `root | session-maybe | session`: - `session-maybe` inherits the nearest `SessionProvider` binding with ADOPTION identity: an incarnation born Session-less keeps its React instance when that Provider receives its first binding, then remounts when the Provider switches generation or returns to absence. Component-local per-Session state clears when the Provider switches generation. Across a switch, only persisted Store values survive generation retirement; binding-owned sources survive only when another reference keeps that generation alive. With no binding, `sessionId`, the results of `useSession`/`useInput`, and `inputActions` may all be absent. Provider-roster changes rematerialize the mounted binding without changing its identity, while the per-entry adoption bookkeeping lives in the renderer's `SessionMaybeEntry`. - `session` guarantees that `sessionId`, every hook source, and every prop exist; each strict entry's error boundary is keyed by `sessionId`, so switching sessions recreates that entry and its session store. -`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: with no Session its machine faces and message actions are inert, while the whole dashed card opens the existing Workspace picker by pointer and its read-only textarea does the same through Enter or Space. The same instance — textarea included — goes live when a binding appears; the remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. +`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: before a Session exists, its injected editor retains the first-use text draft; after connection, the same InputBar instance receives the retained Session's input. The remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. Blank Sessions retain the header's leading and corner slots so navigation controls, including the right-sidebar opener, are available before the first message. Title, actions, utilities, and View tabs remain hidden in the blank phase. The header still requires a selected Session; the Files and Terminal entries use that Session's workspace and execution services without requiring a recorded Turn. @@ -136,5 +136,5 @@ Blank Sessions retain the header's leading and corner slots so navigation contro - Plugins gain session context isomorphic to the host's: per-session state hangs on the actx and mounts/tears down in one piece with the scope fiber, making leaks structurally impossible; two-session isolation is structurally guaranteed by the scope filter. - The client object layer converges to a wire mirror: session identity, lifecycle, and capability adjudication all defer to the host entity — the input system (the next layer) always faces a session with a real Agent, and providers like slash/skill uniformly address by sessionId directly. - Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reuse acquires the persisted writer, and the ordinary ceiling rides same-Workspace reuse. -- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. The single state axis still withholds machine faces until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) routes activation to the Workspace picker during that interval. +- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. Session-scoped input remains unavailable until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) owns the local first-use draft during that interval. - Known gaps: approval/question recovery across prune (TODO); model selection returns in live-mutation shape (the host `selectModel` trio is ready-made, its client consumer not yet built). diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md index 5c90611fab..fd082cc749 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md @@ -26,8 +26,8 @@ web client 只有一张全局会话面:slot 全部从根上下文渲染,插 host 侧 `session.create(workspaceId)` 一体产出 Session + Agent + cwd(作为不可拆分的原子整体);client 侧就是这次出生的镜像——会话行进入 list mirror 的瞬间,client 为它铸 Agent scope(actx + provide + 输入面全套挂上): - 会话身份自出生即为 host 真身:sessionId 由 `session.create` 响应 / `host/session-added` 帧带来,client 侧一切寻址(scope tag、slot store 键、RPC 地址)用的都是同一个 id。 -- 实体化时点 = 用户选定 Workspace(cwd 确定)的瞬间:client 当场调 `session.create({workspaceId})`,拿到完整实体。 -- 「New Session 且未选 workspace」是**纯视图态**(一个导航位置),不对应任何会话/scope 实体;选定之前 composer 整体锁死(无 slash、无纯文本)。 +- 手动选择 Workspace 或成功[准备首次使用默认工作区](../feature/2026-09-20-default-workspace.zh.md)先确定 cwd,client 随后调用 `session.create({workspaceId})` 并取得完整实体。 +- 「New Session 且未选 workspace」没有 Session 或 scope 实体。Composer 保留本地文本草稿;连接后才提供 Session scope 的 slash 命令。 - 「空会话」就是一个日志还空着的普通实体化会话;对 host 上所有 Agent-scope 插件(goal/plan/skill(技能)/…)它与任何会话无异,slash/plan 天然全活。 ### Agent scope:actx 是 client 侧 cordis 世界的唯一会话载体 @@ -95,7 +95,7 @@ slot scope 是闭集 `root | session-maybe | session`: - `session-maybe` 以**收养(adoption)身份语义**继承最近 `SessionProvider` 的 binding:空态出生的化身在该 Provider 第一次收到 binding 时保持 React 实例,此后 Provider 切换 generation 或回到空态时重挂。Provider 切换 generation 时,组件本地的逐 Session 状态会清零。切换过程中,只有持久化 Store 值能活过 generation 退休;只有另一份 reference 保活该 generation 时,binding 自有 source 才能保留。无 binding 时,`sessionId`、`useSession`/`useInput` 的结果与 `inputActions` 均可缺省。Provider roster 变化会重新物化已挂载 binding,但不改变其 identity;逐 entry 的收养记账住在 renderer 的 `SessionMaybeEntry`。 - `session` 保证 `sessionId`、所有钩子 source 与 props 均存在;每个严格 entry 的错误边界以 `sessionId` 为 key,切换会话会重建该 entry 及其会话 store。 -`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:无 Session 时,其 machine faces 和消息动作保持惰性,整张虚线卡片可经指针打开现有 Workspace picker,只读 textarea 也可通过 Enter 或 Space 打开。binding 出现后同一实例(含 textarea)转为 live;其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 +`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:Session 存在前,注入的编辑器保存首次使用文本草稿;连接后,同一 InputBar 实例接收已持有 Session 的输入。其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入口等导航控件在首条消息之前即可使用。标题、actions、utilities 和 View tabs 在 blank phase 中继续隐藏。header 仍要求已选中的 Session;Files 与 Terminal 入口使用该 Session 的工作区和执行服务,无需已有 Turn 记录。 @@ -136,5 +136,5 @@ blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入 - 插件获得与 host 同构的会话上下文:逐会话状态挂 actx、随 scope fiber 一次拆装,泄漏结构性不可能;双会话隔离由 scope filter 结构性保证。 - client 对象层收敛为 wire 镜像:会话身份、生命周期、能力判别全部以 host 实体为准——输入体系(下一层)面对的永远是「有真 Agent 的会话」,slash/skill 等提供方一律以 sessionId 直接寻址。 - 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),复用时获取持久化写锁,常规上限靠同 Workspace 复用。 -- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。单一状态轴仍会在 Session 存在前隐藏 machine face;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)会把激活操作转到 Workspace picker。 +- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。Session 存在前,其 scope 输入仍不可用;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)负责本地首次使用草稿。 - 已知欠账:approval/question 跨 prune 恢复(TODO);模型选择以 live-mutation 形状回归(host `selectModel` 三件套现成,其 client 消费方尚未构建)。 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml new file mode 100644 index 0000000000..cdb2673df8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md +2026-09-20-default-workspace.md: d2a32d47a407dcf211c1cad8bb98f29847a77a3b +2026-09-20-default-workspace.zh.md: 6b0ec542da6e9e4fe76fb56b6562edea9e5777f4 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md new file mode 100644 index 0000000000..d2a32d47a4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -0,0 +1,32 @@ +# Agent Note: First-use default Workspace + +Status: implemented + +English | [中文](2026-09-20-default-workspace.zh.md) + +## Problem + +A new installation requires a directory choice before the user can send a first message. Removing that prerequisite must preserve the Session's fixed working directory and must not treat hidden or archived history as a new installation. + +## Decision + +The conversation shell retains an unsent local text draft without creating a Session. Its first send asks the Host to prepare a default Workspace, then connects a real Session and submits through the ordinary composer pipeline. The first-use draft awaits staged mode selection before automatic submission. This partially supersedes the locked no-Session composer in [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md); that note still owns blank-Session reuse and provisioning rationale. + +The [Workspace registry](../../../../packages/workspace/workspace/README.md#first-use-workspace) owns eligibility and directory preparation. All live Sessions, persisted headers, and archived identities count, including entries absent from the sidebar. The operation shares the registry mutation queue and rechecks Session history after directory preparation because Sessions can start independently. + +The Client resolves the initial directory name and title from its language when sending. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). + +Creation failure preserves the draft and offers the existing folder picker. A successful registration survives Session creation or prompt failure. Picking a folder after failure transfers the text without sending it; a later send remains the user's action. + +## Alternatives considered + +- Creating on application startup would write directories for users who never send a message. +- Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. +- Using the localized path as the initialization marker would allow language changes or deletion to create another default. +- Changing a Session's cwd after creation would change the meaning of its recorded tools and attachments. + +## Consequences + +First-use typing has no Host Session or filesystem effects. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. + +The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and draft recovery; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled first-send and picker paths with an isolated Documents directory and recorded Session replay. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md new file mode 100644 index 0000000000..6b0ec542da --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 首次使用默认 Workspace + +Status: implemented + +[English](2026-09-20-default-workspace.md) | 中文 + +## Problem + +新安装的应用要求用户先选目录才能发送第一条消息。去掉这一步前置操作时,必须保留 Session 的固定工作目录,也不能把隐藏或已归档的历史误判为新安装。 + +## Decision + +会话外壳保存未发送的本地文本草稿,不创建 Session。首次发送请求 Host 准备默认 Workspace,随后连接真实 Session,并通过常规 composer 流程提交。首次使用的草稿会在自动提交前等待暂存的模式选择完成。这部分取代[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)中无 Session 时锁定 composer 的决策;该记录仍负责 blank Session 复用与供给通道的理由。 + +[Workspace registry](../../../../packages/workspace/workspace/README.zh.md#first-use-workspace)负责资格判断和目录准备。所有 live Session、持久化 header 和已归档身份都计入判断,包括侧栏中不可见的条目。操作共用 registry 修改队列,并在目录准备后重新检查 Session 历史,因为 Session 可以独立启动。 + +Client 在发送时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 + +创建失败时保留草稿,并提供现有文件夹选择器。成功的登记会在 Session 创建或提示词发送失败后保留。失败后选择文件夹只转移文本,不发送;随后发送仍由用户操作。 + +## Alternatives considered + +- 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 +- 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 +- 在 Session 创建后更改 cwd,会改变其已记录工具和附件的含义。 + +## Consequences + +首次使用时输入文本不会产生 Host Session 或文件系统副作用。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 + +该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及草稿恢复;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的首次发送与选择器路径。 diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts new file mode 100644 index 0000000000..00bec9de3c --- /dev/null +++ b/apps/web/tests/default-workspace.e2e.ts @@ -0,0 +1,122 @@ +/** First-use messages prepare a durable Workspace through the shipped Web composition. */ +import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { describe, expect, it } from 'vitest' +import { + captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, + selectedSessionFixture, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) +const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) +const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) +const MODE = webSnapshotMode() + +describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { + it('sends the first draft in a newly selected default Workspace and keeps its identity across reload', async () => { + const fixture = await selectedSessionFixture(FIXTURE) + const scaffold = await launchWebScaffold({ + replayFixture: fixture, + // The shared recording remains read-only; replay compares the complete persisted Session. + compareReplaySession: MODE === 'replay', + paceMs: 5, + }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + try { + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.waitFor() + const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! + await input.fill(prompt) + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + const settled = scaffold.whenTurnSettled() + await input.press('Enter') + const sessionId = await settled + const workspace = scaffold.ctx.workspaceRegistry.list()[0]! + expect(workspace.title).toBe('Default workspace') + expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) + expect((await stat(workspace.path)).isDirectory()).toBe(true) + expect(workspace.sessionIds).toContain(sessionId) + expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await page.getByText('DONE', { exact: true }).waitFor() + await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + await page.reload() + await page.getByText('DONE', { exact: true }).waitFor() + expect(scaffold.ctx.workspaceRegistry.list().map(item => item.id)).toEqual([workspace.id]) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace') + throw error + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + }) + + it('keeps the draft on a directory conflict and opens the composed folder picker for recovery', async () => { + const scaffold = await launchWebScaffold() + try { + const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') + await mkdir(parent, { recursive: true }) + await writeFile(join(parent, '默认工作区'), 'occupied') + const chosen = join(scaffold.workspaceCwd, 'chosen') + await mkdir(chosen) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) + try { + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.fill('保留这条消息') + await input.press('Enter') + const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) + await modal.waitFor() + await expect.poll(() => input.textContent()).toBe('保留这条消息') + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) + await modal.getByRole('button', { name: '取消', exact: true }).click() + expect(await input.textContent()).toBe('保留这条消息') + await input.press('Enter') + await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + const picker = page.getByRole('dialog', { name: '选择工作区目录' }) + await picker.waitFor() + await picker.getByRole('button', { name: '编辑路径', exact: true }).click() + await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) + await page.keyboard.press('Enter') + await picker.getByRole('button', { name: '打开', exact: true }).click() + await picker.waitFor({ state: 'hidden' }) + await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) + await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor() + await expect.poll(() => input.textContent()).toBe('保留这条消息') + expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(scaffold.ctx.sessions.list().every(session => + session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace-failure') + throw error + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + }) +}) diff --git a/apps/web/tests/expected/default-workspace/failure.expected.md b/apps/web/tests/expected/default-workspace/failure.expected.md new file mode 100644 index 0000000000..6944d1cf14 --- /dev/null +++ b/apps/web/tests/expected/default-workspace/failure.expected.md @@ -0,0 +1,6 @@ +- dialog "无法创建默认工作区": + - heading "无法创建默认工作区" [level=2] + - button "关闭" + - text: 请选择一个文件夹后重试 + - button "取消" + - button "选择文件夹" diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index e7249a0b67..75371e73b2 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -600,6 +600,8 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { } /** - * Drive the hero's workspace picker through the composed directory dialog - * until the live composer unlocks. A fresh world has no Workspace, so the boot - * lands in the Workspace-trigger view state (startup auto-selection has nothing to - * select); every scenario that types into the composer must connect one - * first. With nothing to list, activating the composer surface raises the dialog directly — - * adding a workspace is the picker's only entry. The directory is staged here - * and adopted through the path editor, which is idempotent across the repeated - * connects a scenario may make; creating a folder from inside the dialog (the - * product's other half of the same route) is covered by - * workspace-management.e2e.ts. The default name 'workspace' keeps the session - * header cwd at /workspace, the materialization proof several scenarios - * assert. + * Select a staged directory through the hero's composed Workspace picker. + * The default name keeps the Session cwd at /workspace for scenarios + * that require a specific directory instead of automatic first-use preparation. * @param page - the page under test. * @param root - host directory the workspace folder is staged in (the scaffold's `workspaceCwd`). * @param name - folder name staged and adopted as the workspace. */ export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('textbox', { name: 'Choose workspace' }).click() + await page.getByRole('button', { name: 'Choose workspace', exact: true }).click() const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: 'Edit path' }).click() @@ -131,8 +122,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - // The pick connected the workspace: the blank session's live composer - // replaces the locked placeholder and enables. + await page.getByRole('treeitem', { name: 'New Session', exact: true }).waitFor({ timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -148,7 +138,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo */ export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('textbox', { name: '选择工作区' }).click() + await page.getByRole('button', { name: '选择工作区', exact: true }).click() const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: '编辑路径' }).click() @@ -156,6 +146,7 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() + await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor({ timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4508e03def..8560d4f99e 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -63,6 +63,7 @@ "tests/deepseek-messages-chat.e2e.ts", "tests/models-settings-recovery.e2e.ts", "tests/default-model.e2e.ts", + "tests/default-workspace.e2e.ts", "tests/github-ready-review.e2e.ts", "tests/streaming-fence-highlight.e2e.ts", "tests/declared-reasoning.e2e.ts", diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 106e1545fb..4274817f94 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: dad6b57ae0712e04ad16729b4067c541f83c68d6 -config-catalog.zh.md: 4ba0378810f3db4797c0d41fa5230f7069438b3f +config-catalog.md: c3dabe13807ef3ec2db7d861fdc93f9016260bc7 +config-catalog.zh.md: bd3b7e4dbc64627b6b9904360fcfb13f7f3da43e diff --git a/docs/config-catalog.md b/docs/config-catalog.md index dad6b57ae0..c3dabe1380 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -274,6 +274,24 @@ export interface Config { Source: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts) + + +## `@deepseek-ai/dsh-api-workspace-controller` + +Requires: `typert` · `workspaceRegistry` + +```ts config-catalog +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} +``` + +Source: [`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts) + ## `@deepseek-ai/dsh-api-workspace-files` @@ -3783,7 +3801,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-acp-app` — requires `cmdlineArgs` ([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts)) - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) - `@deepseek-ai/dsh-api-remotes` — requires `typertGateway` ([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts)) -- `@deepseek-ai/dsh-api-workspace-controller` — requires `typert` · `workspaceRegistry` ([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts)) - `@deepseek-ai/dsh-authorization` — requires `credentials` ([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts)) - `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts)) - `@deepseek-ai/dsh-client-file-upload` — requires `agents` · `attachments` · `commands` · `connection` ([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts)) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4ba0378810..bd3b7e4dbc 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -276,6 +276,24 @@ export interface Config { 来源: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts) + + +## `@deepseek-ai/dsh-api-workspace-controller` + +需要:`typert` · `workspaceRegistry` + +```ts config-catalog +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} +``` + +源码:[`packages/api/workspace-controller/src/index.ts:34`](../packages/api/workspace-controller/src/index.ts) + ## `@deepseek-ai/dsh-api-workspace-files` @@ -3785,7 +3803,6 @@ export interface Config { - `@deepseek-ai/dsh-acp-app` — 需要 `cmdlineArgs`([`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts)) - `@deepseek-ai/dsh-agent`([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) - `@deepseek-ai/dsh-api-remotes` — 需要 `typertGateway`([`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts)) -- `@deepseek-ai/dsh-api-workspace-controller` — 需要 `typert` · `workspaceRegistry`([`packages/api/workspace-controller/src/index.ts`](../packages/api/workspace-controller/src/index.ts)) - `@deepseek-ai/dsh-authorization` — 需要 `credentials`([`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts)) - `@deepseek-ai/dsh-browser-use` ([`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts)) - `@deepseek-ai/dsh-client-file-upload` — 需要 `agents` · `attachments` · `commands` · `connection`([`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts)) diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index db7bb548ef..a7a3e3bb91 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: 9fe5f2bf4c62ba7d4f878b7b2f34490f43ca0b81 -workspace.zh.md: 63681e1a459c81a327654cfafa1f5cb2f231d6c8 +workspace.md: b68acd965b55df462a0751d0b7e3230c82a62172 +workspace.zh.md: 074f59438eb16a4ffb1423540c3e1868857ae40f diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 9fe5f2bf4c..b68acd965b 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -121,6 +121,10 @@ Ownership truth is the record's ordered `sessionIds`, never derived from session Sessions get their cwd at create time from whoever creates them, not from this registry — the API gateway resolves a new session's cwd from the chosen workspace's `path` (falling back to an explicit or default cwd), creates the session so the cwd lands in its immutable [`SessionHeader`](persistence.md#sessionheader--metadata-beside-the-log), then calls `attachSession`, which re-validates that stored header cwd against the workspace path. On the first successful start, the registry bootstraps history from persisted headers alone (`id`, `cwd`, `createdAt` — never event bodies), grouping sessions with a valid canonical cwd into per-directory workspaces, newest first; the initialized marker is written last so an interrupted bootstrap resumes safely. The bootstrap is one-time: cwd-less legacy sessions stay Ungrouped, and sessions created afterwards join a workspace only through `attachSession`. +## Default Workspace initialization + +The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspaceInitializeDefaultRequest`: a Client-resolved `directoryName` and initial `title`. The Host resolves the Documents location and asks the registry to initialize once. Locale selection belongs to the Client; the registry accepts a directory resolver and commits the registration with its durable identity. [First-use behavior and configuration](../../packages/api/workspace-controller/README.md#first-use-workspace) describe reuse and failure handling. + ## Session pinning The controller's [transport types](../../packages/api/workspace-controller/src/types.ts) define `WorkspacePinSessionRequest` and `WorkspaceUnpinSessionRequest`, each carrying one `sessionId`. Both operations return `WorkspacePinValue`: the complete `pinnedSessionIds` array of Session ids, most recently pinned first. Pinning requires a known, unarchived Session; unpinning an id that is not pinned succeeds without changing the set. Archiving removes the Session's pin in the same durable write, and unarchiving does not restore it. @@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace. */ @Remote('create') create(request: WorkspaceCreateRequest): Promise +/** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. @@ -466,6 +478,17 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c */ async create(path: string, title?: string): Promise +/** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ +initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise + /** * Look up a workspace by id. * @param id - Workspace id. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 63681e1a45..074f59438e 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -121,6 +121,10 @@ interface Workspace { 会话的 cwd 在创建时由创建者赋予,而不是由本注册表赋予——API 网关从所选工作区的 `path` 解析新会话的 cwd(回退到显式或默认 cwd),先创建会话使 cwd 落入其不可变的 [`SessionHeader`](persistence.zh.md#sessionheader--metadata-beside-the-log),再调用 `attachSession`,后者会把已存储的 header cwd 与工作区路径重新校验一遍。首次成功启动时,注册表仅凭已持久化的 header(`id`、`cwd`、`createdAt`——绝不读事件正文)引导历史:把规范 cwd 有效的会话按目录分组为工作区,最新的排在最前;「已初始化」标记最后写入,因此被中断的引导可以安全续跑。引导只发生这一次:没有 cwd 的历史遗留会话保持 Ungrouped,此后创建的会话只能通过 `attachSession` 加入工作区。 +## 默认工作区初始化 + +控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspaceInitializeDefaultRequest`,包含 Client 解析出的 `directoryName` 和初始 `title`。Host 解析 Documents 位置,并请求注册表执行一次初始化。语言选择由 Client 负责;注册表接收目录解析器,并将登记与持久化身份一起提交。[首次使用行为与配置](../../packages/api/workspace-controller/README.zh.md#first-use-workspace)说明复用和失败处理。 + ## 会话置顶 控制器的[传输类型](../../packages/api/workspace-controller/src/types.ts)定义了 `WorkspacePinSessionRequest` 和 `WorkspaceUnpinSessionRequest`,两者都携带一个 `sessionId`。两个操作都返回 `WorkspacePinValue`:完整的会话 id 数组 `pinnedSessionIds`,最近置顶的会话排在前面。置顶要求会话已知且未归档;对未置顶的 id 取消置顶会成功,且不改变集合。归档在同一次持久化写入中移除该会话的置顶,取消归档不会恢复置顶。 @@ -301,6 +305,14 @@ Host service backing the generated `ctx.remote.workspace` namespace. */ @Remote('create') create(request: WorkspaceCreateRequest): Promise +/** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. @@ -466,6 +478,17 @@ Durable workspace registry. Startup waits for `sessionPersistence`, builds one c */ async create(path: string, title?: string): Promise +/** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ +initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise + /** * Look up a workspace by id. * @param id - Workspace id. diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index cd584226a9..e7bc836965 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 46556b0105bb5186cf27b56faee4127b358eac9b -README.zh.md: 9d210c10486a71772cf6c0a10480b734fa992441 +README.md: 275c51d0018dda5b2209cc7bece71b618e7d113d +README.zh.md: 92ca3f86f11ce77b51f834ce7c24f195095065b1 diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 46556b0105..275c51d001 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -26,6 +26,18 @@ The Host controller serializes mutations whose correctness depends on current re The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream()`. The model owns Workspace rows, registry order, archived and pinned Session identities, unary mutation echoes, and stream/unary race resolution. A newer Host row wins by `updatedAt`; a committed stream order outranks an older unary response; a removed Workspace id cannot be resurrected by delayed data. Pin snapshots change only when their identities or order change. The package exposes framework-neutral snapshots and subscriptions, leaving navigation policy and React hooks to the UI owner. + +### First-use Workspace + +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory. + +The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. + +| Configuration | Default | Purpose | +| --- | --- | --- | +| `documentsDirectory` | System Documents directory | Fully qualified Host directory override | +| `documentsLookupTimeoutMs` | `10000` | Positive maximum duration of OS directory lookup, in milliseconds | + ----- diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index 9d210c1048..92ca3f86f1 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -26,6 +26,18 @@ Host 控制器会串行执行正确性取决于当前注册表状态的变更, Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。该模型拥有 Workspace 行、registry 顺序、归档与置顶会话身份、一元变更回显,以及流与一元调用的竞态处理。较新的 Host 行按 `updatedAt` 获胜;已提交的流顺序优先于较旧的一元响应;已经移除的 Workspace id 不会被延迟数据复活。置顶快照仅在会话身份或顺序变化时更新。该包公开与框架无关的快照和订阅,把导航策略与 React 钩子留给 UI owner。 + +### 首次使用工作区 + +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录。 + +[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 + +| 配置 | 默认值 | 用途 | +| --- | --- | --- | +| `documentsDirectory` | 系统 Documents 目录 | 完全限定的 Host 目录覆盖值 | +| `documentsLookupTimeoutMs` | `10000` | 操作系统目录查询的正数最大时长,单位为毫秒 | + ----- diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index 48881e37ce..8085412c62 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -66,6 +66,8 @@ "license": "MIT", "dependencies": { "@deepseek-ai/dsh-deque": "workspace:^", + "@deepseek-ai/dsh-native-command": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", "zod": "^4.4.3" }, "peerDependencies": { diff --git a/packages/api/workspace-controller/src/client/index.ts b/packages/api/workspace-controller/src/client/index.ts index 9a1af4c2e7..a9a98085f8 100644 --- a/packages/api/workspace-controller/src/client/index.ts +++ b/packages/api/workspace-controller/src/client/index.ts @@ -17,7 +17,7 @@ export type { } from './model.ts' export { WorkspaceController, WorkspaceCreateError } from './service.ts' export type { IWorkspaces, WorkspaceSource } from './service.ts' -export type { WorkspaceId, WorkspaceView } from '../types.ts' +export type { WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts' type WorkspaceBaselineFrame = Extract diff --git a/packages/api/workspace-controller/src/client/model.ts b/packages/api/workspace-controller/src/client/model.ts index 570b70aeb3..3f6dda9f76 100644 --- a/packages/api/workspace-controller/src/client/model.ts +++ b/packages/api/workspace-controller/src/client/model.ts @@ -12,6 +12,7 @@ import type { WorkspaceCreateValue, WorkspaceDeleteValue, WorkspaceInsertSessionBeforeRequest, + WorkspaceInitializeDefaultRequest, WorkspaceOrderValue, WorkspacePinSessionRequest, WorkspacePinValue, @@ -101,6 +102,18 @@ export class ClientWorkspaceModel implements WorkspaceFollowSink { return result } + /** + * Initialize the default Workspace and merge its authoritative row. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns generated Remote result. + */ + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise> { + const result = await this.remote.initializeDefault(request, signal) + if (result.ok) this.upsert(result.value.workspace) + return result + } + /** * Rename a Workspace and merge the unary result immediately. * @param workspaceId - target Workspace. diff --git a/packages/api/workspace-controller/src/client/service.ts b/packages/api/workspace-controller/src/client/service.ts index 00998f8519..f94baafdb2 100644 --- a/packages/api/workspace-controller/src/client/service.ts +++ b/packages/api/workspace-controller/src/client/service.ts @@ -4,7 +4,7 @@ import { Service, type Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteFailure } from '@deepseek-ai/dsh-typert-protocol' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' -import type { WorkspaceView } from '../types.ts' +import type { WorkspaceInitializeDefaultRequest, WorkspaceView } from '../types.ts' import type { ClientWorkspaceModel, WorkspaceSnapshot } from './model.ts' /** Structured create failure for callers that distinguish Host business errors. */ @@ -39,6 +39,13 @@ export interface IWorkspaces { * @returns the created or idempotently resolved Workspace. */ create(input: { path: string }): Promise + /** + * Initialize or reuse the default Workspace. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns the prepared Workspace; rejects when directory selection is required. + */ + initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise /** * Rename a Workspace. * @param workspaceId - target Workspace. @@ -110,6 +117,12 @@ export class WorkspaceController extends Service implements IWorkspaces { return result.value.workspace } + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + const result = await this.model.initializeDefault(request, signal) + if (!result.ok) throw new WorkspaceCreateError(result.error) + return result.value.workspace + } + async rename(workspaceId: WorkspaceId, title: string): Promise { const result = await this.model.rename(workspaceId, title) if (!result.ok) throw commandError('rename', result.error) diff --git a/packages/api/workspace-controller/src/default-directory.ts b/packages/api/workspace-controller/src/default-directory.ts new file mode 100644 index 0000000000..2001b903c6 --- /dev/null +++ b/packages/api/workspace-controller/src/default-directory.ts @@ -0,0 +1,79 @@ +/** Resolve the Host account's Documents directory for first-use Workspace creation. */ + +import { homedir } from 'node:os' +import { posix, win32 } from 'node:path' +import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' + +/** Platform observations replaceable in directory-resolution tests. */ +interface DocumentsDirectoryInternals { + readonly platform?: NodeJS.Platform + readonly home?: string + readonly run?: NativeCommandRunner +} + +/** + * Validate a configured or OS-returned Documents path without resolving it against cwd. + * @param directory - fully qualified directory spelling. + * @param platform - Host platform. + * @returns the normalized directory. + */ +export function validateDocumentsDirectory(directory: string, platform: NodeJS.Platform = process.platform): string { + const paths = platform === 'win32' ? win32 : posix + const root = paths.parse(directory).root + if (!paths.isAbsolute(directory) || (platform === 'win32' && (root === '\\' || root === '/'))) { + throw new Error(`Documents directory must be fully qualified: '${directory}'`) + } + return paths.normalize(directory) +} + +/** + * Resolve the first-use directory on the Host without creating files. + * @param directoryName - validated single directory name supplied by the Client. + * @param documentsDirectory - explicit deployment override for the system Documents directory. + * @param signal - caller lifetime and lookup deadline. + * @param internals - platform facts and native command runner. + * @returns the absolute candidate path. + */ +export async function defaultWorkspaceDirectory( + directoryName: string, + documentsDirectory: string | undefined, + signal: AbortSignal, + internals: DocumentsDirectoryInternals = {}, +): Promise { + const platform = internals.platform ?? process.platform + const paths = platform === 'win32' ? win32 : posix + signal.throwIfAborted() + let directory = documentsDirectory + if (directory === undefined) { + const run = internals.run ?? runNativeCommand + let stdout: string + switch (platform) { + case 'darwin': + ({ stdout } = await run('osascript', [ + '-e', 'POSIX path of (path to documents folder from user domain without folder creation)', + ], signal)) + break + case 'win32': + ({ stdout } = await run('powershell.exe', [ + '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', + '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' + + '[Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments, ' + + '[Environment+SpecialFolderOption]::DoNotVerify)', + ], signal)) + break + case 'linux': + ({ stdout } = await run('xdg-user-dir', ['DOCUMENTS'], signal)) + break + default: + throw new Error(`system Documents directory is unavailable on ${platform}`) + } + directory = stdout.replace(/[\r\n]+$/, '') + // XDG reports the home directory when this user directory is disabled. + if (directory === '' || (platform === 'linux' && paths.normalize(directory) === (internals.home ?? homedir()))) { + throw new Error('system Documents directory is unavailable') + } + } + directory = validateDocumentsDirectory(directory, platform) + signal.throwIfAborted() + return paths.join(directory, 'deepseek-harness', directoryName) +} diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index deb547e791..2281273e1e 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -1,10 +1,12 @@ /** Host Workspace Remote owner: explicit commands and reconnect-safe state. */ import { Context } from '@deepseek-ai/cordis' -import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import z from '@deepseek-ai/schemastery' +import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { WorkspaceCommands } from './commands.ts' import { DirectoryPickerController } from './directory-picker.ts' -import { WorkspaceFeed } from './feed.ts' +import { WorkspaceFeed, workspaceView } from './feed.ts' +import { defaultWorkspaceDirectory, validateDocumentsDirectory } from './default-directory.ts' import type { WorkspaceArchiveSessionRequest, WorkspaceArchiveValue, @@ -14,6 +16,7 @@ import type { WorkspaceDeleteValue, WorkspaceFollowFrame, WorkspaceInsertBeforeRequest, + WorkspaceInitializeDefaultRequest, WorkspaceInsertSessionBeforeRequest, WorkspaceOrderValue, WorkspacePinSessionRequest, @@ -27,6 +30,14 @@ import type { export type * from './types.ts' export { DirectoryPickerController } from './directory-picker.ts' +/** First-use directory policy for the Host account. */ +export interface Config { + /** Override the system Documents directory with a fully qualified path. */ + documentsDirectory?: string + /** Maximum duration of the operating system's Documents lookup. */ + documentsLookupTimeoutMs?: number +} + declare module '@deepseek-ai/cordis' { interface Context { /** Host Workspace business API and Remote namespace owner. */ @@ -38,12 +49,20 @@ declare module '@deepseek-ai/cordis' { export class WorkspaceController extends TypertRemoteService { static inject = ['typert', 'workspaceRegistry'] + static Config: z = z.object({ + documentsDirectory: z.string(), + documentsLookupTimeoutMs: z.natural().min(1).default(10_000), + }) + + private readonly config: Config private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed - /** @param ctx - Host context containing the Workspace registry. */ - constructor(ctx: Context) { + /** @param ctx - Host context containing the Workspace registry. @param config - first-use directory policy. */ + constructor(ctx: Context, config: Config = {}) { super(ctx, 'workspaceController', { namespace: 'workspace' }) + this.config = WorkspaceController.Config(config) + if (this.config.documentsDirectory !== undefined) validateDocumentsDirectory(this.config.documentsDirectory) this.commands = new WorkspaceCommands(ctx) this.feed = new WorkspaceFeed(ctx) // This package is the Loader entry for both Remote owners it hosts: the @@ -63,6 +82,32 @@ export class WorkspaceController extends TypertRemoteService { return this.commands.create(request) } + /** + * Initialize or reuse the default Workspace before the first user message. + * @param request - initial directory name and title; never rename an existing default. + * @param signal - caller lifetime; cancels native directory lookup. + * @returns the durable Workspace without creating a Session or sending a message. + */ + @Remote('initializeDefault') + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { + const { directoryName, title } = request + if (directoryName.trim() === '' || directoryName !== directoryName.trim() + || directoryName.endsWith('.') || /[/\\:\0]/.test(directoryName) || title.trim() === '') { + throw new RemoteError('gateway/bad-request', 'default Workspace requires a directory name and non-blank title', {}) + } + const workspace = await this.ctx.workspaceRegistry.initializeDefault(async () => { + const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs as number) + const path = await defaultWorkspaceDirectory( + directoryName, this.config.documentsDirectory, AbortSignal.any([signal, timeout]), + ) + return { path, title } + }) + if (workspace === undefined) { + throw new RemoteError('gateway/bad-request', 'choose a directory to create a Workspace', {}) + } + return { workspace: workspaceView(workspace) } + } + /** * Rename one Workspace to a unique non-blank title. * @param request - Workspace identity and proposed title. diff --git a/packages/api/workspace-controller/src/types.ts b/packages/api/workspace-controller/src/types.ts index f2b78e024b..e69c2b8c91 100644 --- a/packages/api/workspace-controller/src/types.ts +++ b/packages/api/workspace-controller/src/types.ts @@ -54,6 +54,14 @@ export interface WorkspaceCreateRequest { readonly path: string } +/** Names chosen by the first-use Client before default Workspace initialization. */ +export interface WorkspaceInitializeDefaultRequest { + /** Single non-blank name; no separators, colon, NUL, surrounding whitespace, or trailing dot. */ + readonly directoryName: string + /** Initial display title, retained across language changes. */ + readonly title: string +} + /** Created or previously registered Workspace. */ export interface WorkspaceCreateValue { readonly workspace: WorkspaceView diff --git a/packages/api/workspace-controller/tests/default-directory.host.spec.ts b/packages/api/workspace-controller/tests/default-directory.host.spec.ts new file mode 100644 index 0000000000..5878f42432 --- /dev/null +++ b/packages/api/workspace-controller/tests/default-directory.host.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest' +import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command' +import { defaultWorkspaceDirectory, validateDocumentsDirectory } from '../src/default-directory.ts' + +describe('system Documents directory', () => { + it.each([ + ['darwin', '/Users/a/文档/\n', '/Users/a/文档/deepseek-harness/默认工作区', 'osascript'], + ['win32', 'D:\\Redirected Documents\r\n', 'D:\\Redirected Documents\\deepseek-harness\\默认工作区', 'powershell.exe'], + ['linux', '/home/a/My Documents\n', '/home/a/My Documents/deepseek-harness/默认工作区', 'xdg-user-dir'], + ] as const)('uses the %s account directory and preserves spaces and Unicode', async (platform, stdout, path, command) => { + const run = vi.fn(async () => ({ stdout, stderr: '' })) + const signal = new AbortController().signal + await expect(defaultWorkspaceDirectory('默认工作区', undefined, signal, { platform, run })).resolves.toBe(path) + expect(run).toHaveBeenCalledWith(command, expect.any(Array), signal) + }) + + it.each(['Default workspace', '默认工作区', 'default-workspace'])('uses the configured directory with name %s', async (folder) => { + const run = vi.fn() + await expect(defaultWorkspaceDirectory(folder, '/documents', new AbortController().signal, { platform: 'linux', run })) + .resolves.toBe(`/documents/deepseek-harness/${folder}`) + expect(run).not.toHaveBeenCalled() + }) + + it.each(['', '\r\n', '/home/a\n'])('rejects an unavailable XDG directory %j', async (stdout) => { + const run: NativeCommandRunner = async () => ({ stdout, stderr: '' }) + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'linux', home: '/home/a', run })) + .rejects.toThrow('unavailable') + }) + + it('propagates lookup failure and cancellation', async () => { + const run: NativeCommandRunner = async () => { throw new Error('lookup denied') } + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'darwin', run })) + .rejects.toThrow('lookup denied') + await expect(defaultWorkspaceDirectory('Default workspace', '/documents', AbortSignal.abort(), { platform: 'linux' })) + .rejects.toThrow() + await expect(defaultWorkspaceDirectory('Default workspace', undefined, new AbortController().signal, { platform: 'freebsd' })) + .rejects.toThrow('unavailable') + }) + + it.each(['relative', 'C:relative', '\\rooted'])('rejects a Windows path without a fully qualified root: %s', (path) => { + expect(() => validateDocumentsDirectory(path, 'win32')).toThrow('fully qualified') + }) + + it('accepts redirected UNC Documents directories', () => { + expect(validateDocumentsDirectory('\\\\server\\share\\Documents', 'win32')).toBe('\\\\server\\share\\Documents') + expect(() => validateDocumentsDirectory('relative', 'linux')).toThrow('fully qualified') + }) +}) diff --git a/packages/api/workspace-controller/tests/model.client.spec.ts b/packages/api/workspace-controller/tests/model.client.spec.ts index b126805183..4558d4f64d 100644 --- a/packages/api/workspace-controller/tests/model.client.spec.ts +++ b/packages/api/workspace-controller/tests/model.client.spec.ts @@ -68,6 +68,7 @@ function deferred(): Deferred { } class FakeWorkspaceRemote implements WorkspaceRemote { + readonly initializeDefault = vi.fn(async () => remoteOk({ workspace: workspace('default') })) readonly calls: Array<{ readonly method: string; readonly request: unknown }> = [] onCreate: (request: WorkspaceCreateRequest) => Promise> = request => Promise.resolve(remoteOk({ workspace: workspace(request.path.split('/').pop() ?? 'workspace'), created: true })) @@ -167,6 +168,22 @@ function baseline( } describe('ClientWorkspaceModel', () => { + it('publishes the prepared Workspace and leaves the list unchanged on refusal', async () => { + const remote = new FakeWorkspaceRemote() + const model = modelFor(remote) + baseline(model) + const signal = new AbortController().signal + await expect(model.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).resolves.toMatchObject({ ok: true }) + expect(remote.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, signal) + expect(model.getSnapshot().items.map(item => item.workspaceId)).toEqual(['default']) + const before = model.getSnapshot() + remote.initializeDefault.mockResolvedValueOnce(workspaceError( + new RemoteError('gateway/bad-request', 'choose a folder', {}), + )) + await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).resolves.toMatchObject({ ok: false }) + expect(model.getSnapshot()).toBe(before) + }) + it('replaces reconnect state and applies ordered increments', () => { const model = modelFor() expect(model.getSnapshot()).toMatchObject({ phase: 'pending', state: 'loading' }) diff --git a/packages/api/workspace-controller/tests/remote/workspace.client.ts b/packages/api/workspace-controller/tests/remote/workspace.client.ts index 6857e8e31d..b8951c0c39 100644 --- a/packages/api/workspace-controller/tests/remote/workspace.client.ts +++ b/packages/api/workspace-controller/tests/remote/workspace.client.ts @@ -91,6 +91,7 @@ export function followGenerations(generations: readonly StreamScript[]): StreamS /** Default answers: every command accepted and echoed back as the row or set it names. */ export const workspaceWorld: RemoteTable = { unary: { + 'workspace/initializeDefault': (): RemoteResult => ok({ workspace: workspace('default') }), 'workspace/create': (request: WorkspaceCreateRequest): RemoteResult => ok({ workspace: workspace('created', { path: request.path }), created: true, }), diff --git a/packages/api/workspace-controller/tests/transport.client.spec.ts b/packages/api/workspace-controller/tests/transport.client.spec.ts index b99406b00c..9829004125 100644 --- a/packages/api/workspace-controller/tests/transport.client.spec.ts +++ b/packages/api/workspace-controller/tests/transport.client.spec.ts @@ -318,6 +318,7 @@ describe('WorkspaceController', () => { expect(controller.list).toBe(model) expect(client.ctx.workspaces.list).toBe(model) + await expect(controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, new AbortController().signal)).resolves.toMatchObject({ workspaceId: 'default' }) await expect(controller.create({ path: '/work/created' })).resolves.toMatchObject({ workspaceId: 'created' }) await expect(controller.rename(wid('one'), 'renamed')).resolves.toMatchObject({ title: 'renamed' }) await expect(controller.insertBefore(wid('one'))).resolves.toBeUndefined() @@ -330,6 +331,7 @@ describe('WorkspaceController', () => { await expect(controller.unpinSession(sid('session'))).resolves.toBeUndefined() await expect(controller.delete(wid('one'))).resolves.toBeUndefined() // Each command crosses the wire as one positional request object. + expect(mock.log.requests('workspace/initializeDefault')).toEqual([{ directoryName: '默认工作区', title: '默认工作区' }]) expect(mock.log.requests('workspace/create')).toEqual([{ path: '/work/created' }]) expect(mock.log.requests('workspace/rename')).toEqual([{ workspaceId: 'one', title: 'renamed' }]) expect(mock.log.requests('workspace/insertBefore')).toEqual([{ workspaceId: 'one' }]) @@ -347,6 +349,9 @@ describe('WorkspaceController', () => { const missingWorkspace = new RemoteError('workspace/not-found', 'gone', { workspaceId: wid('missing') }) const missingSession = new RemoteError('session/not-found', 'missing session', { sessionId: sid('session') }) + mock.remote.workspace.initializeDefault.mockResolvedValueOnce(err(new RemoteError('gateway/internal', 'directory denied', {}))) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })).rejects.toBeInstanceOf(WorkspaceCreateError) + mock.remote.workspace.create.mockResolvedValueOnce(err(new RemoteError('workspace/invalid-path', 'missing path', { path: '/missing' }))) const create = controller.create({ path: '/missing' }) await expect(create).rejects.toBeInstanceOf(WorkspaceCreateError) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index 722b132255..ecaeb9a248 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -59,7 +59,7 @@ async function harness() { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, } as never) - const controller = new WorkspaceController(ctx) + const controller = new WorkspaceController(ctx, { documentsDirectory: root }) return { controller, ctx, root, storageDomain } } @@ -416,3 +416,49 @@ describe('WorkspaceController follow', () => { await expect(closing).resolves.toEqual({ done: true, value: undefined }) }) }) + +describe('first-use Remote', () => { + it.each(['', ' ', '.', '..', '../outside', 'nested/name', 'nested\\name', 'C:outside', 'name\0', '.. ', 'tail.'])( + 'rejects invalid directory name %j before invoking the registry', async (directoryName) => { + const { controller, ctx } = await harness() + const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined) + await expect(controller.initializeDefault({ directoryName, title: 'Default workspace' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + expect(initialize).not.toHaveBeenCalled() + }, + ) + + it('rejects a blank initial title before invoking the registry', async () => { + const { controller, ctx } = await harness() + const initialize = vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockResolvedValue(undefined) + await expect(controller.initializeDefault({ directoryName: 'default-workspace', title: ' ' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + expect(initialize).not.toHaveBeenCalled() + }) + + it('uses the requested display title independently of the directory name', async () => { + const { controller, root } = await harness() + const result = await controller.initializeDefault({ directoryName: 'default-workspace', title: 'Default workspace' }, new AbortController().signal) + expect(result.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) + }) + + it('returns a durable Workspace without allocating a Session', async () => { + const { controller, ctx, root } = await harness() + const signal = new AbortController().signal + const result = await controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal) + expect(result.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) + expect(existsSync(result.workspace.path)).toBe(true) + expect(ctx.sessions.list()).toEqual([]) + expect(await controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).toEqual(result) + }) + + it('rejects ineligible first use and propagates preparation failures', async () => { + const { controller, ctx, root } = await harness() + await ctx.workspaceRegistry.create(root) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockRejectedValueOnce(new Error('permission denied')) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) + .rejects.toThrow('permission denied') + }) +}) diff --git a/packages/api/workspace-controller/tsconfig.host.json b/packages/api/workspace-controller/tsconfig.host.json index 10c17a0c23..17fda7ee38 100644 --- a/packages/api/workspace-controller/tsconfig.host.json +++ b/packages/api/workspace-controller/tsconfig.host.json @@ -10,15 +10,18 @@ "src/types.ts", "src/commands.ts", "src/directory-picker.ts", - "src/feed.ts" + "src/feed.ts", + "src/default-directory.ts" ], "references": [ { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, { "path": "../../core/session" }, { "path": "../../host/directory-picker" }, { "path": "../../storage/storage-domain" }, { "path": "../../typert/protocol" }, { "path": "../../util/deque" }, + { "path": "../../util/native-command" }, { "path": "../../workspace/workspace" } ] } diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 2ed6513974..7f0a28c544 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md -README.md: c7a87da591c1cafc433fbb3bb5fa216d94ab85ef -README.zh.md: a54b47baed132e790fc4f44ad1155f48a19c430b +README.md: 38eba97e2c11ed319a9a5724bece1fbbd1f8095a +README.zh.md: 730c363c0876c6f6bc9ee8565aeb922526ed8f3d diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index c7a87da591..38eba97e2c 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -49,6 +49,8 @@ The settings section writes the Host's existing `agent-presets` namespace throug The chip follows the preset projection of its bound Session while its plugin and Provider generation remain active. Settings synchronization creates the same bound controller when needed, even before the chip mounts. A late projection or another client's preset update refreshes the display without submitting a selection; list notifications do not repeat an in-flight selection. Settings changes wait for that selection and recheck the captured blank Session before applying. A choice staged during a pending request remains available afterward. +After preparing a default Workspace, the first-use draft waits for the staged preset through `conversation/prepare-first-send`. Concurrent `apply()` calls wait for the active selection without repeating it. A refusal keeps the unsent Session draft. + ----- diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index a54b47baed..730c363c08 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -49,6 +49,8 @@ kind: "package-reference" 只要插件及 Provider generation 仍有效,选择芯片就会跟随其绑定 Session 的预设投影。即使选择芯片尚未挂载,设置同步也会按需创建同一个绑定控制器。延后到达的投影或其他客户端的预设更新会刷新显示,而不会提交选择;列表通知不会重复仍在进行中的选择操作。设置修改会等待该操作结束,并在应用之前重新检查已捕获的空白 Session。请求期间暂存的新选择会保留。 +默认工作区准备完成后,首次使用的草稿通过 `conversation/prepare-first-send` 等待暂存的模式选择。并发的 `apply()` 调用等待已有选择操作,不会重复提交。选择被拒绝时保留未发送的 Session 草稿。 + ----- diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index c335518aff..bc8631e577 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -143,6 +143,14 @@ export function apply(ctx: ClientContext): void { // render and simply hides the button while no flow exists. let creatorDraft: (() => void) | undefined ctx.inject(['slots', 'conversation', 'sessions', 'uiWorkspace'], (scope: ClientContext) => { + scope.on('conversation/prepare-first-send', async (sessionId) => { + const binding = scope.sessions.binding(sessionId) + if (binding === undefined) return + const seat = seatFor(binding) + if (staged.id === undefined && !seat.store.getSnapshot().busy) return + const error = await seat.apply() + if (error !== undefined) throw new Error(error) + }) const seatInjected = (sessionId: SessionId | undefined): AgentPresetSeatInjected => { const binding = sessionId === undefined ? undefined : ctx.sessions.binding(sessionId) const seat = binding === undefined ? unboundSeat : seatFor(binding) diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index 45bd9373e4..4e7488bc3b 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -193,11 +193,18 @@ export class AgentPresetSeatController { * * Called both by `select()` and by whoever observes the current session * changing, because the session may appear either before or after the pick. - * List updates do not repeat a selection while its response is pending. - * @returns this attempt's Host refusal, or undefined when successful or no switch starts. + * Concurrent callers wait for the active selection without repeating it. + * @returns the Host refusal, or undefined when successful or no switch starts. */ async apply(): Promise { - if (this.store.getSnapshot().busy) return + let pending = this.pendingSelection + while (pending !== undefined) { + await pending + const error = this.store.getSnapshot().error + if (error !== null) return error + pending = this.pendingSelection + if (pending === undefined && this.staged.id === undefined) return + } const staged = this.staged.id const session = this.currentSession() if (staged === undefined) { diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index 1e28cb44f4..ea312699ce 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -747,10 +747,12 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) + await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() // Connecting a workspace produced the session; the stage reaches it there. await vi.waitFor(() => { expect(calls).toContain('select:minimal') }) + expect(calls.filter(call => call === 'select:minimal')).toHaveLength(1) }) it('applies the stage to a session that records no preset of its own', async () => { @@ -946,6 +948,28 @@ describe('ui-agent-preset apply', () => { }) describe('AgentPresetSeatController reconciliation', () => { + it.each([false, true])('shares the result of an active preset selection (refused: %s)', async (refused) => { + const refusal = { ok: false as const, error: new RemoteError('gateway/internal', 'selection refused', {}) } + const reply = Promise.withResolvers<{ ok: true; value: string } | typeof refusal>() + const select = vi.fn(() => reply.promise) + const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never, + () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) + const selecting = controller.select('minimal') + let prepared = false + const preparation = controller.apply().finally(() => { prepared = true }) + try { + expect(prepared).toBe(false) + expect(select).toHaveBeenCalledOnce() + reply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) + await expect(preparation).resolves.toBe(refused ? 'selection refused' : undefined) + await selecting + expect(select).toHaveBeenCalledOnce() + } finally { + reply.resolve({ ok: true, value: 'minimal' }) + await Promise.allSettled([selecting, preparation]) + } + }) + it.each([ { refuseFirst: false, refuseLatest: false }, { refuseFirst: false, refuseLatest: true }, @@ -966,16 +990,17 @@ describe('AgentPresetSeatController reconciliation', () => { const first = controller.select('minimal') let settingsSettled = false const settings = controller.syncBlankSession(session.id, 'cordis').finally(() => { settingsSettled = true }) - await controller.apply() + const repeatedFirst = controller.apply() expect(requests.map(request => request.preset)).toEqual(['minimal']) requests[0]!.outcome.resolve(refuseFirst ? refusal : { ok: true, value: 'minimal' }) await first expect(requests.map(request => request.preset)).toEqual(['minimal', 'cordis']) expect(settingsSettled).toBe(false) - await controller.apply() + const repeatedLatest = controller.apply() expect(requests).toHaveLength(2) requests[1]!.outcome.resolve(refuseLatest ? refusal : { ok: true, value: 'cordis' }) await expect(settings).resolves.toBe(refuseLatest ? 'selection refused' : undefined) + await Promise.all([repeatedFirst, repeatedLatest]) expect(controller.store.getSnapshot()).toMatchObject({ current: refuseLatest ? 'standard' : 'cordis', busy: false, error: refuseLatest ? 'selection refused' : null, @@ -992,10 +1017,10 @@ describe('AgentPresetSeatController reconciliation', () => { () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) const first = controller.select('minimal') controller.stage('cordis', true) - await controller.apply() + const repeated = controller.apply() expect(select).toHaveBeenCalledOnce() firstReply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await first + await Promise.all([first, repeated]) expect(controller.store.getSnapshot().current).toBe('cordis') await controller.apply() expect(select.mock.calls.map(call => call[1])).toEqual(['minimal', 'cordis']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 74cd3168df..2002de04c1 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: fef3a6551b517af2ac636687883864525aac70ee -README.zh.md: e9ab08c686420c38c11ca2bede2fd00099a247a5 +README.md: 56b9d06ce5e48ab40691bede2ccb9669e180aa9f +README.zh.md: fd02565698171e0b6db35080181e57b8b5abd42d diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index fef3a6551b..56b9d06ce5 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -50,6 +50,10 @@ Claimed commands retain their identity and highlight when only their arguments a Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. +The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. + +On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. + 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. 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 container reserves a 40px drag band on macOS desktop and no empty vertical space on Web, Windows, or Linux. 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. @@ -60,7 +64,7 @@ The shell reads the persisted View preference before rendering when a Session fi Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer intentionally owns its full footer band, which is not a resize target; an already-captured drag lifts its indicator until release ([handle styles](src/client/skeleton/ConversationRoot.module.css)). -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. Before a Session exists, the composer holds a local text draft; sending waits for complete Workspace and Session baselines and then prepares the default Workspace. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index e9ab08c686..fd02565698 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -50,6 +50,10 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在该请求仍为当前请求时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 +Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 + +首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 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。共享正文与 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 不挂载;常驻容器在 macOS 桌面保留 40px 拖拽区域,在 Web、Windows 或 Linux 上不预留空白高度。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。 @@ -60,7 +64,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 刻意拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会将指示线提高到松开为止([拖动手柄样式](src/client/skeleton/ConversationRoot.module.css))。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。Session 尚未存在时,composer 保存本地文字草稿;发送会等待 Workspace 与 Session 基线完整加载,然后准备默认工作区。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 3fef945990..02c1f3a593 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,6 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +import type { WorkspaceInitializeDefaultRequest } from '@deepseek-ai/dsh-api-workspace-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' @@ -17,13 +18,13 @@ import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionInjected, DraftFileUploads, } from './contract/slots.ts' -import type { InputNotice } from './contract/input.ts' import { createConversationStore, readConversationViewPreference } from './stores.ts' import { ConversationController, UnsupportedImageMediaTypeError } from './service.ts' import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' +import { FirstDraft } from './input/first-draft.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -64,19 +65,10 @@ export const Config: z = z.object({ // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. -const ABSENT_NOTICES = { - getSnapshot: (): InputNotice | null => null, - subscribe: () => () => {}, -} const ABSENT_BLOCK = { getSnapshot: (): ComposerBlock | undefined => undefined, subscribe: () => () => {}, } -const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() -const ABSENT_LEXICON = { - getSnapshot: () => EMPTY_LEXICON, - subscribe: () => () => {}, -} const ABSENT_MENU_LAUNCHER = { getSnapshot: (): string | null => null, subscribe: () => () => {}, @@ -87,12 +79,19 @@ const ABSENT_FILE_UPLOADS = { subscribe: () => () => {}, } +// ui-workspace consumes Conversation slots, so this reverse runtime dependency +// uses a local method projection to keep the TypeScript project graph acyclic. interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise + openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -206,6 +205,17 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, 'ui-conversation: View selection') const inputHub = new InputHub(ctx, t) + const firstDraft = new FirstDraft(ctx, { + open: (beforeOpen, signal) => { + const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] + return workspaceNavigation.openDefaultWorkspace({ + directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', + title, + }, beforeOpen, signal) + }, + shell: id => inputHub.shell(id), + }) const composerBlocks = new ComposerBlockRegistry() ctx.inject(['commandUi'], (scope) => { @@ -266,8 +276,11 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ConversationInjected => ({ hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), + firstDraft: firstDraft.state, }, + dismissDefaultFailure: () => { firstDraft.dismiss() }, selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { + if (sessionId === undefined) firstDraft.transfer(nextId) if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) const draft = from.snapshot.draft @@ -373,7 +386,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { - keyboard: undefined, + keyboard: firstDraft.shell, addFiles: undefined, removeAttachment: undefined, resolveDraftAttachments: undefined, @@ -381,10 +394,11 @@ export function apply(ctx: Context, config: Config = Config({})): void { toggleCommandMenu: undefined, stop: undefined, hooks: { + composerInput: firstDraft.shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: ABSENT_FILE_UPLOADS, - notices: ABSENT_NOTICES, - lexicon: ABSENT_LEXICON, + notices: firstDraft.shell.notices, + lexicon: firstDraft.shell.lexicon, menuLauncher: ABSENT_MENU_LAUNCHER, }, } @@ -433,6 +447,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }) }, hooks: { + composerInput: shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: conversation.fileUploads, notices: shell.notices, diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index b4cd6b9bdf..be338eb3df 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -34,6 +34,12 @@ export interface SubmitOutcome { readonly text?: string } +/** State of first-use Workspace preparation. */ +export interface FirstDraftState { + readonly busy: boolean + readonly failed: boolean +} + /** Command-mode credential supplied by one input-trigger source. */ export interface CommandClaim { /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 023babf26e..a0d9a6d592 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -16,7 +16,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ComposerBlock } from './composer-blocks.ts' -import type { DraftAttachmentId, InputActions, InputNotice, InputState } from './input.ts' +import type { DraftAttachmentId, FirstDraftState, InputActions, InputNotice, InputState } from './input.ts' import type { ComposerKeyboard, EditSelection } from './draft-editor.ts' import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' @@ -319,8 +319,13 @@ export type ConvViewProps = PropsRuntime<'conversation.view'> export interface ConversationInjected { /** Connect and open a blank Session in the selected Workspace. */ selectWorkspace: (workspaceId: WorkspaceId) => Promise + /** Dismiss default Workspace creation failure without discarding input. */ + dismissDefaultFailure: () => void /** Session-addressed composer block source, or the stable absent source. */ - hooks: { composerBlock: ObservableSnapshot } + hooks: { + composerBlock: ObservableSnapshot + firstDraft: ObservableSnapshot + } } /** Business callbacks injected into the strict Session body. */ @@ -365,7 +370,7 @@ export interface ComposerBarOwnerProps { /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { - keyboard: ComposerKeyboard | undefined + keyboard: ComposerKeyboard addFiles: ((files: readonly File[]) => string | null) | undefined removeAttachment: ((id: DraftAttachmentId) => void) | undefined resolveDraftAttachments: ((ids: readonly DraftAttachmentId[]) => readonly ComposerAttachment[]) | undefined @@ -374,6 +379,8 @@ export interface ComposerBarInjected { toggleCommandMenu: ((selection: EditSelection) => void) | undefined stop: (() => void) | undefined hooks: { + /** Resident editor state, including input before a Session exists. */ + composerInput: ObservableSnapshot /** * Live busy-state submission preference: the delivery mode plain Enter * and the primary Send button use while the addressed agent is busy. diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 73ddc6d7d3..468fc9c198 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -72,6 +72,14 @@ export type { ArbitrateKey, ArbitrateOutcome, ReferenceInsert, TokenSpan } from export type { ComposerBlock, ComposerBlocks } from './contract/composer-blocks.ts' declare module '@deepseek-ai/cordis' { + interface Events { + /** + * Finish staged settings before automatically submitting the first-use draft to its new Session. + * @mode serial + * @param sessionId - destination Session. + */ + 'conversation/prepare-first-send'(sessionId: import('@deepseek-ai/dsh-session/types').SessionId): void | Promise + } interface Context { /** Scope-addressed Conversation actions and per-Session input registry. */ conversation: import('./service.ts').IConversation diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 4f4d0aa300..77bff28708 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -5,8 +5,8 @@ * scoped-event application verbs, the submit transaction plumbing * (adjudicate via the session's InputTriggerController; claim.submit; default * sink), the notice channel, and the draft persistence mirror. - * Package-private; the hub alone constructs it and wires the scoped event - * listeners onto it. + * Package-private; InputHub binds Session events, while FirstDraft owns the + * local editor used before a Session exists. */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts new file mode 100644 index 0000000000..9e1c486eae --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/first-draft.ts @@ -0,0 +1,79 @@ +/** Local text draft retained until the first Workspace and Session can accept it. */ +import type { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { FirstDraftState, SubmitOutcome } from '../contract/input.ts' +import type { InputSubmitMode } from '../contract/composer-submission.ts' +import { SessionInputShell } from './facade.ts' + +/** First-use navigation and the resident destination input. */ +interface FirstDraftDeps { + open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise + shell(id: SessionId): SessionInputShell +} + +/** Owns a root-lifetime text editor without allocating a Host Session. */ +export class FirstDraft { + /** Preparation progress and the recoverable directory failure. */ + readonly state = createSnapshotStore({ busy: false, failed: false }) + /** Local editor that stays independent of Host Session allocation. */ + readonly shell: SessionInputShell + private pending: { text: string; transferred: boolean } | undefined + + /** @param ctx - Client plugin lifetime. @param deps - Workspace navigation and Session input access. */ + constructor(private readonly ctx: Context, private readonly deps: FirstDraftDeps) { + this.shell = new SessionInputShell({ + actx: ctx, + defaultSink: (text, _attachments, mode, signal) => this.send(text, mode, signal), + commandAttachments: { + serialize: () => Promise.resolve([]), + release: () => {}, + unsupportedNotice: () => '', + }, + }) + ctx.effect(() => () => { this.shell.dispose() }, 'conversation.input: first-use draft') + } + + /** Dismiss the preparation failure while retaining the draft. */ + dismiss(): void { + this.state.set({ ...this.state.getSnapshot(), failed: false }) + } + + /** + * Move the unsent text to a selected Session. + * @param id - retained destination Session receiving the unsent text. + */ + transfer(id: SessionId): void { + const text = this.pending?.text ?? this.shell.snapshot.draft + if (text !== '') this.deps.shell(id).setDraft(text) + if (this.pending !== undefined) this.pending.transferred = true + this.shell.setDraft('') + this.dismiss() + } + + private async send(text: string, mode: InputSubmitMode, signal: AbortSignal): Promise { + if (this.pending !== undefined) return { kind: 'error' } + const pending = { text, transferred: false } + this.pending = pending + this.state.set({ busy: true, failed: false }) + let target: SessionInputShell | undefined + try { + const id = await this.deps.open((nextId) => { this.transfer(nextId) }, signal) + if (id === undefined) return { kind: pending.transferred ? 'success' : 'error' } + target = this.deps.shell(id) + await this.ctx.serial('conversation/prepare-first-send', id) + signal.throwIfAborted() + target.submit(mode) + return { kind: 'success' } + } catch (error) { + if (!signal.aborted) { + if (target !== undefined) target.notify('error', error instanceof Error ? error.message : String(error)) + else if (!pending.transferred) this.state.set({ busy: true, failed: true }) + } + return { kind: pending.transferred ? 'success' : 'error' } + } finally { + this.pending = undefined + this.state.set({ ...this.state.getSnapshot(), busy: false }) + } + } +} diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 464ff55e17..c66fe10a8a 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -9,6 +9,10 @@ const PLAN_NEXT_ACTION_EN = 'describe your task to generate plan' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.title': '默认工作区', + 'defaultWorkspace.retry': '请选择一个文件夹后重试', + 'defaultWorkspace.choose': '选择文件夹', 'hint.plan': PLAN_NEXT_ACTION_ZH, 'hint.goal': '输入目标,智能体将持续执行', 'hint.goal.active': '当前目标进行中。可输入 edit 修改 / pause 暂停 / resume 继续 / clear 清除', @@ -360,6 +364,10 @@ export type ConversationKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.title': 'Default workspace', + 'defaultWorkspace.retry': 'Please choose a folder and try again', + 'defaultWorkspace.choose': 'Choose folder', 'hint.plan': PLAN_NEXT_ACTION_EN, 'hint.goal': 'describe the objective for a long-running task', 'hint.goal.active': 'goal active — edit / pause / resume / clear', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index adace1c113..bf6456291f 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' +import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' import { HeroShell, WorkspaceChip, workspaceLabel } from './EmptyHero.tsx' @@ -22,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + selectWorkspace, dismissDefaultFailure, useFirstDraft, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -33,6 +34,8 @@ export function ConversationContent(props: ConversationContentProps) { const inputState = useInput(s => s) const cwd = useSessions(s => sessionId === undefined ? undefined : s.byId[sessionId]?.cwd) const workspaces = useWorkspaces(s => s) + const sessionsReady = useSessions(s => s.phase === 'ready') + const firstDraft = useFirstDraft(s => s) // A plugin this package cannot import (ui-model-selection) says this session cannot // send; its reason is already localized by whoever raised it. const composerBlock = useComposerBlock(block => block) @@ -127,15 +130,13 @@ export function ConversationContent(props: ConversationContentProps) { ) - // The placeholder chip ("Choose workspace") and the Workspace-trigger input travel - // together: no workspace picked yet (cold start, no session at all), or a - // blank session whose workspace vanished (deleted from the sidebar). The - // bar is ONE session-maybe slot rendered unconditionally — inert is a prop, - // not a different tree, so the textarea DOM survives the transition. - const inert = sessionId === undefined || (hero && chipTitle === undefined) - // A raised block is the same inert posture with the blocker's own reason: - // one disabled textarea, never a second tree. The no-workspace state wins - // when both hold — picking a workspace is the earlier prerequisite. + // First-use sending waits for both baselines. A blank Session whose + // Workspace disappeared still requires explicit directory selection. + const needsWorkspace = sessionId !== undefined && hero && chipTitle === undefined + const inert = firstDraft.busy || (sessionId === undefined + ? workspaces.phase !== 'ready' || !sessionsReady + : needsWorkspace) + // Owner availability takes precedence over a Session-specific model block. const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', @@ -144,7 +145,7 @@ export function ConversationContent(props: ConversationContentProps) { disabled: true, placeholder: t('placeholder.workspace'), workspacePickerOpen: pickerOpen, - onRequestWorkspace: () => { setPickerOpen(true) }, + ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), } : blocked // `blocked`, not `disabled`: the bar refuses input either way, but a @@ -191,6 +192,23 @@ export function ConversationContent(props: ConversationContentProps) { {composerSeat} + + + + + )} + > + {t('defaultWorkspace.retry')} + ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx index c57fe69936..f66ee7a96a 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx @@ -1,6 +1,5 @@ -// Resident conversation skeleton. Hero chrome, composer positioning, the -// chain, AND the composer bar (session-maybe slot) stay mounted across -// no-session/session transitions — the bar renders inert via owner props. +// Resident conversation shell keeps the composer mounted across local-draft, +// blank-Session, and active-conversation views. import type { ConversationSlotProps } from '../contract/slots.ts' import { ConversationMainPanel } from './ConversationMainPanel.tsx' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 6a4ea12740..5852e4b5c4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -1,16 +1,12 @@ /** The default composer body: the 'conversation.composer.bar' slot entry. - * Machine state arrives through the standard provide channel - * (useInput + inputActions); the keyboard/DOM command face and stop arrive - * through this entry's own inject, whose hooks compartment binds - * useNotices/useLexicon; layout-phase inputs (variant and placeholder) ride - * the owner props. Session facts - * (running/removed/promptError) are self-selected via useSession. + * The injected input state and keyboard address the current Session or the + * first-use local draft. Standard Session props supply attachment actions; + * owner props control layout and availability. * * The text surface is the shell-owned Lexical editor bound here through * ComposerContentEditable; chips render as decorator portals, and the * keymap registers submit/menu/paste gestures on the editor command layer. - * The no-session state renders the SAME div inert as the Workspace-picker - * trigger instead of a parallel tree. + * The contenteditable remains mounted when the first Session arrives. */ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -42,7 +38,7 @@ import css from './InputBar.module.css' export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ - useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, + useSession, useComposerInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, retryFileUpload, toggleCommandMenu, stop, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, @@ -50,7 +46,7 @@ export const InputBar = memo(function InputBar({ workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { - const input = useInput(s => s) + const input = useComposerInput(s => s) const notice = useNotices(s => s) const busyEnter = useBusyEnter(s => s) void useLexicon // hook seat stays bound by the inject compartment; text-ref decoration rides the shell's editor transforms @@ -64,14 +60,11 @@ export const InputBar = memo(function InputBar({ const planActive = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) // Absent (undefined: no frame yet) and cleared (null) both mean no goal. const hasGoal = useProjection('goal', goal => goal != null) - // Session-maybe: the machine faces are absent together while no session is - // current; the bar renders the same DOM inert instead of a parallel tree. - const live = input !== undefined && keyboard !== undefined && inputActions !== undefined - const draft = input?.draft ?? '' - const editor = keyboard?.editor ?? null + const draft = input.draft + const editor = keyboard.editor const attachments = useMemo( - () => input === undefined || resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), - [resolveDraftAttachments, input?.attachmentIds], + () => resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), + [resolveDraftAttachments, input.attachmentIds], ) const empty = draft.trim() === '' && attachments.length === 0 const uploads = useFileUploads(snapshot => snapshot) @@ -93,8 +86,7 @@ export const InputBar = memo(function InputBar({ // The deployment's image-intake limits (absent while no attachment service // is composed — the pre-check below then defers entirely to the host). const imageLimits = useProjection('imageLimits') - // Prompt failures are ordinary failures (no create/attach transaction exists - // anymore): the toast announces promptError, the draft stays in the machine, + // The toast announces promptError, the draft stays in the machine, // and the user resubmits. A remount over a session whose machine still holds // an unresolved promptError deliberately re-announces it once — the failure // is still pending, and a transient banner is its only surface. Attachment @@ -122,35 +114,30 @@ export const InputBar = memo(function InputBar({ // but its independent Stop below stays available while it runs. const continuable = subagent?.address.mode === 'continuable' const parentOffline = continuable && subagent.parentAvailable !== true - // Running input stays free; locked = session removed, the - // inert no-workspace state, the machine faces absent (no session), or a - // parent-offline continuable child. An owner block also disables input; - // adjudicating and submitting render read-only so the draft stays visible. - const disabled = removed || inert || !live || blocked !== undefined || parentOffline + // Preparation, removed Sessions, and unavailable parents lock editing. + // Adjudicating and submitting keep the draft visible and read-only. + const disabled = removed || inert || blocked !== undefined || parentOffline const locked = disabled // The model seat is the ONE control a block leaves live: every block this // contract has is cleared by choosing a model, so locking it too would leave // the composer asking for the only thing it prevents. The other reasons to // be disabled do lock it — there is no session to choose a model for. - const modelSeatLocked = removed || inert || !live - const machineBusy = input?.phase === 'adjudicating' || input?.phase === 'submitting' - // The no-workspace surface remains the resident DOM node but acts as the - // existing picker trigger. Message controls stay locked until a Session - // exists; the trigger itself is read-only rather than disabled so pointer - // and keyboard users can reach the recovery action. + const modelSeatLocked = removed || inert + const machineBusy = input.phase === 'adjudicating' || input.phase === 'submitting' + // A blank Session whose Workspace was deleted offers directory selection + // through the same resident input node. const workspaceTrigger = inert && !removed && onRequestWorkspace !== undefined const editorDisabled = removed || (locked && !workspaceTrigger) - const editable = live && !locked && !machineBusy + const editable = !locked && !machineBusy const steeringAvailable = subagent === null || subagent.address.mode === 'continuable' const canSteerQueue = !locked && !machineBusy && !commandMenuOpen && empty && running && steeringAvailable && input.queue.length > 0 useEffect(() => { - if (input === undefined || inputActions === undefined) return - if (attachments.length !== input.attachmentIds.length) { + if (inputActions !== undefined && attachments.length !== input.attachmentIds.length) { inputActions.pruneAttachments(attachments.map(attachment => attachment.id)) } - }, [attachments, input?.attachmentIds, inputActions]) + }, [attachments, input.attachmentIds, inputActions]) // Scroll the draft scrollport the minimum that brings the selection focus // into view — the browser's own behavior for typing, performed for the @@ -167,7 +154,7 @@ export const InputBar = memo(function InputBar({ // is ours to perform — switching to a longer draft otherwise leaves the // caret (restored at the draft's end) off screen. useEffect(() => { - if (locked || editor === null) return + if (locked) return focusDraftEditor(editor, revealSelection) }, [locked, sessionId, editor]) @@ -244,12 +231,10 @@ export const InputBar = memo(function InputBar({ } useEffect(() => { - if (keyboard === undefined) return return installDraftFilePicker(keyboard, gate, fileInputRef) }, [keyboard]) useEffect(() => { - if (editor === null || keyboard === undefined) return return installDraftKeymap(editor, keyboard, gate) }, [editor, keyboard]) @@ -262,17 +247,16 @@ export const InputBar = memo(function InputBar({ } const onToggleCommandMenu = (): void => { - if (keyboard === undefined) return // The menu is a combobox over the editor, so the keyboard has to be there // before the launcher opens it: activating the button from the keyboard // leaves focus on the button, and restoring it afterwards would re-track an // empty draft and close the menu again. - if (editor !== null) focusDraftEditor(editor, revealSelection) + focusDraftEditor(editor, revealSelection) toggleCommandMenu?.(keyboard.caretSpan()) } - // The no-session Workspace trigger: the resident editable div acts as the - // picker trigger for keyboard users (no editor is bound in this state). + // When a blank Session loses its Workspace, the resident editable div acts as the + // picker trigger for keyboard users. const onWorkspaceKeyDown = (e: KeyboardEvent): void => { if (!workspaceTrigger) return if (e.key === 'Enter' || e.key === ' ') { @@ -295,7 +279,7 @@ export const InputBar = memo(function InputBar({ const primaryDisabled = primaryStops ? stop === undefined : empty || disabled || machineBusy || uploadsPending const interruptible = running && continuable const primarySubmitMode = resolveSubmitMode(busyEnter, running, 'enter', steeringAvailable) - const plainMessageDraft = !empty && input?.phase === 'plain' && !draft.trimStart().startsWith('/') + const plainMessageDraft = !empty && input.phase === 'plain' && !draft.trimStart().startsWith('/') const primaryLabel = primaryStops ? t('input.stop') : running && steeringAvailable && !disabled && !uploadsPending && plainMessageDraft @@ -306,7 +290,6 @@ export const InputBar = memo(function InputBar({ stop?.() return } - if (keyboard === undefined) return // absent machine: the button is disabled /* v8 ignore next -- defensive: the primary button is disabled for empty, disabled, and pending-upload states. */ if (!empty && !disabled && !machineBusy && !uploadsPending) keyboard.submit(primarySubmitMode) } @@ -314,7 +297,7 @@ export const InputBar = memo(function InputBar({ // Claim ghost hint: rendered by CSS as generated content after the last // paragraph while the claim's args are blank (a hint implies a single-line // token draft). The translated per-command hint wins over the claim's own. - const claimActive = (input?.phase === 'claimed' || input?.phase === 'submitting') + const claimActive = (input.phase === 'claimed' || input.phase === 'submitting') && input.claim !== undefined && draft.startsWith(input.claim.token) const rawHint = claimActive && input.claim.hint !== undefined && draft.slice(input.claim.token.length).trim() === '' @@ -322,7 +305,7 @@ export const InputBar = memo(function InputBar({ : null const hint = ((): string | null => { if (rawHint === null) return null - const commandName = input?.claim?.name ?? '' + const commandName = input.claim?.name ?? '' const hintKey = `hint.${commandName === 'goal' && hasGoal ? 'goal.active' : commandName}` // Dynamic lookup by claimed command name: unknown commands miss the // dictionary and keep the machine's own hint, so the call is wide. @@ -396,7 +379,7 @@ export const InputBar = memo(function InputBar({ scrollRef={scrollRef} editable={editable} editorDisabled={editorDisabled} - phase={input?.phase ?? 'inert'} + phase={input.phase} placeholderText={placeholderText} ariaLabel={workspaceTrigger ? t('hero.chooseWorkspace') : placeholderText} workspaceTrigger={workspaceTrigger} @@ -433,12 +416,12 @@ export const InputBar = memo(function InputBar({ {sessionId === undefined ? null : renderSlot('conversation.input.permission', { locked })} {sessionId === undefined ? null : renderSlot('conversation.input.plan', { locked })} - {input === undefined || sessionId === undefined + {sessionId === undefined ? null : renderSlot('conversation.input.left', {})}
- {input === undefined || sessionId === undefined + {sessionId === undefined ? null : renderSlot('conversation.input.right', {})} {sessionId === undefined ? null : renderSlot('conversation.input.model', { locked: modelSeatLocked })} @@ -482,7 +465,7 @@ export const InputBar = memo(function InputBar({
- {variant === 'composer' && input !== undefined && sessionId !== undefined + {variant === 'composer' && sessionId !== undefined ? renderSlot('conversation.composer.dock', {}) : null} 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 6c12f28cfb..abc74918d5 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -2,6 +2,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { CommandContribution, CommandUiContract } from '@deepseek-ai/dsh-client-ui-commands/client' +import type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { ISession, SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' @@ -73,12 +74,14 @@ async function bench() { opened(id) } const openSession = vi.fn((id: SessionId) => { replaceMain(id) }) + const openDefaultWorkspace = vi.fn(async () => undefined) runtime.ctx.provide('uiWorkspace', { openWorkspace: async (_workspaceId: WorkspaceId, beforeOpen: (id: SessionId) => void) => { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, openSession, + openDefaultWorkspace, } as never) const sessionFake = sessionFakeFor() await runtime.sessions.add({ @@ -136,10 +139,54 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, + locale, openDefaultWorkspace, } } describe('Conversation inject API', () => { + it.each([ + ['zh', '默认工作区', '默认工作区'], + ['en', 'Default workspace', 'Default workspace'], + ['ja', 'default-workspace', 'Default workspace'], + ])('resolves first-use names in the Client using the send-time locale %s', async (language, directoryName, title) => { + const b = await bench() + if (language === 'ja') b.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' }) + const composer = b.composerApi(undefined) + composer.keyboard.paste('first message') + b.locale.setLocale(language) + composer.keyboard.submit('steer') + await vi.waitFor(() => { + expect(b.openDefaultWorkspace).toHaveBeenCalledWith({ directoryName, title }, expect.any(Function), expect.any(AbortSignal)) + expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) + }) + }) + + it('keeps in-flight names fixed and resolves the new locale when retrying a failed first send', async () => { + const b = await bench() + const pending = Promise.withResolvers() + b.openDefaultWorkspace.mockReturnValueOnce(pending.promise) + const composer = b.composerApi(undefined) + b.locale.setLocale('en') + composer.keyboard.paste('keep this draft') + composer.keyboard.submit('steer') + try { + await vi.waitFor(() => { expect(b.openDefaultWorkspace).toHaveBeenCalledOnce() }) + b.locale.setLocale('zh') + expect(b.openDefaultWorkspace.mock.calls[0]?.[0]).toEqual({ directoryName: 'Default workspace', title: 'Default workspace' }) + pending.reject(new Error('directory unavailable')) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('keep this draft') + composer.keyboard.submit('steer') + await vi.waitFor(() => { + expect(b.openDefaultWorkspace).toHaveBeenLastCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(Function), expect.any(AbortSignal)) + expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) + }) + } finally { + pending.resolve(undefined) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + } + }) + it('owns the File action, reads its mounted composer availability, and unregisters on disposal', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) @@ -159,7 +206,7 @@ describe('Conversation inject API', () => { expect(file.available({ sessionId: 'missing' as SessionId })).toBe(false) if (file.ui.kind !== 'action') throw new Error('File must be an action') file.ui.run({ sessionId: 'missing' as SessionId }) - const keyboard = b.composerApi(ROOT).keyboard! + const keyboard = b.composerApi(ROOT).keyboard const open = vi.fn() let available = true const unbind = keyboard.bindFilePicker({ open, available: () => available }) @@ -386,7 +433,8 @@ describe('Conversation inject API', () => { expect(() => { injectBar('ghost' as SessionId).stop!() }).toThrow(/resolved no binding/) const absent = injectBar(undefined) - expect(absent.keyboard).toBeUndefined() + expect(absent.keyboard).toBeDefined() + expect(absent.hooks.composerInput.getSnapshot().draft).toBe('') expect(absent.toggleCommandMenu).toBeUndefined() expect(absent.stop).toBeUndefined() expect(absent.hooks.notices.getSnapshot()).toBeNull() diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index 84e5ba28a1..51513cb28e 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -100,8 +100,10 @@ async function bench(opts?: { blank?: boolean }) { } describe('resident composer', () => { - it('renders the locked view state while no session exists at all', async () => { + it('accepts a local draft before any Session exists and keeps the Workspace chip available', async () => { const runtime = await SlotTestRuntime.create() + runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'pending' }) + await runtime.workspaces.update((draft) => { draft.phase = 'pending' }) provideWorkspaceNavigation(runtime) runtime.ctx.provide('settingsScope', { developerTools: { enabled: createSnapshotStore(true) }, bind: () => stubSettingsScope().scope } as never) const locale = new LocaleRuntime(runtime.ctx) @@ -113,15 +115,21 @@ describe('resident composer', () => { const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') expect(textarea).not.toBeNull() + expect(textarea!.getAttribute('contenteditable')).toBe('false') + await runtime.workspaces.update((draft) => { draft.phase = 'ready' }) + expect(textarea!.getAttribute('contenteditable')).toBe('false') + await act(async () => { + runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'ready' }) + }) expect(textarea!.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea!.getAttribute('contenteditable')).not.toBe('true') - expect(textarea!.getAttribute('aria-haspopup')).toBe('menu') + expect(textarea!.getAttribute('contenteditable')).toBe('true') + expect(textarea!.getAttribute('aria-haspopup')).toBeNull() expect(view.getByTestId('workspace-probe').textContent).toBe('false:0') - fireEvent.click(textarea!) - expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') - expect(textarea!.getAttribute('aria-expanded')).toBe('true') fireEvent.click(view.getByRole('button', { name: '选择工作区' })) - fireEvent.keyDown(textarea!, { key: 'Enter' }) + expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') + expect(textarea!.getAttribute('aria-expanded')).toBeNull() + fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.click(view.getByRole('button', { name: '选择工作区' })) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') expect(view.getByRole('button', { name: '选择工作区' })).toBeTruthy() await runtime.dispose() @@ -149,7 +157,7 @@ describe('resident composer', () => { const workspaceChip = view.getByRole('button', { name: '选择工作区' }) const workspaceProbe = view.getByTestId('workspace-probe') expect(textarea.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea.getAttribute('contenteditable')).not.toBe('true') + expect(textarea.getAttribute('contenteditable')).toBe('true') fireEvent.click(workspaceChip) fireEvent.click(workspaceProbe) diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts new file mode 100644 index 0000000000..3d223a38fe --- /dev/null +++ b/packages/client/ui-conversation/tests/first-draft.client.spec.ts @@ -0,0 +1,141 @@ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { FirstDraft } from '../src/client/input/first-draft.ts' +import { SessionInputShell } from '../src/client/input/facade.ts' +import type { SubmitOutcome } from '../src/client/contract/input.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() +}) + +function harness() { + const ctx = new Context() + contexts.push(ctx) + const opened = Promise.withResolvers() + ctx.effect(() => () => { opened.resolve(undefined) }) + const submitted = vi.fn(async (): Promise => ({ kind: 'success' })) + const target = new SessionInputShell({ + actx: ctx, + defaultSink: submitted, + commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: () => '' }, + }) + ctx.effect(() => () => { target.dispose() }) + let beforeOpen: ((id: SessionId) => void) | undefined + const open = vi.fn((prepare: (id: SessionId) => void) => { + beforeOpen = prepare + return opened.promise + }) + const first = new FirstDraft(ctx, { open, shell: () => target }) + return { + ctx, first, target, submitted, open, opened, + complete: () => { + const id = SessionId('default') + beforeOpen!(id) + opened.resolve(id) + }, + } +} + +describe('first message draft', () => { + it('retains a local draft without opening a Session until send', async () => { + const h = harness() + h.first.shell.setDraft('first message') + expect(h.open).not.toHaveBeenCalled() + h.first.shell.submit('steer') + expect(h.open).toHaveBeenCalledTimes(1) + expect(h.first.state.getSnapshot().busy).toBe(true) + h.first.shell.submit('steer') + expect(h.open).toHaveBeenCalledTimes(1) + h.complete() + await vi.waitFor(() => { expect(h.submitted).toHaveBeenCalledTimes(1) }) + expect(h.submitted.mock.calls[0]).toEqual(['first message', [], 'steer', expect.any(AbortSignal)]) + expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: false }) + }) + + it.each([false, true])('waits for first-use settings and keeps the Session draft on refusal (refused: %s)', async (refused) => { + const h = harness() + const settings = Promise.withResolvers() + const started = Promise.withResolvers() + h.ctx.on('conversation/prepare-first-send', (id) => { + started.resolve(id) + return settings.promise + }) + try { + h.first.shell.setDraft('use my selected mode') + h.first.shell.submit() + h.complete() + expect(await started.promise).toBe(SessionId('default')) + expect(h.submitted).not.toHaveBeenCalled() + if (refused) settings.reject(new Error('preset refused')) + else settings.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + expect(h.first.state.getSnapshot().failed).toBe(false) + if (refused) { + expect(h.submitted).not.toHaveBeenCalled() + expect(h.target.snapshot.draft).toBe('use my selected mode') + expect(h.target.notices.getSnapshot()?.text).toBe('preset refused') + } else { + expect(h.submitted).toHaveBeenCalledOnce() + } + } finally { + settings.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + } + }) + + it('restores input on preparation failure and dismisses the modal without losing it', async () => { + const h = harness() + h.first.shell.setDraft('preserve me') + h.first.shell.submit() + h.opened.reject(new Error('permission denied')) + await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('preserve me') }) + expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: true }) + expect(h.submitted).not.toHaveBeenCalled() + h.first.dismiss() + expect(h.first.state.getSnapshot().failed).toBe(false) + expect(h.first.shell.snapshot.draft).toBe('preserve me') + }) + + it('hands a draft to a manual selection without sending it', async () => { + const h = harness() + h.first.shell.setDraft('manual folder') + h.first.transfer(SessionId('manual')) + expect(h.target.snapshot.draft).toBe('manual folder') + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.submitted).not.toHaveBeenCalled() + }) + + it('lets manual navigation take the pending draft and cancels automatic submission', async () => { + const h = harness() + h.first.shell.setDraft('pending text') + h.first.shell.submit() + h.first.transfer(SessionId('manual')) + h.opened.resolve(undefined) + await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) + expect(h.target.snapshot.draft).toBe('pending text') + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.submitted).not.toHaveBeenCalled() + }) + + it('restores a superseded draft without a directory error', async () => { + const h = harness() + h.first.shell.setDraft('later') + h.first.shell.submit() + h.opened.resolve(undefined) + await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('later') }) + expect(h.first.state.getSnapshot().failed).toBe(false) + }) + + it('leaves ordinary send failures in the selected Session input', async () => { + const h = harness() + h.submitted.mockResolvedValue({ kind: 'error' }) + h.first.shell.setDraft('retry the prompt') + h.first.shell.submit() + h.complete() + await vi.waitFor(() => { expect(h.target.snapshot.draft).toBe('retry the prompt') }) + expect(h.first.shell.snapshot.draft).toBe('') + expect(h.first.state.getSnapshot().failed).toBe(false) + }) +}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 9e0366952c..a4805db1ec 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -185,6 +185,7 @@ function bench(over?: BenchOptions) { ? over?.plan : key === 'goal' ? over?.goal : key === 'imageLimits' ? over?.imageLimits : undefined)), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index 15d87a0ca7..c8641afcb4 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -67,6 +67,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 347b4d05c1..0c098d95fb 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -161,6 +161,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), + useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 17aadfb056..25f7002ea4 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -137,6 +137,8 @@ function mount( nestedSubagent?: boolean /** A composer block another plugin raised for this session. */ composerBlock?: { reason: string } + /** First-use preparation remains active after selecting its Session. */ + preparingFirstDraft?: boolean /** Mutable view ledger used by registration-order regressions. */ viewTabs?: ViewTab[] } = {}, @@ -280,6 +282,7 @@ function mount( useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} + useComposerInput={useInput} keyboard={wiring} addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} @@ -336,6 +339,8 @@ function mount( useWorkspaces: bindSnapshotSelector(workspaces), useProjection: (() => undefined), useComposerBlock: select => select(options.composerBlock), + useFirstDraft: select => select({ busy: options.preparingFirstDraft === true, failed: false }), + dismissDefaultFailure: () => {}, useInput, inputActions, renderSlot, @@ -405,6 +410,17 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByTestId('view-conversation.session.header.corner')).toBeNull() }) + it('locks the selected Session draft until automatic first-use preparation settles', () => { + const b = mount(sessionSnapshotOf({ blank: true }), undefined, undefined, { + summaryBlank: true, preparingFirstDraft: true, + }) + const box = b.view.getByRole('textbox') + expect(box.getAttribute('aria-disabled')).toBe('true') + expect(box.getAttribute('aria-haspopup')).toBeNull() + fireEvent.keyDown(box, { key: 'Enter' }) + expect(b.sink).not.toHaveBeenCalled() + }) + it('does not redispatch composer child slots for an unrelated Session publication', () => { const b = mount(sessionSnapshotOf()) const childKeys = new Set([ diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 5f4245e471..951fd978ab 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 0125f563e7d0f062dd37f58a218d76dd85b0fa51 -README.zh.md: 9db3ea3a39f7c314ebb7d874d858457f00501bd7 +README.md: 6b34c9bf764d04df591317a22c55a47c2307459d +README.zh.md: 550490a49651d01e20537cb924a43112a233966c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 0125f563e7..6b34c9bf76 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,6 +69,8 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. +`openDefaultWorkspace(request, beforeOpen, signal)` initializes the Host default Workspace from the requested directory name and title before connecting its Session. It captures navigation cancellation before directory preparation; superseded work cannot transfer the draft or select its Session. A successfully registered Workspace remains available when Session creation or later submission fails. [Conversation](../ui-conversation/README.md) owns the first-use draft and failure dialog. + ## Understand the implementation diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 9db3ea3a39..550490a496 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,6 +69,8 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 +`openDefaultWorkspace(request, beforeOpen, signal)` 在连接 Session 前,按请求中的目录名和标题初始化 Host 默认工作区。它在目录准备之前捕获导航取消信号;被取代的操作不能转移草稿或选中 Session。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。[Conversation](../ui-conversation/README.zh.md) 负责首次使用草稿和失败弹窗。 + ## 理解实现 diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 22138ec707..e6ccd65f62 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -12,7 +12,7 @@ import type { import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { - IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' @@ -36,6 +36,18 @@ export interface UiWorkspace { * @returns completion; a superseded request may create a Session but does not open it. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise + /** + * Prepare the first-use Workspace and select its blank Session. + * @param request - initial directory name and title. + * @param beforeOpen - synchronous draft transfer after retaining the Session. + * @param signal - caller cancellation. + * @returns selected Session, or undefined after navigation supersession. + */ + openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise /** * Fork a Session without changing the current selection. * @param sessionId - source Session. @@ -184,6 +196,25 @@ class UiWorkspaceService extends Service implements UiWorkspace { this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) } + async openDefaultWorkspace( + request: WorkspaceInitializeDefaultRequest, + beforeOpen: (sessionId: SessionId) => void, + signal: AbortSignal, + ): Promise { + const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal, signal]) + try { + const workspace = await this.workspaces.initializeDefault(request, navigation) + navigation.throwIfAborted() + const sessionId = await this.connectWorkspace(workspace.workspaceId) + navigation.throwIfAborted() + this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) + return sessionId + } catch (error) { + if (navigation.aborted) return undefined + throw error + } + } + async forkSession(sessionId: SessionId): Promise { await this.sessions.fork({ sessionId, increaseTitle: true }) } diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 310bb3627d..a952cb9d32 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -167,6 +167,11 @@ class FakeSessions implements ISessions { } class FakeWorkspaces implements IWorkspaces { + readonly initializeDefault = vi.fn(async () => { + const item = workspace('default') + this.list.set(workspaceState([item])) + return item + }) readonly list: MutableSource readonly archiveCalls: SessionId[] = [] readonly unarchiveCalls: SessionId[] = [] @@ -272,6 +277,41 @@ function bench(options: BenchOptions = {}) { } describe('UiWorkspaceService', () => { + it('prepares the default Workspace before creating and retaining its Session', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + const beforeOpen = vi.fn(() => { + expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-default'), { source: 'mainView' }) + }) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: '默认工作区', title: '默认工作区' }, beforeOpen, new AbortController().signal)) + .resolves.toBe(sid('created-default')) + expect(b.workspaces.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(AbortSignal)) + expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) + expect(beforeOpen).toHaveBeenCalledWith(sid('created-default')) + }) + + it('does not create a Session when default preparation fails or is superseded', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + b.workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('denied') + expect(b.sessions.create).not.toHaveBeenCalled() + const pending = Promise.withResolvers() + b.workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + const beforeOpen = vi.fn() + const opening = b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, beforeOpen, new AbortController().signal) + b.uiWorkspace.openSession(sid('manual')) + pending.resolve(workspace('default')) + await expect(opening).resolves.toBeUndefined() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(beforeOpen).not.toHaveBeenCalled() + }) + + it('retains the prepared Workspace if creating its Session fails', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) + b.sessions.create.mockRejectedValueOnce(new Error('session failed')) + await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('session failed') + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + }) + it('retains an explicit main target before revealing its Conversation', () => { const b = bench() b.uiWorkspace.openSession(sid('target')) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 78975d4a43..407b489580 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3250,6 +3250,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'request', description: 'directory path to register.' }], returns: 'the Workspace and whether this call created it.', }, + { + signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', + description: 'Initialize or reuse the default Workspace before the first user message.', + parameters: [{ name: 'request', description: 'initial directory name and title; never rename an existing default.' }, { name: 'signal', description: 'caller lifetime; cancels native directory lookup.' }], + returns: 'the durable Workspace without creating a Session or sending a message.', + }, { signature: '@Remote(\'rename\') rename(request: WorkspaceRenameRequest): Promise', description: 'Rename one Workspace to a unique non-blank title.', @@ -3367,6 +3373,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'path', description: 'Existing directory to own, in a fully qualified path spelling.' }, { name: 'title', description: 'Display title used only when a new record is created.' }], returns: 'the existing or newly durable workspace.', }, + { + signature: 'initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise', + description: 'Initialize the default Workspace only while both the registry and Session history are empty. Repeated requests reuse its durable identity; deleting that registration permanently disables automatic creation.', + parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration.' }], + returns: 'the initialized Workspace, or undefined when automatic creation is ineligible.', + }, { signature: 'get(id: WorkspaceId): Workspace | undefined', description: 'Look up a workspace by id.', @@ -7279,6 +7291,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WorkspaceFollowIncrement', declaration: 'export type WorkspaceFollowIncrement = {\n readonly type: \'upsert\';\n readonly workspace: WorkspaceView;\n} | {\n readonly type: \'remove\';\n readonly workspaceId: WorkspaceId;\n} | {\n readonly type: \'order\';\n readonly workspaceIds: readonly WorkspaceId[];\n} | {\n readonly type: \'archived\';\n readonly archivedSessionIds: readonly SessionId[];\n} | {\n readonly type: \'pinned\';\n readonly pinnedSessionIds: readonly SessionId[];\n};', }, + { + name: 'WorkspaceInitializeDefaultRequest', + declaration: 'export interface WorkspaceInitializeDefaultRequest {\n readonly directoryName: string;\n readonly title: string;\n}', + }, { name: 'WorkspaceInsertBeforeRequest', declaration: 'export interface WorkspaceInsertBeforeRequest {\n readonly workspaceId: WorkspaceId;\n readonly beforeWorkspaceId?: WorkspaceId;\n}', diff --git a/packages/test-support/client-runtime/src/workspaces.ts b/packages/test-support/client-runtime/src/workspaces.ts index 68a5c61d09..2c6b788fa3 100644 --- a/packages/test-support/client-runtime/src/workspaces.ts +++ b/packages/test-support/client-runtime/src/workspaces.ts @@ -1,7 +1,7 @@ /** Test-owned workspaces face: the renderer standard-kit observable plus recorded actions. */ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { - IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -80,6 +80,19 @@ export class TestWorkspaces implements IWorkspaces { } as unknown as WorkspaceView } + /** + * Initialize the default Workspace through an explicitly installed test stub. + * @param request - initial directory name and title. + * @param signal - caller lifetime. + * @returns the stubbed Workspace. + */ + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + this.calls.push({ method: 'initializeDefault', args: [request, signal] }) + const stub = this.stubs.get('initializeDefault') + if (stub === undefined) throw new Error('initializeDefault requires a Workspace fixture') + return await (stub(request, signal) as Promise) + } + /** * Rename a Workspace (recorded). The default echoes a minimal view. * @param workspaceId - target workspace. diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index da38092a17..43e9c7d159 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/workspace/workspace/README.md -README.md: 51fa66d346ffc4027397d8851b0c81ea87269ded -README.zh.md: 102308d3257ba13d3ec851adcbdb1d4c159abc14 +README.md: f11d6496c04cf346c21f869e00ec5fb5526008db +README.zh.md: 3d458e13157bda612c3d33d0e7bfb57fa914e9b3 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index 51fa66d346..f11d6496c0 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -33,7 +33,7 @@ Use it when the product shows a persistent workspace surface — a sidebar, sess ### Setting up -The package takes no configuration of its own; it needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition: +The package needs a session store, a session persistence backend, and the storage rows that keep its records. A minimal composition: ```yaml - name: '@deepseek-ai/dsh-session' @@ -59,6 +59,15 @@ await project.setTitle('Renamed') ctx.workspaceRegistry.list() // shows the project, newest first ``` + +### First-use Workspace + +`initializeDefault(resolveDirectory)` initializes the default Workspace without creating a Session. Initial creation requires an empty Workspace registry and no live, persisted, or archived Session, including Sessions without a working directory. The registry checks persistent history directly; an empty visible sidebar is insufficient. + +The directory resolver runs inside the mutation queue only when creation is eligible. It returns an absolute path and initial title; the registry creates missing parent directories, canonicalizes the path, rechecks Session history, and commits the Workspace with its initialization marker. An existing directory is reused; a file conflict or directory failure rejects initialization. The [Host controller](../../api/workspace-controller/README.md#first-use-workspace) supplies the Documents path policy. + +The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. + ### Grouping sessions under a project A session joins the project of the directory it runs in: create a session in a project's directory and it appears under that project, newest first. A session can only belong to one project. A session whose directory cannot be validated — no recorded directory, or a moved or deleted folder — cannot join and stays ungrouped. @@ -102,7 +111,7 @@ The API has two owners: `WorkspaceRegistry` creates, orders, and deletes project ### Durable shape -The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it. +The registry opens the `workspace` domain (version 2): a `workspaces` table keyed by `WorkspaceId` plus one global state holding `workspaceIds` (the authoritative display order), `archivedSessionIds`, `pinnedSessionIds`, the optional `defaultWorkspaceId` first-use identity, and the optional `pendingMutation` marker. Archive and pin sets contain Session id strings, default to empty, and carry no per-entry objects or timestamps; the pin array keeps the most recently pinned id first. Archiving clears the pin in the same global-state write without changing Workspace membership. Unarchive runs no session-existence probe, because dropping an id from the set cannot introduce an unknown one, while archive verifies the session before adding it. ### Lifecycle diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 102308d325..3d458e1315 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 设置 -此包本身不声明任何配置;它需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下: +此包需要会话存储、会话持久化后端,以及保存其记录的存储行。最小组合如下: ```yaml - name: '@deepseek-ai/dsh-session' @@ -59,6 +59,15 @@ await project.setTitle('Renamed') ctx.workspaceRegistry.list() // shows the project, newest first ``` + +### 首次使用工作区 + +`initializeDefault(resolveDirectory)` 初始化默认 Workspace,不创建 Session。首次创建要求 Workspace 注册表为空,且不存在运行时、持久化或已归档 Session,包括没有工作目录的 Session。注册表直接检查持久化历史;仅凭可见侧边栏为空不足以判断。 + +目录解析器仅在允许创建时于变更队列内运行。它返回绝对路径和初始标题;注册表创建缺失的父目录、规范化路径、重新检查 Session 历史,再一起提交 Workspace 和初始化标记。已存在的目录直接复用;文件冲突或目录操作失败时拒绝初始化。[Host 控制器](../../api/workspace-controller/README.zh.md#first-use-workspace)提供 Documents 路径策略。 + +首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 + ### 将会话归入项目 会话加入它运行目录所在的项目:在项目目录中创建会话,它就会出现在该项目下,新到旧排列。一个会话只能属于一个项目。目录无法校验的会话——没有记录目录,或目录被移动、删除——无法加入,保持 Ungrouped。 @@ -102,7 +111,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first ### 持久形态 -注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。 +注册表打开 `workspace` 领域(版本 2):一张以 `WorkspaceId` 为键的 `workspaces` 表,加上一个持有 `workspaceIds`(权威显示顺序)、`archivedSessionIds`、`pinnedSessionIds`、可选的首次使用身份 `defaultWorkspaceId` 与可选 `pendingMutation` 标记的全局状态。归档与置顶集合存储会话 id 字符串,默认值为空,不包含逐项对象或时间戳;置顶数组把最近置顶的 id 放在前面。归档在同一次全局状态写入中清除置顶,但不改变 Workspace 成员关系。取消归档不做会话存在性探测,因为从集合中移除 id 不可能引入未知 id,而归档会在加入前校验会话。 ### 生命周期 diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index ab9ff50409..6cb179022a 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -6,7 +6,7 @@ */ import { randomUUID } from 'node:crypto' -import { stat } from 'node:fs/promises' +import { mkdir, stat } from 'node:fs/promises' import { Context, Service } from '@deepseek-ai/cordis' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-persistence' @@ -15,7 +15,7 @@ import { WorkspaceEntity } from './entity.ts' import type { WorkspaceEntityHost } from './entity.ts' export { WorkspaceMoveInvalidError } from './entity.ts' -import { defaultWorkspaceTitle, realpathNormalize } from './paths.ts' +import { defaultWorkspaceTitle, fullyQualifiedWorkspacePath, realpathNormalize } from './paths.ts' import { workspaceDomainSpec } from './spec.ts' import type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts' import type { Workspace, WorkspaceId as WorkspaceIdBrand } from './types.ts' @@ -175,6 +175,34 @@ export class WorkspaceRegistry extends Service { return await this.enqueueOperation(() => this.createCanonical(canonical, title)) } + /** + * Initialize the default Workspace only while both the registry and Session + * history are empty. Repeated requests reuse its durable identity; deleting + * that registration permanently disables automatic creation. + * @param resolveDirectory - resolve the absolute directory and initial title; + * called only for eligible creation, inside the registry mutation queue. + * Missing directories are created recursively before registration. + * @returns the initialized Workspace, or undefined when automatic creation is ineligible. + */ + initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise { + return this.enqueueOperation(async () => { + const state = this.requireState() + if (state.defaultWorkspaceId !== undefined) return this.entities.get(state.defaultWorkspaceId) + const sessions = this.ctx.get('sessions') + if (sessions === undefined) throw new Error('default Workspace initialization requires the Session store') + if (state.workspaceIds.length > 0 || state.archivedSessionIds.length > 0 + || sessions.list().length > 0 || (await this.listStoredHeaders()).length > 0) return undefined + + const { path, title } = await resolveDirectory() + if (!fullyQualifiedWorkspacePath(path)) throw new TypeError(`Workspace path is not fully qualified: '${path}'`) + await mkdir(path, { recursive: true }) + const canonical = await realpathNormalize(path) + // A Session can start outside the registry queue while directory preparation awaits I/O. + if ((await this.listStoredHeaders()).length > 0 || sessions.list().length > 0) return undefined + return this.createCanonical(canonical, title, true) + }) + } + /** * Look up a workspace by id. * @param id - Workspace id. @@ -379,7 +407,7 @@ export class WorkspaceRegistry extends Service { return undefined } - private async createCanonical(canonical: string, title?: string): Promise { + private async createCanonical(canonical: string, title?: string, firstUse = false): Promise { for (const entity of this.entities.values()) { if (entity.path === canonical) return entity } @@ -425,7 +453,10 @@ export class WorkspaceRegistry extends Service { try { await this.setState({ + ...state, + pendingMutation: undefined, initialized: true, + ...(firstUse ? { defaultWorkspaceId: id } : {}), workspaceIds: [id, ...state.workspaceIds], archivedSessionIds: state.archivedSessionIds, pinnedSessionIds: state.pinnedSessionIds, @@ -458,6 +489,8 @@ export class WorkspaceRegistry extends Service { if (entity === undefined) return false const state = this.requireState() const nextState = { + ...state, + pendingMutation: undefined, initialized: true, workspaceIds: state.workspaceIds.filter(workspaceId => workspaceId !== id), archivedSessionIds: state.archivedSessionIds, @@ -516,6 +549,8 @@ export class WorkspaceRegistry extends Service { } await this.requireTable().delete(pending.workspaceId) await this.setState({ + ...state, + pendingMutation: undefined, initialized: state.initialized, workspaceIds: state.workspaceIds, archivedSessionIds: state.archivedSessionIds, diff --git a/packages/workspace/workspace/src/spec.ts b/packages/workspace/workspace/src/spec.ts index 165bff34e0..9bd792258a 100644 --- a/packages/workspace/workspace/src/spec.ts +++ b/packages/workspace/workspace/src/spec.ts @@ -56,6 +56,8 @@ const workspacePendingMutation = z.discriminatedUnion('operation', [ */ export const workspaceDomainState = z.object({ initialized: z.boolean(), + /** First-use Workspace identity, retained after its registration is deleted. */ + defaultWorkspaceId: workspaceId.optional(), workspaceIds: z.array(workspaceId), archivedSessionIds: z.array(sessionId).default([]), pinnedSessionIds: z.array(sessionId).default([]), diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index f860028d4e..6eafae9f2e 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -2,7 +2,7 @@ import type { z } from 'zod' import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' +import { basename, join, relative } from 'node:path' import { Context } from '@deepseek-ai/cordis' import Storage from '@deepseek-ai/dsh-storage' import type { StorageBackend } from '@deepseek-ai/dsh-storage' @@ -1156,3 +1156,145 @@ describe('registry-global session unpin', () => { expect(result.list.mock.calls.length).toBe(listingsBefore) }) }) + +describe('first-use Workspace preparation', () => { + const contexts: Context[] = [] + + afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + }) + + async function firstUse(options: HarnessOptions = {}) { + const directoryRoot = await makeDir('first-use') + const result = await harness({ liveSessions: [], ...options }) + contexts.push(result.ctx) + const resolveDirectory = vi.fn(async () => ({ path: join(directoryRoot, 'nested', 'Workspace'), title: 'Workspace' })) + return { ...result, directoryRoot, resolveDirectory } + } + + it('creates parent directories and resolves only one directory for concurrent initialization', async () => { + const h = await firstUse() + const laterDirectory = vi.fn(async () => { throw new Error('directory lookup unavailable') }) + const [first, repeated] = await Promise.all([ + h.registry.initializeDefault(h.resolveDirectory), h.registry.initializeDefault(laterDirectory), + ]) + expect(first).toBeDefined() + expect(repeated).toBe(first) + expect(h.resolveDirectory).toHaveBeenCalledOnce() + expect(laterDirectory).not.toHaveBeenCalled() + expect(first?.path).toBe(await realpath(join(h.directoryRoot, 'nested', 'Workspace'))) + expect(first?.title).toBe('Workspace') + expect(h.registry.list()).toEqual([first]) + expect(storedState(h.pool).defaultWorkspaceId).toBe(first?.id) + expect(h.ctx.sessions.list()).toEqual([]) + expect(h.open).not.toHaveBeenCalled() + }) + + it('reuses an existing directory without changing its contents', async () => { + const h = await firstUse() + const directory = join(h.directoryRoot, 'nested', 'Workspace') + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'keep.txt'), 'keep') + expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(directory) + const { readFile } = await import('node:fs/promises') + expect(await readFile(join(directory, 'keep.txt'), 'utf8')).toBe('keep') + }) + + it('leaves initialization retryable when directory resolution fails', async () => { + const h = await firstUse() + h.resolveDirectory.mockRejectedValueOnce(new Error('lookup unavailable')) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('lookup unavailable') + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined() + }) + + it('rejects a relative candidate before creating its directory', async () => { + const h = await firstUse() + const candidate = join(h.directoryRoot, 'relative') + h.resolveDirectory.mockResolvedValueOnce({ path: relative(process.cwd(), candidate), title: 'Workspace' }) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('fully qualified') + await expect(realpath(candidate)).rejects.toMatchObject({ code: 'ENOENT' }) + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('keeps the initialization marker across deletion and restart', async () => { + const h = await firstUse() + const workspace = (await h.registry.initializeDefault(h.resolveDirectory))! + await workspace.setTitle('Renamed') + expect((await h.registry.initializeDefault(h.resolveDirectory))?.title).toBe('Renamed') + await h.registry.delete(workspace.id) + await h.ctx.fiber.dispose() + const restarted = await firstUse({ pool: h.pool }) + await expect(restarted.registry.initializeDefault(restarted.resolveDirectory)).resolves.toBeUndefined() + expect(storedState(h.pool).defaultWorkspaceId).toBe(workspace.id) + expect(restarted.registry.list()).toEqual([]) + expect(restarted.resolveDirectory).not.toHaveBeenCalled() + }) + + it.each(['persisted', 'live', 'archived'] as const)('refuses automatic creation for a %s cwd-less Session', async (kind) => { + const history = header('old') + const h = await firstUse(kind === 'persisted' ? { sessions: [history] } : { liveSessions: [history] }) + if (kind === 'archived') await h.registry.archiveSession(history.id) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(h.resolveDirectory).not.toHaveBeenCalled() + }) + + it('refuses a non-empty Workspace list and newly persisted history', async () => { + const h = await firstUse() + const explicit = await h.registry.create(h.directoryRoot) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + await h.registry.delete(explicit.id) + h.setSessions([header('arrived')]) + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + }) + + it('fails on a same-path file and remains eligible after it is removed', async () => { + const h = await firstUse() + const parent = join(h.directoryRoot, 'nested') + await mkdir(parent) + const path = join(parent, 'Workspace') + await writeFile(path, 'occupied') + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow() + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + expect(h.registry.list()).toEqual([]) + await rm(path) + expect((await h.registry.initializeDefault(h.resolveDirectory))?.path).toBe(path) + }) + + it.each(['persisted', 'live'] as const)('refuses registration when a %s Session appears during directory preparation', async (kind) => { + const h = await firstUse() + const arrived = header('arrived-during-preparation') + if (kind === 'persisted') { + h.list.mockResolvedValueOnce([]).mockResolvedValueOnce([ + { header: arrived, revision: SessionPersistenceRevision('arrived-revision') }, + ]) + } else { + vi.spyOn(h.ctx.sessions, 'list').mockReturnValueOnce([]).mockReturnValueOnce([{ header: arrived }] as never) + } + await expect(h.registry.initializeDefault(h.resolveDirectory)).resolves.toBeUndefined() + expect(h.registry.list()).toEqual([]) + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('does not infer an empty live Session store when the peer is unavailable', async () => { + const h = await harness() + contexts.push(h.ctx) + const resolveDirectory = vi.fn(async () => { throw new Error('unexpected directory lookup') }) + await expect(h.registry.initializeDefault(resolveDirectory)).rejects.toThrow('Session store') + expect(resolveDirectory).not.toHaveBeenCalled() + expect(storedState(h.pool).defaultWorkspaceId).toBeUndefined() + }) + + it('rolls back a failed final marker write and allows a retry', async () => { + const pool = new MemoryMediaPool() + const h = await firstUse({ pool, backend: selectiveFailureBackend(pool, { globalAt: 3 }) }) + await expect(h.registry.initializeDefault(h.resolveDirectory)).rejects.toThrow('marker failure') + expect(h.registry.list()).toEqual([]) + expect(storedState(pool).defaultWorkspaceId).toBeUndefined() + await expect(realpath(join(h.directoryRoot, 'nested', 'Workspace'))).resolves.toBe(join(h.directoryRoot, 'nested', 'Workspace')) + expect(await h.registry.initializeDefault(h.resolveDirectory)).toBeDefined() + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dc16be7fbf..6543dd2ade 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1297,6 +1297,12 @@ importers: '@deepseek-ai/dsh-deque': specifier: workspace:^ version: link:../../util/deque + '@deepseek-ai/dsh-native-command': + specifier: workspace:^ + version: link:../../util/native-command + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery zod: specifier: ^4.4.3 version: 4.4.3 diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index c3a8c6a239..1f19959e7e 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -246,6 +246,7 @@ export const EVENT_SCOPE_PAGE: Record = { export const EVENT_WALK_EXEMPTIONS: Record = { 'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API', 'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API', + 'conversation/prepare-first-send': 'client-face first-use draft preparation — packages/client/ui-conversation/README.md owns the API', 'locale/change': 'client-face locale switch signal — packages/client/locale/README.md owns the API', 'slash/input-begin-command': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', @@ -681,6 +682,7 @@ export const LINK_MAP: Readonly> = { WorkspaceArchiveSessionRequest: 'workspace.md', WorkspaceArchiveValue: 'workspace.md', WorkspaceCreateRequest: 'workspace.md', + WorkspaceInitializeDefaultRequest: 'workspace.md', WorkspaceCreateValue: 'workspace.md', WorkspaceDeleteRequest: 'workspace.md', WorkspaceDeleteValue: 'workspace.md', diff --git a/snapshots/web/default-workspace/snapshot.yml b/snapshots/web/default-workspace/snapshot.yml new file mode 100644 index 0000000000..d1eed14d70 --- /dev/null +++ b/snapshots/web/default-workspace/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: default-workspace +profile: web +composition: web-default +recording: authored +header: + class: web-default +session: + source: ../fresh-round-trip/session.v3.jsonl diff --git a/snapshots/web/default-workspace/ui.expected.md b/snapshots/web/default-workspace/ui.expected.md new file mode 100644 index 0000000000..425343834b --- /dev/null +++ b/snapshots/web/default-workspace/ui.expected.md @@ -0,0 +1,26 @@ +- banner: + - navigation "Session hierarchy": Use the bash tool to + - text: Standard mode + - button "More actions" + - button "Open right sidebar" + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt" +- text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" +- button "Copy" +- button "1 tool call" +- paragraph: DONE +- button "Copy" +- button "Good response" +- button "Bad response" +- button "Branch into a new conversation" +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands" +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash +- button "Send message" [disabled] +- button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s +- button "15.8K tok · Cache hit 99%": 15.8K tokCache hit 99% +- button "6% of context used": 6% diff --git a/tsconfig.host.json b/tsconfig.host.json index c1088e0ae8..0e9797b99b 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -63,6 +63,7 @@ "apps/web/tests/public-mount.e2e.ts", "apps/web/tests/workspace-new-session-folding.e2e.ts", "apps/web/tests/workspace-management.e2e.ts", + "apps/web/tests/default-workspace.e2e.ts", "apps/web/tests/workspace-recency.e2e.ts", "apps/web/tests/session-unarchive.e2e.ts", "apps/web/tests/replay-round-trip.e2e.ts", From 6fa56a0cf7c0d7d588a4f94549e82a4936e2cfa6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:57:45 +0800 Subject: [PATCH 02/11] fix(conversation): preserve first drafts across Session retirement --- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../ui-conversation/src/client/apply.ts | 2 + .../src/client/input/first-draft.ts | 5 +- .../tests/apply-inject.client.spec.tsx | 61 ++++++++++++++++++- .../tests/first-draft.client.spec.ts | 2 +- 7 files changed, 71 insertions(+), 7 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 2002de04c1..d9ee350eac 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 56b9d06ce5e48ab40691bede2ccb9669e180aa9f -README.zh.md: fd02565698171e0b6db35080181e57b8b5abd42d +README.md: 6ea403d46b9a019cbd24f8963a89835be4745980 +README.zh.md: f6e28d563847316b538ab8c4317507ea7761c913 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 56b9d06ce5..6ea403d46b 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -52,7 +52,7 @@ Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and c The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. -On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. +On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. If navigation releases the destination Session while preparation is pending, automatic submission stops and its persisted draft remains available on reopening. 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. 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. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index fd02565698..f6e28d5638 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -52,7 +52,7 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 -首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。 +首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。如果导航在准备期间释放了目标 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。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 02c1f3a593..018cf29579 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -208,6 +208,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { const firstDraft = new FirstDraft(ctx, { open: (beforeOpen, signal) => { const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + // Persisted Workspace names follow the send-time language, including the English fallback. const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] return workspaceNavigation.openDefaultWorkspace({ directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', @@ -215,6 +216,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, beforeOpen, signal) }, shell: id => inputHub.shell(id), + isCurrent: (id, shell) => sessions.binding(id) !== undefined && inputHub.shell(id) === shell, }) const composerBlocks = new ComposerBlockRegistry() diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts index 9e1c486eae..8dc7fb32a6 100644 --- a/packages/client/ui-conversation/src/client/input/first-draft.ts +++ b/packages/client/ui-conversation/src/client/input/first-draft.ts @@ -10,13 +10,15 @@ import { SessionInputShell } from './facade.ts' interface FirstDraftDeps { open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise shell(id: SessionId): SessionInputShell + /** Whether the borrowed input still belongs to the retained Session generation. */ + isCurrent(id: SessionId, shell: SessionInputShell): boolean } /** Owns a root-lifetime text editor without allocating a Host Session. */ export class FirstDraft { /** Preparation progress and the recoverable directory failure. */ readonly state = createSnapshotStore({ busy: false, failed: false }) - /** Local editor that stays independent of Host Session allocation. */ + /** Local editor owns failed-submit restoration before transfer to a Host Session. */ readonly shell: SessionInputShell private pending: { text: string; transferred: boolean } | undefined @@ -63,6 +65,7 @@ export class FirstDraft { target = this.deps.shell(id) await this.ctx.serial('conversation/prepare-first-send', id) signal.throwIfAborted() + if (!this.deps.isCurrent(id, target)) return { kind: 'success' } target.submit(mode) return { kind: 'success' } } catch (error) { 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 abc74918d5..c35aff8227 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -139,11 +139,70 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, - locale, openDefaultWorkspace, + locale, openDefaultWorkspace, replaceMain, } } describe('Conversation inject API', () => { + it.each([false, true])('keeps the saved first draft after its Session retires (reopened during preparation: %s)', async (reopenEarly) => { + const b = await bench() + onTestFinished(() => b.runtime.dispose()) + const settings = Promise.withResolvers() + const started = Promise.withResolvers() + b.runtime.ctx.on('conversation/prepare-first-send', () => { + started.resolve(undefined) + return settings.promise + }) + b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { + b.replaceMain(ROOT, beforeOpen) + return ROOT + }) + const body = b.conversationApi(ROOT) + const unmirror = body.injected.bindDraftMirror(body.instance.actions.setDraft) + const composer = b.composerApi(undefined) + let reopened: SessionReference | undefined + try { + composer.keyboard.paste('keep this first draft') + composer.keyboard.submit('queue') + await started.promise + expect(body.instance.store.getSnapshot().draft).toBe('keep this first draft') + const other = 'other-first-send' as SessionId + await b.runtime.sessions.add({ id: other, session: sessionFakeFor() }) + unmirror() + b.rootReference.release() + b.replaceMain(other) + await vi.waitFor(() => { expect(b.runtime.sessions.binding(ROOT)).toBeUndefined() }) + if (reopenEarly) reopened = b.runtime.sessions.retain(ROOT) + settings.resolve(undefined) + await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) + await b.runtime.flush() + expect(b.sessionFake.prompt).not.toHaveBeenCalled() + reopened ??= b.runtime.sessions.retain(ROOT) + b.references.set(ROOT, reopened) + expect(b.conversationApi(ROOT).instance.store.getSnapshot().draft).toBe('keep this first draft') + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') + } finally { + settings.resolve(undefined) + reopened?.release() + unmirror() + } + }) + + it('submits the first draft through its retained destination input', async () => { + const b = await bench() + onTestFinished(() => b.runtime.dispose()) + b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { + b.replaceMain(ROOT, beforeOpen) + return ROOT + }) + const composer = b.composerApi(undefined) + composer.keyboard.paste('first message') + composer.keyboard.submit('queue') + await vi.waitFor(() => { expect(b.sessionFake.prompt).toHaveBeenCalledOnce() }) + expect(b.sessionFake.prompt.mock.calls[0]?.[0]).toEqual([{ type: 'text', text: 'first message' }]) + expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') + }) + it.each([ ['zh', '默认工作区', '默认工作区'], ['en', 'Default workspace', 'Default workspace'], diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts index 3d223a38fe..b23055dcf1 100644 --- a/packages/client/ui-conversation/tests/first-draft.client.spec.ts +++ b/packages/client/ui-conversation/tests/first-draft.client.spec.ts @@ -27,7 +27,7 @@ function harness() { beforeOpen = prepare return opened.promise }) - const first = new FirstDraft(ctx, { open, shell: () => target }) + const first = new FirstDraft(ctx, { open, shell: () => target, isCurrent: () => true }) return { ctx, first, target, submitted, open, opened, complete: () => { From cfec29eb69bf8c4c78b388547502e324e0e1ecd4 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:10 +0800 Subject: [PATCH 03/11] fix(web): show first-use preparation and update browser readiness --- apps/web/tests/default-workspace.e2e.ts | 20 ++++++++++++++++--- .../default-workspace/preparing.expected.md | 7 +++++++ apps/web/tests/preview-boot.e2e.ts | 4 ++-- apps/web/tests/sessionless-header.e2e.ts | 2 +- apps/web/tests/startup-rpc-budget.e2e.ts | 2 +- apps/web/tests/support.ts | 4 ++-- .../ui-conversation/src/client/locales.ts | 2 ++ .../client/skeleton/ConversationContent.tsx | 2 +- .../tests/skeleton.client.spec.tsx | 1 + snapshots/web/default-workspace/snapshot.yml | 2 ++ .../workspace.expected/.empty | 1 + 11 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 apps/web/tests/expected/default-workspace/preparing.expected.md create mode 100644 snapshots/web/default-workspace/workspace.expected/.empty diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index 00bec9de3c..265fa715b2 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -3,9 +3,9 @@ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { - captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, + assertFinalWorkspaceSnapshot, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, } from './scaffold.ts' import { newEnglishPage, saveFailureShot } from './support.ts' @@ -13,6 +13,7 @@ import { newEnglishPage, saveFailureShot } from './support.ts' const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) +const PREPARING_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/preparing.expected.md', import.meta.url)) const MODE = webSnapshotMode() describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { @@ -38,7 +39,19 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) const settled = scaffold.whenTurnSettled() - await input.press('Enter') + const preparing = Promise.withResolvers() + const initialize = scaffold.ctx.workspaceRegistry.initializeDefault.bind(scaffold.ctx.workspaceRegistry) + vi.spyOn(scaffold.ctx.workspaceRegistry, 'initializeDefault').mockImplementationOnce(async (resolve) => { + await preparing.promise + return initialize(resolve) + }) + try { + await input.press('Enter') + await page.getByRole('textbox', { name: 'Preparing workspace…', exact: true }).waitFor() + await compareOrRefreshGolden(PREPARING_EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + } finally { + preparing.resolve(undefined) + } const sessionId = await settled const workspace = scaffold.ctx.workspaceRegistry.list()[0]! expect(workspace.title).toBe('Default workspace') @@ -46,6 +59,7 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { expect((await stat(workspace.path)).isDirectory()).toBe(true) expect(workspace.sessionIds).toContain(sessionId) expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) await page.getByText('DONE', { exact: true }).waitFor() await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) await page.reload() diff --git a/apps/web/tests/expected/default-workspace/preparing.expected.md b/apps/web/tests/expected/default-workspace/preparing.expected.md new file mode 100644 index 0000000000..09e86fbb6e --- /dev/null +++ b/apps/web/tests/expected/default-workspace/preparing.expected.md @@ -0,0 +1,7 @@ +- banner +- text: Into the Unknown Preview +- button "Choose workspace" +- button "Standard mode" +- textbox "Preparing workspace…" [disabled] +- button "Add files or run commands" [disabled] +- button "Send message" [disabled] diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index bde54fe69e..4797a6e4bf 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -297,7 +297,7 @@ async function bootPreview(origin: string, browser: Browser): Promise { expect(await page.getByText('Empty environment', { exact: true }).count()).toBe(1) expect(await page.getByText('WebFS directory', { exact: true }).count()).toBe(1) expect(await page.locator('input[name="preview-source"][value="webfs"]').isDisabled()).toBe(true) - expect(await page.getByRole('textbox', { name: 'Choose workspace' }).count()).toBe(0) + expect(await page.getByRole('button', { name: 'Choose workspace' }).count()).toBe(0) await compareOrRefreshGolden( SOURCE_CHOOSER_EXPECTED, await captureStableAria(page, '[data-preview-source-card]', '/__preview_no_workspace__'), @@ -471,7 +471,7 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise ) expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`) expect(bootLine).toContain('data overlays=0') - await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) + await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) const sessionCount = await page.evaluate(async () => { const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise } diff --git a/apps/web/tests/sessionless-header.e2e.ts b/apps/web/tests/sessionless-header.e2e.ts index b2c1a85fb0..1de5dfe14f 100644 --- a/apps/web/tests/sessionless-header.e2e.ts +++ b/apps/web/tests/sessionless-header.e2e.ts @@ -30,7 +30,7 @@ describe('navigation without a selected Session', () => { } const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('textbox', { name: 'Choose workspace', exact: true }).waitFor() + await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() const sessionHeader = page.locator('[data-slot="conversation.session.header"]') expect(await sessionHeader.count()).toBe(0) const header = page.locator('[data-slot="conversation.header"] > header') diff --git a/apps/web/tests/startup-rpc-budget.e2e.ts b/apps/web/tests/startup-rpc-budget.e2e.ts index f6655ffbf3..d8c89afcca 100644 --- a/apps/web/tests/startup-rpc-budget.e2e.ts +++ b/apps/web/tests/startup-rpc-budget.e2e.ts @@ -36,7 +36,7 @@ describe('startup RPC budget', () => { await page.goto(scaffold.authenticatedUrl) // Boot settles when the workspace picker is interactive; the trailing wait // absorbs the first-connection reset wave the budget must include. - await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) + await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) await page.waitForTimeout(3000) const describeCount = calls.filter(method => method === 'settings/describe').length expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 884d648e8e..082f5019ae 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -122,7 +122,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - await page.getByRole('treeitem', { name: 'New Session', exact: true }).waitFor({ timeout: 15_000 }) + await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -146,7 +146,7 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() - await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor({ timeout: 15_000 }) + await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index c66fe10a8a..ecf2141f1d 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -22,6 +22,7 @@ export const zh = { 'placeholder.parentOffline': '父会话已离线,无法继续发送;仍可停止当前运行', 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', + 'placeholder.preparing': '正在准备工作区…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', 'input.commands': '添加文件或调用指令', 'input.file': '文件', @@ -377,6 +378,7 @@ export const en = { 'placeholder.parentOffline': 'Parent session offline; sending is unavailable but you can still stop the run', 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', + 'placeholder.preparing': 'Preparing workspace…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', 'input.commands': 'Add files or run commands', 'input.file': 'File', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index bf6456291f..82ea0e533d 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -143,7 +143,7 @@ export function ConversationContent(props: ConversationContentProps) { ...(inert ? { disabled: true, - placeholder: t('placeholder.workspace'), + placeholder: t(firstDraft.busy ? 'placeholder.preparing' : 'placeholder.workspace'), workspacePickerOpen: pickerOpen, ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), } diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 25f7002ea4..619e3fddff 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -416,6 +416,7 @@ describe('ConversationRoot resident composer', () => { }) const box = b.view.getByRole('textbox') expect(box.getAttribute('aria-disabled')).toBe('true') + expect(box.getAttribute('aria-label')).toBe('正在准备工作区…') expect(box.getAttribute('aria-haspopup')).toBeNull() fireEvent.keyDown(box, { key: 'Enter' }) expect(b.sink).not.toHaveBeenCalled() diff --git a/snapshots/web/default-workspace/snapshot.yml b/snapshots/web/default-workspace/snapshot.yml index d1eed14d70..b9efb8a8b7 100644 --- a/snapshots/web/default-workspace/snapshot.yml +++ b/snapshots/web/default-workspace/snapshot.yml @@ -3,6 +3,8 @@ scenario: default-workspace profile: web composition: web-default recording: authored +workspace: + final: true header: class: web-default session: diff --git a/snapshots/web/default-workspace/workspace.expected/.empty b/snapshots/web/default-workspace/workspace.expected/.empty new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/snapshots/web/default-workspace/workspace.expected/.empty @@ -0,0 +1 @@ + From 8e313eaa306b38c35e57a9fd5a4d74174c0360b6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:33 +0800 Subject: [PATCH 04/11] test(workspace): cover first-use configuration and preset failures --- .../api/workspace-controller/src/index.ts | 9 +++++--- .../tests/workspace-controller.host.spec.ts | 12 ++++++++-- .../tests/apply.client.spec.ts | 19 ++++++++++++---- .../tests/runtime.client.spec.tsx | 22 +++++++++++++++++++ 4 files changed, 53 insertions(+), 9 deletions(-) diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 2281273e1e..966a5e9fb9 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -38,6 +38,9 @@ export interface Config { documentsLookupTimeoutMs?: number } +/** Directory policy after schema defaults have been applied. */ +type ResolvedConfig = Config & { documentsLookupTimeoutMs: number } + declare module '@deepseek-ai/cordis' { interface Context { /** Host Workspace business API and Remote namespace owner. */ @@ -49,12 +52,12 @@ declare module '@deepseek-ai/cordis' { export class WorkspaceController extends TypertRemoteService { static inject = ['typert', 'workspaceRegistry'] - static Config: z = z.object({ + static Config: z = z.object({ documentsDirectory: z.string(), documentsLookupTimeoutMs: z.natural().min(1).default(10_000), }) - private readonly config: Config + private readonly config: ResolvedConfig private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed @@ -96,7 +99,7 @@ export class WorkspaceController extends TypertRemoteService { throw new RemoteError('gateway/bad-request', 'default Workspace requires a directory name and non-blank title', {}) } const workspace = await this.ctx.workspaceRegistry.initializeDefault(async () => { - const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs as number) + const timeout = AbortSignal.timeout(this.config.documentsLookupTimeoutMs) const path = await defaultWorkspaceDirectory( directoryName, this.config.documentsDirectory, AbortSignal.any([signal, timeout]), ) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index ecaeb9a248..39cd085879 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -41,7 +41,7 @@ function deferred(): Deferred { return { promise, resolve } } -async function harness() { +async function harness(options: { systemDocuments?: boolean } = {}) { const root = realpathSync.native(mkdtempSync(join(tmpdir(), 'dsh-workspace-controller-'))) tempDirs.push(root) const ctx = new Context() @@ -59,7 +59,7 @@ async function harness() { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, } as never) - const controller = new WorkspaceController(ctx, { documentsDirectory: root }) + const controller = new WorkspaceController(ctx, options.systemDocuments === true ? {} : { documentsDirectory: root }) return { controller, ctx, root, storageDomain } } @@ -418,6 +418,14 @@ describe('WorkspaceController follow', () => { }) describe('first-use Remote', () => { + it('reuses an initialized Workspace without looking up system Documents', async () => { + const { controller, ctx, root } = await harness({ systemDocuments: true }) + const workspace = await ctx.workspaceRegistry.initializeDefault(async () => ({ path: root, title: 'Existing default' })) + const signal = AbortSignal.abort() + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal)) + .resolves.toMatchObject({ workspace: { workspaceId: workspace!.id, path: root, title: 'Existing default' } }) + }) + it.each(['', ' ', '.', '..', '../outside', 'nested/name', 'nested\\name', 'C:outside', 'name\0', '.. ', 'tail.'])( 'rejects invalid directory name %j before invoking the registry', async (directoryName) => { const { controller, ctx } = await harness() diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index ea312699ce..378b40006f 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ */ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' @@ -76,6 +76,7 @@ async function bench(options: { failSettingsUpdate?: boolean selectGate?: Promise settingsRosterGate?: Promise + refuseSelect?: boolean } = {}) { const ctx = new Context() // The host's answer, mutable so a spec can move the default the way the @@ -153,7 +154,9 @@ async function bench(options: { deletePreset: () => Promise.resolve({ ok: true as const, value: undefined }), select: (_agentId: SessionId, agentPreset: string) => { calls.push(`select:${agentPreset}`) - return Promise.resolve(options.selectGate).then(() => ({ ok: true as const, value: agentPreset })) + return Promise.resolve(options.selectGate).then(() => options.refuseSelect === true + ? { ok: false as const, error: new RemoteError('gateway/internal', 'preset refused', {}) } + : { ok: true as const, value: agentPreset }) }, } ctx.provide('remote.agentPresets', agentPresets as never) @@ -715,8 +718,10 @@ describe('ui-agent-preset apply', () => { conversation() }) - it('applies the staged choice to the blank session the flow lands on', async () => { - const { ctx, slots, calls } = await bench() + it.each([false, true])('awaits the staged choice before first send and propagates refusal (%s)', async (refuseSelect) => { + const selection = Promise.withResolvers() + const { ctx, slots, calls } = await bench({ refuseSelect, selectGate: selection.promise }) + onTestFinished(async () => { selection.resolve(undefined); await ctx.fiber.dispose() }) declareRoot(slots) declareConversation(slots) ctx.provide('conversation', {} as never) @@ -736,6 +741,8 @@ describe('ui-agent-preset apply', () => { .inject as unknown as (sessionId?: SessionId) => AgentPresetSeatInjected const chip = injectSeat() + await ctx.serial('conversation/prepare-first-send', SessionId('absent')) + await chip.load() // Picked on the hero screen, where there is no session yet. await chip.select('minimal') @@ -747,6 +754,10 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) + const preparing = ctx.serial('conversation/prepare-first-send', SessionId('s1')) + const settled = refuseSelect ? expect(preparing).rejects.toThrow('preset refused') : expect(preparing).resolves.toBeUndefined() + selection.resolve(undefined) + await settled await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index 7d29ba7f72..aeff2554d1 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -557,6 +557,28 @@ describe('workspaces', () => { expect(view.container.textContent).toContain('ws:pending') await runtime.dispose() }) + it('requires an explicit default Workspace fixture and forwards its request and lifetime', async () => { + const runtime = await SlotTestRuntime.create() + try { + const request = { directoryName: 'default-workspace', title: 'Default workspace' } + const signal = new AbortController().signal + await expect(runtime.workspaces.initializeDefault(request, signal)).rejects.toThrow('requires a Workspace fixture') + const workspace = { + workspaceId: 'default' as WorkspaceId, title: request.title, path: '/default', sessionIds: [], + createdAt: '2026-09-20T00:00:00Z', updatedAt: '2026-09-20T00:00:00Z', + } + const initialize = vi.fn(async () => workspace) + runtime.workspaces.stub('initializeDefault', initialize) + await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBe(workspace) + expect(initialize).toHaveBeenCalledWith(request, signal) + expect(runtime.workspaces.calls).toEqual([ + { method: 'initializeDefault', args: [request, signal] }, + { method: 'initializeDefault', args: [request, signal] }, + ]) + } finally { + await runtime.dispose() + } + }) }) describe('feature mount and disposal', () => { From d4d03b7c41ad12ea07254ca1ca9c170a476f8517 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 15:58:53 +0800 Subject: [PATCH 05/11] docs(workspace): clarify default directory lookup and cancellation --- .../feature/2026-09-20-default-workspace.i18n.yaml | 4 ++-- .../notes/implemented/feature/2026-09-20-default-workspace.md | 1 + .../implemented/feature/2026-09-20-default-workspace.zh.md | 1 + docs/subsystems/workspace.i18n.yaml | 4 ++-- docs/subsystems/workspace.md | 1 + docs/subsystems/workspace.zh.md | 1 + packages/api/workspace-controller/README.i18n.yaml | 4 ++-- packages/api/workspace-controller/README.md | 4 +++- packages/api/workspace-controller/README.zh.md | 4 +++- packages/api/workspace-controller/src/types.ts | 2 +- packages/extensions/tool-cordis/src/api-catalog.ts | 2 +- packages/workspace/workspace/README.i18n.yaml | 4 ++-- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/index.ts | 1 + 15 files changed, 23 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml index cdb2673df8..a3ed2bee71 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md -2026-09-20-default-workspace.md: d2a32d47a407dcf211c1cad8bb98f29847a77a3b -2026-09-20-default-workspace.zh.md: 6b0ec542da6e9e4fe76fb56b6562edea9e5777f4 +2026-09-20-default-workspace.md: 376b2eaf7ac26c13e7483838700c88151b44135d +2026-09-20-default-workspace.zh.md: e16c5d47c6e1bceef293089edf882162812dfa1b diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md index d2a32d47a4..376b2eaf7a 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -21,6 +21,7 @@ Creation failure preserves the draft and offers the existing folder picker. A su ## Alternatives considered - Creating on application startup would write directories for users who never send a message. +- Falling back to `/Documents` when system lookup is unavailable would choose an unverified Documents location; deployments that need another directory use the explicit Host override. - Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. - Using the localized path as the initialization marker would allow language changes or deletion to create another default. - Changing a Session's cwd after creation would change the meaning of its recorded tools and attachments. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md index 6b0ec542da..e16c5d47c6 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -21,6 +21,7 @@ Client 在发送时按其语言解析初始目录名和标题。Host 控制器 ## Alternatives considered - 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 系统查询不可用时回退到 `/Documents`,会选择未经确认的 Documents 位置;需要其他目录的部署使用显式 Host 覆盖配置。 - 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 - 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 - 在 Session 创建后更改 cwd,会改变其已记录工具和附件的含义。 diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index a7a3e3bb91..f9bef3d306 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: b68acd965b55df462a0751d0b7e3230c82a62172 -workspace.zh.md: 074f59438eb16a4ffb1423540c3e1868857ae40f +workspace.md: 43a631ad0b04dd272436e272c931c2a16b7bbe88 +workspace.zh.md: c4571083f3e445828b4b3b41a27ed8abee9ee04d diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index b68acd965b..43a631ad0b 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -485,6 +485,7 @@ async create(path: string, title?: string): Promise * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 074f59438e..c4571083f3 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -485,6 +485,7 @@ async create(path: string, title?: string): Promise * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index e7bc836965..6300d2f2e4 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 275c51d0018dda5b2209cc7bece71b618e7d113d -README.zh.md: 92ca3f86f11ce77b51f834ce7c24f195095065b1 +README.md: 24bf0610689bfb857b24e7c8298b1b0494f1ca02 +README.zh.md: ca140abfdda246b62b0485e63ebfd05ab2efe6f9 diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 275c51d001..24bf061068 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -29,7 +29,7 @@ The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream ### First-use Workspace -`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory. +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. @@ -38,6 +38,8 @@ The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace | `documentsDirectory` | System Documents directory | Fully qualified Host directory override | | `documentsLookupTimeoutMs` | `10000` | Positive maximum duration of OS directory lookup, in milliseconds | +Documents lookup holds the registry mutation queue, so other Workspace mutations, including registration of a picked directory, can wait up to `documentsLookupTimeoutMs`. Cancellation can stop the lookup; after resolution succeeds, it does not roll back creation or registration. + ----- diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index 92ca3f86f1..ca140abfdd 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -29,7 +29,7 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 ### 首次使用工作区 -`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录。 +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 [Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 @@ -38,6 +38,8 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 | `documentsDirectory` | 系统 Documents 目录 | 完全限定的 Host 目录覆盖值 | | `documentsLookupTimeoutMs` | `10000` | 操作系统目录查询的正数最大时长,单位为毫秒 | +Documents 查询占用注册表变更队列,因此其他 Workspace 变更(包括登记已选目录)最多可能等待 `documentsLookupTimeoutMs`。取消可以停止查询;解析成功后,取消不会回滚创建或登记。 + ----- diff --git a/packages/api/workspace-controller/src/types.ts b/packages/api/workspace-controller/src/types.ts index e69c2b8c91..97188d9f23 100644 --- a/packages/api/workspace-controller/src/types.ts +++ b/packages/api/workspace-controller/src/types.ts @@ -56,7 +56,7 @@ export interface WorkspaceCreateRequest { /** Names chosen by the first-use Client before default Workspace initialization. */ export interface WorkspaceInitializeDefaultRequest { - /** Single non-blank name; no separators, colon, NUL, surrounding whitespace, or trailing dot. */ + /** Host rejects blank names, separators, colon, NUL, surrounding whitespace, and trailing dots; OS filename restrictions also apply. */ readonly directoryName: string /** Initial display title, retained across language changes. */ readonly title: string diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index eac1fcac40..b89f2f3ada 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3376,7 +3376,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise', description: 'Initialize the default Workspace only while both the registry and Session history are empty. Repeated requests reuse its durable identity; deleting that registration permanently disables automatic creation.', - parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration.' }], + parameters: [{ name: 'resolveDirectory', description: 'resolve the absolute directory and initial title; called only for eligible creation, inside the registry mutation queue. Missing directories are created recursively before registration. After resolution, caller cancellation does not roll back creation or registration.' }], returns: 'the initialized Workspace, or undefined when automatic creation is ineligible.', }, { diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index 43e9c7d159..7f50ab3f55 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/workspace/workspace/README.md -README.md: f11d6496c04cf346c21f869e00ec5fb5526008db -README.zh.md: 3d458e13157bda612c3d33d0e7bfb57fa914e9b3 +README.md: 897aca8eb725bc9c3e0808e394e5c976886dd877 +README.zh.md: dc7a81340c9b134110975e700d43d5569fa6f03d diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index f11d6496c0..897aca8eb7 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -66,7 +66,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first The directory resolver runs inside the mutation queue only when creation is eligible. It returns an absolute path and initial title; the registry creates missing parent directories, canonicalizes the path, rechecks Session history, and commits the Workspace with its initialization marker. An existing directory is reused; a file conflict or directory failure rejects initialization. The [Host controller](../../api/workspace-controller/README.md#first-use-workspace) supplies the Documents path policy. -The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. +The first successful registration records its identity durably. Repeated calls return it without resolving a directory again; renaming keeps that identity, and deleting its registration does not permit another automatic creation. Directory or registration failure leaves initialization unset for retry. Directories created before a later failure remain on disk. Once directory resolution succeeds, caller cancellation does not roll back directory creation or registration. The [first-use decision](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.md) explains this lifetime. ### Grouping sessions under a project diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 3d458e1315..dc7a81340c 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -66,7 +66,7 @@ ctx.workspaceRegistry.list() // shows the project, newest first 目录解析器仅在允许创建时于变更队列内运行。它返回绝对路径和初始标题;注册表创建缺失的父目录、规范化路径、重新检查 Session 历史,再一起提交 Workspace 和初始化标记。已存在的目录直接复用;文件冲突或目录操作失败时拒绝初始化。[Host 控制器](../../api/workspace-controller/README.zh.md#first-use-workspace)提供 Documents 路径策略。 -首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 +首次成功登记会持久保存工作区身份。重复调用直接返回它,不再解析目录;改名保留该身份,删除登记也不会允许再次自动创建。目录或登记失败时,初始化状态保持未设置,可以重试。后续步骤失败前已创建的目录会保留在磁盘上。目录解析成功后,调用方取消操作不会回滚目录创建或登记。[首次使用决策](../../../.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md)说明这一生命周期。 ### 将会话归入项目 diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 6cb179022a..d0f3d3b8a5 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -182,6 +182,7 @@ export class WorkspaceRegistry extends Service { * @param resolveDirectory - resolve the absolute directory and initial title; * called only for eligible creation, inside the registry mutation queue. * Missing directories are created recursively before registration. + * After resolution, caller cancellation does not roll back creation or registration. * @returns the initialized Workspace, or undefined when automatic creation is ineligible. */ initializeDefault(resolveDirectory: () => Promise<{ path: string; title: string }>): Promise { From 4d2e420ef852578770b9fb72dddcb2dcba85a236 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:19:54 +0800 Subject: [PATCH 06/11] refactor(workspace): initialize the default workspace on startup --- ...ession-scope-and-provide-channel.i18n.yaml | 4 +- ...lient-session-scope-and-provide-channel.md | 9 +- ...nt-session-scope-and-provide-channel.zh.md | 9 +- .../2026-09-20-default-workspace.i18n.yaml | 4 +- .../feature/2026-09-20-default-workspace.md | 12 +- .../2026-09-20-default-workspace.zh.md | 12 +- apps/web/tests/README.i18n.yaml | 4 +- apps/web/tests/README.md | 2 + apps/web/tests/README.zh.md | 2 + apps/web/tests/default-workspace.e2e.ts | 199 +++++++++--------- .../default-workspace/preparing.expected.md | 7 - apps/web/tests/scaffold.ts | 8 +- docs/subsystems/workspace.i18n.yaml | 4 +- docs/subsystems/workspace.md | 6 +- docs/subsystems/workspace.zh.md | 6 +- .../api/workspace-controller/README.i18n.yaml | 4 +- packages/api/workspace-controller/README.md | 4 +- .../api/workspace-controller/README.zh.md | 4 +- .../workspace-controller/src/client/model.ts | 6 +- .../src/client/service.ts | 8 +- .../api/workspace-controller/src/index.ts | 11 +- .../tests/model.client.spec.ts | 4 + .../tests/transport.client.spec.ts | 12 ++ .../tests/workspace-controller.host.spec.ts | 10 +- .../client/ui-agent-preset/README.i18n.yaml | 4 +- packages/client/ui-agent-preset/README.md | 2 - packages/client/ui-agent-preset/README.zh.md | 2 - .../ui-agent-preset/src/client/index.ts | 8 - .../ui-agent-preset/src/client/seat-store.ts | 13 +- .../tests/apply.client.spec.ts | 52 +---- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 6 +- packages/client/ui-conversation/README.zh.md | 6 +- .../ui-conversation/src/client/apply.ts | 43 ++-- .../src/client/contract/input.ts | 6 - .../src/client/contract/slots.ts | 13 +- .../ui-conversation/src/client/index.ts | 8 - .../src/client/input/facade.ts | 4 +- .../src/client/input/first-draft.ts | 82 -------- .../ui-conversation/src/client/locales.ts | 10 - .../client/skeleton/ConversationContent.tsx | 42 ++-- .../src/client/skeleton/ConversationRoot.tsx | 5 +- .../src/client/skeleton/InputBar.tsx | 81 ++++--- .../tests/apply-inject.client.spec.tsx | 111 +--------- .../tests/assembly-surfaces.client.spec.tsx | 22 +- .../tests/first-draft.client.spec.ts | 141 ------------- .../tests/input-bar.client.spec.tsx | 1 - .../tests/input-matrix.client.spec.tsx | 1 - .../tests/input-scenarios.client.spec.tsx | 1 - .../tests/skeleton.client.spec.tsx | 17 -- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 4 +- packages/client/ui-workspace/README.zh.md | 4 +- .../src/client/WorkspacePicker.tsx | 48 +++-- .../ui-workspace/src/client/contract/slots.ts | 8 +- .../client/ui-workspace/src/client/index.ts | 3 +- .../client/ui-workspace/src/client/locales.ts | 8 + .../ui-workspace/src/client/navigation.ts | 56 +++-- .../tests/workspace-picker.client.spec.tsx | 35 ++- .../tests/workspaces-service.client.spec.ts | 115 +++++++--- .../extensions/tool-cordis/src/api-catalog.ts | 6 +- .../client-runtime/src/workspaces.ts | 9 +- .../tests/runtime.client.spec.tsx | 4 +- scripts/gen-cordis-catalog.ts | 1 - 64 files changed, 509 insertions(+), 832 deletions(-) delete mode 100644 apps/web/tests/expected/default-workspace/preparing.expected.md delete mode 100644 packages/client/ui-conversation/src/client/input/first-draft.ts delete mode 100644 packages/client/ui-conversation/tests/first-draft.client.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml index 8790781b63..da98873480 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md -2026-07-25-web-client-session-scope-and-provide-channel.md: f1e83e8b38561d5edd3bf6a212aa2bd4ac5028f8 -2026-07-25-web-client-session-scope-and-provide-channel.zh.md: 6eea0af064caf976774ae2bb2992fd6651daf695 +2026-07-25-web-client-session-scope-and-provide-channel.md: 76561bc0e330b3e3a26607569ae327217d0a0b67 +2026-07-25-web-client-session-scope-and-provide-channel.zh.md: d5d92b2ca53ba78929dd8591a6ded7028e4fed24 diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md index f1e83e8b38..76561bc0e3 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.md @@ -26,8 +26,8 @@ The reference-owned lifetime and Provider targeting now follow [Client Session r Host-side `session.create(workspaceId)` produces Session + Agent + cwd in one piece (an atomic bundle, never split); the client side is the mirror of that birth — the instant a session row enters the list mirror, the client mints its Agent scope (actx + provide + the full input surface mounted): - Session identity is the host's true form from birth: the sessionId arrives via the `session.create` response / the `host/session-added` frame, and every client-side address (the scope tag, slot store keys, RPC addressing) uses that same id. -- A manual Workspace pick or successful [first-use default preparation](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. -- "New Session with no workspace picked" has no Session or scope entity. The composer retains a local text draft; Session-scoped slash commands become available after connection. +- A manual Workspace pick or successful [first-use startup initialization](../feature/2026-09-20-default-workspace.md) establishes cwd before the client calls `session.create({workspaceId})` and receives the complete entity. +- "New Session with no workspace picked" is a **pure view state** (a navigation position) corresponding to no session/scope entity; until the pick, the composer is locked whole (no slash, no plain text). - A "blank session" is an ordinary materialized session with no turn yet; to Agent-scope plugins on the host (goal/plan/skill/…) it remains an ordinary Session, so slash/plan are naturally live. ### Agent scope: the actx is the sole session carrier in the client-side cordis world @@ -95,7 +95,7 @@ Slot scope is the closed set `root | session-maybe | session`: - `session-maybe` inherits the nearest `SessionProvider` binding with ADOPTION identity: an incarnation born Session-less keeps its React instance when that Provider receives its first binding, then remounts when the Provider switches generation or returns to absence. Component-local per-Session state clears when the Provider switches generation. Across a switch, only persisted Store values survive generation retirement; binding-owned sources survive only when another reference keeps that generation alive. With no binding, `sessionId`, the results of `useSession`/`useInput`, and `inputActions` may all be absent. Provider-roster changes rematerialize the mounted binding without changing its identity, while the per-entry adoption bookkeeping lives in the renderer's `SessionMaybeEntry`. - `session` guarantees that `sessionId`, every hook source, and every prop exist; each strict entry's error boundary is keyed by `sessionId`, so switching sessions recreates that entry and its session store. -`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: before a Session exists, its injected editor retains the first-use text draft; after connection, the same InputBar instance receives the retained Session's input. The remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. +`conversation` is the resident `session-maybe` shell under its owning `SessionProvider`: `ConversationRoot`, HeroShell, the Workspace picker, the scrollport and composer stack, and the overlay chain's fallback frame retain their React instances across the no-Session → blank-Session switch. Two strict entries fill fixed regions without reparenting that tree: `conversation.session.header` carries breadcrumb/tabs/actions above the scrollport, while `conversation.session` carries the view ring and draft mirror inside it; both share the same Session-scoped chat store. The composer bar (`conversation.composer.bar`) is itself `session-maybe`: with no Session its machine faces and message actions are inert, while the whole dashed card opens the existing Workspace picker by pointer and its read-only textarea does the same through Enter or Space. The same instance — textarea included — goes live when a binding appears; the remaining input slots stay strict `session` and dispatch nothing until then. The blank → engaging/active transition never rebuilds the InputBar on a phase flip. Blank Sessions retain the header's leading and corner slots so navigation controls, including the right-sidebar opener, are available before the first message. Title, actions, utilities, and View tabs remain hidden in the blank phase. The header still requires a selected Session; the Files and Terminal entries use that Session's workspace and execution services without requiring a recorded Turn. @@ -136,5 +136,6 @@ Blank Sessions retain the header's leading and corner slots so navigation contro - Plugins gain session context isomorphic to the host's: per-session state hangs on the actx and mounts/tears down in one piece with the scope fiber, making leaks structurally impossible; two-session isolation is structurally guaranteed by the scope filter. - The client object layer converges to a wire mirror: session identity, lifecycle, and capability adjudication all defer to the host entity — the input system (the next layer) always faces a session with a real Agent, and providers like slash/skill uniformly address by sessionId directly. - Blank-session governance takes zero dedicated mechanisms: state rides one derived bit, visibility rides the unified list projection (only the current blank shows, as `New Session`), reuse acquires the persisted writer, and the ordinary ceiling rides same-Workspace reuse. The accepted/running display memory that guards the conversion is Client-local. -- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. Session-scoped input remains unavailable until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) owns the local first-use draft during that interval. + +- The cost: the id→ctx handoff discipline and provide's Concurrent discipline are conventions rather than type-enforced, pinned by review and tests. The single state axis still withholds machine faces until a Session exists; the [resident conversation shell](../../../../packages/client/ui-conversation/README.md) routes activation to the Workspace picker during that interval. - Known gaps: approval/question recovery across prune (TODO); model selection returns in live-mutation shape (the host `selectModel` trio is ready-made, its client consumer not yet built). diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md index 6eea0af064..d5d92b2ca5 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md @@ -26,8 +26,8 @@ web client 只有一张全局会话面:slot 全部从根上下文渲染,插 host 侧 `session.create(workspaceId)` 一体产出 Session + Agent + cwd(作为不可拆分的原子整体);client 侧就是这次出生的镜像——会话行进入 list mirror 的瞬间,client 为它铸 Agent scope(actx + provide + 输入面全套挂上): - 会话身份自出生即为 host 真身:sessionId 由 `session.create` 响应 / `host/session-added` 帧带来,client 侧一切寻址(scope tag、slot store 键、RPC 地址)用的都是同一个 id。 -- 手动选择 Workspace 或成功[准备首次使用默认工作区](../feature/2026-09-20-default-workspace.zh.md)先确定 cwd,client 随后调用 `session.create({workspaceId})` 并取得完整实体。 -- 「New Session 且未选 workspace」没有 Session 或 scope 实体。Composer 保留本地文本草稿;连接后才提供 Session scope 的 slash 命令。 +- 手动选定 Workspace 或完成[首次使用的启动初始化](../feature/2026-09-20-default-workspace.zh.md) 后,cwd 已确定,client 再调 `session.create({workspaceId})`,拿到完整实体。 +- 「New Session 且未选 workspace」是**纯视图态**(一个导航位置),不对应任何会话/scope 实体;选定之前 composer 整体锁死(无 slash、无纯文本)。 - 「空会话」是尚无轮次的普通实体化会话;对 host 上的 Agent-scope 插件(goal/plan/skill(技能)/…)而言,它仍是普通 Session,因此 slash/plan 自然可用。 ### Agent scope:actx 是 client 侧 cordis 世界的唯一会话载体 @@ -95,7 +95,7 @@ slot scope 是闭集 `root | session-maybe | session`: - `session-maybe` 以**收养(adoption)身份语义**继承最近 `SessionProvider` 的 binding:空态出生的化身在该 Provider 第一次收到 binding 时保持 React 实例,此后 Provider 切换 generation 或回到空态时重挂。Provider 切换 generation 时,组件本地的逐 Session 状态会清零。切换过程中,只有持久化 Store 值能活过 generation 退休;只有另一份 reference 保活该 generation 时,binding 自有 source 才能保留。无 binding 时,`sessionId`、`useSession`/`useInput` 的结果与 `inputActions` 均可缺省。Provider roster 变化会重新物化已挂载 binding,但不改变其 identity;逐 entry 的收养记账住在 renderer 的 `SessionMaybeEntry`。 - `session` 保证 `sessionId`、所有钩子 source 与 props 均存在;每个严格 entry 的错误边界以 `sessionId` 为 key,切换会话会重建该 entry 及其会话 store。 -`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:Session 存在前,注入的编辑器保存首次使用文本草稿;连接后,同一 InputBar 实例接收已持有 Session 的输入。其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 +`conversation` 是其 owner `SessionProvider` 下的 `session-maybe` 常驻外壳:`ConversationRoot`、HeroShell、Workspace picker、scrollport 与 composer stack,以及 overlay chain 的 fallback 外框,在无 Session → blank Session 的切换中保持 React 实例。两个严格 session entry 只填入固定区域,不改变该树的父级:`conversation.session.header` 在 scrollport 上方承载 breadcrumb/tab/action,`conversation.session` 在其内部承载 view ring 与 draft mirror;二者共享同一个 Session scope chat store。composer bar(`conversation.composer.bar`)本身即为 `session-maybe`:无 Session 时,其 machine faces 和消息动作保持惰性,整张虚线卡片可经指针打开现有 Workspace picker,只读 textarea 也可通过 Enter 或 Space 打开。binding 出现后同一实例(含 textarea)转为 live;其余输入 slot 保持严格 `session`,在此之前不派发任何内容。blank → engaging/active 的 InputBar 不因 phase 翻转而重建。 blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入口等导航控件在首条消息之前即可使用。标题、actions、utilities 和 View tabs 在 blank phase 中继续隐藏。header 仍要求已选中的 Session;Files 与 Terminal 入口使用该 Session 的工作区和执行服务,无需已有 Turn 记录。 @@ -136,5 +136,6 @@ blank Session 保留 header 的 leading 与 corner slot,让右侧栏展开入 - 插件获得与 host 同构的会话上下文:逐会话状态挂 actx、随 scope fiber 一次拆装,泄漏结构性不可能;双会话隔离由 scope filter 结构性保证。 - client 对象层收敛为 wire 镜像:会话身份、生命周期、能力判别全部以 host 实体为准——输入体系(下一层)面对的永远是「有真 Agent 的会话」,slash/skill 等提供方一律以 sessionId 直接寻址。 - 空会话治理零专用机制:状态靠一个派生位,可见性靠统一列表投影(仅 current blank 以 `New Session` 展示),复用时获取持久化写锁,常规上限靠同 Workspace 复用。转正所依赖的受理/运行展示记忆仅保留在客户端。 -- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。Session 存在前,其 scope 输入仍不可用;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)负责本地首次使用草稿。 + +- 代价:id→ctx 换乘纪律、provide 的 Concurrent 纪律都是约定而非类型强制,靠 review 与测试钉住。单一状态轴仍会在 Session 存在前隐藏 machine face;这段时间内,[常驻会话壳](../../../../packages/client/ui-conversation/README.zh.md)会把激活操作转到 Workspace picker。 - 已知欠账:approval/question 跨 prune 恢复(TODO);模型选择以 live-mutation 形状回归(host `selectModel` 三件套现成,其 client 消费方尚未构建)。 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml index a3ed2bee71..89b4d5dabf 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-20-default-workspace.md -2026-09-20-default-workspace.md: 376b2eaf7ac26c13e7483838700c88151b44135d -2026-09-20-default-workspace.zh.md: e16c5d47c6e1bceef293089edf882162812dfa1b +2026-09-20-default-workspace.md: 1674079403b17fb1bd984052a85975609179cad0 +2026-09-20-default-workspace.zh.md: 81a7c96efa3d8b8d4673b684b59babe339706f29 diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md index 376b2eaf7a..1674079403 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.md @@ -10,17 +10,17 @@ A new installation requires a directory choice before the user can send a first ## Decision -The conversation shell retains an unsent local text draft without creating a Session. Its first send asks the Host to prepare a default Workspace, then connects a real Session and submits through the ordinary composer pipeline. The first-use draft awaits staged mode selection before automatic submission. This partially supersedes the locked no-Session composer in [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md); that note still owns blank-Session reuse and provisioning rationale. +Startup waits for complete Workspace and Session baselines. When both lists are empty, the Client asks the Host to prepare the default Workspace, then creates or reuses and selects its blank Session. Input stays unavailable until a Session exists and uses the ordinary composer pipeline thereafter. [Session scope and provisioning](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.md) owns blank-Session reuse and provisioning rationale. The [Workspace registry](../../../../packages/workspace/workspace/README.md#first-use-workspace) owns eligibility and directory preparation. All live Sessions, persisted headers, and archived identities count, including entries absent from the sidebar. The operation shares the registry mutation queue and rechecks Session history after directory preparation because Sessions can start independently. -The Client resolves the initial directory name and title from its language when sending. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). +The Client resolves the initial directory name and title from its language at startup. The Host controller resolves the Documents location; the registry receives a directory resolver with no locale dependency. The resolver runs inside the mutation queue only for eligible creation, so repeated requests reuse the durable Workspace without another OS lookup. A durable Workspace id records successful initialization independently of that name. Renaming, changing language, restarting, or deleting the registration cannot initialize another default. The marker commits with the registration, so a failed registration can retry. Directory contents remain subject to the existing [metadata-only deletion policy](2026-07-27-workspace-registration-deletion.md). -Creation failure preserves the draft and offers the existing folder picker. A successful registration survives Session creation or prompt failure. Picking a folder after failure transfers the text without sending it; a later send remains the user's action. +Ineligible first use returns no Workspace without a failure dialog. Preparation failure offers the existing folder picker; startup does not retry on later list notifications. A successful registration survives Session creation or prompt failure. Selecting either the default or a manually picked Workspace never submits a message. ## Alternatives considered -- Creating on application startup would write directories for users who never send a message. +- Creating only when sending avoids unused directories but requires a separate local draft, transfer into a Session, and coordination of the first submission. Startup creation accepts the early filesystem effect and uses ordinary Session input throughout. - Falling back to `/Documents` when system lookup is unavailable would choose an unverified Documents location; deployments that need another directory use the explicit Host override. - Inferring first use from visible sidebar rows would ignore archived, hidden, and cwd-less Sessions. - Using the localized path as the initialization marker would allow language changes or deletion to create another default. @@ -28,6 +28,6 @@ Creation failure preserves the draft and offers the existing folder picker. A su ## Consequences -First-use typing has no Host Session or filesystem effects. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. +Opening a new installation can create a directory and blank Session before the user sends a message. Directory authorization and preparation failures can appear during startup. Preparation remains a Host responsibility for both Desktop and remote Web clients, so remote users use the Host account's Documents location. Unavailable Documents lookup fails with the same folder-selection recovery as directory creation failure. -The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and draft recovery; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled first-send and picker paths with an isolated Documents directory and recorded Session replay. +The feature preserves [reference-owned Client Session lifetimes](../architecture/2026-09-15-client-session-references.md) and requires no agent-loop or Session-event change. Registry and client tests cover retries, hidden history, concurrency, and startup cancellation; the [browser scenario](../../../../apps/web/tests/default-workspace.e2e.ts) verifies the assembled startup, reload, first-send, and picker paths with an isolated Documents directory and recorded Session replay. diff --git a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md index e16c5d47c6..81a7c96efa 100644 --- a/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md +++ b/.agents/notes/implemented/feature/2026-09-20-default-workspace.zh.md @@ -10,17 +10,17 @@ Status: implemented ## Decision -会话外壳保存未发送的本地文本草稿,不创建 Session。首次发送请求 Host 准备默认 Workspace,随后连接真实 Session,并通过常规 composer 流程提交。首次使用的草稿会在自动提交前等待暂存的模式选择完成。这部分取代[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)中无 Session 时锁定 composer 的决策;该记录仍负责 blank Session 复用与供给通道的理由。 +启动时等待完整的 Workspace 和 Session 基线。两份列表均为空时,Client 请求 Host 准备默认 Workspace,随后创建或复用并选中其空白 Session。Session 存在前不可输入,之后使用常规 composer 流程。[Session scope 与供给通道](../architecture/2026-07-25-web-client-session-scope-and-provide-channel.zh.md)负责 blank Session 复用与供给通道的理由。 [Workspace registry](../../../../packages/workspace/workspace/README.zh.md#first-use-workspace)负责资格判断和目录准备。所有 live Session、持久化 header 和已归档身份都计入判断,包括侧栏中不可见的条目。操作共用 registry 修改队列,并在目录准备后重新检查 Session 历史,因为 Session 可以独立启动。 -Client 在发送时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 +Client 在启动时按其语言解析初始目录名和标题。Host 控制器解析 Documents 位置;注册表接收不依赖 locale 的目录解析器。解析器仅在允许创建时于变更队列内运行,因此重复请求直接复用持久化的 Workspace,无需再次查询操作系统目录。持久化 Workspace id 独立于名称记录初始化成功。改名、切换语言、重启或删除登记均不能再次初始化默认工作区。标记与登记一起提交,因此登记失败可以重试。目录内容仍遵循已有的[仅删除元数据策略](2026-07-27-workspace-registration-deletion.zh.md)。 -创建失败时保留草稿,并提供现有文件夹选择器。成功的登记会在 Session 创建或提示词发送失败后保留。失败后选择文件夹只转移文本,不发送;随后发送仍由用户操作。 +不符合首次使用条件时不返回 Workspace,也不显示失败弹窗。准备失败时提供现有文件夹选择器;后续列表通知不会触发启动流程重试。成功的登记会在 Session 创建或提示词发送失败后保留。选中默认或手动选择的 Workspace 均不会提交消息。 ## Alternatives considered -- 在应用启动时创建,会为从未发送消息的用户写入目录。 +- 仅在发送时创建可以避免未使用的目录,但需要独立的本地草稿、向 Session 转移草稿及首次提交协调逻辑。启动时创建接受提前写入文件系统的副作用,始终使用普通 Session 输入。 - 系统查询不可用时回退到 `/Documents`,会选择未经确认的 Documents 位置;需要其他目录的部署使用显式 Host 覆盖配置。 - 根据侧栏可见行推断首次使用,会忽略已归档、隐藏和无 cwd 的 Session。 - 将本地化路径作为初始化标记,会允许切换语言或删除后再次创建默认工作区。 @@ -28,6 +28,6 @@ Client 在发送时按其语言解析初始目录名和标题。Host 控制器 ## Consequences -首次使用时输入文本不会产生 Host Session 或文件系统副作用。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 +打开新安装的应用即可在用户发送消息前创建目录和空白 Session。目录授权与准备失败提示可能在启动期间出现。Desktop 和远程 Web 客户端均由 Host 准备目录,因此远程用户使用 Host 账户的 Documents 位置。Documents 查询不可用时,采用与目录创建失败相同的文件夹选择恢复路径。 -该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及草稿恢复;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的首次发送与选择器路径。 +该功能保留[由引用持有的 Client Session 生命周期](../architecture/2026-09-15-client-session-references.zh.md),无需修改 agent-loop 或 Session 事件。Registry 和客户端测试覆盖重试、隐藏历史、并发及启动取消;[浏览器场景](../../../../apps/web/tests/default-workspace.e2e.ts)通过隔离的 Documents 目录和已录制 Session 回放验证完整装配下的启动、刷新、首次发送与选择器路径。 diff --git a/apps/web/tests/README.i18n.yaml b/apps/web/tests/README.i18n.yaml index cf707e6cb3..4d920402fa 100644 --- a/apps/web/tests/README.i18n.yaml +++ b/apps/web/tests/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/web/tests/README.md -README.md: b2fa27bb7a60ed78309bf81e77b9cd5217bbee2a -README.zh.md: 29ae2e86018257a4fc2379ea2563c8b5e5e9036f +README.md: 8b9c58ce9e4cf2f5f6978c0c6eb5517fe000d3d2 +README.zh.md: 199ae3b56166aa2ffa1c0bed9a16b844ffd7b74f diff --git a/apps/web/tests/README.md b/apps/web/tests/README.md index b2fa27bb7a..8b9c58ce9e 100644 --- a/apps/web/tests/README.md +++ b/apps/web/tests/README.md @@ -4,6 +4,8 @@ English | [中文](README.zh.md) These tests boot the real web composition in-process and drive it with a real Chromium over real HTTP. The lane's mechanics — modes, fixtures, goldens, and the deliberate composition divergences from `dsh web` — are documented in [`scaffold.ts`](scaffold.ts) and the [browser e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md). +Ordinary scenarios begin with no registered Workspace or Session and a durable marker recording a removed default Workspace, so explicit folder-selection scenarios retain control of their cwd. `launchWebScaffold({ firstUse: true })` leaves initialization eligible for startup scenarios. + ## Completion observations State-sensitive cases use Workspace, admission, attachment, and model-stream barriers to separate visible intermediate states from completed operations. Details close waits for frame transitions; archive verification assigns an explicit title to the seeded Session and follows that identity across reload. See the [CI fixture synchronization decision](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md). diff --git a/apps/web/tests/README.zh.md b/apps/web/tests/README.zh.md index 29ae2e8601..199ae3b561 100644 --- a/apps/web/tests/README.zh.md +++ b/apps/web/tests/README.zh.md @@ -4,6 +4,8 @@ 这些测试在进程内启动真实的 web 组合,并用真实 Chromium 通过真实 HTTP 驱动它。该 lane 的运行机制——模式、fixture(测试前置数据)、golden,以及与 `dsh web` 之间刻意保留的组合差异——记录在 [`scaffold.ts`](scaffold.ts) 和 [浏览器 e2e Agent Note](../../../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md) 中。 +普通场景以没有已登记 Workspace 或 Session、但持久化标记记录默认 Workspace 已被删除的状态启动,使显式文件夹选择场景自行决定 cwd。`launchWebScaffold({ firstUse: true })` 保留初始化资格,供启动场景使用。 + ## 完成状态观察 依赖状态的用例使用 Workspace、接纳、附件和模型流屏障,区分可见中间状态与已完成操作。详情关闭等待框架过渡结束;归档验证为 seed Session 设置显式标题,并跨重载跟踪该身份。参见 [CI fixture 同步决策](../../../.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md)。 diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index 265fa715b2..d3b6db624d 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -1,9 +1,9 @@ -/** First-use messages prepare a durable Workspace through the shipped Web composition. */ +/** First-use startup prepares a durable Workspace through the shipped Web composition. */ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished } from 'vitest' import { assertFinalWorkspaceSnapshot, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, @@ -13,124 +13,125 @@ import { newEnglishPage, saveFailureShot } from './support.ts' const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) const EXPECTED = fileURLToPath(new URL('../../../snapshots/web/default-workspace/ui.expected.md', import.meta.url)) const FAILURE_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/failure.expected.md', import.meta.url)) -const PREPARING_EXPECTED = fileURLToPath(new URL('./expected/default-workspace/preparing.expected.md', import.meta.url)) const MODE = webSnapshotMode() describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { - it('sends the first draft in a newly selected default Workspace and keeps its identity across reload', async () => { + it('prepares a blank Session on startup, reuses it after reload, and sends through the ordinary composer', async () => { const fixture = await selectedSessionFixture(FIXTURE) const scaffold = await launchWebScaffold({ + firstUse: true, replayFixture: fixture, // The shared recording remains read-only; replay compares the complete persisted Session. compareReplaySession: MODE === 'replay', paceMs: 5, }) + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() try { - const browser = await chromium.launch() + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) try { - const page = await newEnglishPage(browser) - const tripwire = watchConsole(page) - try { - await page.goto(scaffold.authenticatedUrl) - const input = page.locator('[data-composer-input][contenteditable="true"]').first() - await input.waitFor() - const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! - await input.fill(prompt) - expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) - expect(scaffold.ctx.sessions.list()).toEqual([]) - const settled = scaffold.whenTurnSettled() - const preparing = Promise.withResolvers() - const initialize = scaffold.ctx.workspaceRegistry.initializeDefault.bind(scaffold.ctx.workspaceRegistry) - vi.spyOn(scaffold.ctx.workspaceRegistry, 'initializeDefault').mockImplementationOnce(async (resolve) => { - await preparing.promise - return initialize(resolve) - }) - try { - await input.press('Enter') - await page.getByRole('textbox', { name: 'Preparing workspace…', exact: true }).waitFor() - await compareOrRefreshGolden(PREPARING_EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) - } finally { - preparing.resolve(undefined) - } - const sessionId = await settled - const workspace = scaffold.ctx.workspaceRegistry.list()[0]! - expect(workspace.title).toBe('Default workspace') - expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) - expect((await stat(workspace.path)).isDirectory()).toBe(true) - expect(workspace.sessionIds).toContain(sessionId) - expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) - await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) - await page.getByText('DONE', { exact: true }).waitFor() - await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) - await page.reload() - await page.getByText('DONE', { exact: true }).waitFor() - expect(scaffold.ctx.workspaceRegistry.list().map(item => item.id)).toEqual([workspace.id]) - expect(tripwire.pageErrors).toEqual([]) - expect(tripwire.warnings).toEqual([]) - } catch (error) { - await saveFailureShot(page, 'web-e2e-default-workspace') - throw error - } - } finally { - await browser.close() + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + await input.waitFor() + expect(scaffold.ctx.workspaceRegistry.list()).toHaveLength(1) + const initialSession = scaffold.ctx.sessions.list()[0]! + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(initialSession.snapshotEvents().some(event => event.type === 'user/message')).toBe(false) + await page.reload() + await input.waitFor() + expect(scaffold.ctx.sessions.list().map(session => session.id)).toEqual([initialSession.id]) + const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! + await input.fill(prompt) + const settled = scaffold.whenTurnSettled() + await input.press('Enter') + const sessionId = await settled + const workspace = scaffold.ctx.workspaceRegistry.list()[0]! + expect(workspace.title).toBe('Default workspace') + expect(workspace.path).toBe(join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness', 'Default workspace')) + expect((await stat(workspace.path)).isDirectory()).toBe(true) + expect(workspace.sessionIds).toContain(sessionId) + expect(scaffold.ctx.sessions.get(sessionId)?.header.cwd).toBe(workspace.path) + await assertFinalWorkspaceSnapshot(fileURLToPath(new URL('../../../snapshots/web/default-workspace', import.meta.url)), workspace.path) + await page.getByText('DONE', { exact: true }).waitFor() + await compareOrRefreshGolden(EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace') + throw error } } finally { - await scaffold.close() + await browser.close() } }) - it('keeps the draft on a directory conflict and opens the composed folder picker for recovery', async () => { - const scaffold = await launchWebScaffold() + it('reports a startup directory conflict and opens the composed folder picker for recovery', async () => { + const scaffold = await launchWebScaffold({ firstUse: true }) + onTestFinished(() => scaffold.close()) + const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') + await mkdir(parent, { recursive: true }) + await writeFile(join(parent, '默认工作区'), 'occupied') + const chosen = join(scaffold.workspaceCwd, 'chosen') + await mkdir(chosen) + const browser = await chromium.launch() try { - const parent = join(scaffold.workspaceCwd, 'Documents', 'deepseek-harness') - await mkdir(parent, { recursive: true }) - await writeFile(join(parent, '默认工作区'), 'occupied') - const chosen = join(scaffold.workspaceCwd, 'chosen') - await mkdir(chosen) - const browser = await chromium.launch() + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) try { - const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) - const tripwire = watchConsole(page) - try { - await page.goto(scaffold.authenticatedUrl) - const input = page.locator('[data-composer-input][contenteditable="true"]').first() - await input.fill('保留这条消息') - await input.press('Enter') - const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) - await modal.waitFor() - await expect.poll(() => input.textContent()).toBe('保留这条消息') - expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) - expect(scaffold.ctx.sessions.list()).toEqual([]) - await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) - await modal.getByRole('button', { name: '取消', exact: true }).click() - expect(await input.textContent()).toBe('保留这条消息') - await input.press('Enter') - await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() - const picker = page.getByRole('dialog', { name: '选择工作区目录' }) - await picker.waitFor() - await picker.getByRole('button', { name: '编辑路径', exact: true }).click() - await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) - await page.keyboard.press('Enter') - await picker.getByRole('button', { name: '打开', exact: true }).click() - await picker.waitFor({ state: 'hidden' }) - await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) - await page.getByRole('treeitem', { name: '新会话', exact: true }).waitFor() - await expect.poll(() => input.textContent()).toBe('保留这条消息') - expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) - expect(scaffold.ctx.sessions.list()).toHaveLength(1) - expect(scaffold.ctx.sessions.list().every(session => - session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) - expect(tripwire.pageErrors).toEqual([]) - expect(tripwire.warnings).toEqual([]) - } catch (error) { - await saveFailureShot(page, 'web-e2e-default-workspace-failure') - throw error - } - } finally { - await browser.close() + await page.goto(scaffold.authenticatedUrl) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) + await modal.waitFor() + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) + await modal.getByRole('button', { name: '取消', exact: true }).click() + expect(await input.count()).toBe(0) + await page.reload() + await modal.waitFor() + await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + const picker = page.getByRole('dialog', { name: '选择工作区目录' }) + await picker.waitFor() + await picker.getByRole('button', { name: '编辑路径', exact: true }).click() + await picker.getByRole('textbox', { name: '编辑路径' }).fill(chosen) + await page.keyboard.press('Enter') + await picker.getByRole('button', { name: '打开', exact: true }).click() + await picker.waitFor({ state: 'hidden' }) + await expect.poll(() => scaffold.ctx.workspaceRegistry.list().length).toBe(1) + await input.waitFor() + expect(await input.textContent()).toBe('') + expect(scaffold.ctx.workspaceRegistry.list()[0]?.path).toBe(chosen) + expect(scaffold.ctx.sessions.list()).toHaveLength(1) + expect(scaffold.ctx.sessions.list().every(session => + session.snapshotEvents().every(event => event.type !== 'user/message'))).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, 'web-e2e-default-workspace-failure') + throw error } } finally { - await scaffold.close() + await browser.close() + } + }) + + it('keeps an explicitly deleted default absent on startup', async () => { + const scaffold = await launchWebScaffold() + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const attempted = page.waitForResponse(response => response.url().includes('/api/workspace/initializeDefault')) + await page.goto(scaffold.authenticatedUrl) + expect((await attempted).ok()).toBe(true) + await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() + expect(await page.getByRole('dialog', { name: 'Unable to create default workspace' }).count()).toBe(0) + expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) + expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) + expect(scaffold.ctx.sessions.list()).toEqual([]) + } finally { + await browser.close() } }) }) diff --git a/apps/web/tests/expected/default-workspace/preparing.expected.md b/apps/web/tests/expected/default-workspace/preparing.expected.md deleted file mode 100644 index 09e86fbb6e..0000000000 --- a/apps/web/tests/expected/default-workspace/preparing.expected.md +++ /dev/null @@ -1,7 +0,0 @@ -- banner -- text: Into the Unknown Preview -- button "Choose workspace" -- button "Standard mode" -- textbox "Preparing workspace…" [disabled] -- button "Add files or run commands" [disabled] -- button "Send message" [disabled] diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index f903205c80..16a80f5dd2 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -395,6 +395,8 @@ export interface LaunchOptions { deepSeekMessages?: boolean /** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */ welcomeNoticePending?: boolean + /** Leave first-use Workspace initialization eligible; ordinary scenarios start after the default was removed. */ + firstUse?: boolean /** * Patch the shipped DeepSeek search row to a deterministic endpoint and * credential reference. Browser search scenarios keep the real provider and @@ -600,7 +602,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise ({ path: workspaceCwd, title: 'Workspace' })) + if (initial !== undefined) await ctx.workspaceRegistry.delete(initial.id) + } const boundPort = ctx.get('webServer')?.port if (boundPort === undefined) { throw new Error('web e2e scaffold: webServer service missing after settled boot') diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index f9bef3d306..452d200cf5 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md -workspace.md: 43a631ad0b04dd272436e272c931c2a16b7bbe88 -workspace.zh.md: c4571083f3e445828b4b3b41a27ed8abee9ee04d +workspace.md: 323323946ac92bbc03962b83c5e77a81a960d89a +workspace.zh.md: aedd1134305aaa7e97ccd449631ff72446bf28b4 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 43a631ad0b..323323946a 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -306,12 +306,12 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('create') create(request: WorkspaceCreateRequest): Promise /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ -@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise /** * Rename one Workspace to a unique non-blank title. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index c4571083f3..aedd113430 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -306,12 +306,12 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('create') create(request: WorkspaceCreateRequest): Promise /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ -@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise +@Remote('initializeDefault') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise /** * Rename one Workspace to a unique non-blank title. diff --git a/packages/api/workspace-controller/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index 6300d2f2e4..0520266936 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-controller/README.md -README.md: 24bf0610689bfb857b24e7c8298b1b0494f1ca02 -README.zh.md: ca140abfdda246b62b0485e63ebfd05ab2efe6f9 +README.md: 27053331007681eb373b4537514bbe701dad660d +README.zh.md: d0726496de5dcf623fedb531ad988b3c608fc2ac diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index 24bf061068..2705333100 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -29,9 +29,9 @@ The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream ### First-use Workspace -`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Conversation Client](../../client/ui-conversation/README.md) resolves these names from its send-time language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. +`workspace.initializeDefault({ directoryName, title })` returns the durable default Workspace; the Client service exposes the same request as `workspaces.initializeDefault(request, signal?)`. The [Workspace Client](../../client/ui-workspace/README.md) resolves these names from its startup language. The Host places the directory under its account's `/deepseek-harness`, including on remote Web hosts. The directory name must be one non-blank segment without separators, colon, NUL, surrounding whitespace, or a trailing dot; the title must be non-blank. OS filename restrictions also apply. Linux system lookup requires `xdg-user-dir` with an enabled Documents directory; hosts without it must configure `documentsDirectory` or use the folder picker. -The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Invalid names or ineligible first use reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. +The [Workspace registry](../../workspace/workspace/README.md#first-use-workspace) owns eligibility, directory creation, and durable initialization. An existing default Workspace is returned without another Documents lookup; request names do not rename it. Ineligible first use returns `undefined`, so startup can leave directory selection to the user. Invalid names reject with `gateway/bad-request`; lookup and creation failures use standard Remote error handling. Initialization creates no Session and sends no message. | Configuration | Default | Purpose | | --- | --- | --- | diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index ca140abfdd..d0726496de 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -29,9 +29,9 @@ Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。 ### 首次使用工作区 -`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Conversation Client](../../client/ui-conversation/README.zh.md)按发送时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 +`workspace.initializeDefault({ directoryName, title })` 返回持久化的默认工作区;Client service 通过 `workspaces.initializeDefault(request, signal?)` 提供同一请求。[Workspace Client](../../client/ui-workspace/README.zh.md)按启动时的语言解析这些名称。Host 将目录放在其账户的 `/deepseek-harness` 下,远程 Web Host 也遵循此规则。目录名必须是非空的单个片段,不能含分隔符、冒号、NUL、首尾空白或末尾句点;标题不能为空。操作系统的文件名限制同样适用。Linux 系统查询要求存在 `xdg-user-dir` 且启用了 Documents 目录;不具备该条件的 Host 必须配置 `documentsDirectory` 或使用文件夹选择器。 -[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。名称无效或不满足首次使用条件时,以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 +[Workspace 注册表](../../workspace/workspace/README.zh.md#first-use-workspace)负责资格判断、目录创建和持久化初始化。已有默认工作区直接返回,不再查询 Documents;请求中的名称不会将其重命名。不满足首次使用条件时返回 `undefined`,启动流程可将目录选择留给用户。名称无效时以 `gateway/bad-request` 拒绝;查询和创建失败遵循标准 Remote 错误处理。初始化不创建 Session,也不发送消息。 | 配置 | 默认值 | 用途 | | --- | --- | --- | diff --git a/packages/api/workspace-controller/src/client/model.ts b/packages/api/workspace-controller/src/client/model.ts index 3f6dda9f76..25a84d655e 100644 --- a/packages/api/workspace-controller/src/client/model.ts +++ b/packages/api/workspace-controller/src/client/model.ts @@ -108,9 +108,11 @@ export class ClientWorkspaceModel implements WorkspaceFollowSink { * @param signal - caller lifetime. * @returns generated Remote result. */ - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise> { + async initializeDefault( + request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal, + ): Promise> { const result = await this.remote.initializeDefault(request, signal) - if (result.ok) this.upsert(result.value.workspace) + if (result.ok && result.value !== undefined) this.upsert(result.value.workspace) return result } diff --git a/packages/api/workspace-controller/src/client/service.ts b/packages/api/workspace-controller/src/client/service.ts index f94baafdb2..393fed0b7f 100644 --- a/packages/api/workspace-controller/src/client/service.ts +++ b/packages/api/workspace-controller/src/client/service.ts @@ -43,9 +43,9 @@ export interface IWorkspaces { * Initialize or reuse the default Workspace. * @param request - initial directory name and title. * @param signal - caller lifetime. - * @returns the prepared Workspace; rejects when directory selection is required. + * @returns the prepared Workspace, or undefined when first-use initialization is ineligible; rejects on preparation failure. */ - initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise + initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise /** * Rename a Workspace. * @param workspaceId - target Workspace. @@ -117,10 +117,10 @@ export class WorkspaceController extends Service implements IWorkspaces { return result.value.workspace } - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { const result = await this.model.initializeDefault(request, signal) if (!result.ok) throw new WorkspaceCreateError(result.error) - return result.value.workspace + return result.value?.workspace } async rename(workspaceId: WorkspaceId, title: string): Promise { diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 966a5e9fb9..7a63e5b699 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -86,13 +86,13 @@ export class WorkspaceController extends TypertRemoteService { } /** - * Initialize or reuse the default Workspace before the first user message. + * Initialize or reuse the default Workspace during first-use startup. * @param request - initial directory name and title; never rename an existing default. * @param signal - caller lifetime; cancels native directory lookup. - * @returns the durable Workspace without creating a Session or sending a message. + * @returns the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message. */ @Remote('initializeDefault') - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise { const { directoryName, title } = request if (directoryName.trim() === '' || directoryName !== directoryName.trim() || directoryName.endsWith('.') || /[/\\:\0]/.test(directoryName) || title.trim() === '') { @@ -105,10 +105,7 @@ export class WorkspaceController extends TypertRemoteService { ) return { path, title } }) - if (workspace === undefined) { - throw new RemoteError('gateway/bad-request', 'choose a directory to create a Workspace', {}) - } - return { workspace: workspaceView(workspace) } + return workspace === undefined ? undefined : { workspace: workspaceView(workspace) } } /** diff --git a/packages/api/workspace-controller/tests/model.client.spec.ts b/packages/api/workspace-controller/tests/model.client.spec.ts index 4558d4f64d..e4f11a7678 100644 --- a/packages/api/workspace-controller/tests/model.client.spec.ts +++ b/packages/api/workspace-controller/tests/model.client.spec.ts @@ -177,6 +177,10 @@ describe('ClientWorkspaceModel', () => { expect(remote.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, signal) expect(model.getSnapshot().items.map(item => item.workspaceId)).toEqual(['default']) const before = model.getSnapshot() + remote.initializeDefault.mockResolvedValueOnce(remoteOk(undefined)) + await expect(model.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })) + .resolves.toEqual({ ok: true, value: undefined }) + expect(model.getSnapshot()).toBe(before) remote.initializeDefault.mockResolvedValueOnce(workspaceError( new RemoteError('gateway/bad-request', 'choose a folder', {}), )) diff --git a/packages/api/workspace-controller/tests/transport.client.spec.ts b/packages/api/workspace-controller/tests/transport.client.spec.ts index 9829004125..220f83e069 100644 --- a/packages/api/workspace-controller/tests/transport.client.spec.ts +++ b/packages/api/workspace-controller/tests/transport.client.spec.ts @@ -310,6 +310,18 @@ describe('Workspace state stream', () => { }) describe('WorkspaceController', () => { + it('returns no Workspace when startup is ineligible without changing the list', async ({ mock, start }) => { + const { remote, client } = await gatewayClient(mock, start) + const model = new ClientWorkspaceModel(remote.workspace) + model.replaceBaseline({ items: [], archivedSessionIds: [], pinnedSessionIds: [] }) + const controller = new WorkspaceController(client.ctx, model) + const before = model.getSnapshot() + mock.remote.workspace.initializeDefault.mockResolvedValueOnce({ ok: true, value: undefined }) + await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' })) + .resolves.toBeUndefined() + expect(model.getSnapshot()).toBe(before) + }) + it('publishes the model source and exposes successful Workspace commands', async ({ mock, start }) => { const { remote, client } = await gatewayClient(mock, start) const model = new ClientWorkspaceModel(remote.workspace) diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index 39cd085879..0656aaf8bf 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -447,24 +447,24 @@ describe('first-use Remote', () => { it('uses the requested display title independently of the directory name', async () => { const { controller, root } = await harness() const result = await controller.initializeDefault({ directoryName: 'default-workspace', title: 'Default workspace' }, new AbortController().signal) - expect(result.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) + expect(result?.workspace).toMatchObject({ path: join(root, 'deepseek-harness', 'default-workspace'), title: 'Default workspace' }) }) it('returns a durable Workspace without allocating a Session', async () => { const { controller, ctx, root } = await harness() const signal = new AbortController().signal const result = await controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, signal) - expect(result.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) - expect(existsSync(result.workspace.path)).toBe(true) + expect(result!.workspace.path).toBe(join(root, 'deepseek-harness', 'Default workspace')) + expect(existsSync(result!.workspace.path)).toBe(true) expect(ctx.sessions.list()).toEqual([]) expect(await controller.initializeDefault({ directoryName: '默认工作区', title: '默认工作区' }, signal)).toEqual(result) }) - it('rejects ineligible first use and propagates preparation failures', async () => { + it('skips ineligible first use and propagates preparation failures', async () => { const { controller, ctx, root } = await harness() await ctx.workspaceRegistry.create(root) await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) - .rejects.toMatchObject({ code: 'gateway/bad-request' }) + .resolves.toBeUndefined() vi.spyOn(ctx.workspaceRegistry, 'initializeDefault').mockRejectedValueOnce(new Error('permission denied')) await expect(controller.initializeDefault({ directoryName: 'Default workspace', title: 'Default workspace' }, new AbortController().signal)) .rejects.toThrow('permission denied') diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 9a9afcdd63..3b67b4ca8a 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md -README.md: 5545dbbddf18d6f181d5e8c17e194043b3e0bf9d -README.zh.md: 4ef159280dd5e72c9d12aa75905855a2b9bf8d27 +README.md: 5f2c9acaa5840e71d6ca237c5fc5eccb52724cda +README.zh.md: 5c61823c25f145c0e516f3f2a16c2de05c250ef1 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 5545dbbddf..5f2c9acaa5 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -49,8 +49,6 @@ The settings section writes the Host's existing `agent-presets` namespace throug The chip follows the preset projection of its bound Session while its plugin and Provider generation remain active. Settings synchronization creates the same bound controller when needed, even before the chip mounts. A late projection or another client's preset update refreshes the display without submitting a selection; list notifications do not repeat an in-flight selection. Settings changes wait for that selection and recheck the captured blank Session before applying. A choice staged during a pending request remains available afterward. -After preparing a default Workspace, the first-use draft waits for the staged preset through `conversation/prepare-first-send`. Concurrent `apply()` calls wait for the active selection without repeating it. A refusal keeps the unsent Session draft. - ----- diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index 4ef159280d..5c61823c25 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -49,8 +49,6 @@ kind: "package-reference" 只要插件及 Provider generation 仍有效,选择芯片就会跟随其绑定 Session 的预设投影。即使选择芯片尚未挂载,设置同步也会按需创建同一个绑定控制器。延后到达的投影或其他客户端的预设更新会刷新显示,而不会提交选择;列表通知不会重复仍在进行中的选择操作。设置修改会等待该操作结束,并在应用之前重新检查已捕获的空白 Session。请求期间暂存的新选择会保留。 -默认工作区准备完成后,首次使用的草稿通过 `conversation/prepare-first-send` 等待暂存的模式选择。并发的 `apply()` 调用等待已有选择操作,不会重复提交。选择被拒绝时保留未发送的 Session 草稿。 - ----- diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index 113e440900..0838fd89aa 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -143,14 +143,6 @@ export function apply(ctx: ClientContext): void { // render and simply hides the button while no flow exists. let creatorDraft: (() => void) | undefined ctx.inject(['slots', 'conversation', 'sessions', 'uiWorkspace'], (scope: ClientContext) => { - scope.on('conversation/prepare-first-send', async (sessionId) => { - const binding = scope.sessions.binding(sessionId) - if (binding === undefined) return - const seat = seatFor(binding) - if (staged.id === undefined && !seat.store.getSnapshot().busy) return - const error = await seat.apply() - if (error !== undefined) throw new Error(error) - }) const seatInjected = (sessionId: SessionId | undefined): AgentPresetSeatInjected => { const binding = sessionId === undefined ? undefined : ctx.sessions.binding(sessionId) const seat = binding === undefined ? unboundSeat : seatFor(binding) diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index 4e7488bc3b..45bd9373e4 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -193,18 +193,11 @@ export class AgentPresetSeatController { * * Called both by `select()` and by whoever observes the current session * changing, because the session may appear either before or after the pick. - * Concurrent callers wait for the active selection without repeating it. - * @returns the Host refusal, or undefined when successful or no switch starts. + * List updates do not repeat a selection while its response is pending. + * @returns this attempt's Host refusal, or undefined when successful or no switch starts. */ async apply(): Promise { - let pending = this.pendingSelection - while (pending !== undefined) { - await pending - const error = this.store.getSnapshot().error - if (error !== null) return error - pending = this.pendingSelection - if (pending === undefined && this.staged.id === undefined) return - } + if (this.store.getSnapshot().busy) return const staged = this.staged.id const session = this.currentSession() if (staged === undefined) { diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index 378b40006f..1e28cb44f4 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ */ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' @@ -76,7 +76,6 @@ async function bench(options: { failSettingsUpdate?: boolean selectGate?: Promise settingsRosterGate?: Promise - refuseSelect?: boolean } = {}) { const ctx = new Context() // The host's answer, mutable so a spec can move the default the way the @@ -154,9 +153,7 @@ async function bench(options: { deletePreset: () => Promise.resolve({ ok: true as const, value: undefined }), select: (_agentId: SessionId, agentPreset: string) => { calls.push(`select:${agentPreset}`) - return Promise.resolve(options.selectGate).then(() => options.refuseSelect === true - ? { ok: false as const, error: new RemoteError('gateway/internal', 'preset refused', {}) } - : { ok: true as const, value: agentPreset }) + return Promise.resolve(options.selectGate).then(() => ({ ok: true as const, value: agentPreset })) }, } ctx.provide('remote.agentPresets', agentPresets as never) @@ -718,10 +715,8 @@ describe('ui-agent-preset apply', () => { conversation() }) - it.each([false, true])('awaits the staged choice before first send and propagates refusal (%s)', async (refuseSelect) => { - const selection = Promise.withResolvers() - const { ctx, slots, calls } = await bench({ refuseSelect, selectGate: selection.promise }) - onTestFinished(async () => { selection.resolve(undefined); await ctx.fiber.dispose() }) + it('applies the staged choice to the blank session the flow lands on', async () => { + const { ctx, slots, calls } = await bench() declareRoot(slots) declareConversation(slots) ctx.provide('conversation', {} as never) @@ -741,8 +736,6 @@ describe('ui-agent-preset apply', () => { .inject as unknown as (sessionId?: SessionId) => AgentPresetSeatInjected const chip = injectSeat() - await ctx.serial('conversation/prepare-first-send', SessionId('absent')) - await chip.load() // Picked on the hero screen, where there is no session yet. await chip.select('minimal') @@ -754,16 +747,10 @@ describe('ui-agent-preset apply', () => { } sessions.notify() const bound = injectSeat(SessionId('s1')) - const preparing = ctx.serial('conversation/prepare-first-send', SessionId('s1')) - const settled = refuseSelect ? expect(preparing).rejects.toThrow('preset refused') : expect(preparing).resolves.toBeUndefined() - selection.resolve(undefined) - await settled - await ctx.serial('conversation/prepare-first-send', SessionId('s1')) await bound.load() // Connecting a workspace produced the session; the stage reaches it there. await vi.waitFor(() => { expect(calls).toContain('select:minimal') }) - expect(calls.filter(call => call === 'select:minimal')).toHaveLength(1) }) it('applies the stage to a session that records no preset of its own', async () => { @@ -959,28 +946,6 @@ describe('ui-agent-preset apply', () => { }) describe('AgentPresetSeatController reconciliation', () => { - it.each([false, true])('shares the result of an active preset selection (refused: %s)', async (refused) => { - const refusal = { ok: false as const, error: new RemoteError('gateway/internal', 'selection refused', {}) } - const reply = Promise.withResolvers<{ ok: true; value: string } | typeof refusal>() - const select = vi.fn(() => reply.promise) - const controller = new AgentPresetSeatController({ remote: { agentPresets: { select } } } as never, - () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) - const selecting = controller.select('minimal') - let prepared = false - const preparation = controller.apply().finally(() => { prepared = true }) - try { - expect(prepared).toBe(false) - expect(select).toHaveBeenCalledOnce() - reply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await expect(preparation).resolves.toBe(refused ? 'selection refused' : undefined) - await selecting - expect(select).toHaveBeenCalledOnce() - } finally { - reply.resolve({ ok: true, value: 'minimal' }) - await Promise.allSettled([selecting, preparation]) - } - }) - it.each([ { refuseFirst: false, refuseLatest: false }, { refuseFirst: false, refuseLatest: true }, @@ -1001,17 +966,16 @@ describe('AgentPresetSeatController reconciliation', () => { const first = controller.select('minimal') let settingsSettled = false const settings = controller.syncBlankSession(session.id, 'cordis').finally(() => { settingsSettled = true }) - const repeatedFirst = controller.apply() + await controller.apply() expect(requests.map(request => request.preset)).toEqual(['minimal']) requests[0]!.outcome.resolve(refuseFirst ? refusal : { ok: true, value: 'minimal' }) await first expect(requests.map(request => request.preset)).toEqual(['minimal', 'cordis']) expect(settingsSettled).toBe(false) - const repeatedLatest = controller.apply() + await controller.apply() expect(requests).toHaveLength(2) requests[1]!.outcome.resolve(refuseLatest ? refusal : { ok: true, value: 'cordis' }) await expect(settings).resolves.toBe(refuseLatest ? 'selection refused' : undefined) - await Promise.all([repeatedFirst, repeatedLatest]) expect(controller.store.getSnapshot()).toMatchObject({ current: refuseLatest ? 'standard' : 'cordis', busy: false, error: refuseLatest ? 'selection refused' : null, @@ -1028,10 +992,10 @@ describe('AgentPresetSeatController reconciliation', () => { () => ({ id: SessionId('blank'), blank: true, projectionValues: { agentPreset: 'standard' } })) const first = controller.select('minimal') controller.stage('cordis', true) - const repeated = controller.apply() + await controller.apply() expect(select).toHaveBeenCalledOnce() firstReply.resolve(refused ? refusal : { ok: true, value: 'minimal' }) - await Promise.all([first, repeated]) + await first expect(controller.store.getSnapshot().current).toBe('cordis') await controller.apply() expect(select.mock.calls.map(call => call[1])).toEqual(['minimal', 'cordis']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 2bcda4be9c..b871029e8d 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: f921aa4a9aa7e9cea0a8a2c2c875b3f1d7c27bd8 -README.zh.md: b432995b1e42292a65558f37f153920cc7ecbbf2 +README.md: 16e821ed4caabae491d552a823bd69a2e976e2bd +README.zh.md: 7316b00c69ca74284b81678082d93e870dee6bbe diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index f921aa4a9a..16e821ed4c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -50,10 +50,6 @@ Claimed commands retain their identity and highlight when only their arguments a Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. -The Client chooses the default directory name and initial title when sending: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A retry after failed initialization uses the current language; a successfully initialized Workspace keeps its directory and title across language changes. - -On first use, the same input accepts text before a Workspace is selected. The first send prepares the [default Workspace](../../workspace/workspace/README.md#first-use-workspace), selects its blank Session, transfers the draft, and uses ordinary message submission. Preparation locks further input. Failure preserves the draft and offers Cancel or Choose folder through the existing picker. A manually chosen folder receives the unsent draft; the user sends again. Once created, the Workspace survives a prompt failure. `conversation/prepare-first-send` awaits staged Session settings before automatically submitting the transferred first-use draft; a rejected listener keeps that draft and reports its error. If navigation releases the destination Session while preparation is pending, automatic submission stops and its persisted draft remains available on reopening. - 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. 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 container reserves a 40px drag band on macOS desktop and no empty vertical space on Web, Windows, or Linux. 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. @@ -64,7 +60,7 @@ The shell reads the persisted View preference before rendering when a Session fi Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer intentionally owns its full footer band, which is not a resize target; an already-captured drag lifts its indicator until release ([handle styles](src/client/skeleton/ConversationRoot.module.css)). -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. Before a Session exists, the composer holds a local text draft; sending waits for complete Workspace and Session baselines and then prepares the default Workspace. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index b432995b1e..7316b00c69 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -50,10 +50,6 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在该请求仍为当前请求时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 -Client 在发送时决定默认目录名和初始标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化期间,请求保留这些名称。初始化失败后的重试使用当前语言;初始化成功的 Workspace 在切换语言后仍保留原目录和标题。 - -首次使用时,同一个输入框允许在选择 Workspace 前输入文字。首条消息会准备[默认工作区](../../workspace/workspace/README.zh.md#first-use-workspace)、选中其 blank Session、转移草稿,再使用普通消息提交流程。准备期间锁定后续输入。失败时保留草稿,并提供“取消”或通过已有选择器“选择文件夹”。手动选择的文件夹接收未发送草稿,用户再次发送。Workspace 创建成功后,不会因提示词发送失败而消失。`conversation/prepare-first-send` 在自动提交已转移的首次使用草稿前等待暂存的 Session 设置完成;监听器拒绝时保留该草稿并显示错误。如果导航在准备期间释放了目标 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。共享正文与 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 不挂载;常驻容器在 macOS 桌面保留 40px 拖拽区域,在 Web、Windows 或 Linux 上不预留空白高度。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。 @@ -64,7 +60,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 刻意拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会将指示线提高到松开为止([拖动手柄样式](src/client/skeleton/ConversationRoot.module.css))。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。Session 尚未存在时,composer 保存本地文字草稿;发送会等待 Workspace 与 Session 基线完整加载,然后准备默认工作区。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index a02e0737f0..07d754d873 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,7 +2,6 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' -import type { WorkspaceInitializeDefaultRequest } from '@deepseek-ai/dsh-api-workspace-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' @@ -18,13 +17,13 @@ import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionInjected, DraftFileUploads, } from './contract/slots.ts' +import type { InputNotice } from './contract/input.ts' import { createConversationStore, readConversationViewPreference } from './stores.ts' import { ConversationController, UnsupportedImageMediaTypeError } from './service.ts' import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' -import { FirstDraft } from './input/first-draft.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -65,10 +64,19 @@ export const Config: z = z.object({ // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. +const ABSENT_NOTICES = { + getSnapshot: (): InputNotice | null => null, + subscribe: () => () => {}, +} const ABSENT_BLOCK = { getSnapshot: (): ComposerBlock | undefined => undefined, subscribe: () => () => {}, } +const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() +const ABSENT_LEXICON = { + getSnapshot: () => EMPTY_LEXICON, + subscribe: () => () => {}, +} const ABSENT_MENU_LAUNCHER = { getSnapshot: (): string | null => null, subscribe: () => () => {}, @@ -79,19 +87,12 @@ const ABSENT_FILE_UPLOADS = { subscribe: () => () => {}, } -// ui-workspace consumes Conversation slots, so this reverse runtime dependency -// uses a local method projection to keep the TypeScript project graph acyclic. interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise - openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise } /** Action registration used by the composer without importing its command-UI consumer. */ @@ -205,19 +206,6 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, 'ui-conversation: View selection') const inputHub = new InputHub(ctx, t) - const firstDraft = new FirstDraft(ctx, { - open: (beforeOpen, signal) => { - const language = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] - // Persisted Workspace names follow the send-time language, including the English fallback. - const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] - return workspaceNavigation.openDefaultWorkspace({ - directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', - title, - }, beforeOpen, signal) - }, - shell: id => inputHub.shell(id), - isCurrent: (id, shell) => sessions.binding(id) !== undefined && inputHub.shell(id) === shell, - }) const composerBlocks = new ComposerBlockRegistry() ctx.inject(['commandUi'], (scope) => { @@ -278,11 +266,8 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ConversationInjected => ({ hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), - firstDraft: firstDraft.state, }, - dismissDefaultFailure: () => { firstDraft.dismiss() }, selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { - if (sessionId === undefined) firstDraft.transfer(nextId) if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) const draft = from.snapshot.draft @@ -388,7 +373,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { - keyboard: firstDraft.shell, + keyboard: undefined, addFiles: undefined, removeAttachment: undefined, resolveDraftAttachments: undefined, @@ -396,11 +381,10 @@ export function apply(ctx: Context, config: Config = Config({})): void { toggleCommandMenu: undefined, stop: undefined, hooks: { - composerInput: firstDraft.shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: ABSENT_FILE_UPLOADS, - notices: firstDraft.shell.notices, - lexicon: firstDraft.shell.lexicon, + notices: ABSENT_NOTICES, + lexicon: ABSENT_LEXICON, menuLauncher: ABSENT_MENU_LAUNCHER, }, } @@ -449,7 +433,6 @@ export function apply(ctx: Context, config: Config = Config({})): void { }) }, hooks: { - composerInput: shell.state, busyEnter: submissionPolicy.busyEnter, fileUploads: conversation.fileUploads, notices: shell.notices, diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index be338eb3df..b4cd6b9bdf 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -34,12 +34,6 @@ export interface SubmitOutcome { readonly text?: string } -/** State of first-use Workspace preparation. */ -export interface FirstDraftState { - readonly busy: boolean - readonly failed: boolean -} - /** Command-mode credential supplied by one input-trigger source. */ export interface CommandClaim { /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index a0d9a6d592..023babf26e 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -16,7 +16,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ComposerBlock } from './composer-blocks.ts' -import type { DraftAttachmentId, FirstDraftState, InputActions, InputNotice, InputState } from './input.ts' +import type { DraftAttachmentId, InputActions, InputNotice, InputState } from './input.ts' import type { ComposerKeyboard, EditSelection } from './draft-editor.ts' import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' @@ -319,13 +319,8 @@ export type ConvViewProps = PropsRuntime<'conversation.view'> export interface ConversationInjected { /** Connect and open a blank Session in the selected Workspace. */ selectWorkspace: (workspaceId: WorkspaceId) => Promise - /** Dismiss default Workspace creation failure without discarding input. */ - dismissDefaultFailure: () => void /** Session-addressed composer block source, or the stable absent source. */ - hooks: { - composerBlock: ObservableSnapshot - firstDraft: ObservableSnapshot - } + hooks: { composerBlock: ObservableSnapshot } } /** Business callbacks injected into the strict Session body. */ @@ -370,7 +365,7 @@ export interface ComposerBarOwnerProps { /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { - keyboard: ComposerKeyboard + keyboard: ComposerKeyboard | undefined addFiles: ((files: readonly File[]) => string | null) | undefined removeAttachment: ((id: DraftAttachmentId) => void) | undefined resolveDraftAttachments: ((ids: readonly DraftAttachmentId[]) => readonly ComposerAttachment[]) | undefined @@ -379,8 +374,6 @@ export interface ComposerBarInjected { toggleCommandMenu: ((selection: EditSelection) => void) | undefined stop: (() => void) | undefined hooks: { - /** Resident editor state, including input before a Session exists. */ - composerInput: ObservableSnapshot /** * Live busy-state submission preference: the delivery mode plain Enter * and the primary Send button use while the addressed agent is busy. diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 468fc9c198..73ddc6d7d3 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -72,14 +72,6 @@ export type { ArbitrateKey, ArbitrateOutcome, ReferenceInsert, TokenSpan } from export type { ComposerBlock, ComposerBlocks } from './contract/composer-blocks.ts' declare module '@deepseek-ai/cordis' { - interface Events { - /** - * Finish staged settings before automatically submitting the first-use draft to its new Session. - * @mode serial - * @param sessionId - destination Session. - */ - 'conversation/prepare-first-send'(sessionId: import('@deepseek-ai/dsh-session/types').SessionId): void | Promise - } interface Context { /** Scope-addressed Conversation actions and per-Session input registry. */ conversation: import('./service.ts').IConversation diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 77bff28708..4f4d0aa300 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -5,8 +5,8 @@ * scoped-event application verbs, the submit transaction plumbing * (adjudicate via the session's InputTriggerController; claim.submit; default * sink), the notice channel, and the draft persistence mirror. - * Package-private; InputHub binds Session events, while FirstDraft owns the - * local editor used before a Session exists. + * Package-private; the hub alone constructs it and wires the scoped event + * listeners onto it. */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' diff --git a/packages/client/ui-conversation/src/client/input/first-draft.ts b/packages/client/ui-conversation/src/client/input/first-draft.ts deleted file mode 100644 index 8dc7fb32a6..0000000000 --- a/packages/client/ui-conversation/src/client/input/first-draft.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** Local text draft retained until the first Workspace and Session can accept it. */ -import type { Context } from '@deepseek-ai/cordis' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { FirstDraftState, SubmitOutcome } from '../contract/input.ts' -import type { InputSubmitMode } from '../contract/composer-submission.ts' -import { SessionInputShell } from './facade.ts' - -/** First-use navigation and the resident destination input. */ -interface FirstDraftDeps { - open(beforeOpen: (id: SessionId) => void, signal: AbortSignal): Promise - shell(id: SessionId): SessionInputShell - /** Whether the borrowed input still belongs to the retained Session generation. */ - isCurrent(id: SessionId, shell: SessionInputShell): boolean -} - -/** Owns a root-lifetime text editor without allocating a Host Session. */ -export class FirstDraft { - /** Preparation progress and the recoverable directory failure. */ - readonly state = createSnapshotStore({ busy: false, failed: false }) - /** Local editor owns failed-submit restoration before transfer to a Host Session. */ - readonly shell: SessionInputShell - private pending: { text: string; transferred: boolean } | undefined - - /** @param ctx - Client plugin lifetime. @param deps - Workspace navigation and Session input access. */ - constructor(private readonly ctx: Context, private readonly deps: FirstDraftDeps) { - this.shell = new SessionInputShell({ - actx: ctx, - defaultSink: (text, _attachments, mode, signal) => this.send(text, mode, signal), - commandAttachments: { - serialize: () => Promise.resolve([]), - release: () => {}, - unsupportedNotice: () => '', - }, - }) - ctx.effect(() => () => { this.shell.dispose() }, 'conversation.input: first-use draft') - } - - /** Dismiss the preparation failure while retaining the draft. */ - dismiss(): void { - this.state.set({ ...this.state.getSnapshot(), failed: false }) - } - - /** - * Move the unsent text to a selected Session. - * @param id - retained destination Session receiving the unsent text. - */ - transfer(id: SessionId): void { - const text = this.pending?.text ?? this.shell.snapshot.draft - if (text !== '') this.deps.shell(id).setDraft(text) - if (this.pending !== undefined) this.pending.transferred = true - this.shell.setDraft('') - this.dismiss() - } - - private async send(text: string, mode: InputSubmitMode, signal: AbortSignal): Promise { - if (this.pending !== undefined) return { kind: 'error' } - const pending = { text, transferred: false } - this.pending = pending - this.state.set({ busy: true, failed: false }) - let target: SessionInputShell | undefined - try { - const id = await this.deps.open((nextId) => { this.transfer(nextId) }, signal) - if (id === undefined) return { kind: pending.transferred ? 'success' : 'error' } - target = this.deps.shell(id) - await this.ctx.serial('conversation/prepare-first-send', id) - signal.throwIfAborted() - if (!this.deps.isCurrent(id, target)) return { kind: 'success' } - target.submit(mode) - return { kind: 'success' } - } catch (error) { - if (!signal.aborted) { - if (target !== undefined) target.notify('error', error instanceof Error ? error.message : String(error)) - else if (!pending.transferred) this.state.set({ busy: true, failed: true }) - } - return { kind: pending.transferred ? 'success' : 'error' } - } finally { - this.pending = undefined - this.state.set({ ...this.state.getSnapshot(), busy: false }) - } - } -} diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index ecf2141f1d..464ff55e17 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -9,10 +9,6 @@ const PLAN_NEXT_ACTION_EN = 'describe your task to generate plan' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'defaultWorkspace.failed': '无法创建默认工作区', - 'defaultWorkspace.title': '默认工作区', - 'defaultWorkspace.retry': '请选择一个文件夹后重试', - 'defaultWorkspace.choose': '选择文件夹', 'hint.plan': PLAN_NEXT_ACTION_ZH, 'hint.goal': '输入目标,智能体将持续执行', 'hint.goal.active': '当前目标进行中。可输入 edit 修改 / pause 暂停 / resume 继续 / clear 清除', @@ -22,7 +18,6 @@ export const zh = { 'placeholder.parentOffline': '父会话已离线,无法继续发送;仍可停止当前运行', 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', - 'placeholder.preparing': '正在准备工作区…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', 'input.commands': '添加文件或调用指令', 'input.file': '文件', @@ -365,10 +360,6 @@ export type ConversationKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'defaultWorkspace.failed': 'Unable to create default workspace', - 'defaultWorkspace.title': 'Default workspace', - 'defaultWorkspace.retry': 'Please choose a folder and try again', - 'defaultWorkspace.choose': 'Choose folder', 'hint.plan': PLAN_NEXT_ACTION_EN, 'hint.goal': 'describe the objective for a long-running task', 'hint.goal.active': 'goal active — edit / pause / resume / clear', @@ -378,7 +369,6 @@ export const en = { 'placeholder.parentOffline': 'Parent session offline; sending is unavailable but you can still stop the run', 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', - 'placeholder.preparing': 'Preparing workspace…', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', 'input.commands': 'Add files or run commands', 'input.file': 'File', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 82ea0e533d..adace1c113 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 { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { ConversationContentProps, ConversationViewsProps, InputZone } from '../contract/slots.ts' import { HeroShell, WorkspaceChip, workspaceLabel } from './EmptyHero.tsx' @@ -23,7 +22,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, dismissDefaultFailure, useFirstDraft, t, useFactorySlot, + selectWorkspace, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -34,8 +33,6 @@ export function ConversationContent(props: ConversationContentProps) { const inputState = useInput(s => s) const cwd = useSessions(s => sessionId === undefined ? undefined : s.byId[sessionId]?.cwd) const workspaces = useWorkspaces(s => s) - const sessionsReady = useSessions(s => s.phase === 'ready') - const firstDraft = useFirstDraft(s => s) // A plugin this package cannot import (ui-model-selection) says this session cannot // send; its reason is already localized by whoever raised it. const composerBlock = useComposerBlock(block => block) @@ -130,22 +127,24 @@ export function ConversationContent(props: ConversationContentProps) {
) - // First-use sending waits for both baselines. A blank Session whose - // Workspace disappeared still requires explicit directory selection. - const needsWorkspace = sessionId !== undefined && hero && chipTitle === undefined - const inert = firstDraft.busy || (sessionId === undefined - ? workspaces.phase !== 'ready' || !sessionsReady - : needsWorkspace) - // Owner availability takes precedence over a Session-specific model block. + // The placeholder chip ("Choose workspace") and the Workspace-trigger input travel + // together: no workspace picked yet (cold start, no session at all), or a + // blank session whose workspace vanished (deleted from the sidebar). The + // bar is ONE session-maybe slot rendered unconditionally — inert is a prop, + // not a different tree, so the textarea DOM survives the transition. + const inert = sessionId === undefined || (hero && chipTitle === undefined) + // A raised block is the same inert posture with the blocker's own reason: + // one disabled textarea, never a second tree. The no-workspace state wins + // when both hold — picking a workspace is the earlier prerequisite. const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', ...(inert ? { disabled: true, - placeholder: t(firstDraft.busy ? 'placeholder.preparing' : 'placeholder.workspace'), + placeholder: t('placeholder.workspace'), workspacePickerOpen: pickerOpen, - ...(needsWorkspace ? { onRequestWorkspace: () => { setPickerOpen(true) } } : {}), + onRequestWorkspace: () => { setPickerOpen(true) }, } : blocked // `blocked`, not `disabled`: the bar refuses input either way, but a @@ -192,23 +191,6 @@ export function ConversationContent(props: ConversationContentProps) { {composerSeat} - - - - - )} - > - {t('defaultWorkspace.retry')} - ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx index f66ee7a96a..c57fe69936 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx @@ -1,5 +1,6 @@ -// Resident conversation shell keeps the composer mounted across local-draft, -// blank-Session, and active-conversation views. +// Resident conversation skeleton. Hero chrome, composer positioning, the +// chain, AND the composer bar (session-maybe slot) stay mounted across +// no-session/session transitions — the bar renders inert via owner props. import type { ConversationSlotProps } from '../contract/slots.ts' import { ConversationMainPanel } from './ConversationMainPanel.tsx' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 5852e4b5c4..6a4ea12740 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -1,12 +1,16 @@ /** The default composer body: the 'conversation.composer.bar' slot entry. - * The injected input state and keyboard address the current Session or the - * first-use local draft. Standard Session props supply attachment actions; - * owner props control layout and availability. + * Machine state arrives through the standard provide channel + * (useInput + inputActions); the keyboard/DOM command face and stop arrive + * through this entry's own inject, whose hooks compartment binds + * useNotices/useLexicon; layout-phase inputs (variant and placeholder) ride + * the owner props. Session facts + * (running/removed/promptError) are self-selected via useSession. * * The text surface is the shell-owned Lexical editor bound here through * ComposerContentEditable; chips render as decorator portals, and the * keymap registers submit/menu/paste gestures on the editor command layer. - * The contenteditable remains mounted when the first Session arrives. + * The no-session state renders the SAME div inert as the Workspace-picker + * trigger instead of a parallel tree. */ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -38,7 +42,7 @@ import css from './InputBar.module.css' export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ - useSession, useComposerInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, + useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, retryFileUpload, toggleCommandMenu, stop, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, @@ -46,7 +50,7 @@ export const InputBar = memo(function InputBar({ workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { - const input = useComposerInput(s => s) + const input = useInput(s => s) const notice = useNotices(s => s) const busyEnter = useBusyEnter(s => s) void useLexicon // hook seat stays bound by the inject compartment; text-ref decoration rides the shell's editor transforms @@ -60,11 +64,14 @@ export const InputBar = memo(function InputBar({ const planActive = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) // Absent (undefined: no frame yet) and cleared (null) both mean no goal. const hasGoal = useProjection('goal', goal => goal != null) - const draft = input.draft - const editor = keyboard.editor + // Session-maybe: the machine faces are absent together while no session is + // current; the bar renders the same DOM inert instead of a parallel tree. + const live = input !== undefined && keyboard !== undefined && inputActions !== undefined + const draft = input?.draft ?? '' + const editor = keyboard?.editor ?? null const attachments = useMemo( - () => resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), - [resolveDraftAttachments, input.attachmentIds], + () => input === undefined || resolveDraftAttachments === undefined ? [] : resolveDraftAttachments(input.attachmentIds), + [resolveDraftAttachments, input?.attachmentIds], ) const empty = draft.trim() === '' && attachments.length === 0 const uploads = useFileUploads(snapshot => snapshot) @@ -86,7 +93,8 @@ export const InputBar = memo(function InputBar({ // The deployment's image-intake limits (absent while no attachment service // is composed — the pre-check below then defers entirely to the host). const imageLimits = useProjection('imageLimits') - // The toast announces promptError, the draft stays in the machine, + // Prompt failures are ordinary failures (no create/attach transaction exists + // anymore): the toast announces promptError, the draft stays in the machine, // and the user resubmits. A remount over a session whose machine still holds // an unresolved promptError deliberately re-announces it once — the failure // is still pending, and a transient banner is its only surface. Attachment @@ -114,30 +122,35 @@ export const InputBar = memo(function InputBar({ // but its independent Stop below stays available while it runs. const continuable = subagent?.address.mode === 'continuable' const parentOffline = continuable && subagent.parentAvailable !== true - // Preparation, removed Sessions, and unavailable parents lock editing. - // Adjudicating and submitting keep the draft visible and read-only. - const disabled = removed || inert || blocked !== undefined || parentOffline + // Running input stays free; locked = session removed, the + // inert no-workspace state, the machine faces absent (no session), or a + // parent-offline continuable child. An owner block also disables input; + // adjudicating and submitting render read-only so the draft stays visible. + const disabled = removed || inert || !live || blocked !== undefined || parentOffline const locked = disabled // The model seat is the ONE control a block leaves live: every block this // contract has is cleared by choosing a model, so locking it too would leave // the composer asking for the only thing it prevents. The other reasons to // be disabled do lock it — there is no session to choose a model for. - const modelSeatLocked = removed || inert - const machineBusy = input.phase === 'adjudicating' || input.phase === 'submitting' - // A blank Session whose Workspace was deleted offers directory selection - // through the same resident input node. + const modelSeatLocked = removed || inert || !live + const machineBusy = input?.phase === 'adjudicating' || input?.phase === 'submitting' + // The no-workspace surface remains the resident DOM node but acts as the + // existing picker trigger. Message controls stay locked until a Session + // exists; the trigger itself is read-only rather than disabled so pointer + // and keyboard users can reach the recovery action. const workspaceTrigger = inert && !removed && onRequestWorkspace !== undefined const editorDisabled = removed || (locked && !workspaceTrigger) - const editable = !locked && !machineBusy + const editable = live && !locked && !machineBusy const steeringAvailable = subagent === null || subagent.address.mode === 'continuable' const canSteerQueue = !locked && !machineBusy && !commandMenuOpen && empty && running && steeringAvailable && input.queue.length > 0 useEffect(() => { - if (inputActions !== undefined && attachments.length !== input.attachmentIds.length) { + if (input === undefined || inputActions === undefined) return + if (attachments.length !== input.attachmentIds.length) { inputActions.pruneAttachments(attachments.map(attachment => attachment.id)) } - }, [attachments, input.attachmentIds, inputActions]) + }, [attachments, input?.attachmentIds, inputActions]) // Scroll the draft scrollport the minimum that brings the selection focus // into view — the browser's own behavior for typing, performed for the @@ -154,7 +167,7 @@ export const InputBar = memo(function InputBar({ // is ours to perform — switching to a longer draft otherwise leaves the // caret (restored at the draft's end) off screen. useEffect(() => { - if (locked) return + if (locked || editor === null) return focusDraftEditor(editor, revealSelection) }, [locked, sessionId, editor]) @@ -231,10 +244,12 @@ export const InputBar = memo(function InputBar({ } useEffect(() => { + if (keyboard === undefined) return return installDraftFilePicker(keyboard, gate, fileInputRef) }, [keyboard]) useEffect(() => { + if (editor === null || keyboard === undefined) return return installDraftKeymap(editor, keyboard, gate) }, [editor, keyboard]) @@ -247,16 +262,17 @@ export const InputBar = memo(function InputBar({ } const onToggleCommandMenu = (): void => { + if (keyboard === undefined) return // The menu is a combobox over the editor, so the keyboard has to be there // before the launcher opens it: activating the button from the keyboard // leaves focus on the button, and restoring it afterwards would re-track an // empty draft and close the menu again. - focusDraftEditor(editor, revealSelection) + if (editor !== null) focusDraftEditor(editor, revealSelection) toggleCommandMenu?.(keyboard.caretSpan()) } - // When a blank Session loses its Workspace, the resident editable div acts as the - // picker trigger for keyboard users. + // The no-session Workspace trigger: the resident editable div acts as the + // picker trigger for keyboard users (no editor is bound in this state). const onWorkspaceKeyDown = (e: KeyboardEvent): void => { if (!workspaceTrigger) return if (e.key === 'Enter' || e.key === ' ') { @@ -279,7 +295,7 @@ export const InputBar = memo(function InputBar({ const primaryDisabled = primaryStops ? stop === undefined : empty || disabled || machineBusy || uploadsPending const interruptible = running && continuable const primarySubmitMode = resolveSubmitMode(busyEnter, running, 'enter', steeringAvailable) - const plainMessageDraft = !empty && input.phase === 'plain' && !draft.trimStart().startsWith('/') + const plainMessageDraft = !empty && input?.phase === 'plain' && !draft.trimStart().startsWith('/') const primaryLabel = primaryStops ? t('input.stop') : running && steeringAvailable && !disabled && !uploadsPending && plainMessageDraft @@ -290,6 +306,7 @@ export const InputBar = memo(function InputBar({ stop?.() return } + if (keyboard === undefined) return // absent machine: the button is disabled /* v8 ignore next -- defensive: the primary button is disabled for empty, disabled, and pending-upload states. */ if (!empty && !disabled && !machineBusy && !uploadsPending) keyboard.submit(primarySubmitMode) } @@ -297,7 +314,7 @@ export const InputBar = memo(function InputBar({ // Claim ghost hint: rendered by CSS as generated content after the last // paragraph while the claim's args are blank (a hint implies a single-line // token draft). The translated per-command hint wins over the claim's own. - const claimActive = (input.phase === 'claimed' || input.phase === 'submitting') + const claimActive = (input?.phase === 'claimed' || input?.phase === 'submitting') && input.claim !== undefined && draft.startsWith(input.claim.token) const rawHint = claimActive && input.claim.hint !== undefined && draft.slice(input.claim.token.length).trim() === '' @@ -305,7 +322,7 @@ export const InputBar = memo(function InputBar({ : null const hint = ((): string | null => { if (rawHint === null) return null - const commandName = input.claim?.name ?? '' + const commandName = input?.claim?.name ?? '' const hintKey = `hint.${commandName === 'goal' && hasGoal ? 'goal.active' : commandName}` // Dynamic lookup by claimed command name: unknown commands miss the // dictionary and keep the machine's own hint, so the call is wide. @@ -379,7 +396,7 @@ export const InputBar = memo(function InputBar({ scrollRef={scrollRef} editable={editable} editorDisabled={editorDisabled} - phase={input.phase} + phase={input?.phase ?? 'inert'} placeholderText={placeholderText} ariaLabel={workspaceTrigger ? t('hero.chooseWorkspace') : placeholderText} workspaceTrigger={workspaceTrigger} @@ -416,12 +433,12 @@ export const InputBar = memo(function InputBar({ {sessionId === undefined ? null : renderSlot('conversation.input.permission', { locked })} {sessionId === undefined ? null : renderSlot('conversation.input.plan', { locked })} - {sessionId === undefined + {input === undefined || sessionId === undefined ? null : renderSlot('conversation.input.left', {})}
- {sessionId === undefined + {input === undefined || sessionId === undefined ? null : renderSlot('conversation.input.right', {})} {sessionId === undefined ? null : renderSlot('conversation.input.model', { locked: modelSeatLocked })} @@ -465,7 +482,7 @@ export const InputBar = memo(function InputBar({
- {variant === 'composer' && sessionId !== undefined + {variant === 'composer' && input !== undefined && sessionId !== undefined ? renderSlot('conversation.composer.dock', {}) : null} 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 0339ef042d..e90a11a163 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -2,7 +2,6 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { CommandContribution, CommandUiContract } from '@deepseek-ai/dsh-client-ui-commands/client' -import type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { ISession, SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' @@ -74,14 +73,12 @@ async function bench() { opened(id) } const openSession = vi.fn((id: SessionId) => { replaceMain(id) }) - const openDefaultWorkspace = vi.fn(async () => undefined) runtime.ctx.provide('uiWorkspace', { openWorkspace: async (_workspaceId: WorkspaceId, beforeOpen: (id: SessionId) => void) => { const id = await connectWorkspace() replaceMain(id, beforeOpen) }, openSession, - openDefaultWorkspace, } as never) const sessionFake = sessionFakeFor() await runtime.sessions.add({ @@ -139,113 +136,10 @@ async function bench() { return { runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, - locale, openDefaultWorkspace, replaceMain, } } describe('Conversation inject API', () => { - it.each([false, true])('keeps the saved first draft after its Session retires (reopened during preparation: %s)', async (reopenEarly) => { - const b = await bench() - onTestFinished(() => b.runtime.dispose()) - const settings = Promise.withResolvers() - const started = Promise.withResolvers() - b.runtime.ctx.on('conversation/prepare-first-send', () => { - started.resolve(undefined) - return settings.promise - }) - b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { - b.replaceMain(ROOT, beforeOpen) - return ROOT - }) - const body = b.conversationApi(ROOT) - const unmirror = body.injected.bindDraftMirror(body.instance.actions.setDraft) - const composer = b.composerApi(undefined) - let reopened: SessionReference | undefined - try { - composer.keyboard.paste('keep this first draft') - composer.keyboard.submit('queue') - await started.promise - expect(body.instance.store.getSnapshot().draft).toBe('keep this first draft') - const other = 'other-first-send' as SessionId - await b.runtime.sessions.add({ id: other, session: sessionFakeFor() }) - unmirror() - b.rootReference.release() - b.replaceMain(other) - await vi.waitFor(() => { expect(b.runtime.sessions.binding(ROOT)).toBeUndefined() }) - if (reopenEarly) reopened = b.runtime.sessions.retain(ROOT) - settings.resolve(undefined) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - await b.runtime.flush() - expect(b.sessionFake.prompt).not.toHaveBeenCalled() - reopened ??= b.runtime.sessions.retain(ROOT) - b.references.set(ROOT, reopened) - expect(b.conversationApi(ROOT).instance.store.getSnapshot().draft).toBe('keep this first draft') - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') - } finally { - settings.resolve(undefined) - reopened?.release() - unmirror() - } - }) - - it('submits the first draft through its retained destination input', async () => { - const b = await bench() - onTestFinished(() => b.runtime.dispose()) - b.openDefaultWorkspace.mockImplementation(async (_request, beforeOpen) => { - b.replaceMain(ROOT, beforeOpen) - return ROOT - }) - const composer = b.composerApi(undefined) - composer.keyboard.paste('first message') - composer.keyboard.submit('queue') - await vi.waitFor(() => { expect(b.sessionFake.prompt).toHaveBeenCalledOnce() }) - expect(b.sessionFake.prompt.mock.calls[0]?.[0]).toEqual([{ type: 'text', text: 'first message' }]) - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('') - }) - - it.each([ - ['zh', '默认工作区', '默认工作区'], - ['en', 'Default workspace', 'Default workspace'], - ['ja', 'default-workspace', 'Default workspace'], - ])('resolves first-use names in the Client using the send-time locale %s', async (language, directoryName, title) => { - const b = await bench() - if (language === 'ja') b.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' }) - const composer = b.composerApi(undefined) - composer.keyboard.paste('first message') - b.locale.setLocale(language) - composer.keyboard.submit('steer') - await vi.waitFor(() => { - expect(b.openDefaultWorkspace).toHaveBeenCalledWith({ directoryName, title }, expect.any(Function), expect.any(AbortSignal)) - expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) - }) - }) - - it('keeps in-flight names fixed and resolves the new locale when retrying a failed first send', async () => { - const b = await bench() - const pending = Promise.withResolvers() - b.openDefaultWorkspace.mockReturnValueOnce(pending.promise) - const composer = b.composerApi(undefined) - b.locale.setLocale('en') - composer.keyboard.paste('keep this draft') - composer.keyboard.submit('steer') - try { - await vi.waitFor(() => { expect(b.openDefaultWorkspace).toHaveBeenCalledOnce() }) - b.locale.setLocale('zh') - expect(b.openDefaultWorkspace.mock.calls[0]?.[0]).toEqual({ directoryName: 'Default workspace', title: 'Default workspace' }) - pending.reject(new Error('directory unavailable')) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - expect(composer.hooks.composerInput.getSnapshot().draft).toBe('keep this draft') - composer.keyboard.submit('steer') - await vi.waitFor(() => { - expect(b.openDefaultWorkspace).toHaveBeenLastCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(Function), expect.any(AbortSignal)) - expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) - }) - } finally { - pending.resolve(undefined) - await vi.waitFor(() => { expect(b.residentApi(undefined).hooks.firstDraft.getSnapshot().busy).toBe(false) }) - } - }) - it('owns the File action, reads its mounted composer availability, and unregisters on disposal', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) @@ -265,7 +159,7 @@ describe('Conversation inject API', () => { expect(file.available({ sessionId: 'missing' as SessionId })).toBe(false) if (file.ui.kind !== 'action') throw new Error('File must be an action') file.ui.run({ sessionId: 'missing' as SessionId }) - const keyboard = b.composerApi(ROOT).keyboard + const keyboard = b.composerApi(ROOT).keyboard! const open = vi.fn() let available = true const unbind = keyboard.bindFilePicker({ open, available: () => available }) @@ -514,8 +408,7 @@ describe('Conversation inject API', () => { expect(() => { injectBar('ghost' as SessionId).stop!() }).toThrow(/resolved no binding/) const absent = injectBar(undefined) - expect(absent.keyboard).toBeDefined() - expect(absent.hooks.composerInput.getSnapshot().draft).toBe('') + expect(absent.keyboard).toBeUndefined() expect(absent.toggleCommandMenu).toBeUndefined() expect(absent.stop).toBeUndefined() expect(absent.hooks.notices.getSnapshot()).toBeNull() diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index 51513cb28e..84e5ba28a1 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -100,10 +100,8 @@ async function bench(opts?: { blank?: boolean }) { } describe('resident composer', () => { - it('accepts a local draft before any Session exists and keeps the Workspace chip available', async () => { + it('renders the locked view state while no session exists at all', async () => { const runtime = await SlotTestRuntime.create() - runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'pending' }) - await runtime.workspaces.update((draft) => { draft.phase = 'pending' }) provideWorkspaceNavigation(runtime) runtime.ctx.provide('settingsScope', { developerTools: { enabled: createSnapshotStore(true) }, bind: () => stubSettingsScope().scope } as never) const locale = new LocaleRuntime(runtime.ctx) @@ -115,21 +113,15 @@ describe('resident composer', () => { const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') expect(textarea).not.toBeNull() - expect(textarea!.getAttribute('contenteditable')).toBe('false') - await runtime.workspaces.update((draft) => { draft.phase = 'ready' }) - expect(textarea!.getAttribute('contenteditable')).toBe('false') - await act(async () => { - runtime.sessions.list.set({ ...runtime.sessions.list.getSnapshot(), phase: 'ready' }) - }) expect(textarea!.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea!.getAttribute('contenteditable')).toBe('true') - expect(textarea!.getAttribute('aria-haspopup')).toBeNull() + expect(textarea!.getAttribute('contenteditable')).not.toBe('true') + expect(textarea!.getAttribute('aria-haspopup')).toBe('menu') expect(view.getByTestId('workspace-probe').textContent).toBe('false:0') - fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.click(textarea!) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') - expect(textarea!.getAttribute('aria-expanded')).toBeNull() - fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + expect(textarea!.getAttribute('aria-expanded')).toBe('true') fireEvent.click(view.getByRole('button', { name: '选择工作区' })) + fireEvent.keyDown(textarea!, { key: 'Enter' }) expect(view.getByTestId('workspace-probe').textContent).toBe('true:0') expect(view.getByRole('button', { name: '选择工作区' })).toBeTruthy() await runtime.dispose() @@ -157,7 +149,7 @@ describe('resident composer', () => { const workspaceChip = view.getByRole('button', { name: '选择工作区' }) const workspaceProbe = view.getByTestId('workspace-probe') expect(textarea.getAttribute('aria-disabled')).not.toBe('true') - expect(textarea.getAttribute('contenteditable')).toBe('true') + expect(textarea.getAttribute('contenteditable')).not.toBe('true') fireEvent.click(workspaceChip) fireEvent.click(workspaceProbe) diff --git a/packages/client/ui-conversation/tests/first-draft.client.spec.ts b/packages/client/ui-conversation/tests/first-draft.client.spec.ts deleted file mode 100644 index b23055dcf1..0000000000 --- a/packages/client/ui-conversation/tests/first-draft.client.spec.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { Context } from '@deepseek-ai/cordis' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { SessionId } from '@deepseek-ai/dsh-session/types' -import { FirstDraft } from '../src/client/input/first-draft.ts' -import { SessionInputShell } from '../src/client/input/facade.ts' -import type { SubmitOutcome } from '../src/client/contract/input.ts' - -const contexts: Context[] = [] -afterEach(async () => { - for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() -}) - -function harness() { - const ctx = new Context() - contexts.push(ctx) - const opened = Promise.withResolvers() - ctx.effect(() => () => { opened.resolve(undefined) }) - const submitted = vi.fn(async (): Promise => ({ kind: 'success' })) - const target = new SessionInputShell({ - actx: ctx, - defaultSink: submitted, - commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: () => '' }, - }) - ctx.effect(() => () => { target.dispose() }) - let beforeOpen: ((id: SessionId) => void) | undefined - const open = vi.fn((prepare: (id: SessionId) => void) => { - beforeOpen = prepare - return opened.promise - }) - const first = new FirstDraft(ctx, { open, shell: () => target, isCurrent: () => true }) - return { - ctx, first, target, submitted, open, opened, - complete: () => { - const id = SessionId('default') - beforeOpen!(id) - opened.resolve(id) - }, - } -} - -describe('first message draft', () => { - it('retains a local draft without opening a Session until send', async () => { - const h = harness() - h.first.shell.setDraft('first message') - expect(h.open).not.toHaveBeenCalled() - h.first.shell.submit('steer') - expect(h.open).toHaveBeenCalledTimes(1) - expect(h.first.state.getSnapshot().busy).toBe(true) - h.first.shell.submit('steer') - expect(h.open).toHaveBeenCalledTimes(1) - h.complete() - await vi.waitFor(() => { expect(h.submitted).toHaveBeenCalledTimes(1) }) - expect(h.submitted.mock.calls[0]).toEqual(['first message', [], 'steer', expect.any(AbortSignal)]) - expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: false }) - }) - - it.each([false, true])('waits for first-use settings and keeps the Session draft on refusal (refused: %s)', async (refused) => { - const h = harness() - const settings = Promise.withResolvers() - const started = Promise.withResolvers() - h.ctx.on('conversation/prepare-first-send', (id) => { - started.resolve(id) - return settings.promise - }) - try { - h.first.shell.setDraft('use my selected mode') - h.first.shell.submit() - h.complete() - expect(await started.promise).toBe(SessionId('default')) - expect(h.submitted).not.toHaveBeenCalled() - if (refused) settings.reject(new Error('preset refused')) - else settings.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - expect(h.first.state.getSnapshot().failed).toBe(false) - if (refused) { - expect(h.submitted).not.toHaveBeenCalled() - expect(h.target.snapshot.draft).toBe('use my selected mode') - expect(h.target.notices.getSnapshot()?.text).toBe('preset refused') - } else { - expect(h.submitted).toHaveBeenCalledOnce() - } - } finally { - settings.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - } - }) - - it('restores input on preparation failure and dismisses the modal without losing it', async () => { - const h = harness() - h.first.shell.setDraft('preserve me') - h.first.shell.submit() - h.opened.reject(new Error('permission denied')) - await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('preserve me') }) - expect(h.first.state.getSnapshot()).toEqual({ busy: false, failed: true }) - expect(h.submitted).not.toHaveBeenCalled() - h.first.dismiss() - expect(h.first.state.getSnapshot().failed).toBe(false) - expect(h.first.shell.snapshot.draft).toBe('preserve me') - }) - - it('hands a draft to a manual selection without sending it', async () => { - const h = harness() - h.first.shell.setDraft('manual folder') - h.first.transfer(SessionId('manual')) - expect(h.target.snapshot.draft).toBe('manual folder') - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.submitted).not.toHaveBeenCalled() - }) - - it('lets manual navigation take the pending draft and cancels automatic submission', async () => { - const h = harness() - h.first.shell.setDraft('pending text') - h.first.shell.submit() - h.first.transfer(SessionId('manual')) - h.opened.resolve(undefined) - await vi.waitFor(() => { expect(h.first.state.getSnapshot().busy).toBe(false) }) - expect(h.target.snapshot.draft).toBe('pending text') - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.submitted).not.toHaveBeenCalled() - }) - - it('restores a superseded draft without a directory error', async () => { - const h = harness() - h.first.shell.setDraft('later') - h.first.shell.submit() - h.opened.resolve(undefined) - await vi.waitFor(() => { expect(h.first.shell.snapshot.draft).toBe('later') }) - expect(h.first.state.getSnapshot().failed).toBe(false) - }) - - it('leaves ordinary send failures in the selected Session input', async () => { - const h = harness() - h.submitted.mockResolvedValue({ kind: 'error' }) - h.first.shell.setDraft('retry the prompt') - h.first.shell.submit() - h.complete() - await vi.waitFor(() => { expect(h.target.snapshot.draft).toBe('retry the prompt') }) - expect(h.first.shell.snapshot.draft).toBe('') - expect(h.first.state.getSnapshot().failed).toBe(false) - }) -}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index a4805db1ec..9e0366952c 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -185,7 +185,6 @@ function bench(over?: BenchOptions) { ? over?.plan : key === 'goal' ? over?.goal : key === 'imageLimits' ? over?.imageLimits : undefined)), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index c8641afcb4..15d87a0ca7 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -67,7 +67,6 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 0c098d95fb..347b4d05c1 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -161,7 +161,6 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo })), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), - useComposerInput: bindSnapshotSelector(shell.state), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 619e3fddff..17aadfb056 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -137,8 +137,6 @@ function mount( nestedSubagent?: boolean /** A composer block another plugin raised for this session. */ composerBlock?: { reason: string } - /** First-use preparation remains active after selecting its Session. */ - preparingFirstDraft?: boolean /** Mutable view ledger used by registration-order regressions. */ viewTabs?: ViewTab[] } = {}, @@ -282,7 +280,6 @@ function mount( useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} - useComposerInput={useInput} keyboard={wiring} addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} @@ -339,8 +336,6 @@ function mount( useWorkspaces: bindSnapshotSelector(workspaces), useProjection: (() => undefined), useComposerBlock: select => select(options.composerBlock), - useFirstDraft: select => select({ busy: options.preparingFirstDraft === true, failed: false }), - dismissDefaultFailure: () => {}, useInput, inputActions, renderSlot, @@ -410,18 +405,6 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByTestId('view-conversation.session.header.corner')).toBeNull() }) - it('locks the selected Session draft until automatic first-use preparation settles', () => { - const b = mount(sessionSnapshotOf({ blank: true }), undefined, undefined, { - summaryBlank: true, preparingFirstDraft: true, - }) - const box = b.view.getByRole('textbox') - expect(box.getAttribute('aria-disabled')).toBe('true') - expect(box.getAttribute('aria-label')).toBe('正在准备工作区…') - expect(box.getAttribute('aria-haspopup')).toBeNull() - fireEvent.keyDown(box, { key: 'Enter' }) - expect(b.sink).not.toHaveBeenCalled() - }) - it('does not redispatch composer child slots for an unrelated Session publication', () => { const b = mount(sessionSnapshotOf()) const childKeys = new Set([ diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index b98485e434..4af8adc8d4 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 03dc8a9ff45fbc1fc1ab8585db15c19437807f5e -README.zh.md: ac8000f78d3a9394ec2c83790aa3e0349cac2ab0 +README.md: 768c66503af70d0b587b25c09aa8412b0a647439 +README.zh.md: 25df6f8e6a2ec0a001d784c7bde18e454e9d706f diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 03dc8a9ff4..768c66503a 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,9 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. -`openDefaultWorkspace(request, beforeOpen, signal)` initializes the Host default Workspace from the requested directory name and title before connecting its Session. It captures navigation cancellation before directory preparation; superseded work cannot transfer the draft or select its Session. A successfully registered Workspace remains available when Session creation or later submission fails. [Conversation](../ui-conversation/README.md) owns the first-use draft and failure dialog. +Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Preparation failure offers Cancel or Choose folder through the existing picker, and is not retried until the next startup. A successfully registered Workspace remains available when Session creation or later submission fails. + +The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes. ## Understand the implementation diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index ac8000f78d..25df6f8e6a 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,9 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 -`openDefaultWorkspace(request, beforeOpen, signal)` 在连接 Session 前,按请求中的目录名和标题初始化 Host 默认工作区。它在目录准备之前捕获导航取消信号;被取代的操作不能转移草稿或选中 Session。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。[Conversation](../ui-conversation/README.zh.md) 负责首次使用草稿和失败弹窗。 +Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。准备失败时通过现有选择器提供取消或选择文件夹操作,直到下次启动才重试。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 + +Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。 ## 理解实现 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index b74e3689dc..42e177afce 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -231,21 +231,45 @@ export function WorkspacePicker({ onClose, createWorkspace, useDirectoryFlow, + useDefaultFailure, + dismissDefaultFailure, renderSlot, t, }: WorkspacePickerProps) { + const failed = useDefaultFailure(value => value) + const flowAvailable = useDirectoryFlow(value => value) + const [recovering, setRecovering] = useState(false) return ( - renderSlot('conversation.hero.workspace.directoryFlow', owner)} - selectedId={selectedId} - onPick={onPick} - onClose={onClose} - /> + <> + renderSlot('conversation.hero.workspace.directoryFlow', owner)} + selectedId={selectedId} + onPick={onPick} + onClose={() => { setRecovering(false); onClose() }} + /> + + + + + )} + > + {t('defaultWorkspace.retry')} + + ) } diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 6a54d79146..b878e24986 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -364,6 +364,12 @@ export type WorkspaceBrowserProps = * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = DirectoryPickingInjected & { + /** Dismiss the startup failure before choosing a directory manually. */ + dismissDefaultFailure: () => void + hooks: { + /** Whether first-use startup failed to prepare a Workspace and Session. */ + defaultFailure: HostObservable + } /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } @@ -377,5 +383,5 @@ export type WorkspacePickerProps = PropsRuntime<'conversation.hero.workspace'> & PropsRenderSlots<'conversation.hero.workspace.directoryFlow'> & Omit - & DirectoryPickingHooks + & PropsHooks & PropsLocale<'workspace'> diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 0614dea6a4..8d96c65d77 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -219,7 +219,8 @@ export function apply(ctx: Context): void { }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => workspaces.create(input), - hooks: { directoryFlow: pickerFlowSource }, + dismissDefaultFailure: () => { uiWorkspace.defaultFailure.set(false) }, + hooks: { directoryFlow: pickerFlowSource, defaultFailure: uiWorkspace.defaultFailure }, }) // Each registration declares its owned children in the same call; slot // injection follows both the owner and declaration HMR lifetimes. diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index e721af231f..d926ce987f 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -6,6 +6,10 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.title': '默认工作区', + 'defaultWorkspace.retry': '请选择一个文件夹后重试', + 'defaultWorkspace.choose': '选择文件夹', 'group.ungrouped': '未分组', 'session.new': '新会话', 'section.workspaces': '工作区', @@ -99,6 +103,10 @@ export type WorkspaceKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.title': 'Default workspace', + 'defaultWorkspace.retry': 'Please choose a folder and try again', + 'defaultWorkspace.choose': 'Choose folder', 'group.ungrouped': 'Ungrouped', 'session.new': 'New Session', 'section.workspaces': 'Workspaces', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 29c4c8d3f7..b21cf06f15 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -12,10 +12,12 @@ import type { import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { - IWorkspaces, WorkspaceId, WorkspaceInitializeDefaultRequest, WorkspaceSnapshot, WorkspaceView, + IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import { en, zh } from './locales.ts' import { pinOrderAccounts, pinOrderSource } from './pin-order.ts' import type { WorkspaceViewStoreActions } from './stores.ts' @@ -38,18 +40,6 @@ export interface UiWorkspace { * @returns completion; a superseded request may create a Session but does not open it. */ openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise - /** - * Prepare the first-use Workspace and select its blank Session. - * @param request - initial directory name and title. - * @param beforeOpen - synchronous draft transfer after retaining the Session. - * @param signal - caller cancellation. - * @returns selected Session, or undefined after navigation supersession. - */ - openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise /** * Fork a Session without changing the current selection. * @param sessionId - source Session. @@ -130,6 +120,8 @@ export class DirectoryBrowseError extends Error { /** Implements Workspace archive and directory UI operations. */ class UiWorkspaceService extends Service implements UiWorkspace { + /** Startup failure awaiting dismissal or explicit directory selection. */ + readonly defaultFailure = createSnapshotStore(false) private readonly connecting = new Map>() private readonly lifetime = new AbortController() private readonly selection = createSnapshotStore( @@ -213,25 +205,6 @@ class UiWorkspaceService extends Service implements UiWorkspace { this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) } - async openDefaultWorkspace( - request: WorkspaceInitializeDefaultRequest, - beforeOpen: (sessionId: SessionId) => void, - signal: AbortSignal, - ): Promise { - const navigation = AbortSignal.any([this.ctx.layout.beginNavigation(), this.lifetime.signal, signal]) - try { - const workspace = await this.workspaces.initializeDefault(request, navigation) - navigation.throwIfAborted() - const sessionId = await this.connectWorkspace(workspace.workspaceId) - navigation.throwIfAborted() - this.replaceMain(sessionId, navigation, 'reveal', beforeOpen) - return sessionId - } catch (error) { - if (navigation.aborted) return undefined - throw error - } - } - async forkSession(sessionId: SessionId): Promise { await this.sessions.fork({ sessionId, increaseTitle: true }) } @@ -353,11 +326,30 @@ class UiWorkspaceService extends Service implements UiWorkspace { } const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) + if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) { + sessionId = await this.initializeDefaultWorkspace(navigation) + } if (sessionId !== undefined && !navigation.aborted) { this.replaceMain(sessionId, navigation, 'preserve') } } + private async initializeDefaultWorkspace(signal: AbortSignal): Promise { + const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] + const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] + try { + const workspace = await this.workspaces.initializeDefault({ + directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', + title, + }, signal) + if (workspace === undefined || signal.aborted) return undefined + return await this.connectWorkspace(workspace.workspaceId) + } catch (_error: unknown) { + if (!signal.aborted) this.defaultFailure.set(true) + return undefined + } + } + /** @returns true when an archived current selection was cleared. */ private clearArchivedCurrent(): boolean { const current = this.mainReference?.sessionId diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index 9ff0181207..e72d523668 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -88,14 +89,19 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), occupancy = occupancySource(), + options: { defaultFailure?: boolean; open?: boolean } = {}, ) { + const failure = createSnapshotStore(options.defaultFailure ?? false) + const useDefaultFailure = bindSnapshotSelector(failure) + const dismissDefaultFailure = vi.fn(() => { failure.set(false) }) const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( { view.rerender(renderPicker(nextItems)) }, } } @@ -220,6 +226,7 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -238,6 +245,7 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -321,3 +329,26 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: '添加工作区…' })).toBeNull() }) }) + +describe('default Workspace startup recovery', () => { + it('dismisses the failure without opening the directory flow', () => { + const b = mount([], vi.fn(), occupancySource(), { defaultFailure: true, open: false }) + expect(screen.getByRole('dialog', { name: '无法创建默认工作区' })).toBeTruthy() + expect(b.probe.owner?.open).toBe(false) + fireEvent.click(screen.getByRole('button', { name: '取消' })) + expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() + expect(screen.queryByRole('dialog', { name: '无法创建默认工作区' })).toBeNull() + expect(b.probe.owner?.open).toBe(false) + }) + + it('opens the composed directory flow from the startup failure', async () => { + const create = vi.fn(async () => workspace('chosen')) + const b = mount([], create, occupancySource(), { defaultFailure: true, open: false }) + fireEvent.click(screen.getByRole('button', { name: '选择文件夹' })) + expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() + expect(b.probe.owner?.open).toBe(true) + await act(async () => { b.probe.owner!.onPicked('/chosen') }) + expect(create).toHaveBeenCalledExactlyOnceWith({ path: '/chosen' }) + expect(b.onPick).toHaveBeenCalledExactlyOnceWith(wid('chosen')) + }) +}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 422de2dc2d..4f9cd973b8 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -1,4 +1,6 @@ +import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { afterEach, describe, expect, it, vi } from 'vitest' import type { ISessions, SessionListState, SessionReference, SessionSummary, @@ -169,11 +171,7 @@ class FakeSessions implements ISessions { } class FakeWorkspaces implements IWorkspaces { - readonly initializeDefault = vi.fn(async () => { - const item = workspace('default') - this.list.set(workspaceState([item])) - return item - }) + readonly initializeDefault = vi.fn(async () => undefined) readonly list: MutableSource readonly archiveCalls: SessionId[] = [] readonly unarchiveCalls: SessionId[] = [] @@ -268,6 +266,8 @@ class FakeDirectoryPicker { } interface BenchOptions { + readonly language?: string + readonly configureWorkspaces?: (workspaces: FakeWorkspaces) => void readonly workspaces?: WorkspaceSnapshot readonly sessions?: SessionListState readonly configureSessions?: (sessions: FakeSessions) => void @@ -276,6 +276,10 @@ interface BenchOptions { function bench(options: BenchOptions = {}) { const ctx = new Context() contexts.push(ctx) + const locale = new LocaleRuntime(ctx) + if (options.language === 'fr') locale.addLanguage({ id: 'fr', label: 'Français', fallback: 'en' }) + locale.setLocale(options.language ?? 'en') + ctx.provide('locale', locale) const layout = new LayoutController({ selectPanel: vi.fn(), retainMainPanels: vi.fn(), setSidebar: vi.fn(), toggleSidebar: vi.fn(), setViewportWidth: vi.fn(), @@ -287,6 +291,7 @@ function bench(options: BenchOptions = {}) { const directoryPicker = new FakeDirectoryPicker() const workspaces = new FakeWorkspaces(options.workspaces ?? workspaceState([], [], 'pending')) const sessions = new FakeSessions(options.sessions ?? sessionState([], 'pending')) + options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() const uiWorkspace = new UiWorkspaceService( @@ -300,39 +305,95 @@ function bench(options: BenchOptions = {}) { } describe('UiWorkspaceService', () => { - it('prepares the default Workspace before creating and retaining its Session', async () => { - const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - const beforeOpen = vi.fn(() => { - expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-default'), { source: 'mainView' }) + it.each([ + ['zh', '默认工作区', '默认工作区'], + ['en', 'Default workspace', 'Default workspace'], + ['fr', 'default-workspace', 'Default workspace'], + ])('prepares and selects the default Workspace after both startup baselines (%s)', async (language, directoryName, title) => { + const b = bench({ language, configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementation(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + } }) + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + b.sessions.list.set(sessionState()) + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + b.workspaces.list.set(workspaceState()) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-default'), { source: 'mainView' }) }) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: '默认工作区', title: '默认工作区' }, beforeOpen, new AbortController().signal)) - .resolves.toBe(sid('created-default')) - expect(b.workspaces.initializeDefault).toHaveBeenCalledWith({ directoryName: '默认工作区', title: '默认工作区' }, expect.any(AbortSignal)) + expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(beforeOpen).toHaveBeenCalledWith(sid('created-default')) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) }) - it('does not create a Session when default preparation fails or is superseded', async () => { + it('leaves an ineligible empty installation without a Session or failure dialog', async () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - b.workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('denied') + await setImmediate() + b.workspaces.list.set(workspaceState()) + b.sessions.list.set(sessionState()) + await setImmediate() + expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + }) + + it('requires explicit selection when the startup Session list contains history', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState([summary('history')]) }) + await setImmediate() + expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() + expect(b.sessions.create).not.toHaveBeenCalled() + }) + + it('publishes a startup directory failure once without creating a Session', async () => { + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) + } }) + await vi.waitFor(() => { expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(true) }) + b.uiWorkspace.defaultFailure.set(false) + b.workspaces.list.set(workspaceState()) + await setImmediate() + expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + }) + + it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { const pending = Promise.withResolvers() - b.workspaces.initializeDefault.mockReturnValueOnce(pending.promise) - const beforeOpen = vi.fn() - const opening = b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, beforeOpen, new AbortController().signal) - b.uiWorkspace.openSession(sid('manual')) + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + } }) + if (kind === 'session') b.uiWorkspace.openSession(sid('manual')) + else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId) + else await b.ctx.fiber.dispose() + expect(b.workspaces.initializeDefault.mock.calls[0]![1]?.aborted).toBe(true) pending.resolve(workspace('default')) - await expect(opening).resolves.toBeUndefined() + await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() - expect(beforeOpen).not.toHaveBeenCalled() + expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) }) - it('retains the prepared Workspace if creating its Session fails', async () => { - const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) - b.sessions.create.mockRejectedValueOnce(new Error('session failed')) - await expect(b.uiWorkspace.openDefaultWorkspace({ directoryName: 'Default workspace', title: 'Default workspace' }, vi.fn(), new AbortController().signal)).rejects.toThrow('session failed') - expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + it('retains a prepared Workspace when its Session fails and suppresses a superseded failure', async () => { + for (const superseded of [false, true]) { + const created = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementationOnce(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) + await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) + if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) + created.reject(new Error('session failed')) + await setImmediate() + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(!superseded) + expect(b.sessions.retain).not.toHaveBeenCalled() + } }) it('retains an explicit main target before revealing its Conversation', () => { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index b89f2f3ada..37f5d7ec0e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3251,10 +3251,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the Workspace and whether this call created it.', }, { - signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', - description: 'Initialize or reuse the default Workspace before the first user message.', + signature: '@Remote(\'initializeDefault\') async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal: AbortSignal): Promise', + description: 'Initialize or reuse the default Workspace during first-use startup.', parameters: [{ name: 'request', description: 'initial directory name and title; never rename an existing default.' }, { name: 'signal', description: 'caller lifetime; cancels native directory lookup.' }], - returns: 'the durable Workspace without creating a Session or sending a message.', + returns: 'the durable Workspace, or undefined when first-use initialization is ineligible; creates no Session or message.', }, { signature: '@Remote(\'rename\') rename(request: WorkspaceRenameRequest): Promise', diff --git a/packages/test-support/client-runtime/src/workspaces.ts b/packages/test-support/client-runtime/src/workspaces.ts index 2c6b788fa3..63c1ec78d9 100644 --- a/packages/test-support/client-runtime/src/workspaces.ts +++ b/packages/test-support/client-runtime/src/workspaces.ts @@ -81,16 +81,15 @@ export class TestWorkspaces implements IWorkspaces { } /** - * Initialize the default Workspace through an explicitly installed test stub. + * Initialize the default Workspace through a test stub; defaults to an ineligible first use. * @param request - initial directory name and title. * @param signal - caller lifetime. - * @returns the stubbed Workspace. + * @returns the stubbed Workspace, or undefined when initialization is ineligible. */ - async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { + async initializeDefault(request: WorkspaceInitializeDefaultRequest, signal?: AbortSignal): Promise { this.calls.push({ method: 'initializeDefault', args: [request, signal] }) const stub = this.stubs.get('initializeDefault') - if (stub === undefined) throw new Error('initializeDefault requires a Workspace fixture') - return await (stub(request, signal) as Promise) + return await (stub?.(request, signal) as Promise | undefined) } /** diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index aeff2554d1..ca9523edbe 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -557,12 +557,12 @@ describe('workspaces', () => { expect(view.container.textContent).toContain('ws:pending') await runtime.dispose() }) - it('requires an explicit default Workspace fixture and forwards its request and lifetime', async () => { + it('skips default initialization without a fixture and forwards a configured request and lifetime', async () => { const runtime = await SlotTestRuntime.create() try { const request = { directoryName: 'default-workspace', title: 'Default workspace' } const signal = new AbortController().signal - await expect(runtime.workspaces.initializeDefault(request, signal)).rejects.toThrow('requires a Workspace fixture') + await expect(runtime.workspaces.initializeDefault(request, signal)).resolves.toBeUndefined() const workspace = { workspaceId: 'default' as WorkspaceId, title: request.title, path: '/default', sessionIds: [], createdAt: '2026-09-20T00:00:00Z', updatedAt: '2026-09-20T00:00:00Z', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 1f19959e7e..adababb1a4 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -246,7 +246,6 @@ export const EVENT_SCOPE_PAGE: Record = { export const EVENT_WALK_EXEMPTIONS: Record = { 'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API', 'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API', - 'conversation/prepare-first-send': 'client-face first-use draft preparation — packages/client/ui-conversation/README.md owns the API', 'locale/change': 'client-face locale switch signal — packages/client/locale/README.md owns the API', 'slash/input-begin-command': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', From 3a7f8f9657c1516aab510fbadecbc3e10152185d Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:20:44 +0800 Subject: [PATCH 07/11] test(web): restore ordinary workspace picker readiness --- apps/web/tests/preview-boot.e2e.ts | 4 ++-- apps/web/tests/sessionless-header.e2e.ts | 2 +- apps/web/tests/startup-rpc-budget.e2e.ts | 2 +- apps/web/tests/support.ts | 23 ++++++++++++++++------- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 4797a6e4bf..bde54fe69e 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -297,7 +297,7 @@ async function bootPreview(origin: string, browser: Browser): Promise { expect(await page.getByText('Empty environment', { exact: true }).count()).toBe(1) expect(await page.getByText('WebFS directory', { exact: true }).count()).toBe(1) expect(await page.locator('input[name="preview-source"][value="webfs"]').isDisabled()).toBe(true) - expect(await page.getByRole('button', { name: 'Choose workspace' }).count()).toBe(0) + expect(await page.getByRole('textbox', { name: 'Choose workspace' }).count()).toBe(0) await compareOrRefreshGolden( SOURCE_CHOOSER_EXPECTED, await captureStableAria(page, '[data-preview-source-card]', '/__preview_no_workspace__'), @@ -471,7 +471,7 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise ) expect(bootLine).toContain(`image lowering=${WRAPPER_CONTRACT}`) expect(bootLine).toContain('data overlays=0') - await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) + await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: HERO_TIMEOUT_MS }) const sessionCount = await page.evaluate(async () => { const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise } diff --git a/apps/web/tests/sessionless-header.e2e.ts b/apps/web/tests/sessionless-header.e2e.ts index 1de5dfe14f..b2c1a85fb0 100644 --- a/apps/web/tests/sessionless-header.e2e.ts +++ b/apps/web/tests/sessionless-header.e2e.ts @@ -30,7 +30,7 @@ describe('navigation without a selected Session', () => { } const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() + await page.getByRole('textbox', { name: 'Choose workspace', exact: true }).waitFor() const sessionHeader = page.locator('[data-slot="conversation.session.header"]') expect(await sessionHeader.count()).toBe(0) const header = page.locator('[data-slot="conversation.header"] > header') diff --git a/apps/web/tests/startup-rpc-budget.e2e.ts b/apps/web/tests/startup-rpc-budget.e2e.ts index d8c89afcca..f6655ffbf3 100644 --- a/apps/web/tests/startup-rpc-budget.e2e.ts +++ b/apps/web/tests/startup-rpc-budget.e2e.ts @@ -36,7 +36,7 @@ describe('startup RPC budget', () => { await page.goto(scaffold.authenticatedUrl) // Boot settles when the workspace picker is interactive; the trailing wait // absorbs the first-connection reset wave the budget must include. - await page.getByRole('button', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) + await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) await page.waitForTimeout(3000) const describeCount = calls.filter(method => method === 'settings/describe').length expect(describeCount, `startup /api calls:\n${calls.join('\n')}`).toBe(DESCRIBE_BUDGET) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 082f5019ae..fc29e7f913 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -105,16 +105,25 @@ export function probeFreePort(): Promise { } /** - * Select a staged directory through the hero's composed Workspace picker. - * The default name keeps the Session cwd at /workspace for scenarios - * that require a specific directory instead of automatic first-use preparation. + * Drive the hero's workspace picker through the composed directory dialog + * until the live composer unlocks. A fresh world has no Workspace, so the boot + * lands in the Workspace-trigger view state (startup auto-selection has nothing to + * select); every scenario that types into the composer must connect one + * first. With nothing to list, activating the composer surface raises the dialog directly — + * adding a workspace is the picker's only entry. The directory is staged here + * and adopted through the path editor, which is idempotent across the repeated + * connects a scenario may make; creating a folder from inside the dialog (the + * product's other half of the same route) is covered by + * workspace-management.e2e.ts. The default name 'workspace' keeps the session + * header cwd at /workspace, the materialization proof several scenarios + * assert. * @param page - the page under test. * @param root - host directory the workspace folder is staged in (the scaffold's `workspaceCwd`). * @param name - folder name staged and adopted as the workspace. */ export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('button', { name: 'Choose workspace', exact: true }).click() + await page.getByRole('textbox', { name: 'Choose workspace' }).click() const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: 'Edit path' }).click() @@ -122,7 +131,8 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: 'Open', exact: true }).click() - await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) + // The pick connected the workspace: the blank session's live composer + // replaces the locked placeholder and enables. await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build, / commands, @ files or sessions"]') .waitFor({ timeout: 15_000 }) } @@ -138,7 +148,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo */ export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) - await page.getByRole('button', { name: '选择工作区', exact: true }).click() + await page.getByRole('textbox', { name: '选择工作区' }).click() const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) await dialog.waitFor({ timeout: 10_000 }) await dialog.getByRole('button', { name: '编辑路径' }).click() @@ -146,7 +156,6 @@ export async function connectFreshWorkspaceZh(page: Page, root: string, name = ' await pathInput.fill(join(root, name)) await pathInput.press('Enter') await dialog.getByRole('button', { name: '打开', exact: true }).click() - await page.locator('[data-slot="conversation.session.header"]').waitFor({ state: 'attached', timeout: 15_000 }) await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容, / 调用指令, @ 文件或对话"]') .waitFor({ timeout: 15_000 }) } From 2cd03c97582f84924ceafab9b0c8809d7606979d Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:20:54 +0800 Subject: [PATCH 08/11] refactor(workspace): omit unchanged registry state fields --- packages/workspace/workspace/src/index.ts | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index d0f3d3b8a5..e2f67d948a 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -459,8 +459,6 @@ export class WorkspaceRegistry extends Service { initialized: true, ...(firstUse ? { defaultWorkspaceId: id } : {}), workspaceIds: [id, ...state.workspaceIds], - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, }) } catch (error) { this.entities.delete(id) @@ -494,8 +492,6 @@ export class WorkspaceRegistry extends Service { pendingMutation: undefined, initialized: true, workspaceIds: state.workspaceIds.filter(workspaceId => workspaceId !== id), - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, } await this.setState({ ...nextState, @@ -549,14 +545,7 @@ export class WorkspaceRegistry extends Service { ) } await this.requireTable().delete(pending.workspaceId) - await this.setState({ - ...state, - pendingMutation: undefined, - initialized: state.initialized, - workspaceIds: state.workspaceIds, - archivedSessionIds: state.archivedSessionIds, - pinnedSessionIds: state.pinnedSessionIds, - }) + await this.setState({ ...state, pendingMutation: undefined }) } private async bootstrap(headers: readonly SessionHeader[]): Promise { From 78d6f7bc1fafe4d60fd69fab03c043d4f4a90d66 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:48:46 +0800 Subject: [PATCH 09/11] test(client): mock default workspace initialization during boot --- .../client-runtime/src/assembly/remote-default-responses.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index c54130bca5..485882f05f 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -13,6 +13,8 @@ export const remoteDefaultResponses: RemoteTable = { unary: { // api-session-controller `sessions.handleConnected()` on `connection/reset`. 'session/list': ok({ items: [] }), + // ui-workspace startup with no entries; first-use initialization is ineligible. + 'workspace/initializeDefault': ok(undefined), // ui-settings `mirror.ensure()` at apply and again on `connection/reset`. 'settings/describe': ok({ writable: true, hasDocument: false, namespaces: [] }), // ui-model-selection `ModelDirectoryResolver` constructor. From 5294b15b3102bfd4899b13fa3fb1a4ac69419c5a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 17:48:58 +0800 Subject: [PATCH 10/11] docs(workspace): separate constructor parameter tags --- packages/api/workspace-controller/src/index.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 7a63e5b699..928f52f883 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -61,7 +61,10 @@ export class WorkspaceController extends TypertRemoteService { private readonly commands: WorkspaceCommands private readonly feed: WorkspaceFeed - /** @param ctx - Host context containing the Workspace registry. @param config - first-use directory policy. */ + /** + * @param ctx - Host context containing the Workspace registry. + * @param config - first-use directory policy. + */ constructor(ctx: Context, config: Config = {}) { super(ctx, 'workspaceController', { namespace: 'workspace' }) this.config = WorkspaceController.Config(config) From 5ec3353af2be73c6773ae3ce917d547f0ea5cd3a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 20 Sep 2026 20:42:50 +0800 Subject: [PATCH 11/11] refactor(workspace): reuse toast for default initialization failures --- apps/web/tests/default-workspace.e2e.ts | 14 ++-- .../default-workspace/failure.expected.md | 7 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspacePicker.tsx | 48 ++++--------- .../ui-workspace/src/client/contract/slots.ts | 9 +-- .../client/ui-workspace/src/client/index.ts | 13 ++-- .../client/ui-workspace/src/client/locales.ts | 8 +-- .../ui-workspace/src/client/navigation.ts | 20 +++--- .../client/session-actions/RowActionToast.tsx | 13 ++-- .../ui-workspace/tests/apply.client.spec.ts | 20 +++++- .../tests/session-actions.client.spec.tsx | 1 + .../tests/workspace-picker.client.spec.tsx | 35 +--------- .../tests/workspaces-service.client.spec.ts | 69 ++++++++++++------- 15 files changed, 114 insertions(+), 151 deletions(-) diff --git a/apps/web/tests/default-workspace.e2e.ts b/apps/web/tests/default-workspace.e2e.ts index d3b6db624d..d27f430fd3 100644 --- a/apps/web/tests/default-workspace.e2e.ts +++ b/apps/web/tests/default-workspace.e2e.ts @@ -81,16 +81,14 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { try { await page.goto(scaffold.authenticatedUrl) const input = page.locator('[data-composer-input][contenteditable="true"]').first() - const modal = page.getByRole('dialog', { name: '无法创建默认工作区' }) - await modal.waitFor() + const notice = page.getByRole('alert').filter({ hasText: '无法创建默认工作区' }) + await notice.waitFor() expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) - await compareOrRefreshGolden(FAILURE_EXPECTED, await modal.ariaSnapshot(), MODE) - await modal.getByRole('button', { name: '取消', exact: true }).click() + await compareOrRefreshGolden(FAILURE_EXPECTED, await notice.ariaSnapshot(), MODE) + expect(await page.getByRole('dialog').count()).toBe(0) expect(await input.count()).toBe(0) - await page.reload() - await modal.waitFor() - await modal.getByRole('button', { name: '选择文件夹', exact: true }).click() + await page.getByRole('button', { name: '选择工作区', exact: true }).click() const picker = page.getByRole('dialog', { name: '选择工作区目录' }) await picker.waitFor() await picker.getByRole('button', { name: '编辑路径', exact: true }).click() @@ -126,7 +124,7 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => { await page.goto(scaffold.authenticatedUrl) expect((await attempted).ok()).toBe(true) await page.getByRole('button', { name: 'Choose workspace', exact: true }).waitFor() - expect(await page.getByRole('dialog', { name: 'Unable to create default workspace' }).count()).toBe(0) + expect(await page.getByRole('alert').filter({ hasText: 'Unable to create default workspace' }).count()).toBe(0) expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(0) expect(scaffold.ctx.workspaceRegistry.list()).toEqual([]) expect(scaffold.ctx.sessions.list()).toEqual([]) diff --git a/apps/web/tests/expected/default-workspace/failure.expected.md b/apps/web/tests/expected/default-workspace/failure.expected.md index 6944d1cf14..c9624749f0 100644 --- a/apps/web/tests/expected/default-workspace/failure.expected.md +++ b/apps/web/tests/expected/default-workspace/failure.expected.md @@ -1,6 +1 @@ -- dialog "无法创建默认工作区": - - heading "无法创建默认工作区" [level=2] - - button "关闭" - - text: 请选择一个文件夹后重试 - - button "取消" - - button "选择文件夹" +- alert: 无法创建默认工作区,请通过“选择工作区”选择文件夹 diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 4af8adc8d4..2f176f2329 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 768c66503af70d0b587b25c09aa8412b0a647439 -README.zh.md: 25df6f8e6a2ec0a001d784c7bde18e454e9d706f +README.md: bf67f12f15f634a29dc05744c079255723ae2a62 +README.zh.md: e57700d983b31872383fc4b26f9b5b080d66ba6c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 768c66503a..bf67f12f15 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -69,7 +69,7 @@ The value is intentionally best effort for cold Sessions. An identity-matching u New Session tries to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request and are currently reported only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. -Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Preparation failure offers Cancel or Choose folder through the existing picker, and is not retried until the next startup. A successfully registered Workspace remains available when Session creation or later submission fails. +Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. The Client chooses the initial directory name and title from its language at startup: Chinese uses `默认工作区`, English uses `Default workspace`, and other languages use directory `default-workspace` with title `Default workspace`. The request retains those names during initialization. A successfully initialized Workspace keeps its directory and title across language changes. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 25df6f8e6a..e57700d983 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -69,7 +69,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 新建会话尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求,目前只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 -Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。准备失败时通过现有选择器提供取消或选择文件夹操作,直到下次启动才重试。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 +Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 Client 在启动时按其语言选择初始目录名和标题:中文使用 `默认工作区`,英文使用 `Default workspace`,其他语言使用目录 `default-workspace` 和标题 `Default workspace`。初始化过程中保留请求中的名称。成功初始化的工作区在切换语言后保留原目录和标题。 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 42e177afce..b74e3689dc 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -231,45 +231,21 @@ export function WorkspacePicker({ onClose, createWorkspace, useDirectoryFlow, - useDefaultFailure, - dismissDefaultFailure, renderSlot, t, }: WorkspacePickerProps) { - const failed = useDefaultFailure(value => value) - const flowAvailable = useDirectoryFlow(value => value) - const [recovering, setRecovering] = useState(false) return ( - <> - renderSlot('conversation.hero.workspace.directoryFlow', owner)} - selectedId={selectedId} - onPick={onPick} - onClose={() => { setRecovering(false); onClose() }} - /> - - - - - )} - > - {t('defaultWorkspace.retry')} - - + renderSlot('conversation.hero.workspace.directoryFlow', owner)} + selectedId={selectedId} + onPick={onPick} + onClose={onClose} + /> ) } diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index b878e24986..36ab1850d4 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -238,12 +238,13 @@ export type SessionRowActionProps = & PropsLocale<'workspace'> & InjectFace -/** One transient notice a row action raises; the overlay toast entry renders it. */ +/** One transient Workspace notice rendered by the overlay toast entry. */ export type RowToast = | { kind: 'archived'; sessionId: SessionId } | { kind: 'pinFailed' } | { kind: 'unpinFailed' } | { kind: 'archivedNotOpenable' } + | { kind: 'defaultWorkspaceFailed' } /** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ export type RowToastState = RowToast & { seq: number } @@ -364,12 +365,6 @@ export type WorkspaceBrowserProps = * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = DirectoryPickingInjected & { - /** Dismiss the startup failure before choosing a directory manually. */ - dismissDefaultFailure: () => void - hooks: { - /** Whether first-use startup failed to prepare a Workspace and Session. */ - defaultFailure: HostObservable - } /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 8d96c65d77..7c821033d6 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -103,8 +103,13 @@ export function apply(ctx: Context): void { const viewHandle = createWorkspaceViewStore() const viewInstance = viewHandle.create() const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance } + const rowToast = createSnapshotStore(null) + let toastSeq = 0 + const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions) + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, + () => { notify({ kind: 'defaultWorkspaceFailed' }) }, + ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries') @@ -137,9 +142,6 @@ export function apply(ctx: Context): void { // writes through its own injected callback and the surface reads through // its bound hook. const renameRequest = createSnapshotStore(null) - const rowToast = createSnapshotStore(null) - let toastSeq = 0 - const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => { renameRequest.set({ sessionId, currentTitle }) } @@ -219,8 +221,7 @@ export function apply(ctx: Context): void { }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => workspaces.create(input), - dismissDefaultFailure: () => { uiWorkspace.defaultFailure.set(false) }, - hooks: { directoryFlow: pickerFlowSource, defaultFailure: uiWorkspace.defaultFailure }, + hooks: { directoryFlow: pickerFlowSource }, }) // Each registration declares its owned children in the same call; slot // injection follows both the owner and declaration HMR lifetimes. diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index d926ce987f..3ecc46741f 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -6,10 +6,8 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'defaultWorkspace.failed': '无法创建默认工作区', + 'defaultWorkspace.failed': '无法创建默认工作区,请通过“选择工作区”选择文件夹', 'defaultWorkspace.title': '默认工作区', - 'defaultWorkspace.retry': '请选择一个文件夹后重试', - 'defaultWorkspace.choose': '选择文件夹', 'group.ungrouped': '未分组', 'session.new': '新会话', 'section.workspaces': '工作区', @@ -103,10 +101,8 @@ export type WorkspaceKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { - 'defaultWorkspace.failed': 'Unable to create default workspace', + 'defaultWorkspace.failed': 'Unable to create default workspace. Use Choose workspace to select a folder.', 'defaultWorkspace.title': 'Default workspace', - 'defaultWorkspace.retry': 'Please choose a folder and try again', - 'defaultWorkspace.choose': 'Choose folder', 'group.ungrouped': 'Ungrouped', 'session.new': 'New Session', 'section.workspaces': 'Workspaces', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index b21cf06f15..13c12651fd 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -120,8 +120,6 @@ export class DirectoryBrowseError extends Error { /** Implements Workspace archive and directory UI operations. */ class UiWorkspaceService extends Service implements UiWorkspace { - /** Startup failure awaiting dismissal or explicit directory selection. */ - readonly defaultFailure = createSnapshotStore(false) private readonly connecting = new Map>() private readonly lifetime = new AbortController() private readonly selection = createSnapshotStore( @@ -135,6 +133,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param workspaces - pure Workspace Controller. * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). + * @param notifyDefaultFailure - show the startup creation failure through the Workspace notice channel. */ constructor( ctx: Context, @@ -142,6 +141,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly workspaces: IWorkspaces, private readonly sessions: ISessions, private readonly view: Pick, + private readonly notifyDefaultFailure: () => void, ) { super(ctx, 'uiWorkspace') ctx.effect(() => { @@ -324,28 +324,28 @@ class UiWorkspaceService extends Service implements UiWorkspace { && !workspaces.archivedSessionIds.includes(summary.id)) { sessionId = await this.reuseBlank(workspace.workspaceId, summary.id) } - const target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) - if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) + let target = workspace?.workspaceId ?? recentWorkspace(workspaces.items, sessions.byId) if (target === undefined && workspaces.items.length === 0 && sessions.ids.length === 0) { - sessionId = await this.initializeDefaultWorkspace(navigation) + const prepared = await this.initializeDefaultWorkspace(navigation) + if (navigation.aborted) return + target = prepared?.workspaceId } + if (sessionId === undefined && target !== undefined) sessionId = await this.connectWorkspace(target) if (sessionId !== undefined && !navigation.aborted) { this.replaceMain(sessionId, navigation, 'preserve') } } - private async initializeDefaultWorkspace(signal: AbortSignal): Promise { + private async initializeDefaultWorkspace(signal: AbortSignal): Promise { const language = this.ctx.locale.getSnapshot().active.toLowerCase().split('-')[0] const title = (language === 'zh' ? zh : en)['defaultWorkspace.title'] try { - const workspace = await this.workspaces.initializeDefault({ + return await this.workspaces.initializeDefault({ directoryName: language === 'zh' || language === 'en' ? title : 'default-workspace', title, }, signal) - if (workspace === undefined || signal.aborted) return undefined - return await this.connectWorkspace(workspace.workspaceId) } catch (_error: unknown) { - if (!signal.aborted) this.defaultFailure.set(true) + if (!signal.aborted) this.notifyDefaultFailure() return undefined } } diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index f000fc4b4a..c5a3caccc6 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -1,8 +1,6 @@ /** - * The `shell.overlay` entry that shows the row actions' notices: the archived - * notice with its undo and "show archived" actions, pin failures, and the - * browser's "archived rows cannot be opened" notice. One notice at a time; - * a parent rerender does not extend its hold. + * The `shell.overlay` entry for Workspace and Session notices. + * One notice is visible at a time; a parent rerender does not extend its hold. */ import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' import type { RowToastProps } from '../contract/slots.ts' @@ -11,9 +9,9 @@ import type { RowToastProps } from '../contract/slots.ts' const ARCHIVED_TOAST_HOLD_MS = 6000 /** - * Render the row actions' current notice: the archived notice with its undo + * Render the current notice: the archived notice with its undo * and show-archived actions on a 6 s hold, or a plain warning for a failed - * pin or an archived row that was clicked. + * pin, an archived row that was clicked, or default Workspace creation. * @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat. * @returns the notice on display, or null. */ @@ -38,7 +36,8 @@ export function RowActionToast({ useToast, dismissToast, undoArchive, showArchiv } const text = toast.kind === 'pinFailed' ? t('toast.pinFailed') - : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable') + : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') + : toast.kind === 'defaultWorkspaceFailed' ? t('defaultWorkspace.failed') : t('toast.archivedNotOpenable') return ( () => {} const workspacesSubscribe = vi.fn(subscribe) + const initializeDefault = vi.fn(async (): Promise => undefined) ctx.provide('workspaces', { list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe }, create, + initializeDefault, rename, delete: vi.fn(async () => undefined), insertBefore: vi.fn(async () => undefined), @@ -128,7 +130,7 @@ async function bench() { return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, - workspacesSubscribe, + workspacesSubscribe, initializeDefault, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot }, } @@ -182,6 +184,20 @@ describe('ui-workspace apply', () => { ]) }) + it('reports a default Workspace creation failure through the shared notice overlay', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + b.initializeDefault.mockRejectedValueOnce(new Error('denied')) + declare(b.slots, 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const face = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + await vi.waitFor(() => { + expect(face.hooks.toast.getSnapshot()).toMatchObject({ kind: 'defaultWorkspaceFailed' }) + }) + face.dismissToast() + expect(face.hooks.toast.getSnapshot()).toBeNull() + }) + it('registers browser and pickers for declarations arriving before or after apply', async () => { const before = await bench() declare(before.slots, 'sidebar.workspaces') diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index ce5cb47dda..c7e3b1150d 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -387,6 +387,7 @@ describe('RowActionToast', () => { ['pinFailed', '置顶失败,请稍后重试'], ['unpinFailed', '取消置顶失败,请稍后重试'], ['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'], + ['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'], ] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => { vi.useFakeTimers() try { diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index e72d523668..9ff0181207 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -1,7 +1,6 @@ // @vitest-environment jsdom import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -89,19 +88,14 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), occupancy = occupancySource(), - options: { defaultFailure?: boolean; open?: boolean } = {}, ) { - const failure = createSnapshotStore(options.defaultFailure ?? false) - const useDefaultFailure = bindSnapshotSelector(failure) - const dismissDefaultFailure = vi.fn(() => { failure.set(false) }) const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( { view.rerender(renderPicker(nextItems)) }, } } @@ -226,7 +220,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -245,7 +238,6 @@ describe('WorkspacePicker', () => { const { renderSlot } = flowProbe() render( undefined} @@ -329,26 +321,3 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: '添加工作区…' })).toBeNull() }) }) - -describe('default Workspace startup recovery', () => { - it('dismisses the failure without opening the directory flow', () => { - const b = mount([], vi.fn(), occupancySource(), { defaultFailure: true, open: false }) - expect(screen.getByRole('dialog', { name: '无法创建默认工作区' })).toBeTruthy() - expect(b.probe.owner?.open).toBe(false) - fireEvent.click(screen.getByRole('button', { name: '取消' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(screen.queryByRole('dialog', { name: '无法创建默认工作区' })).toBeNull() - expect(b.probe.owner?.open).toBe(false) - }) - - it('opens the composed directory flow from the startup failure', async () => { - const create = vi.fn(async () => workspace('chosen')) - const b = mount([], create, occupancySource(), { defaultFailure: true, open: false }) - fireEvent.click(screen.getByRole('button', { name: '选择文件夹' })) - expect(b.dismissDefaultFailure).toHaveBeenCalledOnce() - expect(b.probe.owner?.open).toBe(true) - await act(async () => { b.probe.owner!.onPicked('/chosen') }) - expect(create).toHaveBeenCalledExactlyOnceWith({ path: '/chosen' }) - expect(b.onPick).toHaveBeenCalledExactlyOnceWith(wid('chosen')) - }) -}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 4f9cd973b8..8efdb0af95 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -294,14 +294,16 @@ function bench(options: BenchOptions = {}) { options.configureWorkspaces?.(workspaces) options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() + const notifyDefaultFailure = vi.fn() const uiWorkspace = new UiWorkspaceService( ctx, directoryPicker.remote, workspaces, sessions, view.actions, + notifyDefaultFailure, ) - return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view } + return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notifyDefaultFailure } } describe('UiWorkspaceService', () => { @@ -326,10 +328,10 @@ describe('UiWorkspaceService', () => { }) expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith({ directoryName, title }, expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('leaves an ineligible empty installation without a Session or failure dialog', async () => { + it('leaves an ineligible empty installation without a Session or failure notice', async () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState() }) await setImmediate() b.workspaces.list.set(workspaceState()) @@ -337,7 +339,7 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) it('requires explicit selection when the startup Session list contains history', async () => { @@ -351,13 +353,12 @@ describe('UiWorkspaceService', () => { const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { workspaces.initializeDefault.mockRejectedValueOnce(new Error('denied')) } }) - await vi.waitFor(() => { expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(true) }) - b.uiWorkspace.defaultFailure.set(false) + await vi.waitFor(() => { expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) b.workspaces.list.set(workspaceState()) await setImmediate() expect(b.workspaces.initializeDefault).toHaveBeenCalledOnce() expect(b.sessions.create).not.toHaveBeenCalled() - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).toHaveBeenCalledOnce() }) it.each(['session', 'panel', 'disposal'] as const)('cancels startup directory preparation after %s navigation', async (kind) => { @@ -373,27 +374,43 @@ describe('UiWorkspaceService', () => { await setImmediate() expect(b.sessions.create).not.toHaveBeenCalled() expect(b.sessions.retain.mock.calls.map(args => args[0])).toEqual(kind === 'session' ? [sid('manual')] : []) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(false) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() }) - it('retains a prepared Workspace when its Session fails and suppresses a superseded failure', async () => { - for (const superseded of [false, true]) { - const created = Promise.withResolvers() - const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { - workspaces.initializeDefault.mockImplementationOnce(async () => { - const item = workspace('default') - workspaces.list.set(workspaceState([item])) - return item - }) - }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) - await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) - if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) - created.reject(new Error('session failed')) - await setImmediate() - expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) - expect(b.uiWorkspace.defaultFailure.getSnapshot()).toBe(!superseded) - expect(b.sessions.retain).not.toHaveBeenCalled() - } + it.each(['session', 'panel', 'disposal'] as const)('suppresses a startup directory failure after %s navigation', async (kind) => { + const pending = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockReturnValueOnce(pending.promise) + } }) + if (kind === 'session') b.uiWorkspace.openSession(sid('manual')) + else if (kind === 'panel') b.layout.selectPanel('other-panel' as MainPanelId) + else await b.ctx.fiber.dispose() + pending.reject(new Error('late failure')) + await setImmediate() + expect(b.sessions.create).not.toHaveBeenCalled() + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + }) + + it.each([false, true])('reports Session failure without a directory error and retains the Workspace (superseded: %s)', async (superseded) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const created = Promise.withResolvers() + const b = bench({ workspaces: workspaceState(), sessions: sessionState(), configureWorkspaces: (workspaces) => { + workspaces.initializeDefault.mockImplementationOnce(async () => { + const item = workspace('default') + workspaces.list.set(workspaceState([item])) + return item + }) + }, configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(created.promise) } }) + await vi.waitFor(() => { expect(b.sessions.create).toHaveBeenCalledOnce() }) + if (superseded) b.layout.selectPanel('other-panel' as MainPanelId) + const failure = new Error('session failed') + created.reject(failure) + await vi.waitFor(() => { + expect(warning).toHaveBeenCalledExactlyOnceWith('initial Session restoration failed:', failure) + }) + expect(b.workspaces.list.getSnapshot().items).toEqual([workspace('default')]) + expect(b.notifyDefaultFailure).not.toHaveBeenCalled() + expect(b.sessions.retain).not.toHaveBeenCalled() }) it('retains an explicit main target before revealing its Conversation', () => {