diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index cccd955846..510cb78fd5 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -15,8 +15,8 @@ en: 0e1399cad4151f87 zh: 960fa0ccbe0f8fea /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/cancellation-codes-record-whether-dispatch-occurred: - en: 86c5566581c1d3d6 - zh: 3cb71fbb97bdb291 + en: 4d8436958c27f98e + zh: cd4ed8238428a2c4 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/pre-aborted-entry-short-circuits-after-materialization: en: 53362db6a0c71698 zh: 311de45ca26d3fdc diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 3f4fbcc597..72a99de358 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -32,7 +32,7 @@ An around-dispatch wrapper may replace `exec.signal` for its delegated lifetime `ABORTED_BEFORE_DISPATCH` carries `{ name: 'AbortError' }` and model text `Error: tool call aborted before dispatch`. It applies whenever cancellation prevents body invocation, including pre-aborted entry, cancellation during pre-policy or approval, an aborted wrapper signal, a wrapper success overtaken by caller cancellation before delegation, and agent-loop siblings skipped after turn cancellation. -`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A denial, wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. +`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, with `ABORTED_BEFORE_DISPATCH` when the body never started. A denial, other wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. ### Pre-aborted entry short-circuits after materialization diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index 15856a1cce..d098a385da 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -32,7 +32,7 @@ Status: implemented `ABORTED_BEFORE_DISPATCH` 携带 `{ name: 'AbortError' }` 和模型可见文本 `Error: tool call aborted before dispatch`。凡取消阻止工具主体调用时都使用该结果,包括进入时已中止、前置策略或审批期间取消、包装层信号已中止、包装层在委托前返回的成功结果被调用方取消抢先,以及轮次取消后 agent loop(智能体循环)跳过的同批调用。 -`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。拒绝、包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 +`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。拒绝、其他包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 ### 进入时已中止会在物化后短路 diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml index 93feec2b95..617d73c1af 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.i18n.yaml @@ -18,8 +18,8 @@ en: fb2c7bcde3b1672a zh: a05bd30be07e5413 /agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotestream: - en: d55c2ce88400e448 - zh: 344d510ab946bb9f + en: 867f3ac763f81d8d + zh: a936269f2fc40f8d /agent-note-session-history-control-state-and-remote-event-transport/decision/general-remote-stream-model/remotesnapshotstream: en: f2c1d2b00d9554fd zh: c3e85cf344f7ef24 diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md index ee43b551eb..c9447a8b1a 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.md @@ -101,7 +101,7 @@ Domain Controllers use them through composition or thin adapters; Session and Wo Each item carries a monotonic generation, that generation's `AbortSignal`, and `accept()`. A domain consumer calls `accept()` only after validating the opening cursor or baseline. -Only `RemoteStreamCarrierError` permits retry. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately. +Only a failure whose `code` is `gateway/carrier-lost` permits retry; `RemoteStreamCarrierError` carries that code, and a domain `ended` callback may return a plain `Error` with it. When the Host remains available, one independent reopen is allowed; otherwise the stream waits for a new Connection generation. Business errors, protocol errors, and opening failures terminate immediately. `restart()` replaces only the current physical generation and preserves the logical stream. `dispose()` permanently ends the logical stream, pending retry, and iterator, then waits for quiescence. diff --git a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md index 9df5c55701..4347de301c 100644 --- a/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-18-session-history-and-event-transport.zh.md @@ -101,7 +101,7 @@ RemoteStream 每个 item 携带单调 generation、该 generation 的 `AbortSignal` 与 `accept()`。领域 consumer 只有在验证 opening cursor 或 baseline 后才调用 `accept()`。 -只有 `RemoteStreamCarrierError` 可触发重试。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。 +只有 `code` 为 `gateway/carrier-lost` 的失败可触发重试;`RemoteStreamCarrierError` 带有该 code,领域的 `ended` 回调也可以返回带该 code 的普通 `Error`。Host 仍可用时允许一次独立重开;否则等待新的 Connection generation。业务错误、协议错误和 opening 失败直接终止。 `restart()` 只淘汰当前物理 generation,保留 logical stream;`dispose()` 永久结束 logical stream、pending retry 与 iterator,并等待 quiescence。 diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml index 802e66d820..7795233f7c 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.i18n.yaml @@ -24,8 +24,8 @@ en: b6f585ca87e1fc6f zh: 53fd58c3e93cf17c /agent-note-client-session-conversation-and-ui-ownership-layers/package-ownership: - en: 89f75f7cc2fe0e6c - zh: e50974fad3baf69c + en: f3f1e545f7b15d9a + zh: 80927e6b4e8ed5bc /agent-note-client-session-conversation-and-ui-ownership-layers/overall-data-flow: en: 002d9f406580684b zh: a86742c6c943ac85 diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md index 4ef7434535..b3286623c4 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.md @@ -81,7 +81,7 @@ Adding a target does not add a branch to the renderer or Session Controller. The | `api/session-controller/client` | Session objects, catalog, references, source counts, commands, projections, event windows, and Agent Contexts | Navigation, completion reminders, Conversation targets, React, Slots, Workspace | | `api/workspace-controller/client` | Workspace objects, ordering, archive state, commands, and snapshots | React, Session navigation policy, directory UI | | `client/ui-session` | Explicit Session scope, standard sources, `SessionProvider`, and effective pending interactions | Session transport, reference ownership, Conversation assembly, Approval/Question results, unified UI status | -| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders | Pending-interaction registration, Session transport, React | +| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders; Host reading records and their Client copy; main-view reading acknowledgement | Pending-interaction registration, Session transport, React | | `client/ui-workspace` | Workspace hook, browser UI, main-area reference, and cross-Controller navigation policy | Workspace transport, copies of Session data | | `client/ui-conversation` | Conversation core, registries, bindings, shell, input, composer, queue, and View navigation | Session transport, Chat/Trajectory snapshots | | `client/ui-chat` | Chat target, Node definitions, renderers, selection, details, and locale | Session lifecycle, generic View navigation, Trajectory, historical-image cache | diff --git a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md index cf3b65492d..6a604e52cb 100644 --- a/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-20-client-session-conversation-ownership.zh.md @@ -81,7 +81,7 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把 | `api/session-controller/client` | 会话对象、目录、引用、来源计数、命令、投影、事件窗口与 Agent Context | 导航、完成提醒、Conversation target、React、Slot、Workspace | | `api/workspace-controller/client` | Workspace 对象、顺序、归档、命令和 snapshot | React、Session 导航策略、目录 UI | | `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与有效待处理交互 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果、统一 UI 状态 | -| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒 | 待处理交互登记、会话传输、React | +| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒;宿主阅读记录及其前端副本;主视图阅读确认 | 待处理交互登记、会话传输、React | | `client/ui-workspace` | Workspace 钩子、浏览器 UI、主区域引用与跨控制器导航策略 | Workspace 传输、会话数据副本 | | `client/ui-conversation` | Conversation core、registry、binding、shell、input、composer、queue 和 View 导航 | Session transport、Chat/Trajectory snapshot | | `client/ui-chat` | Chat target、Node definitions、renderer、selection、details 和 locale | Session 生命周期、通用 View 导航、Trajectory、历史图片 cache | diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml index 12ad701c1e..6826d6a497 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml @@ -24,8 +24,8 @@ en: e2de83d10542f93b zh: 3855b38fc8c48ea3 /agent-note-client-session-references-reference-sources-and-ui-status/decision/unified-ui-session-status: - en: 07ea04b9ca50dd8f - zh: e025fcea4c9f0fb9 + en: 45038468e95179f9 + zh: ac8f2f098f5b2427 /agent-note-client-session-references-reference-sources-and-ui-status/decision/explicit-providers-and-consumer-lifetimes: en: 04802baa0147fec1 zh: b86037bf2e4bc936 diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md index ac8eb95cf7..6a7c15ad86 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md @@ -96,22 +96,16 @@ Window-level consumers may inspect source markers. Session business operations s | --- | --- | --- | | `running` | `boolean` or `undefined` | Latest known Session running fact; absence of a baseline is not confirmed idle | | `pendingInteraction` | `SessionPendingInteraction` or `undefined` | Effective domain-owned request, or absence when no request is pending | -| `completionUnread` | `boolean` | UI reminder for an observed stop that has not been acknowledged | +| `completionUnread` | `boolean` | Host reading record carries a manual unread mark or an unacknowledged completed turn | +| `completionFailed` | `boolean` | The Session is unread and its latest completed turn ended with an execution error | Source counts remain authoritative in `SessionListState.byId[id].retainedBy`; UI status reads them for acknowledgement policy without owning another reference registry. Titles, Workspace associations, history, queues, and projection data remain with their existing owners. Pending domains retain `SessionPendingInteractionMap`, request identities, precedence, publication disposers, and teardown delegation in `ui-session`, which publishes each Session's effective request read-only as `ctx.uiSession.pendingInteractions`. The unified status includes the same effective request object; it does not copy requests or create a second pending registry. Workspace status indicators and Conversation composer selection read `useSessionStatus` instead of separate `useSessionPendingInteraction` and `useCompletedSessionIds` hooks. -Completion tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared. The update rules are: +Running tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared, and removing a Session clears its running baseline; pending-request teardown stays with the request's domain. -- An initial idle baseline does not create a completion reminder. -- Observing running clears an earlier reminder and records the running baseline. -- A known running-to-idle transition sets `completionUnread` only when the Session lacks main-view ownership. -- Acquiring main-view ownership clears the reminder; retaining from an unrelated source does not. -- Releasing main-view ownership does not manufacture a reminder for an earlier stop. -- Removing a Session clears its completion reminder and running baseline; pending-request teardown stays with the request's domain. - -The reminder denotes an observed stop, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount. +Completion reminders follow the Host reading records described in [Host-memory Session reading state](../feature/2026-10-23-session-reading-memory.md), which supersedes this note's earlier Client-local reminder rules: running changes and main-view ownership neither set nor clear a reminder, and the visible main view acknowledges a completed turn only after its body arrives. The reminder denotes a completed turn, not successful task completion or completion of a particular queued message. Main-view ownership preserves selection-based acknowledgement even while a global panel temporarily hides the Conversation. The design has no `ui-session/view-presence` event, mounted-Provider index, or implicit acknowledgement from Provider mount. The Session Controller publishes running and reference-source facts but owns no completion-reminder set, `consumeCompletion` method, or pending-interaction presentation. Reference acquisition does not execute completion-reminder business logic. diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md index 3a4168f4c4..167dbac7b9 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md @@ -96,22 +96,16 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源 | --- | --- | --- | | `running` | `boolean` 或 `undefined` | 最新已知的 Session 运行事实;缺少基线不表示已确认 idle | | `pendingInteraction` | `SessionPendingInteraction` 或 `undefined` | 领域拥有的有效请求;没有待处理请求时缺失 | -| `completionUnread` | `boolean` | 已观察到停止、但尚未确认的 UI 提醒 | +| `completionUnread` | `boolean` | 宿主阅读记录带有手动未读标记或尚未确认的完成轮次 | +| `completionFailed` | `boolean` | Session 未读,且最近完成的轮次以执行错误结束 | 来源计数以 `SessionListState.byId[id].retainedBy` 为准;UI 状态读取它以执行确认策略,不维护另一套引用注册表。标题、Workspace 关联、历史、队列和投影数据保留在各自的既有所有者中。 待处理领域在 `ui-session` 中保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托,`ui-session` 以只读的 `ctx.uiSession.pendingInteractions` 发布每个 Session 的有效请求。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。 -完成跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失。更新规则如下: +运行跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失;移除 Session 时清除其运行基线,待处理请求的清理仍属于请求领域。 -- 初始 idle 基线不产生完成提醒。 -- 观察到 running 时清除旧提醒,并记录运行基线。 -- 从已知 running 变为 idle 时,仅在 Session 没有主视图持有的情况下设置 `completionUnread`。 -- 获得主视图持有时清除提醒;无关来源的 retain 不清除提醒。 -- 释放主视图持有不会为更早的一次停止补造提醒。 -- 移除 Session 时清除其完成提醒与运行基线;待处理请求的清理仍属于请求领域。 - -提醒表示观察到的一次停止,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。 +完成提醒跟随[宿主内存中的会话阅读状态](../feature/2026-10-23-session-reading-memory.zh.md)所述的宿主阅读记录,该记录取代本记录早先的前端本地提醒规则:运行变化和主视图持有都不会设置或清除提醒,可见的主视图只在正文到达后确认完成的轮次。提醒表示完成的一个轮次,不代表任务成功,也不代表某条排队消息完成。即使全局面板暂时隐藏 Conversation,主视图所有权仍保持基于选择的确认语义。本设计不提供 `ui-session/view-presence` 事件、已挂载 Provider 索引或 Provider 挂载时的隐式确认。 Session Controller 发布运行与引用来源事实,但不拥有完成提醒集合、`consumeCompletion` 方法或待处理交互展示。引用获取不执行完成提醒业务逻辑。 diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml new file mode 100644 index 0000000000..b101719d93 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-23-session-reading-memory.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-23-session-reading-memory.md +/agent-note-host-memory-session-reading-state: + en: d0d93ca91b0bfd16 + zh: 55f67f2074612e4d +/agent-note-host-memory-session-reading-state/problem: + en: 61f665a6dc1bc503 + zh: 3421cf192528179e +/agent-note-host-memory-session-reading-state/decision: + en: a15c7c13f167e5ac + zh: 63bcc2ef60c2f344 +/agent-note-host-memory-session-reading-state/decision/package-structure: + en: e22765435a1ab422 + zh: 7ac9fbcea4c15387 +/agent-note-host-memory-session-reading-state/decision/client-dependency-rules: + en: e38746215940a163 + zh: a4e343dac7942aa2 +/agent-note-host-memory-session-reading-state/decision/host-records: + en: ea1b8aa4ed60f04c + zh: 9c979b7b40eacb3e +/agent-note-host-memory-session-reading-state/decision/automatic-acknowledgement: + en: 64f9e14597dbc3d4 + zh: e2d20a5105c9d950 +/agent-note-host-memory-session-reading-state/alternatives-considered: + en: 755d2e5eb626b445 + zh: 898f83b86d2e2209 +/agent-note-host-memory-session-reading-state/consequences: + en: 01f6beaeff1e6c7f + zh: 1fdee75b2c4bf646 diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md new file mode 100644 index 0000000000..52951c5b06 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md @@ -0,0 +1,58 @@ +# Agent Note: Host-memory Session reading state + +Status: implemented + +English | [中文](2026-10-23-session-reading-memory.zh.md) + +## Problem + +Clients connected to the same Host need consistent reading reminders, including completions that end while every Client is offline. Automatic acknowledgements must not clear unseen completions or manual unread marks. Reading activity must not change model history. The reminders appear in the Client Session status table that [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md) owns, so the reading records, their Client follower, and the table that consumes them need one owner whose Client face may follow a Host Remote stream. + +## Decision + +### Package structure + +`@deepseek-ai/dsh-client-ui-session-status` owns the feature on both faces, following the Host-and-Client package precedent of ui-trajectory: + +| Face | Service | Responsibility | +|---|---|---| +| Host (`.`) | `ctx.sessionStatus` (`SessionStatusService`) | Keeps one reading record per Session in an in-memory Map; the `sessionStatus` Remote namespace serves `mark` and `follow`; failures use `session-status/not-found` and `session-status/unavailable` | +| Client (`./client`) | `ctx.uiSession.sessionStatus` (service name `uiSession.sessionStatus`) | Follows the Host reading stream, builds the status table with `completionUnread` and `completionFailed`, exposes `mark` and `readingReady`, and acknowledges main-view reading | + +The Client copy of the reading records is a package-internal module: it exports no value or type and provides no Client service of its own, so consumers such as ui-workspace and ui-conversation depend only on `ctx.uiSession.sessionStatus` and the exported status types. The Web bundle's single `ui-session-status` row loads both faces, api/remotes mounts the package's `/remote` descriptor, and the Web client lists the package among its required boot entries. ui-session, pending-interaction registration, and `ctx.uiSession.pendingInteractions` stay unchanged. + +### Client dependency rules + +Following the Host stream needs the Gateway's `RemoteSnapshotStream` at runtime. `verify-client-packages` lets a `packages/client` feature package request rows under `packages/api/` through `dsh.client.external`, while still rejecting requests for another feature plugin's row; the Remote API group is infrastructure, not a feature plugin. The package requests only `@deepseek-ai/dsh-api-gateway/client`. The stream runs only while `ctx.remoteAccess` allows `sessionStatus/follow`; that endpoint is owner-only for LiveShare, so a viewer page opens no stream, keeps `readingReady` false, and reports no synchronization failure. + +`RemoteStream` decides reconnection by the stable error code `gateway/carrier-lost` rather than by `instanceof RemoteStreamCarrierError`. The class carries that code, so existing callers keep their behavior, and the package's `ended` callback returns a plain `Error` with the code, typed by the exported `RemoteStreamCarrierFailure` type, without importing the class. The code is produced only inside the Client process: a `RemoteError` returned by the Host terminates the stream even when it carries the same code. + +### Host records + +The Host service owns one in-memory record per Session and derives the latest ended turn and its failure flag from `turn/end` events itself. Mutations update the Map synchronously. Read actions carry the Client-observed completed turn; the Host advances the read position monotonically and never beyond its known completion. Automatic acknowledgements leave manual unread unchanged; explicit marks replace it in Host processing order. Only the ordered baseline and whole-record change stream updates the Client, so mutation replies need no record or revision. + +Cold Session marks read metadata without opening history. A Session without a record reads as read, so history neither needs a startup scan nor distinguishes a cold Session from a live zero-turn one. Shutdown closes followers and clears records. A pending metadata lookup rejects its mark after disposal rather than delaying teardown for an in-memory write. + +### Automatic acknowledgement + +Only a visible, focused main view acknowledges reading, after a rendering frame and evidence that the body reached the completed turn. Window focus advances only the natural read position. A main-view switch to a different Session, including the first selection after a page load, clears that Session's existing manual reminder once its body arrives; the check waits for a ready reading baseline. Window focus, a replaced binding for the same Session, and activity in the open Session do not clear it, so a mark made in the open Session stays until the view leaves and returns. Later automatic acknowledgements preserve manual marks, including those received while the body loads. Keeping the rule inside the acknowledgement plugin avoids a cross-package reading event and changes to the Conversation body. While the visible, focused main view retains an open Session, the status table does not show that Session's unacknowledged completion, so its row does not flash unread before the acknowledgement round trip; manual marks stay visible, and the reminder returns when the window loses focus or the view moves away first. Archived rows read as read and offer no reading mark. + +## Alternatives considered + +- **ui-session reads reading state:** the base UI package would depend on a feature package, and every UI above it could not start without the reading plugin. +- **A separate reading package with a Client service:** consumers would see a second reading API beside `ctx.uiSession.sessionStatus`, and the status table would depend on another package's service only to fold its records. +- **An api-group reading package beside the client table:** splits one feature across two packages whose Host contract, Client follower, and table evolve together; the relaxed external rule lets the client package follow the stream itself. +- **Reimplementing the snapshot protocol over `ctx.remote.$stream`:** duplicates Gateway-owned baseline and reconnection logic in a feature package. +- **Importing `RemoteStreamCarrierError` into the client package:** a feature package would depend on a Gateway class identity for one retry decision; a stable code states the decision without class identity across separately bundled modules. +- **Host face in the shared base bundle:** profiles without a Web Client would run a reading service no Client reads, and the Host face would load from a different bundle than its Client face. +- **Frontend memory or local storage:** cannot provide one authority for browsers and Desktop clients, or collect completions while all frontends are offline. +- **Persistent Host records:** preserve reminders across Host restarts but require a separate lifecycle design for Session checkpoints, domain ownership, backend shutdown, and failed writes. This implementation deliberately limits ownership to memory; persistence is a separate change. +- **Reading events in the Session log:** mix viewer intent with model history and require loading cold histories for metadata-only actions. +- **Revision-based conditional writes:** prevent delayed explicit actions from replacing newer manual intent, but require conflict responses, revision bookkeeping and unary-result reconciliation. Session reminders accept Host processing order instead. A read-position cursor still prevents unseen completions from being acknowledged. +- **Message ID cursor:** identifies a message but does not order completed turns, including failures without a new assistant message. The existing completed-turn number directly represents this feature's unit of progress. + +## Consequences + +Browser refresh and temporary disconnect preserve reminders while this Host service runs. Host restart or plugin reload resets every reading record and treats existing history as read; a turn that failed before the restart leaves no outcome, so marking that Session unread shows the ordinary reminder. Profiles without the Web bundle run no reading service. There are no read-state files, storage-domain dependencies, checkpoint writes, or cross-process synchronization guarantees. Reminders remain for detached Sessions until the service stops; reclaiming records requires a Session deletion lifecycle. + +Concurrent explicit actions have last-processed semantics; an entry acknowledgement can clear another manual mark that arrives before it is processed. Verification covers two followers, monotonic read positions and manual-mark preservation during automatic acknowledgements, a first completion after manual marks, access-driven rebaselines, shutdown with a pending metadata lookup, service reload, independence from Session flush, and the failure flag of a completing turn. Client tests cover the reading stream's baseline replacement and terminal failure, delayed body delivery, manual marks during loading, and manual-reminder clearing on main-view switches but not on window focus or a replaced binding. Gateway tests cover reconnection for a plain error carrying the carrier code and termination without it. Persistent restart recovery, crash consistency, storage-provider ordering, and cross-process writers require separate validation before persistence is enabled. The main-view retention signal does not distinguish every settings or auxiliary panel; that visibility refinement remains part of the notification work. diff --git a/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md new file mode 100644 index 0000000000..e47c4435f4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md @@ -0,0 +1,58 @@ +# Agent Note: 宿主内存中的会话阅读状态 + +Status: implemented + +[English](2026-10-23-session-reading-memory.md) | 中文 + +## 问题 + +连接同一宿主的前端需要一致的阅读提醒,包括所有前端都离线时结束的轮次。自动阅读确认不能清除尚未看到的完成提醒或手动未读标记。阅读行为不能改变模型历史。这些提醒显示在 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md) 拥有的前端会话状态表中,因此阅读记录、它的前端订阅方和使用它的状态表需要同一个归属方,而且其前端面能够订阅宿主 Remote 流。 + +## 决策 + +### 包结构 + +`@deepseek-ai/dsh-client-ui-session-status` 在两个面上拥有该功能,沿用 ui-trajectory 同时提供宿主面和前端面的先例: + +| 面 | 服务 | 职责 | +|---|---|---| +| 宿主(`.`) | `ctx.sessionStatus`(`SessionStatusService`) | 在内存 Map 中为每个会话保存一条阅读记录;Remote 命名空间 `sessionStatus` 提供 `mark` 和 `follow`;失败使用 `session-status/not-found` 和 `session-status/unavailable` | +| 前端(`./client`) | `ctx.uiSession.sessionStatus`(服务名 `uiSession.sessionStatus`) | 订阅宿主阅读流,构建含 `completionUnread` 和 `completionFailed` 的状态表,提供 `mark` 和 `readingReady`,并确认主视图已读 | + +前端的阅读记录副本是包内部模块:它不导出任何值或类型,也不提供自己的前端服务,因此 ui-workspace、ui-conversation 等使用方只依赖 `ctx.uiSession.sessionStatus` 和导出的状态类型。Web bundle 中唯一的 `ui-session-status` 行加载两个面,api/remotes 挂载本包的 `/remote` 描述,Web 前端把本包列为启动必需入口。ui-session、待交互登记和 `ctx.uiSession.pendingInteractions` 保持不变。 + +### 前端依赖规则 + +订阅宿主流在运行时需要 Gateway 的 `RemoteSnapshotStream`。`verify-client-packages` 允许 `packages/client` 下的功能包通过 `dsh.client.external` 请求 `packages/api/` 下的行,但仍拒绝请求另一个功能插件的行;Remote API 组是基础设施,不是功能插件。本包只请求 `@deepseek-ai/dsh-api-gateway/client`。只有 `ctx.remoteAccess` 允许 `sessionStatus/follow` 时才运行该流;该端点在 LiveShare 中仅限所有者,因此查看者页面不打开该流,`readingReady` 保持 false,也不报告同步失败。 + +`RemoteStream` 按稳定的 error code `gateway/carrier-lost` 判断是否重连,而不是按 `instanceof RemoteStreamCarrierError`。该 class 自带这个 code,现有调用方行为不变;本包的 `ended` 回调返回带该 code 的普通 `Error`,用导出的 `RemoteStreamCarrierFailure` 类型描述,而不导入该 class。该 code 只在前端进程内产生:宿主返回的 `RemoteError` 即使带有相同 code 也会终止流。 + +### 宿主记录 + +宿主服务在内存中为每个会话保存一条记录,自己从 `turn/end` 事件取得最近结束的轮次及其失败标记。修改同步更新 Map。已读请求携带前端已看到的完成轮次;宿主单调推进阅读位置,且不越过已知完成位置。自动确认保留手动未读,主动标记按宿主处理顺序替换它。前端只通过有序基线和整条记录的更新流取得状态,修改回复不需要记录或版本。 + +对冷会话的标记只读取元信息,不打开历史。没有记录的会话按已读处理,因此历史既不需要启动扫描,也不需要区分冷会话和零轮次的活跃会话。关闭时结束订阅并清空记录;尚在等待元信息的标记请求会在查询返回后被拒绝,不会为了内存写入延迟卸载。 + +### 自动确认 + +只有可见且聚焦的主视图会确认阅读,并等待一次渲染帧及正文已到达完成轮次的证据。窗口聚焦只推进自然已读位置。主视图切换到另一个会话(包括页面加载后的首次选中)时,会在正文到达后清除该会话已有的手动提醒;检查会等待阅读基线就绪。窗口聚焦、同一会话更换 binding 以及在已打开会话中的操作都不会清除它,因此在已打开会话中做的标记会保留到视图切走再切回。后续自动确认保留手动标记,包括正文加载期间收到的标记。把规则留在确认插件内部,可以避免跨包的阅读事件,也不需要修改 Conversation 正文。可见且聚焦的主视图持有某个已打开的会话时,状态表不显示该会话尚未确认的完成轮次,避免在确认往返完成前闪现未读;手动标记照常显示,窗口失焦或视图先行切走时提醒会重新出现。归档行按已读处理,不提供阅读标记。 + +## 考虑过的替代方案 + +- **ui-session 读取阅读状态:** 基础 UI 包会依赖功能包,阅读插件缺席时其上的所有界面都无法启动。 +- **单独的阅读包并提供前端服务:** 使用方会在 `ctx.uiSession.sessionStatus` 之外看到第二套阅读 API,状态表也只为汇总记录而依赖另一个包的服务。 +- **在前端状态表旁另建 api 组阅读包:** 把一个功能拆到两个包中,而宿主接口、前端订阅方和状态表同步演进;放宽 external 规则后,前端包可以自己订阅该流。 +- **在 `ctx.remote.$stream` 之上重写快照协议:** 会在功能包中复制 Gateway 负责的基线与重连逻辑。 +- **在前端包中导入 `RemoteStreamCarrierError`:** 功能包会为一次重试判断依赖 Gateway 的 class 身份;稳定的 code 能表达这一判断,而不依赖跨独立打包模块的 class 身份。 +- **宿主面放在共享基础 bundle:** 没有 Web 前端的 profile 会运行无人读取的阅读服务,宿主面也会与前端面从不同的 bundle 加载。 +- **前端内存或本地存储:** 无法为浏览器和 Desktop 前端提供共同的权威状态,也无法收集所有前端离线期间的完成提醒。 +- **宿主持久化记录:** 能够让提醒跨宿主重启保留,但需要单独设计会话检查点、存储域归属、后端关闭及写入失败的生命周期。本实现将状态限制在内存,持久化另行实现。 +- **在会话日志中记录阅读事件:** 会把使用者意图混入模型历史,并使只需元信息的操作也要加载冷会话历史。 +- **按版本条件写入:** 可防止延迟的主动操作覆盖较新的手动意图,但需要冲突响应、版本维护和请求响应的状态合并。会话提醒接受宿主处理顺序,仍保留阅读位置以防误读新完成内容。 +- **消息 ID 游标:** 只能定位消息,不能直接排序已完成轮次,也不能覆盖未产生新助手消息的失败。已有完成轮次直接对应本功能的进度单位。 + +## 结果 + +宿主服务运行期间,刷新浏览器或临时断线会保留提醒。宿主重启或插件重载会重置全部阅读记录,并把已有历史视为已读;重启前失败的轮次不留下结果,因此把该会话标为未读时显示普通提醒。不含 Web bundle 的 profile 不运行阅读服务。没有阅读状态文件、存储域依赖、检查点写入或跨进程同步保证。会话从内存卸载后,其提醒保留到服务停止;回收记录需要会话删除生命周期。 + +并发主动操作以宿主最后处理的操作为准;进入视图的确认可能清除处理前到达的另一条手动标记。验证覆盖双订阅、单调阅读位置与自动确认保留手动标记、手动标记后的首次完成、访问权限变化后的新基线、元信息查询期间关闭、服务重载、不依赖会话刷盘,以及结束轮次的失败标记。前端测试覆盖阅读流的基线替换与终态失败、正文延迟、加载期间的手动标记,以及主视图切换时清除手动提醒、窗口聚焦或更换 binding 时不清除。Gateway 测试覆盖带 carrier code 的普通错误会重连、不带 code 时终止。启用持久化前,需单独验证重启恢复、崩溃一致性、存储提供方关闭顺序和跨进程写入。当前主视图保留信号不能区分所有设置或辅助面板;该可见性细化仍属于通知工作的范围。 diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index 67cf503d7a..4312455bed 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -17,7 +17,7 @@ Convert foreign failures where the dependency is owned. Node errno, SDK, protoco ## Tool failures -The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: +The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body or a `tools/execute` wrapper throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: - Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`. - Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`. diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 3ac6e18bfe..869eda7fdc 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -31,7 +31,7 @@ const RECEIPT_LOCALES = [ }, { language: 'Chinese', code: 'zh', browserLocale: 'zh-CN', connect: connectFreshWorkspaceZh, - modelButton: /^选择模型/u, toggle: '启用智能体团队协作', title: '智能体团队协作', + modelButton: /^选择模型/u, toggle: '开启智能体团队协作', title: '智能体团队协作', enabled: '已开启', disabled: '已停用', suggestions: '触发候选建议', commandLabel: '智能体团队协作', failure: '执行失败:Use /team on or /team off.', @@ -40,6 +40,19 @@ const RECEIPT_LOCALES = [ type ReceiptLocale = typeof RECEIPT_LOCALES[number] +async function openTeamSettings(page: Page, chinese = false): Promise { + const trigger = page.getByRole('button', { name: chinese ? /^选择模型/u : /^Select model/u }) + await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('true') + await page.getByRole('menuitem', { name: chinese ? /^智能体团队协作 /u : /^Agent teamwork /u }).click() +} + +async function closeModelMenu(page: Page): Promise { + const trigger = page.getByRole('button', { name: /^(Select model|选择模型)/u }) + if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click() + await expect.poll(() => trigger.getAttribute('aria-expanded')).toBe('false') +} + async function seedTeamConversation(page: Page, scaffold: WebScaffold): Promise { const agent = scaffold.ctx.agents.list()[0] if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') @@ -115,81 +128,144 @@ describe('web e2e: agent teamwork panel', () => { await scaffold?.close() }) - it('explains agent teamwork on hover and focus without changing the Session selection', async () => { + it('shows the explanation and switch only on the detail pane and returns to the summary', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) - await page.getByRole('button', { name: /^Select model/u }).click() - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const tooltip = page.getByRole('tooltip') - await info.hover() - await tooltip.waitFor({ state: 'visible' }) - await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), await captureStableAria(page, '[role="tooltip"]', scaffold.workspaceCwd), MODE) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.getByRole('button', { name: /^Select model/u }).hover() - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Shift') - await info.focus() - await tooltip.waitFor({ state: 'visible' }) - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - expect(await toggle.isVisible()).toBe(true) - await info.click() - await tooltip.waitFor({ state: 'visible' }) - expect(await info.getAttribute('aria-describedby')).toBe(await tooltip.getAttribute('id')) - expect(await toggle.getAttribute('aria-checked')).toBe('false') - await page.keyboard.press('Escape') - await tooltip.waitFor({ state: 'hidden' }) - await page.keyboard.press('Escape') - expect(tripwire.pageErrors).toEqual([]) + const trigger = page.getByRole('button', { name: /^Select model/u }) + await trigger.click() + const menu = page.locator('[data-model-menu]') + const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) + await summary.waitFor() + const stateColor = await summary.getByText('Off', { exact: true }).evaluate(element => getComputedStyle(element).color) + const modelColor = await menu.getByRole('menuitem', { name: 'Model DeepSeek-V4-Flash', exact: true }) + .getByText('DeepSeek-V4-Flash', { exact: true }).evaluate(element => getComputedStyle(element).color) + expect(stateColor).toBe(modelColor) + const inspectArrow = (element: HTMLElement | SVGElement) => { + const { left, right, width, height } = element.getBoundingClientRect() + return { left, right, width, height, color: getComputedStyle(element).color, glyph: element.innerHTML } + } + const peerArrow = menu.getByRole('menuitem', { name: 'Model DeepSeek-V4-Flash', exact: true }).locator('svg').last() + expect(await summary.locator('svg').evaluate(inspectArrow)).toEqual(await peerArrow.evaluate(inspectArrow)) + expect(await menu.getByRole('switch').count()).toBe(0) + expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) + const rootSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) + const original = await menu.elementHandle() + if (original === null) throw new Error('Model menu is missing') + try { + await summary.click() + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.waitFor() + expect(await original.evaluate(element => element.isConnected)).toBe(true) + await menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await page.mouse.move(0, 0) + await toggle.press('ArrowDown') + expect(await toggle.evaluate(element => ({ + rowBackground: getComputedStyle(element.parentElement!).backgroundColor, + focusVisible: element.matches(':focus-visible'), + outline: getComputedStyle(element).outlineStyle, + descriptionGap: element.parentElement!.nextElementSibling!.getBoundingClientRect().top + - element.parentElement!.getBoundingClientRect().bottom, + }))).toEqual({ rowBackground: 'rgba(0, 0, 0, 0)', focusVisible: true, outline: 'solid', descriptionGap: 0 }) + const settingsSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), + `## Root\n\n${rootSnapshot}\n\n## Team settings\n\n${settingsSnapshot}`, MODE) + await page.keyboard.press('Escape') + await expect.poll(() => summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(await menu.getByRole('switch').count()).toBe(0) + await summary.press('Enter') + await toggle.waitFor() + await page.keyboard.press('Escape') + await summary.waitFor() + expect(await summary.evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentTeams.isEnabled(scaffold.ctx.agents.list()[0]!)).toBe(false) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await original.dispose() + } }) - it('toggles from the row label and empty space while keeping the information button independent', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-team-row')) - await page.getByRole('button', { name: /^Select model/u }).click() - const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) - const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) - const label = page.getByText('Enable agent teamwork', { exact: true }) - const labelBounds = await label.boundingBox() - if (labelBounds === null) throw new Error('Team label is not visible') - const labelPoint = { x: labelBounds.x + labelBounds.width / 2, y: labelBounds.y + labelBounds.height / 2 } - await page.mouse.move(labelPoint.x, labelPoint.y) - expect(await toggle.evaluate((element) => { - const row = element.parentElement! - return getComputedStyle(row).backgroundColor !== 'rgba(0, 0, 0, 0)' - })).toBe(true) - await page.mouse.click(labelPoint.x, labelPoint.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await info.click() - await page.getByRole('tooltip').waitFor({ state: 'visible' }) - expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') - const gap = await toggle.evaluate((element) => { - const control = element.getBoundingClientRect() - const help = element.parentElement!.querySelector('button:not([role="switch"])')!.getBoundingClientRect() - return { x: (help.right + control.left) / 2, y: control.top + control.height / 2 } - }) - await page.mouse.click(gap.x, gap.y) - await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') - expect(await page.getByRole('tooltip').count()).toBe(0) - await page.keyboard.press('Escape') - expect(tripwire.pageErrors).toEqual([]) + it('aligns settings with the root menu and keeps explanatory text noninteractive in wide and narrow viewports', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-settings-page')) + const viewport = page.viewportSize()! + try { + await openTeamSettings(page) + const menu = page.locator('[data-model-menu]') + const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + const description = menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }) + await description.click() + expect(await menu.isVisible()).toBe(true) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + for (const size of [viewport, { width: 390, height: 700 }]) { + await page.setViewportSize(size) + await page.keyboard.press('Escape') + const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) + await summary.waitFor() + const rootBounds = await menu.evaluate((element) => { + const { width, left, right } = element.getBoundingClientRect() + return { width, left, right } + }) + expect(rootBounds.width).toBe(240) + await summary.click() + await toggle.waitFor() + await expect.poll(() => menu.evaluate((element) => { + const { width, left, right } = element.getBoundingClientRect() + return { width, left, right } + })).toEqual(rootBounds) + await expect.poll(() => menu.evaluate((element) => { + const bounds = element.getBoundingClientRect() + return bounds.left >= 12 && bounds.right <= innerWidth - 12 + && bounds.top >= 12 && bounds.bottom <= innerHeight - 12 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + expect(await description.evaluate((element) => { + const bounds = element.getBoundingClientRect() + const style = getComputedStyle(element) + return bounds.height > Number.parseFloat(style.lineHeight) + && element.scrollHeight <= element.clientHeight && style.textOverflow !== 'ellipsis' + })).toBe(true) + } + const labelBounds = await menu.getByText('Enable agent teamwork', { exact: true }).boundingBox() + if (labelBounds === null) throw new Error('Team label is not visible') + await page.mouse.click(labelBounds.x + labelBounds.width / 2, labelBounds.y + labelBounds.height / 2) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await expect.poll(() => toggle.isEnabled()).toBe(true) + await toggle.press('Escape') + await menu.getByRole('menuitem', { name: 'Agent teamwork On', exact: true }).click() + const gap = await toggle.evaluate((element) => { + const control = element.getBoundingClientRect() + const label = element.parentElement!.querySelector('span')!.getBoundingClientRect() + return { x: (label.right + control.left) / 2, y: control.top + control.height / 2 } + }) + await page.mouse.click(gap.x, gap.y) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await closeModelMenu(page) + await page.setViewportSize(viewport) + } }) it('defaults off and saves a Session selection in the model menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode')) expect(await page.locator('[data-subagent-action]').count()).toBe(0) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.waitFor() expect(await toggle.getAttribute('aria-checked')).toBe('false') await toggle.focus() - await page.keyboard.press('ArrowUp') - expect(await toggle.evaluate(element => element === document.activeElement)).toBe(false) - await page.keyboard.press('ArrowDown') + await page.keyboard.press('Shift+Tab') + expect(await page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + expect(await toggle.count()).toBe(0) + await openTeamSettings(page) expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Space') await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) const agent = scaffold.ctx.agents.list()[0]! expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) @@ -199,10 +275,10 @@ describe('web e2e: agent teamwork panel', () => { await other.dispose() const beforeReload = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) expect(await page.locator('[data-subagent-action]').count()).toBe(0) expect(await toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) acknowledgeReloadConnectionLoss(tripwire, beforeReload) }, 60_000) @@ -211,11 +287,11 @@ describe('web e2e: agent teamwork panel', () => { const input = page.locator('[data-composer-input]').first() const agent = scaffold.ctx.agents.list()[0]! for (const enabled of [false, true]) { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) - await page.keyboard.press('Escape') + await closeModelMenu(page) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) await expect.poll(() => input.textContent()).toBe('') await page.getByRole('button', { name: 'Account menu', exact: true }).focus() @@ -435,22 +511,22 @@ describe('web e2e: agent teamwork panel', () => { }, 60_000) it('hides the board while disabled and restores its tasks when re-enabled', async () => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') expect(await page.locator('[data-subagent-action]').count()).toBe(1) - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click() await page.getByRole('treeitem', { name: /Researcher/u }).waitFor() expect(await page.locator('[data-team-panel]').count()).toBe(0) expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360) expect(await page.locator('[data-subagent-section-header]').count()).toBe(0) await page.keyboard.press('Escape') - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.keyboard.press('Escape') + await closeModelMenu(page) await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click() await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor() await page.keyboard.press('Escape') @@ -785,14 +861,15 @@ describe('web e2e: agent teamwork panel', () => { agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) const openConfirmation = async (): Promise => { - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }).waitFor() } await openConfirmation() const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) await assertWarningDialogLayout(dialog) - expect(await page.getByRole('menu', { name: 'Model and reasoning effort', exact: true }).count()).toBe(0) + expect(await page.getByRole('group', { name: 'Agent teamwork', exact: true }).count()).toBe(0) + expect(await page.getByRole('button', { name: /^Select model/u }).getAttribute('aria-expanded')).toBe('false') expect(await dialog.getByRole('checkbox').count()).toBe(0) expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'disable-confirmation.expected.md'), @@ -811,11 +888,11 @@ describe('web e2e: agent teamwork panel', () => { await dialog.waitFor({ state: 'hidden' }) await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) - await page.getByRole('button', { name: /^Select model/u }).click() + await openTeamSettings(page) await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) expect(await dialog.count()).toBe(0) - await page.keyboard.press('Escape') + await closeModelMenu(page) expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([]) expect(tripwire.pageErrors).toEqual([]) }) @@ -892,14 +969,14 @@ it.each(RECEIPT_LOCALES)('toggles teamwork in $language without command records await expect.poll(captureLayout).toEqual(recordedLayout) } for (const enabled of [true, false]) { - await page.getByRole('button', { name: locale.modelButton }).click() + await openTeamSettings(page, locale.code === 'zh') const toggle = page.getByRole('switch', { name: locale.toggle, exact: true }) await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) expect(commandEvents()).toEqual([]) - await page.keyboard.press('Escape') + await closeModelMenu(page) await assertChatUnchanged() } await scaffold.ctx.sessions.flush(agent.session) @@ -999,21 +1076,27 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) const agent = scaffold.ctx.agents.list()[0] if (agent === undefined) throw new Error('Chinese Team fixture has no Agent') + const trigger = page.getByRole('button', { name: /^选择模型/u }) + await trigger.click() + await page.getByRole('menuitem', { name: '智能体团队协作 关闭', exact: true }).waitFor() + await closeModelMenu(page) await scaffold.ctx.agentTeams.setEnabled(agent, true) const selection = agent.model.current() if (selection === undefined) throw new Error('Chinese Team fixture has no model') agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) await scaffold.ctx.sessions.flush(agent.session) - await page.getByRole('button', { name: /^选择模型/u }).click() - const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await trigger.click() + await page.getByRole('menuitem', { name: '智能体团队协作 开启', exact: true }).click() + const toggle = page.getByRole('switch', { name: '开启智能体团队协作', exact: true }) await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') - await page.getByRole('button', { name: '关于智能体团队协作', exact: true }).waitFor() + await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() + expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) - const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const menu = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) await toggle.click() - const dialog = page.getByRole('dialog', { name: '确认停用智能体团队协作?', exact: true }) + const dialog = page.getByRole('dialog', { name: '确认关闭智能体团队协作?', exact: true }) await dialog.waitFor() - await dialog.getByText('对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', { exact: true }).waitFor() + await dialog.getByText('对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。', { exact: true }).waitFor() await assertWarningDialogLayout(dialog) const confirmation = await captureStableAria(page, '[aria-modal="true"]', scaffold.workspaceCwd) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'collaboration.zh.expected.md'), diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 72a389f9c8..21495dc936 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -196,7 +196,7 @@ it('keeps ordered legacy Session menu rows before Archive and removes them with await row.hover() await trigger.click() await menu.waitFor() - const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Copy Session ID', 'Archive session'] + const remainingNames = ['Pin session', 'Rename', 'Mark as unread', 'Fork session', 'Copy Session ID', 'Archive session'] const remainingItems = menu.getByRole('menuitem') expect(await remainingItems.count()).toBe(remainingNames.length) for (const [index, name] of remainingNames.entries()) { diff --git a/apps/web/tests/context-menus.e2e.ts b/apps/web/tests/context-menus.e2e.ts index 79fe82f2f1..b5035f449a 100644 --- a/apps/web/tests/context-menus.e2e.ts +++ b/apps/web/tests/context-menus.e2e.ts @@ -75,7 +75,9 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s', const menu = page.getByRole('menu') await menu.getByRole('menuitem', { name: /Copy.*[Ii][Dd]/ }).waitFor() const names = await menuLabels(menu) - expect(names.slice(0, 4)).toEqual(['Pin session', 'Rename', 'Fork session', 'Copy Session ID']) + expect(names.slice(0, 5)).toEqual([ + 'Pin session', 'Rename', 'Mark as unread', 'Fork session', 'Copy Session ID', + ]) expect(names).not.toContain('Open in') expect(names.at(-1)).toBe('Archive session') expect(await menu.getByRole('menuitem').evaluateAll(rows => rows.every(row => row.querySelector('svg[data-icon]')))).toBe(true) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index a38d961b68..b750a3ff58 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -142,7 +142,13 @@ describe('web e2e: the composer model switch is the default for later sessions', badge.textContent = ' — Provider identification badge with a long channel name' node.appendChild(badge) }) - await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + if (pane === 'root') { + expect(original!.width).toBe(240) + await expect.poll(async () => (await surface.boundingBox())!.width).toBe(240) + await expect.poll(async () => (await surface.boundingBox())!.x).toBeCloseTo(original!.x) + } else { + await expect.poll(async () => (await surface.boundingBox())!.width).toBeGreaterThan(original!.width + 50) + } await expect.poll(async () => { const box = (await surface.boundingBox())! return box.x >= 12 && box.x + box.width <= 378 diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md index 93f241e0fc..19356fc99e 100644 --- a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/context-menus/session.txt b/apps/web/tests/expected/context-menus/session.txt index ac477e2304..7036ac96e9 100644 --- a/apps/web/tests/expected/context-menus/session.txt +++ b/apps/web/tests/expected/context-menus/session.txt @@ -1,5 +1,6 @@ Pin session Rename +Mark as unread Fork session Copy Session ID Archive session diff --git a/apps/web/tests/expected/menu-material/session-menu.expected.md b/apps/web/tests/expected/menu-material/session-menu.expected.md index c7c535b9e4..0bfe2df5d3 100644 --- a/apps/web/tests/expected/menu-material/session-menu.expected.md +++ b/apps/web/tests/expected/menu-material/session-menu.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/session-reading/failed-unread.expected.md b/apps/web/tests/expected/session-reading/failed-unread.expected.md new file mode 100644 index 0000000000..7422403748 --- /dev/null +++ b/apps/web/tests/expected/session-reading/failed-unread.expected.md @@ -0,0 +1 @@ +- treeitem "Unread Untitled {{age}}" diff --git a/apps/web/tests/expected/session-reading/unread-menu.expected.md b/apps/web/tests/expected/session-reading/unread-menu.expected.md new file mode 100644 index 0000000000..14b42ba2d1 --- /dev/null +++ b/apps/web/tests/expected/session-reading/unread-menu.expected.md @@ -0,0 +1,11 @@ +- menu: + - menuitem "Pin session" + - menuitem "Rename" + - menuitem "Mark as read" + - menuitem "Fork session" + - separator + - menuitem "Copy Session ID" + - separator + - menuitem "Archive session" +Row state: done +Title font weight: 400 diff --git a/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md b/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md index 180988c7c7..68be7e2bb6 100644 --- a/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/macos-defaults.expected.md @@ -54,6 +54,9 @@ - listitem: - button "Edit shortcut for Close current page or window" - text: Close current page or window ⌥ ⌘ W + - listitem: + - button "Edit shortcut for Toggle read/unread" + - text: Toggle read/unread ⇧ ⌘ U - region "Message input": - heading "Message input" [level=3] - list: diff --git a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md index f3836b2d55..7c3e33a81d 100644 --- a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md @@ -1,6 +1,7 @@ - menu: - menuitem "Pin session" - menuitem "Rename" + - menuitem "Mark as unread" - menuitem "Fork session" - separator - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/shortcuts/en-US.expected.md b/apps/web/tests/expected/shortcuts/en-US.expected.md index 9cbb7a0562..2360979af0 100644 --- a/apps/web/tests/expected/shortcuts/en-US.expected.md +++ b/apps/web/tests/expected/shortcuts/en-US.expected.md @@ -54,6 +54,9 @@ - listitem: - button "Edit shortcut for Close current page or window" - text: Close current page or window Ctrl + Alt + W + - listitem: + - button "Edit shortcut for Toggle read/unread" + - text: Toggle read/unread Ctrl + Shift + U - region "Message input": - heading "Message input" [level=3] - list: diff --git a/apps/web/tests/expected/shortcuts/zh-CN.expected.md b/apps/web/tests/expected/shortcuts/zh-CN.expected.md index 157d94b120..149ac1ff0b 100644 --- a/apps/web/tests/expected/shortcuts/zh-CN.expected.md +++ b/apps/web/tests/expected/shortcuts/zh-CN.expected.md @@ -54,6 +54,9 @@ - listitem: - button "修改关闭当前页面/窗口快捷键" - text: 关闭当前页面/窗口 ⌥ ⌘ W + - listitem: + - button "修改切换已读/未读快捷键" + - text: 切换已读/未读 ⇧ ⌘ U - region "消息输入": - heading "消息输入" [level=3] - list: diff --git a/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md b/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md index e17e9cdfa1..bf3bfab624 100644 --- a/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md +++ b/apps/web/tests/expected/sidebar-subagent-activity/owner-running.expected.md @@ -1,4 +1,4 @@ - tree "Sessions": - treeitem "workspace" [expanded] - treeitem "New Session" [selected] - - treeitem "1 subagent running Delegate a background job. now" + - treeitem "1 subagent running Unread Delegate a background job. now" diff --git a/apps/web/tests/github-ready-review.e2e.ts b/apps/web/tests/github-ready-review.e2e.ts index 9c9ae295e9..96bfa66fe8 100644 --- a/apps/web/tests/github-ready-review.e2e.ts +++ b/apps/web/tests/github-ready-review.e2e.ts @@ -195,8 +195,11 @@ describe.skipIf(MODE === 'record')('web e2e: GitHub ready-for-review', () => { const workspaceRow = page.locator('[role="treeitem"]').first() if (await workspaceRow.getAttribute('aria-expanded') !== 'true') await workspaceRow.click() + await page.bringToFront() await page.getByText(TITLE, { exact: true }).click() await page.getByText(REPLY, { exact: true }).waitFor({ state: 'visible', timeout: 30_000 }) + const reviewRow = page.locator('[role="treeitem"]').filter({ has: page.getByText(TITLE, { exact: true }) }) + await expect.poll(() => reviewRow.getByText('Unread', { exact: true }).count()).toBe(0) const tree = await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd) const conversation = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd) await compareOrRefreshGolden(EXPECTED, `${tree}\n\n---\n\n${conversation}`, MODE) diff --git a/apps/web/tests/plan-review.e2e.ts b/apps/web/tests/plan-review.e2e.ts index e59c1239ba..d2a46e5c8a 100644 --- a/apps/web/tests/plan-review.e2e.ts +++ b/apps/web/tests/plan-review.e2e.ts @@ -149,7 +149,7 @@ describe('web e2e: plan review takeover round trip', () => { await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) // Card gone; regular input restored. expect(await page.locator('[data-plan-review-key]').count()).toBe(0) - expect(await selectedRow.locator('[data-state="warning"]').count()).toBe(0) + await expect.poll(() => selectedRow.getByText('Plan awaiting review', { exact: true }).count()).toBe(0) await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true) // Completed plans join the final artifacts after the Turn's closing reply. await planCard.waitFor({ state: 'visible' }) @@ -245,7 +245,7 @@ describe('web e2e: plan review takeover round trip', () => { }) const outcome = asked.then(value => value, (error: unknown) => ({ error })) try { - const row = page.locator('[role="treeitem"]').filter({ has: page.locator('[data-state="warning"]') }).first() + const row = page.locator(`[data-row-key="session:${reviewedSession}"]`) await row.waitFor({ timeout: 10_000 }) await row.click() const card = page.locator('[data-plan-review-key]') @@ -325,7 +325,7 @@ describe.skipIf(MODE === 'record')('web e2e: pending plan review across Sidebar }) const outcome = asked.then(value => value, (error: unknown) => ({ error })) try { - await row(session).locator('[data-state="warning"]').waitFor({ timeout: 10_000 }) + await row(session).getByText('Plan awaiting review', { exact: true }).waitFor({ timeout: 10_000 }) await scenario() } finally { controller.abort() diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 0c355a4388..63e9e5427c 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -1191,7 +1191,8 @@ describe('web e2e: plugin manager', () => { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) await teamPage.getByRole('button', { name: /^选择模型/u }).click() - const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await teamPage.getByRole('menuitem', { name: '智能体团队协作 关闭', exact: true }).click() + const mode = teamPage.getByRole('switch', { name: '开启智能体团队协作', exact: true }) await mode.waitFor() expect(await mode.getAttribute('aria-checked')).toBe('false') await mode.click() diff --git a/apps/web/tests/question-composer.e2e.ts b/apps/web/tests/question-composer.e2e.ts index afe0f3cb39..8403ce534d 100644 --- a/apps/web/tests/question-composer.e2e.ts +++ b/apps/web/tests/question-composer.e2e.ts @@ -545,7 +545,7 @@ describe('web e2e: resident question composer round trip', () => { await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) // Composer gone; regular input restored. expect(await page.locator('[data-question-key]').count()).toBe(0) - expect(await selectedRow.locator('[data-state="warning"]').count()).toBe(0) + await expect.poll(() => selectedRow.getByText('Waiting for answer', { exact: true }).count()).toBe(0) await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true) const reply = page.locator('[data-question-reply]') await reply.waitFor({ state: 'visible', timeout: 15_000 }) diff --git a/apps/web/tests/session-reading.e2e.ts b/apps/web/tests/session-reading.e2e.ts new file mode 100644 index 0000000000..1edf0c8868 --- /dev/null +++ b/apps/web/tests/session-reading.e2e.ts @@ -0,0 +1,179 @@ +/** Reading marks through the shipped Web profile, real Session history, and two Clients. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, expect, it, onTestFailed } from 'vitest' +import { + acknowledgeReloadConnectionLoss, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) +const EXPECTED = fileURLToPath(new URL('./expected/session-reading/unread-menu.expected.md', import.meta.url)) +const FAILED_EXPECTED = fileURLToPath(new URL('./expected/session-reading/failed-unread.expected.md', import.meta.url)) +let scaffold: WebScaffold +let browser: Browser +let first: Page +let second: Page +let sessionId: string +let failedSessionId: string + +beforeAll(async () => { + scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + const history = await readFile(SEED, 'utf8') + sessionId = await seedSession(scaffold, history, 'session-reading-web') + const failedHistory = `${history.trimEnd()}\n${JSON.stringify({ type: 'turn/start', data: { turn: 2 } })}\n${JSON.stringify({ + type: 'turn/end', data: { turn: 2, reason: { kind: 'error', error: { code: 'UNKNOWN', message: 'Request failed' } } }, + })}\n` + failedSessionId = await seedSession(scaffold, failedHistory, 'session-reading-failed') + browser = await chromium.launch() + first = await newEnglishPage(browser) + second = await newEnglishPage(browser) + for (const [page, platform] of [[first, 'MacIntel'], [second, 'Win32']] as const) { + await page.addInitScript((value) => { Object.defineProperty(navigator, 'platform', { value }) }, platform) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const group = page.getByText('Ungrouped', { exact: true }).locator('xpath=ancestor::*[@role="treeitem"][1]') + await group.waitFor({ timeout: 30_000 }) + if (await group.getAttribute('aria-expanded') !== 'true') await group.click() + await page.locator(`[data-row-key="session:${sessionId}"]`).waitFor({ timeout: 10_000 }) + } +}, 120_000) + +afterAll(async () => { + await browser?.close() + await scaffold?.close() +}) + +async function mark(page: Page, name: 'Mark as read' | 'Mark as unread', id = sessionId): Promise { + await page.bringToFront() + const row = page.locator(`[data-row-key="session:${id}"]`) + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + await page.getByRole('menuitem', { name, exact: true }).click() +} + +async function unread(page: Page): Promise { + return page.locator(`[data-row-key="session:${sessionId}"]`).getByText('Unread', { exact: true }).count() +} + +it('synchronizes manual marks, retains them across reload, and acknowledges only on a new view entry', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading')) + const left = watchConsole(first) + const right = watchConsole(second) + const row = first.locator(`[data-row-key="session:${sessionId}"]`) + const title = row.locator(':scope > span').nth(1) + const initialWeight = await title.evaluate(element => getComputedStyle(element).fontWeight) + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + expect(await row.locator('[data-state="done"]').count()).toBe(1) + expect(await title.evaluate(element => getComputedStyle(element).fontWeight)).toBe(initialWeight) + expect(await first.getByRole('alert').count()).toBe(0) + + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + expect(await first.getByRole('menuitem', { name: 'Mark as read', exact: true }).getAttribute('aria-keyshortcuts')).toBe('Shift+Meta+U') + const menuSnapshot = await captureStableAria(first, '[role="menu"]', scaffold.workspaceCwd) + const rowState = await row.locator('[data-state]').getAttribute('data-state') + const titleWeight = await title.evaluate(element => getComputedStyle(element).fontWeight) + await compareOrRefreshGolden(EXPECTED, `${menuSnapshot}\nRow state: ${rowState}\nTitle font weight: ${titleWeight}`, webSnapshotMode()) + await first.keyboard.press('Escape') + + const warningStart = right.warnings.length + await second.reload({ waitUntil: 'load' }) + await expect.poll(() => unread(second)).toBe(1) + acknowledgeReloadConnectionLoss(right, warningStart) + + await first.bringToFront() + await row.click() + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + await first.bringToFront() + await first.keyboard.press('Meta+Shift+U') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await first.keyboard.press('Meta+Shift+U') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + await second.bringToFront() + await second.locator(`[data-row-key="session:${sessionId}"]`).click() + await second.keyboard.press('Control+Shift+U') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await second.keyboard.press('Control+Shift+U') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + expect(await first.getByRole('alert').count()).toBe(0) + expect(await second.getByRole('alert').count()).toBe(0) + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + await mark(second, 'Mark as read') + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) + expect(left.pageErrors).toEqual([]) + expect(right.pageErrors).toEqual([]) + expect(left.warnings).toEqual([]) + expect(right.warnings).toEqual([]) +}) + +it('shares a manual reminder on restored history without claiming its outcome', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading-restored')) + const row = (page: Page) => page.locator(`[data-row-key="session:${failedSessionId}"]`) + const errors = (page: Page) => row(page).locator('[data-state="error"]').count() + const done = (page: Page) => row(page).locator('[data-state="done"]').count() + await first.bringToFront() + await mark(first, 'Mark as unread', failedSessionId) + await expect.poll(() => done(first)).toBe(1) + await expect.poll(() => done(second)).toBe(1) + expect(await errors(first)).toBe(0) + expect(await row(first).getByText('Unread', { exact: true }).count()).toBe(1) + await compareOrRefreshGolden(FAILED_EXPECTED, await captureStableAria( + first, `[data-row-key="session:${failedSessionId}"]`, scaffold.workspaceCwd, { normalizeAge: true }, + ), webSnapshotMode()) + const consoleState = watchConsole(second) + const warningStart = consoleState.warnings.length + await second.reload({ waitUntil: 'load' }) + await expect.poll(() => done(second)).toBe(1) + acknowledgeReloadConnectionLoss(consoleState, warningStart) + await mark(first, 'Mark as read', failedSessionId) + await expect.poll(() => done(first)).toBe(0) + await expect.poll(() => done(second)).toBe(0) + await mark(first, 'Mark as unread', failedSessionId) + await expect.poll(() => done(second)).toBe(1) + expect(consoleState.pageErrors).toEqual([]) + expect(consoleState.warnings).toEqual([]) +}) + +it('preserves manual unread on window focus and clears it after the main view leaves and returns', async () => { + onTestFailed(() => saveFailureShot(first, 'session-reading-entry')) + const row = first.locator(`[data-row-key="session:${sessionId}"]`) + const content = (id: string) => first.locator(`[data-conversation-content][data-conversation-session="${id}"]`) + await first.bringToFront() + await row.click() + await content(sessionId).waitFor() + await mark(first, 'Mark as unread') + await expect.poll(() => unread(first)).toBe(1) + await expect.poll(() => unread(second)).toBe(1) + + await second.bringToFront() + await first.bringToFront() + await expect.poll(() => first.evaluate(() => document.hasFocus())).toBe(true) + await row.hover() + await row.getByRole('button', { name: /^Session actions for / }).click() + await first.getByRole('menuitem', { name: 'Mark as read', exact: true }).waitFor() + expect(await unread(first)).toBe(1) + expect(await unread(second)).toBe(1) + await first.keyboard.press('Escape') + + await first.locator(`[data-row-key="session:${failedSessionId}"]`).click() + await content(failedSessionId).waitFor() + expect(await unread(first)).toBe(1) + await row.click() + await expect.poll(() => unread(first)).toBe(0) + await expect.poll(() => unread(second)).toBe(0) +}) diff --git a/apps/web/tests/sidebar-subagent-activity.e2e.ts b/apps/web/tests/sidebar-subagent-activity.e2e.ts index c4a923f1a4..bbe961d7bc 100644 --- a/apps/web/tests/sidebar-subagent-activity.e2e.ts +++ b/apps/web/tests/sidebar-subagent-activity.e2e.ts @@ -136,7 +136,7 @@ describe('web e2e: sidebar subagent activity', () => { it('pins a running descendant on its visible idle owner row', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-subagent-activity')) const sidebar = page.getByRole('tree', { name: 'Sessions' }) - const ownerRow = sidebar.getByRole('treeitem', { name: /1 subagent running Delegate a background job/ }) + const ownerRow = sidebar.getByRole('treeitem', { name: /1 subagent running.*Delegate a background job/ }) await ownerRow.waitFor({ timeout: 10_000 }) expect(parentHandle.agent.status).toBe('idle') await compareOrRefreshGolden( diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index 07a6ac96dc..ceb1d1097a 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,17 +1,16 @@ ## Menu -- menu "模型与推理等级": - - menuitem "模型 DeepSeek-V4-Flash" - - text: 启用智能体团队协作 - - button "关于智能体团队协作" - - switch "启用智能体团队协作" [checked] +- group "智能体团队协作": + - text: 开启智能体团队协作 + - switch "开启智能体团队协作" [checked] + - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 ## Confirmation -- dialog "确认停用智能体团队协作?": - - heading "确认停用智能体团队协作?" [level=2] +- dialog "确认关闭智能体团队协作?": + - heading "确认关闭智能体团队协作?" [level=2] - button "关闭" - - paragraph: 对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。 - - paragraph: 停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。 + - paragraph: 对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。 + - paragraph: 关闭后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。 - button "取消" - - button "确认停用" + - button "确认关闭" diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md index 5e675607a5..23af3abb18 100644 --- a/apps/web/tests/snapshots/agent-team-panel/info.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -1 +1,12 @@ -- tooltip "Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs." +## Root + +- menu "Model and reasoning effort": + - menuitem "Model DeepSeek-V4-Flash" + - menuitem "Agent teamwork Off" + +## Team settings + +- group "Agent teamwork": + - text: Enable agent teamwork + - switch "Enable agent teamwork" + - paragraph: Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs. diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 491b459b0d..a652e166b1 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -32,6 +32,7 @@ "tests/additional-locales.e2e.ts", "tests/rich-text-quotes.e2e.ts", "tests/hover-input.e2e.ts", + "tests/session-reading.e2e.ts", "tests/collapse-timing.e2e.ts", "tests/notice-wake-tail.e2e.ts", "tests/fold-blank-matrix.e2e.ts", diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 818f40b452..70e40c2b68 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -56,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 1,100; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index a226a4be68..a7c01f3ef1 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 9f66fbb344cf1074 - zh: 7f985c73b1e6a34e + en: 78778294644e7b42 + zh: 2985cca0ffc69256 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index ee9d7bb82c..943631f1b0 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -105,6 +105,8 @@ flowchart LR pkg_message_feedback["message-feedback"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] svc_speechController["ctx.speechController
Experimental transcription Remote"] + pkg_client_ui_session_status["client-ui-session-status"] + svc_sessionStatus["ctx.sessionStatus
Host Session reading records"] svc_sessionController["ctx.sessionController
Host Session Remote controller"] svc_sessionFileReferences["ctx.sessionFileReferences
Session-addressed file-reference Remote adapter"] svc_sessionSkillCatalog["ctx.sessionSkillCatalog
Session-addressed skill Remote adapter"] @@ -346,6 +348,7 @@ flowchart LR pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe + pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -576,6 +579,7 @@ flowchart LR svc_sessionProjections --> pkg_tool_todo svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query + svc_sessionStatus --> pkg_client_ui_session_status svc_sessions --> pkg_agent svc_sessions --> pkg_agent_loop svc_sessions --> pkg_message_feedback @@ -684,6 +688,7 @@ flowchart LR | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent`](../packages/subagent/subagent), [`message-feedback`](../packages/feedback/message-feedback) | - | Owns append-only Session instances and emits the durable session event feed. | | `ctx.speechController` | `core` | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | - | - | Validates bounded browser audio before provider dispatch. | +| `ctx.sessionStatus` | `core` | [`client-ui-session-status`](../packages/client/ui-session-status) | - | [`client-ui-session-status`](../packages/client/ui-session-status) | - | Stores owner reading acknowledgements and manual unread marks outside Session history; its Client half follows committed changes over Remote, acknowledges loaded completions, and serves the Session status table. | | `ctx.sessionController` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Owns Session commands, cold reads, durable-event following, live control state, model catalogs, workspace opening, and Agent activation policy. | | `ctx.sessionFileReferences` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Delegates file-reference discovery through the Session Controller's established Agent lookup policy. | | `ctx.sessionSkillCatalog` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | Lists the Session composition's user-invocable skills without activating a cold Agent. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index f09e02313c..3f33e41e82 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -107,6 +107,8 @@ flowchart LR pkg_message_feedback["message-feedback"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] svc_speechController["ctx.speechController
Experimental transcription Remote"] + pkg_client_ui_session_status["client-ui-session-status"] + svc_sessionStatus["ctx.sessionStatus
Host Session reading records"] svc_sessionController["ctx.sessionController
Host Session Remote controller"] svc_sessionFileReferences["ctx.sessionFileReferences
Session-addressed file-reference Remote adapter"] svc_sessionSkillCatalog["ctx.sessionSkillCatalog
Session-addressed skill Remote adapter"] @@ -348,6 +350,7 @@ flowchart LR pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe + pkg_client_ui_session_status --> svc_sessionStatus pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -578,6 +581,7 @@ flowchart LR svc_sessionProjections --> pkg_tool_todo svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query + svc_sessionStatus --> pkg_client_ui_session_status svc_sessions --> pkg_agent svc_sessions --> pkg_agent_loop svc_sessions --> pkg_message_feedback @@ -686,6 +690,7 @@ flowchart LR | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 在摘要压缩前,通过可回放的单节点表层替换来改写过大的当前工具结果。 | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent`](../packages/subagent/subagent), [`message-feedback`](../packages/feedback/message-feedback) | - | 拥有仅追加的 Session 实例,并发出持久的会话事件流。 | | `ctx.speechController` | `core` | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | - | - | 在 Provider 调用前校验受限的浏览器音频。 | +| `ctx.sessionStatus` | `core` | [`client-ui-session-status`](../packages/client/ui-session-status) | - | [`client-ui-session-status`](../packages/client/ui-session-status) | - | 在会话历史之外保存使用者的阅读确认和手动未读标记;其前端部分通过 Remote 订阅已保存的更新、确认已加载的完成内容,并提供会话状态表。 | | `ctx.sessionController` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 负责 Session 命令、冷读取、持久事件跟随、实时控制状态、模型目录、workspace 打开与 Agent 激活策略。 | | `ctx.sessionFileReferences` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 通过 Session Controller 的既有 Agent lookup 策略委托文件引用发现。 | | `ctx.sessionSkillCatalog` | `core` | [`api-session-controller`](../packages/api/session-controller) | - | - | - | 在不激活冷 Agent 的前提下列出 Session 组合中允许用户调用的 skill。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 0125a08ad0..b8f6bd6c0d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1068,7 +1068,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:29`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:32`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1471,7 +1471,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1559,7 +1559,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1722,7 +1722,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1761,7 +1761,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4458,7 +4458,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -5089,7 +5089,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-session-status` | — | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5e08abfb15..f5ba2ed90b 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1070,7 +1070,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:29`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:32`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1473,7 +1473,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1561,7 +1561,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1724,7 +1724,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1763,7 +1763,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4460,7 +4460,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ @@ -5091,7 +5091,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-session-status` | — | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 95208e20dd..1e32371657 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -74,7 +74,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 2d44561b3f..675cd96348 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -76,7 +76,7 @@ | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/module-graph.md b/docs/module-graph.md index 622c918987..5acbcafb0c 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -497,7 +497,6 @@ flowchart TD pkg_app_boot --> pkg_launch_environment pkg_client_connection --> pkg_scope pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -971,11 +970,17 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1123,6 +1128,7 @@ flowchart TD pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions @@ -1267,6 +1273,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1274,6 +1281,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1286,6 +1294,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1431,6 +1440,7 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1447,6 +1457,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1703,7 +1714,6 @@ flowchart TD | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1834,8 +1844,9 @@ flowchart TD | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | @@ -1864,7 +1875,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | @@ -1885,9 +1896,9 @@ flowchart TD | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1906,11 +1917,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 652e14ca38..62aa9576c9 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -499,7 +499,6 @@ flowchart TD pkg_app_boot --> pkg_launch_environment pkg_client_connection --> pkg_scope pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -973,11 +972,17 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1125,6 +1130,7 @@ flowchart TD pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions @@ -1269,6 +1275,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1276,6 +1283,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1288,6 +1296,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1433,6 +1442,7 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1449,6 +1459,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1705,7 +1716,6 @@ flowchart TD | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1836,8 +1846,9 @@ flowchart TD | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | @@ -1866,7 +1877,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | @@ -1887,9 +1898,9 @@ flowchart TD | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1908,11 +1919,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/subsystems/liveshare.i18n.yaml b/docs/subsystems/liveshare.i18n.yaml index 608e65a930..40240826c1 100644 --- a/docs/subsystems/liveshare.i18n.yaml +++ b/docs/subsystems/liveshare.i18n.yaml @@ -18,8 +18,8 @@ en: 6b1346e73ab6eab9 zh: 888cfc08c6bc8522 /liveshare/constraining-a-shared-session: - en: 7607ed3f99df06cc - zh: 290c9b8ed064da00 + en: 7fbb31bbc29817d6 + zh: 0a9542ab1d48a9e6 /liveshare/viewer-states: en: b8bcb009e419fa25 zh: 31c4662b52e99ea7 diff --git a/docs/subsystems/liveshare.md b/docs/subsystems/liveshare.md index 604ef23c12..6705717b81 100644 --- a/docs/subsystems/liveshare.md +++ b/docs/subsystems/liveshare.md @@ -38,7 +38,7 @@ Child tool guards recheck the share’s current mode, expiry, viewer admission, Every share lets its viewer drive the *source* Session through the normal prompt path, and any share at either tier installs the bounded sandbox while it is active. `installSourceSessionAccess` registers a confined replacement for every view-surface tool the deployment ships in that Session's own scope, and bounded `edit` and `write` replacements whenever any share over the Session allows writing. The layer is mounted on the Session, but it confines only the turns a share viewer starts: `agent/pre-step` records, in Host memory, whether a turn's admitted input names a share viewer, and the guard and the replacements read that answer for every execution of that turn. A viewer-started turn runs those replacements and nothing else; a turn the owner starts keeps the Session's own tools, including `bash` and its unrestricted filesystem tools. The answer is decided when the turn is admitted and never written to the Session log; a restart recomputes it from the next admitted step. An owner's steering input inside a viewer's turn stays confined with it. Stopping every share over the Session disposes the layer, which restores the Session's own tools; narrowing the last write share to `view` re-installs the read-only layer. -The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. +The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A refusal records the same identity whether the guard or a confined tool decides: a path outside the grant is `FsError` `FS_SANDBOX_DENIED`, and other grant refusals are `LiveshareForkDeniedError` with a `FORK_*` code. Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs. diff --git a/docs/subsystems/liveshare.zh.md b/docs/subsystems/liveshare.zh.md index 4c26825027..a274d8957d 100644 --- a/docs/subsystems/liveshare.zh.md +++ b/docs/subsystems/liveshare.zh.md @@ -38,7 +38,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检 每个分享都让它的 viewer 通过正常 prompt 路径驱动*源*会话,任一档位的分享在活跃期间都会安装有界沙箱。`installSourceSessionAccess` 在该会话自身作用域中为部署提供的每个读取与检索面工具注册受限替代,并在任一同会话分享允许写入时再注册有界 `edit` 与 `write` 替代。执行层挂在会话上,但只约束分享查看者发起的轮次:`agent/pre-step` 在 Host 内存中记录一个轮次的已准入输入是否带有 share-viewer principal,守卫与替代定义对该轮次的每次执行读取这一结论。查看者发起的轮次只能运行这些替代定义;所有者自己发起的轮次保留会话原生工具,包括 `bash` 与不受限的文件工具。该结论在轮次准入时确定,不写入会话日志;重启后从下一个准入步骤重新计算。所有者在查看者轮次中追加的输入仍留在该受限轮次内。该会话的所有分享停止后执行层被释放,会话恢复自己的工具;最后一个可写分享降为 `view` 时重装只读层。 -安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。 +安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。无论由守卫还是受限工具判定,拒绝都记录同一标识:授权范围外的路径为 `FsError` `FS_SANDBOX_DENIED`,其他授权拒绝为 `LiveshareForkDeniedError` 及 `FORK_*` code。 每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。 diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index 7259adff93..bcefbfdd3b 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: 0900eea6efe5a500 - zh: 13fa6eb7dbd8c9dd + en: a6d9db4237438b2a + zh: 1fe07dedc426c5eb /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index bc2aadbeca..64ae21eeb3 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -532,7 +532,7 @@ interface ToolErrorInfo { } ``` -The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. +The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`, and a `tools/execute` wrapper that throws such a value after caller cancellation gets the same identity, with `ABORTED_BEFORE_DISPATCH` when the body never started; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. On success the registry snapshots and validates the body value, freezes it, and invokes the pure renderer plus the optional presentation metadata projector for native and nested calls. It separately materializes the durable presentation fields immediately before `tools/result`; an invalid value, renderer/projector failure, or non-JSON presentation becomes a JSON-safe `isError`. The final live observer therefore sees the exact execution-local value beside fields safe for the later durable append. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 0edd8063a6..34d5e414c6 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -532,7 +532,7 @@ interface ToolErrorInfo { } ``` -结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 +结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`,`tools/execute` 包装器在调用方取消后抛出这类值时也得到同样的标识,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 成功时,注册表会快照并校验函数体返回值,将其冻结,然后调用纯渲染器,并为原生与嵌套调用执行可选的展示元数据投影器。注册表会在 `tools/result` 之前另行物化持久展示字段;无效值、渲染器/投影器失败或非 JSON 展示都会转为 JSON 安全的 `isError`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。 diff --git a/docs/subsystems/web-client.i18n.yaml b/docs/subsystems/web-client.i18n.yaml index 4ff473259e..47748543cf 100644 --- a/docs/subsystems/web-client.i18n.yaml +++ b/docs/subsystems/web-client.i18n.yaml @@ -24,14 +24,26 @@ en: c063711f8247c240 zh: 5e54758bbaf1670c /web-client-architecture/conversation-and-presentation: - en: f37ba948a8838fb0 - zh: df19542d87860221 + en: 1283921eb19b9be3 + zh: bc42b48592d50f3a /web-client-architecture/data-paths: en: a254278432416473 zh: 567c2d3c6a20b304 /web-client-architecture/reconnection: en: 478f461e261b1ca5 zh: 626791d04656faee +/web-client-architecture/reading-reminders: + en: 59427b3b5d8d633c + zh: 864e0ea121534aa3 +/web-client-architecture/reading-reminders/sessionreadstate: + en: 62e6bfae05af614a + zh: cbd33ee7b57ac723 +/web-client-architecture/reading-reminders/sessionreadaction: + en: 7ed7e42b233ee2c0 + zh: fd4e5b67f3358059 +/web-client-architecture/reading-reminders/sessionreadframe: + en: 993e0b409439b15c + zh: f7785bea2e8f5b00 /web-client-architecture/package-boundaries: - en: 3e64e8c28f0c4cb1 - zh: 47aa81c2ace5ba89 + en: 085622c76f4d5b06 + zh: 12ef92771b4d9a4a diff --git a/docs/subsystems/web-client.md b/docs/subsystems/web-client.md index fbdaecf3d5..f9c248b9ad 100644 --- a/docs/subsystems/web-client.md +++ b/docs/subsystems/web-client.md @@ -57,7 +57,7 @@ This pairing is not a second source of business truth. Host controllers decide d Web and desktop share the [Coding Tools preference](../../packages/client/ui-settings/README.md#use-this-package). It controls diagnostic Views, [available preset choices](../../packages/client/ui-agent-preset/README.md), changed-file cards, and the builtin HTML preview policy without changing Session records. -`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionRetainInfo`, `useSessionAccess`, `useSession`, `sessionId`, `useProjection`, and the Session-scope `useAccess` over the [remote-access](../../packages/api/remote-access/README.md) Client service. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. [`ui-session-status`](../../packages/client/ui-session-status/README.md) publishes `useSessionStatus` from the `ctx.uiSession.sessionStatus` table of running state, the effective pending interaction, and completion reminders. Domain adapters add further standard sources without putting React hooks on the model objects. +`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionRetainInfo`, `useSessionAccess`, `useSession`, `sessionId`, `useProjection`, and the Session-scope `useAccess` over the [remote-access](../../packages/api/remote-access/README.md) Client service. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. [`ui-session-status`](../../packages/client/ui-session-status/README.md) publishes `useSessionStatus` from the `ctx.uiSession.sessionStatus` table of running state, the effective pending interaction, and reading reminders that its Host face keeps for every Client of one Host. Domain adapters add further standard sources without putting React hooks on the model objects. `ui-conversation` binds once to each `SessionBinding.eventSource`. Its event registry correlates durable Session events and Client-only `assistant/live-chunk` updates into stable business Contexts, and its view registry materializes target snapshots. Chat Assistant, Trajectory Assistant, and Turn Tail interpret both live chunks and the compact streams embedded in durable settlements, so reconnect and paged history reproduce the same Assistant state without durable token rows. `ui-chat` and `ui-trajectory` register separate Definitions and builders: they may interpret the same event family, but they do not import or share each other's final display model. The shell selects a registered view and passes its snapshot through standard hooks and Slots. [Conversation](conversation.md) defines Context identity, replay, Location data, target builders, and keyed renderers. @@ -86,11 +86,29 @@ Recovery follows the data's semantics: There is no monolithic Client `Runtime`, `HostFrame`, `events.mux`, `events.host`, or universal `resync()` API. The Connection exposes generation state, Gateway owns logical stream supervision, and each Client model defines replacement or resume semantics appropriate to its data. +## Reading reminders + +[Session status](../../packages/client/ui-session-status/README.md) holds read acknowledgements and explicit unread marks in Host memory, outside the conversation log. Its Host Remote service sends complete reconnect baselines and committed changes; its Client plugin folds them into the `ctx.uiSession.sessionStatus` status table and acknowledges loaded completions in the visible, focused main view. Reading state does not change model history. + +### SessionReadState + +A whole reading record names its `sessionId`, latest `completedTurn`, whether that turn `failed` with an execution error this Host observed, acknowledged `readTurn`, and `manualUnread` flag. A Session is unread when the flag is set or its latest ended turn exceeds the acknowledged turn. + +`mark(sessionId, action)` updates one Session in Host processing order. Only the ordered subscription updates Client records. The service records `turn/end` events itself, including whether that turn failed. + +### SessionReadAction + +An `unread` action sets the manual flag. A `read` action clears it and advances the read position through its `throughTurn`; an `acknowledge` action advances that position without changing the flag. Positions never move backwards or beyond the Host's latest completed turn. Mutation replies report success or failure without echoing a record. + +### SessionReadFrame + +A follow generation starts with `type: 'baseline'` and every accessible record in `items`. Each later `type: 'changed'` carries one complete committed `state`. Reconnection replaces the previous generation's records. + ## Package boundaries Feature plugin packages may share declarations through `import type`; they do not runtime-import or re-export another feature plugin's values. Cross-package behavior uses injected Cordis services, and cross-package UI uses Slots. Target-specific Conversation Definitions, projection helpers, and final view data stay with their target package even when Chat and Trajectory intentionally implement parallel logic. -Shared runtime values need a narrow static owner with no feature lifecycle, such as `client/store`, `ui-primitives`, or a browser-safe utility package. Transport and generated API assembly may import runtime contributions because assembling one protocol is their explicit responsibility. A feature package does not add `dsh.client.external` merely to bypass this rule. +Shared runtime values need a narrow static owner with no feature lifecycle, such as `client/store`, `ui-primitives`, or a browser-safe utility package. Transport and generated API assembly may import runtime contributions because assembling one protocol is their explicit responsibility. A feature package may request the runtime values of a row under `packages/api/` through `dsh.client.external`, but never another feature plugin's row. Use the four detailed references according to the extension being added: @@ -98,3 +116,40 @@ Use the four detailed references according to the extension being added: - [API Gateway](../api-gateway.md) for Host methods, generated Remote contributions, streams, and forwarded events. - [Web Client Slots](slots.md) for components, hooks, stores, injection, and placement. - [Conversation](conversation.md) for durable event correlation, target snapshots, and Chat or Trajectory view contributions. + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.sessionStatus` — `SessionStatusService` + +Shared owner reading records; no reading operation changes model history. + +```ts cordis-catalog +/** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ +@Remote async mark(sessionId: SessionId, action: SessionReadAction): Promise + +/** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Types: [SessionId](core.md) + +Source: [`packages/client/ui-session-status/src/index.ts`](../../packages/client/ui-session-status/src/index.ts) + diff --git a/docs/subsystems/web-client.zh.md b/docs/subsystems/web-client.zh.md index 50ef3f9146..7b92946915 100644 --- a/docs/subsystems/web-client.zh.md +++ b/docs/subsystems/web-client.zh.md @@ -57,7 +57,7 @@ Connection 拥有请求 URL 解析、request correlation、`/api` carrier、trus Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settings/README.zh.md#use-this-package)。它控制诊断 View、[可用的预设选项](../../packages/client/ui-agent-preset/README.zh.md)、改动文件卡片和内置 HTML 预览策略,不改变 Session 记录。 -`ui-session` 安装 Session scope adapter,并在 [remote-access](../../packages/api/remote-access/README.zh.md) Client 服务之上提供 `useSessions`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。[`ui-session-status`](../../packages/client/ui-session-status/README.zh.md) 从 `ctx.uiSession.sessionStatus` 状态表提供 `useSessionStatus`,该表汇总运行状态、生效的待交互请求和完成提醒。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 +`ui-session` 安装 Session scope adapter,并在 [remote-access](../../packages/api/remote-access/README.zh.md) Client 服务之上提供 `useSessions`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。[`ui-session-status`](../../packages/client/ui-session-status/README.zh.md) 从 `ctx.uiSession.sessionStatus` 状态表提供 `useSessionStatus`,该表汇总运行状态、生效的待交互请求,以及其宿主面为同一宿主各前端保存的阅读提醒。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 `ui-conversation` 对每个 `SessionBinding.eventSource` 只绑定一次。它的 event registry 把持久 Session event 与 Client-only `assistant/live-chunk` update 关联成稳定的业务 Context,view registry 则 materialize target snapshot。Chat Assistant、Trajectory Assistant 与 Turn Tail 同时解释 live chunk 和持久 settlement 中嵌入的紧凑 stream,因此重连与分页历史无需持久 token 行即可复现相同 Assistant 状态。`ui-chat` 与 `ui-trajectory` 分别注册自己的 Definition 和 builder:它们可以解释同一 event family,但不会导入或共享彼此的最终 display model。Shell 选择一个已注册 view,再通过标准 hook 与 Slot 交付其 snapshot。[Conversation](conversation.zh.md)定义 Context identity、replay、Location data、target builder 与 keyed renderer。 @@ -86,11 +86,29 @@ Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settin 架构中没有统一的 Client `Runtime`、`HostFrame`、`events.mux`、`events.host` 或通用 `resync()` API。Connection 公开 generation state,Gateway 管理 logical stream,Client model 则按自身数据定义 replacement 或 resume 语义。 +## 阅读提醒 + +[会话状态](../../packages/client/ui-session-status/README.zh.md)在宿主内存中保存使用者的阅读确认和手动未读标记。其宿主 Remote 服务发送重连快照和已保存的更新;其前端插件把这些记录汇入 `ctx.uiSession.sessionStatus` 状态表,并在可见且聚焦的主视图中确认已加载的完成内容。阅读状态不改变模型历史。 + +### SessionReadState + +完整阅读记录包含 `sessionId`、最近结束的 `completedTurn`、该轮是否以本宿主观察到的执行错误结束的 `failed`、已确认的 `readTurn` 和 `manualUnread` 标记。设置了手动标记,或最近结束的轮次大于已确认轮次时,会话为未读。 + +`mark(sessionId, action)` 按宿主处理顺序更新会话。前端只通过有序订阅流更新记录。该服务自己记录 `turn/end` 事件,包括该轮是否失败。 + +### SessionReadAction + +`unread` 操作设置手动标记。`read` 操作清除标记,并将阅读位置推进至它的 `throughTurn`;`acknowledge` 操作只推进位置,不改变标记。位置不会回退,也不越过宿主最近完成的轮次。修改回复仅表示成功或失败,不回传记录。 + +### SessionReadFrame + +每次同步先发送 `type: 'baseline'`,在 `items` 中包含所有可访问的记录。后续每个 `type: 'changed'` 都携带一条已保存的完整 `state`。重连会替换上一代同步流的记录。 + ## 包边界 功能插件包可以通过 `import type` 共享声明;不得运行时导入或转发另一个功能插件的值。跨包行为使用注入的 Cordis service,跨包 UI 使用 Slots。特定 target 的 Conversation Definition、projection helper 与最终 view data 留在所属 target 包中,即使 Chat 和 Trajectory 有意实现平行逻辑。 -共享运行时值需要一个职责收窄、没有功能生命周期的静态 owner,例如 `client/store`、`ui-primitives` 或浏览器安全的 util 包。Transport 与生成 API assembly 可以导入运行时 contribution,因为组装同一个 protocol 正是它们的显式职责。功能包不能只为绕过此规则而添加 `dsh.client.external`。 +共享运行时值需要一个职责收窄、没有功能生命周期的静态 owner,例如 `client/store`、`ui-primitives` 或浏览器安全的 util 包。Transport 与生成 API assembly 可以导入运行时 contribution,因为组装同一个 protocol 正是它们的显式职责。功能包可以通过 `dsh.client.external` 请求 `packages/api/` 下某一行的运行时值,但不能请求另一个功能插件的行。 根据所添加的扩展查阅四篇详细参考: @@ -98,3 +116,40 @@ Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settin - [API Gateway](../api-gateway.zh.md):Host method、生成的 Remote contribution、stream 与 forwarded event。 - [Web Client Slots](slots.zh.md):component、hook、store、injection 与 placement。 - [Conversation](conversation.zh.md):持久 event correlation、target snapshot,以及 Chat 或 Trajectory view contribution。 + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.sessionStatus` — `SessionStatusService` + +Shared owner reading records; no reading operation changes model history. + +```ts cordis-catalog +/** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ +@Remote async mark(sessionId: SessionId, action: SessionReadAction): Promise + +/** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Types: [SessionId](core.zh.md) + +Source: [`packages/client/ui-session-status/src/index.ts`](../../packages/client/ui-session-status/src/index.ts) + diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index 23dde9244e..a6b14d164b 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -6,8 +6,8 @@ en: 3a3d69d2b12a78f9 zh: a7a7d12487968bbc /git-worktrees/creation-and-retention: - en: 53f643c5d30e00b2 - zh: ba9e52efc62c7656 + en: 4c28ae6baae4ef5f + zh: 0c83d90ea3cd3c2e /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 492a1dbb1a..a837e99625 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -10,7 +10,7 @@ The calling Session's current directory selects the source repository. Creation The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. -Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. +Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. Worktree failures throw `WorktreeError` with a `WORKTREE_*` code; a failure after allocation keeps the wrapped error's `name` and `code`, and caller cancellation stays an `AbortError`. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. ## Request and result @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. + * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out + * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; it must not throw. * @returns the directory and whether the branch was created again. + * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, + * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index d96ef21893..3d2b4d7286 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -10,7 +10,7 @@ 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 -通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 +通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。worktree 失败抛出带 `WORKTREE_*` code 的 `WorktreeError`;分配开始后的失败保留被包装错误的 `name` 与 `code`,调用方取消仍为 `AbortError`。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 ## 请求与结果 @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. + * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out + * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; it must not throw. * @returns the directory and whether the branch was created again. + * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, + * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml new file mode 100644 index 0000000000..1ff6a94445 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md +/: + en: 4d6f7a78d1415f20 + zh: a5a906f4f1266243 +/experimental-plugin-failures-carry-error-codes: + en: 13f43192e549438f + zh: ce8c5bf26aefbd4f +/experimental-plugin-failures-carry-error-codes/change: + en: d5878c5ce6fbfb76 + zh: 2f2d29a1f3a9d6f3 +/experimental-plugin-failures-carry-error-codes/migration: + en: 6365d4f60118cf64 + zh: c2f1378dee8ea4b4 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md new file mode 100644 index 0000000000..c4e579dd36 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental and hook plugin tool failures record error codes, NativeError, OarFailure, and StagehandDrainError become HarnessError subclasses, and browser cleanup rejects with BrowserSessionError." +--- + +# Experimental plugin failures carry error codes + +English | [中文](guide.zh.md) + +## Change + +Tool failures from the CUA, browser-use, Cua Driver, worktree, Ralph, terminal, OAR subagent, Liveshare, Claude Code and Codex hook, and claude-code-mods plugins now record `error: { name, code }` on `tool/result`; previously most of these results had no `error`. The [package READMEs](../../../../packages/experimental/README.md) list each class and code. + +Code that handles these failures in-process sees these changes: + +- `NativeError` from `@deepseek-ai/dsh-cua` and `OarFailure` from `@deepseek-ai/dsh-experimental-subagent-oar` now extend `HarnessError` from `@deepseek-ai/dsh-error`. `NativeError` keeps its name, codes, and `CODE: message` text. `OarFailure` drops its `stage` and `category` fields; the same summary stays in `message`, and `code` names the stage. Cancellation before an OAR run starts rejects with a `DOMException` named `AbortError` instead of an `OarFailure`. +- `StagehandDrainError` from `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` now extends `StagehandError` and has the code `STAGEHAND_CLEANUP_FAILED`. +- `SessionResources.dispose()` from `@deepseek-ai/dsh-experimental-browser-use-runtime` rejects with `BrowserSessionError` (`BROWSER_CLEANUP_FAILED`) whose `cause` is the `AggregateError` it previously threw; `instanceof AggregateError` no longer matches. +- Liveshare guard functions return `{ reason, info }` instead of a reason string. +- Argument failures that now throw `ToolArgsError` show `invalid arguments: ` before the message the model sees, and a CUA screenshot request for a model without image input shows `MODEL_DOES_NOT_SUPPORT_IMAGES: ` before its message. + +## Migration + +1. If analytics or retry rules read `tool/result` `error`, add the new names and codes from the package READMEs. Earlier Session logs keep results without `error`. +2. Replace `instanceof AggregateError` checks on `SessionResources.dispose()` rejections with `instanceof BrowserSessionError` and read the individual failures from `error.cause.errors`. +3. Replace reads of `OarFailure.stage` or `category` with `error.code`. +4. If code catches `HarnessError` before `NativeError`, `OarFailure`, or `StagehandDrainError`, move the specific check first where the handling differs. +5. Confirm with `pnpm run typecheck` and your own failure-path tests. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md new file mode 100644 index 0000000000..41e8ba1902 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental 与 hook 插件的工具失败带上错误 code,NativeError、OarFailure 与 StagehandDrainError 改为 HarnessError 子类,浏览器清理失败改为以 BrowserSessionError 拒绝。" +--- + +# Experimental 插件的失败带上错误 code + +[English](guide.md) | 中文 + +## 变更 + +CUA、browser-use、Cua Driver、worktree、Ralph、终端、OAR 子 agent、Liveshare、Claude Code 与 Codex hook,以及 claude-code-mods 插件的工具失败现在会在 `tool/result` 上记录 `error: { name, code }`;此前这些结果大多没有 `error`。各[包 README](../../../../packages/experimental/README.zh.md) 列出了每个类和 code。 + +在进程内处理这些失败的代码会看到以下变化: + +- `@deepseek-ai/dsh-cua` 的 `NativeError` 与 `@deepseek-ai/dsh-experimental-subagent-oar` 的 `OarFailure` 现在继承 `@deepseek-ai/dsh-error` 的 `HarnessError`。`NativeError` 的 name、code 与 `CODE: message` 文本不变。`OarFailure` 去掉了 `stage` 与 `category` 字段;同样的摘要保留在 `message` 中,`code` 标明阶段。OAR 运行开始前的取消改为以 name 为 `AbortError` 的 `DOMException` 拒绝,不再是 `OarFailure`。 +- `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` 的 `StagehandDrainError` 现在继承 `StagehandError`,code 为 `STAGEHAND_CLEANUP_FAILED`。 +- `@deepseek-ai/dsh-experimental-browser-use-runtime` 的 `SessionResources.dispose()` 改为以 `BrowserSessionError`(`BROWSER_CLEANUP_FAILED`)拒绝,其 `cause` 是此前直接抛出的 `AggregateError`;`instanceof AggregateError` 不再成立。 +- Liveshare 的 guard 函数改为返回 `{ reason, info }`,不再返回原因字符串。 +- 改为抛出 `ToolArgsError` 的参数失败,模型看到的 message 前多了 `invalid arguments: `;为不支持图片输入的模型请求 CUA 截图时,message 前多了 `MODEL_DOES_NOT_SUPPORT_IMAGES: `。 + +## 迁移 + +1. 如果分析或重试规则读取 `tool/result` 的 `error`,按包 README 补充新的 name 与 code。较早的 Session 日志中这些结果仍没有 `error`。 +2. 把对 `SessionResources.dispose()` 拒绝值的 `instanceof AggregateError` 检查改为 `instanceof BrowserSessionError`,并从 `error.cause.errors` 读取各个失败。 +3. 把读取 `OarFailure.stage` 或 `category` 的代码改为读取 `error.code`。 +4. 如果代码在 `NativeError`、`OarFailure` 或 `StagehandDrainError` 之前捕获 `HarnessError`,在处理方式不同的地方把具体类的检查移到前面。 +5. 用 `pnpm run typecheck` 和自己的失败路径测试确认迁移完成。 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml index b2225275ad..72f725d176 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md /: - en: 34a382f0eacc70b6 - zh: 251d8ba446d1b358 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status: - en: 97c85d1b9ace1ddf - zh: 0c4d30289336b324 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status/change: - en: 62ea699966c0e9d5 - zh: 31afc236690b0cd5 -/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status/migration: - en: 529f2def0221d26d - zh: 6009726243e1c8a6 + en: 3ac349a835a29b14 + zh: 2c0d4c7e3cfb59ca +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records: + en: fb71a29f84e6d36d + zh: 5f46ad954c473f7e +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records/change: + en: ec4737fe7f5e4839 + zh: e68a22fe18216760 +/session-status-moves-to-deepseek-ai-dsh-client-ui-session-status-and-completion-reminders-follow-host-reading-records/migration: + en: 20d2b7a2809ffc2d + zh: 9ca5578f94130755 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md index c4fdfe189a..3addbda815 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md @@ -1,28 +1,31 @@ --- kind: upgrade-guide -description: "SessionStatus, SessionStatusSnapshot, UseSessionStatus, and the useSessionStatus hook move from @deepseek-ai/dsh-client-ui-session/client to @deepseek-ai/dsh-client-ui-session-status/client, and ctx.uiSession.sessionStatus becomes the separate uiSession.sessionStatus service that readers inject." +description: "Session status types and the useSessionStatus hook move to @deepseek-ai/dsh-client-ui-session-status/client, ctx.uiSession.sessionStatus becomes an injected service, and completion reminders follow Host reading records." --- -# Session status moves to `@deepseek-ai/dsh-client-ui-session-status` +# Session status moves to `@deepseek-ai/dsh-client-ui-session-status` and completion reminders follow Host reading records English | [中文](guide.zh.md) ## Change -`@deepseek-ai/dsh-client-ui-session/client` no longer exports `SessionStatus`, `SessionStatusSnapshot`, or `UseSessionStatus`, and ui-session no longer declares or provides the `useSessionStatus` root hook. Both now belong to the Client plugin [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md), which the Web bundle loads beside ui-session. The `SessionStatus` fields `running`, `pendingInteraction`, and `completionUnread` and their meaning are unchanged. A Client composition that loads ui-session without ui-session-status has no status table and no `useSessionStatus` hook. +`@deepseek-ai/dsh-client-ui-session/client` no longer exports `SessionStatus`, `SessionStatusSnapshot`, or `UseSessionStatus`, and ui-session no longer declares or provides the `useSessionStatus` root hook. Both now belong to the Client plugin [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.md), one Web bundle row with a Host reading service and the Client table. A Client composition that loads ui-session without ui-session-status has no status table and no `useSessionStatus` hook. -`ctx.uiSession.sessionStatus` is now the separate `uiSession.sessionStatus` service. Reading it through `ctx.uiSession.sessionStatus.getSnapshot()` and `subscribe()` keeps its form, but a plugin that reads it without injecting `'uiSession.sessionStatus'` fails with `cannot get property "uiSession.sessionStatus" without inject`. A plugin whose components call `useSessionStatus` without that injection stays active when the status table unloads, and its components then fail with `useSessionStatus is not a function`. `ctx.uiSession` now has the type `UiSessionService`, which extends the unchanged `UiSession` class with members such as `sessionStatus`; a value annotated as `UiSession` does not show `sessionStatus`. +`ctx.uiSession.sessionStatus` is now the separate `uiSession.sessionStatus` service. Reading it through `ctx.uiSession.sessionStatus.getSnapshot()` and `subscribe()` keeps its form, but a plugin that reads it without injecting `'uiSession.sessionStatus'` fails with `cannot get property "uiSession.sessionStatus" without inject`. Components of a plugin without that injection fail with `useSessionStatus is not a function` after the table unloads. `ctx.uiSession` now has the type `UiSessionService`, which extends the unchanged `UiSession` class with members such as `sessionStatus`; a value annotated as `UiSession` does not show `sessionStatus`. -Pending interactions stay in ui-session: `ctx.uiSession.registerPendingInteraction(precedence)`, `SessionPendingInteractionBase`, `SessionPendingInteractionMap`, `SessionPendingInteraction`, and `PendingInteractionPublisher` keep their names, behavior, and `@deepseek-ai/dsh-client-ui-session/client` export. Declarations that extend `SessionPendingInteractionMap` keep targeting that module. ui-session additionally exposes the read-only `ctx.uiSession.pendingInteractions` source. +Pending interactions stay in ui-session: `ctx.uiSession.registerPendingInteraction(precedence)`, `SessionPendingInteractionBase`, `SessionPendingInteractionMap`, `SessionPendingInteraction`, and `PendingInteractionPublisher` keep their names, behavior, and `@deepseek-ai/dsh-client-ui-session/client` export. Extensions of `SessionPendingInteractionMap` keep targeting that module. ui-session additionally exposes the read-only `ctx.uiSession.pendingInteractions` source. -This affects Client plugins and tests that import the three status types, render components that read `useSessionStatus`, or read `ctx.uiSession.sessionStatus`. +`completionUnread` follows Host-memory reading records shared by every Client and changes through Host completions, explicit marks, and visible main-view acknowledgement; only a main-view switch, including a reload, clears a manual mark. The open viewed Session hides its unacknowledged turn; earlier history reads as read. The required `completionFailed` field marks an unread Session whose latest turn failed. The new `mark(sessionId, unread)` rejects until `readingReady` reports the Host baseline. + +This affects Client plugins and tests that import the three status types, construct `SessionStatus` values, render components that read `useSessionStatus`, or read `ctx.uiSession.sessionStatus`. ## Migration 1. Import `SessionStatus`, `SessionStatusSnapshot`, and `UseSessionStatus` from `@deepseek-ai/dsh-client-ui-session-status/client`. A package that only imports these types, for example in tests, declares `@deepseek-ai/dsh-client-ui-session-status` in `devDependencies` and its TypeScript project references. -2. A package whose source components call `useSessionStatus` additionally lists the package in `dsh.client.inject`, adds `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'` when it imports none of the types, and adds `'uiSession.sessionStatus'` to the Cordis `inject` of the plugin that registers those components, so the plugin unloads and reloads with the status table. -3. In each plugin that reads `ctx.uiSession.sessionStatus` in JavaScript, add `'uiSession.sessionStatus'` to `inject`. A plugin that only needs the effective pending request may read and subscribe to `ctx.uiSession.pendingInteractions` instead. +2. A package whose components call `useSessionStatus` also lists the package in `dsh.client.inject`, adds `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'` when it imports none of the types, and adds `'uiSession.sessionStatus'` to the Cordis `inject` of the plugin that registers them. +3. Each plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession.sessionStatus'` to `inject`; one that needs only the effective pending request may subscribe to `ctx.uiSession.pendingInteractions` instead. 4. Where code passes `ctx.uiSession` through a parameter or field annotated as `UiSession` and then reads `sessionStatus`, annotate it as `UiSessionService` from `@deepseek-ai/dsh-client-ui-session/client`. 5. Leave `registerPendingInteraction` calls and `declare module '@deepseek-ai/dsh-client-ui-session/client'` augmentations of `SessionPendingInteractionMap` unchanged. -6. A custom Client composition that loads `@deepseek-ai/dsh-client-ui-session` also loads `@deepseek-ai/dsh-client-ui-session-status`, so `useSessionStatus` remains available. -7. Confirm that the plugin type-checks and that a Session row still shows its running or waiting indicator. +6. Add `completionFailed` to `SessionStatus` values in tests and fixtures, and script Host reading records to drive `completionUnread`. +7. A custom composition that loads `@deepseek-ai/dsh-client-ui-session` also loads `@deepseek-ai/dsh-client-ui-session-status` as a plugin row, so its Host reading service and `useSessionStatus` are available. +8. Confirm that the plugin type-checks, that a Session row still shows its running or waiting indicator, and that a Session finishing outside the main view shows an unread reminder. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md index 8403fc5f48..8fa30ace12 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md @@ -1,28 +1,31 @@ --- kind: upgrade-guide -description: "SessionStatus、SessionStatusSnapshot、UseSessionStatus 和 useSessionStatus hook 从 @deepseek-ai/dsh-client-ui-session/client 移到 @deepseek-ai/dsh-client-ui-session-status/client,ctx.uiSession.sessionStatus 改为读取方需要注入的独立 uiSession.sessionStatus 服务。" +description: "会话状态类型与 useSessionStatus hook 移到 @deepseek-ai/dsh-client-ui-session-status/client,ctx.uiSession.sessionStatus 改为需要注入的服务,完成提醒改为跟随宿主阅读记录。" --- -# 会话状态移到 `@deepseek-ai/dsh-client-ui-session-status` +# 会话状态移到 `@deepseek-ai/dsh-client-ui-session-status`,完成提醒改由宿主阅读记录提供 [English](guide.md) | 中文 ## 变更 -`@deepseek-ai/dsh-client-ui-session/client` 不再导出 `SessionStatus`、`SessionStatusSnapshot` 或 `UseSessionStatus`,ui-session 也不再声明或提供根 hook `useSessionStatus`。它们现在属于 Client 插件 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md),Web bundle 会与 ui-session 一起加载它。`SessionStatus` 的字段 `running`、`pendingInteraction`、`completionUnread` 及其含义不变。只加载 ui-session、不加载 ui-session-status 的 Client 组合没有状态表,也没有 `useSessionStatus` hook。 +`@deepseek-ai/dsh-client-ui-session/client` 不再导出 `SessionStatus`、`SessionStatusSnapshot` 或 `UseSessionStatus`,ui-session 也不再声明或提供根 hook `useSessionStatus`。它们现在属于 Client 插件 [`@deepseek-ai/dsh-client-ui-session-status`](../../../../packages/client/ui-session-status/README.zh.md),即 Web bundle 中同时提供宿主阅读服务和前端状态表的一行。只加载 ui-session、不加载 ui-session-status 的 Client 组合没有状态表,也没有 `useSessionStatus` hook。 -`ctx.uiSession.sessionStatus` 现在是独立的 `uiSession.sessionStatus` 服务。通过 `ctx.uiSession.sessionStatus.getSnapshot()` 和 `subscribe()` 读取的写法不变,但未注入 `'uiSession.sessionStatus'` 就读取它的插件会报错 `cannot get property "uiSession.sessionStatus" without inject`。组件调用 `useSessionStatus`、却未注入该服务的插件,在状态表卸载后仍保持激活,其组件随后报错 `useSessionStatus is not a function`。`ctx.uiSession` 的类型改为 `UiSessionService`,它在不变的 `UiSession` class 之上加入 `sessionStatus` 等成员;标注为 `UiSession` 的值看不到 `sessionStatus`。 +`ctx.uiSession.sessionStatus` 现在是独立的 `uiSession.sessionStatus` 服务。通过 `ctx.uiSession.sessionStatus.getSnapshot()` 和 `subscribe()` 读取的写法不变,但未注入 `'uiSession.sessionStatus'` 就读取它的插件会报错 `cannot get property "uiSession.sessionStatus" without inject`。未注入该服务的插件,其组件会在状态表卸载后报错 `useSessionStatus is not a function`。`ctx.uiSession` 的类型改为 `UiSessionService`,它在不变的 `UiSession` class 之上加入 `sessionStatus` 等成员;标注为 `UiSession` 的值看不到 `sessionStatus`。 待交互仍归 ui-session:`ctx.uiSession.registerPendingInteraction(precedence)`、`SessionPendingInteractionBase`、`SessionPendingInteractionMap`、`SessionPendingInteraction` 和 `PendingInteractionPublisher` 的名称、行为以及从 `@deepseek-ai/dsh-client-ui-session/client` 的导出都不变。扩展 `SessionPendingInteractionMap` 的声明继续指向该模块。ui-session 另外提供只读的 `ctx.uiSession.pendingInteractions` 数据源。 -受影响的是导入这三个状态类型、渲染读取 `useSessionStatus` 的组件,或读取 `ctx.uiSession.sessionStatus` 的 Client 插件和测试。 +`completionUnread` 跟随宿主内存中、由所有前端共享的阅读记录,因宿主完成轮次、主动标记和可见主视图的确认而变化;只有主视图切换到该会话(包括刷新后恢复)会自动清除手动标记。正在查看且已打开的会话不显示尚未确认的轮次;宿主启动前已有的历史按已读处理。新增的必填字段 `completionFailed` 标记最近一轮失败的未读会话。新增的 `mark(sessionId, unread)` 在 `readingReady` 报告取得宿主基线之前会拒绝。 + +受影响的是导入这三个状态类型、构造 `SessionStatus` 值、渲染读取 `useSessionStatus` 的组件,或读取 `ctx.uiSession.sessionStatus` 的 Client 插件和测试。 ## 迁移 1. 从 `@deepseek-ai/dsh-client-ui-session-status/client` 导入 `SessionStatus`、`SessionStatusSnapshot` 和 `UseSessionStatus`。只导入这些类型(例如只在测试中导入)的包,在 `devDependencies` 和 TypeScript 项目引用中声明 `@deepseek-ai/dsh-client-ui-session-status`。 -2. 源码组件调用 `useSessionStatus` 的包,另外在 `dsh.client.inject` 中列出该包;不导入任何上述类型时加入 `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'`;并在注册这些组件的插件的 Cordis `inject` 中加入 `'uiSession.sessionStatus'`,使该插件随状态表一起卸载和重新加载。 -3. 在每个在 JS 中读取 `ctx.uiSession.sessionStatus` 的插件中,把 `'uiSession.sessionStatus'` 加到 `inject`。只需要生效待交互请求的插件,可以改为读取并订阅 `ctx.uiSession.pendingInteractions`。 +2. 组件调用 `useSessionStatus` 的包,另外在 `dsh.client.inject` 中列出该包;不导入任何上述类型时加入 `import type {} from '@deepseek-ai/dsh-client-ui-session-status/client'`;并在注册这些组件的插件的 Cordis `inject` 中加入 `'uiSession.sessionStatus'`。 +3. 每个读取 `ctx.uiSession.sessionStatus` 的插件把 `'uiSession.sessionStatus'` 加入 `inject`;只需要生效待交互请求的插件,可以改为订阅 `ctx.uiSession.pendingInteractions`。 4. 代码把 `ctx.uiSession` 传给标注为 `UiSession` 的参数或字段、之后又读取 `sessionStatus` 时,把标注改为 `@deepseek-ai/dsh-client-ui-session/client` 的 `UiSessionService`。 5. `registerPendingInteraction` 调用和对 `SessionPendingInteractionMap` 的 `declare module '@deepseek-ai/dsh-client-ui-session/client'` 扩展保持不变。 -6. 加载 `@deepseek-ai/dsh-client-ui-session` 的自定义 Client 组合同时加载 `@deepseek-ai/dsh-client-ui-session-status`,使 `useSessionStatus` 继续可用。 -7. 确认插件通过类型检查,并且会话行仍显示运行或等待标记。 +6. 在测试和 fixture 的 `SessionStatus` 值中加入 `completionFailed`,并编排宿主阅读记录来驱动 `completionUnread`。 +7. 加载 `@deepseek-ai/dsh-client-ui-session` 的自定义组合同时以插件行加载 `@deepseek-ai/dsh-client-ui-session-status`,使其宿主阅读服务和 `useSessionStatus` 可用。 +8. 确认插件通过类型检查、会话行仍显示运行或等待标记,并且在主视图之外结束的会话显示未读提醒。 diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index eb3352e60d..4caa0e8c59 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -18,8 +18,8 @@ en: 6ee072ffebd2eb38 zh: 6a8723d13f443d51 /deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote: - en: 0916113cdbe794fb - zh: 14893c2cba95bfd6 + en: 610e48ec8d772f85 + zh: 627da164fc8297ba /deepseek-ai-dsh-api-gateway/model-experience: en: 6cb309d3378f035d zh: 998042a02ee32850 diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index fea754c891..20f87506d0 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -63,7 +63,7 @@ Every unary call resolves to `RemoteResult` — `{ ok: true, value }` or `{ o `ctx.remote.$host` reads the fixed Host facts as plain values: `home` (undefined until the first ready frame) and `isLoopback`. It is not a store — no subscription, no generation counter — so a consumer that must react to reconnection listens for `connection/reset` instead of polling it. -`ctx.remote.$stream()` returns a single-consumer `RemoteStream` spanning physical carrier generations. For answering Clients it permits one immediate retry after an isolated stream failure while the carrier remains available; after physical WebSocket loss it waits for Connection to reopen the carrier. If the Host generation is already unavailable, it waits for the next connected generation. Each item carries its physical generation. Passive Clients cannot use `$stream()`; they call generated raw stream methods and handle terminal carrier failure themselves. The domain consumer validates and accepts each generation's opening value; business and protocol failures remain terminal. Every terminal failure leaves this face as a `RemoteError`, including exhausted carrier retries and a generation that ends before its opening value, so a stream consumer discriminates the same way a unary caller does. `RemoteStreamCarrierError` names a retryable physical loss and reaches a domain only as the `carrierFailed` callback argument, never as a terminal outcome. `RemoteSnapshotStream` adds one opening snapshot followed by deltas. `RemoteJournalStream` adds follow-before-page opening, pagination, reconnect catch-up, and gap repair over domain-defined inclusive entry ranges; it removes complete duplicates and rejects gaps, inverted ranges, and partial overlaps. A domain may also carry cursorless notifications: they never advance or repair the durable cursor, and notifications received during gap repair publish only after the replacement page commits. If a newer generation supersedes that repair, held notifications from the superseded generation are discarded with its page. Disposing any stream cancels its requests and resolves after the active iterator is fully stopped. +`ctx.remote.$stream()` returns a single-consumer `RemoteStream` spanning physical carrier generations. For answering Clients it permits one immediate retry after an isolated stream failure while the carrier remains available; after physical WebSocket loss it waits for Connection to reopen the carrier. If the Host generation is already unavailable, it waits for the next connected generation. Each item carries its physical generation. Passive Clients cannot use `$stream()`; they call generated raw stream methods and handle terminal carrier failure themselves. The domain consumer validates and accepts each generation's opening value; business and protocol failures remain terminal. Every terminal failure leaves this face as a `RemoteError`, including exhausted carrier retries and a generation that ends before its opening value, so a stream consumer discriminates the same way a unary caller does. A failure whose `code` is `gateway/carrier-lost` names a retryable physical loss: `RemoteStreamCarrierError` carries that code, the `RemoteStreamCarrierFailure` type describes it, `isRemoteStreamCarrierFailure(error)` applies the same retry test for a domain that classifies its own failures, and a domain `ended` callback may return a plain `Error` with it to request reconnection without importing the class. Retry follows the code, not the class; the code is produced only inside the Client process, so a `RemoteError` from the Host terminates the stream even when it carries that code; such a failure reaches a domain only as the `carrierFailed` callback argument, never as a terminal outcome. `RemoteSnapshotStream` adds one opening snapshot followed by deltas. `RemoteJournalStream` adds follow-before-page opening, pagination, reconnect catch-up, and gap repair over domain-defined inclusive entry ranges; it removes complete duplicates and rejects gaps, inverted ranges, and partial overlaps. A domain may also carry cursorless notifications: they never advance or repair the durable cursor, and notifications received during gap repair publish only after the replacement page commits. If a newer generation supersedes that repair, held notifications from the superseded generation are discarded with its page. Disposing any stream cancels its requests and resolves after the active iterator is fully stopped. `ctx.remote.$on()` subscribes to one forwarded Host event. Its legal keys are exactly the Host assembly's forwarding selection, and the listener type is the owning package's own Cordis `Events` declaration, so no second signature can drift from it. Each subscription belongs to the calling fiber and disappears with it. The Client Remote service registers the `$events` pump as a Connection generation source only when `connection.interactions` is `answer`, whether any `$on` listener exists. With `none`, `$on()` is unavailable and the Client opens only the physical lifecycle socket; unary calls never wait for socket readiness. Browsers use Remote mux, while in-process compositions use `connection.rpc.open`; the opening `ready` item establishes a Connection generation and supplies its Host facts. Carrier failure, Remote stream failure, unexpected normal completion, a non-ready opening item, or a malformed event item ends that generation and lets Connection reopen it under continuous, capped jittered exponential backoff. Ordinary notifications run in registration order and isolate listener failures. Agent-scoped waterfalls let a listener return a result, call `next()`, or reject; Gateway returns that outcome through the existing HTTP unary carrier. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index 1dad623204..008b6af7bb 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -63,7 +63,7 @@ Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source `ctx.remote.$host` 以普通值读取固定的 Host 事实:`home`(首个 ready 帧之前为 undefined)与 `isLoopback`。它不是存储——没有订阅、没有代次计数——所以需要响应重连的消费方去监听 `connection/reset`,而不是轮询它。 -`ctx.remote.$stream()` 返回跨越多个物理载体代次的单消费方 `RemoteStream`。对于回答型 Client,载体仍可用时的独立流故障允许一次立即重试;物理 WebSocket 丢失后等待 Connection 重开载体。如果 Host generation 已不可用,则等待下一代连接。每个流项都带有其物理代次。被动 Client 不使用 `$stream()`,而是调用生成的原始流方法,并自行处理终态载体故障。领域消费方校验并接受各代次的 opening value;业务与协议错误仍然终止流。一切终态失败离开本面时都是 `RemoteError`,包括重试耗尽和在 opening value 之前就结束的代次,因此流消费方与一元调用方用同一种方式判别。`RemoteStreamCarrierError` 命名的是可重试的物理丢失,它只作为 `carrierFailed` 回调参数到达领域,绝不作为终态结果。`RemoteSnapshotStream` 在此之上规定每代由一个初始快照和后续 delta 组成。`RemoteJournalStream` 基于领域提供的 entry 闭区间提供 follow-before-page、分页、重连追赶与缺口修复;它丢弃完整重复项,并拒绝缺口、倒置区间和部分重叠。领域还可以携带无 cursor 的通知:通知绝不推进或修复持久 cursor,在缺口修复期间收到的通知只会在 replacement page 提交后发布。若更新代次取代该修复,旧代次 held notification 会与其 page 一同丢弃。对任一种流执行 dispose(资源释放)时,系统会取消该流的请求,并在活动 iterator 完全停止后完成资源释放。 +`ctx.remote.$stream()` 返回跨越多个物理载体代次的单消费方 `RemoteStream`。对于回答型 Client,载体仍可用时的独立流故障允许一次立即重试;物理 WebSocket 丢失后等待 Connection 重开载体。如果 Host generation 已不可用,则等待下一代连接。每个流项都带有其物理代次。被动 Client 不使用 `$stream()`,而是调用生成的原始流方法,并自行处理终态载体故障。领域消费方校验并接受各代次的 opening value;业务与协议错误仍然终止流。一切终态失败离开本面时都是 `RemoteError`,包括重试耗尽和在 opening value 之前就结束的代次,因此流消费方与一元调用方用同一种方式判别。`code` 为 `gateway/carrier-lost` 的失败表示可重试的物理丢失:`RemoteStreamCarrierError` 带有该 code,`RemoteStreamCarrierFailure` 类型描述它,`isRemoteStreamCarrierFailure(error)` 供自行分类失败的领域复用同一重试判断,领域的 `ended` 回调也可以返回带该 code 的普通 `Error` 来请求重连,而无需导入该 class。是否重试只看 code,不看 class;该 code 只在前端进程内产生,因此宿主返回的 `RemoteError` 即使带有该 code 也会终止流;这类失败只作为 `carrierFailed` 回调参数到达领域,绝不作为终态结果。`RemoteSnapshotStream` 在此之上规定每代由一个初始快照和后续 delta 组成。`RemoteJournalStream` 基于领域提供的 entry 闭区间提供 follow-before-page、分页、重连追赶与缺口修复;它丢弃完整重复项,并拒绝缺口、倒置区间和部分重叠。领域还可以携带无 cursor 的通知:通知绝不推进或修复持久 cursor,在缺口修复期间收到的通知只会在 replacement page 提交后发布。若更新代次取代该修复,旧代次 held notification 会与其 page 一同丢弃。对任一种流执行 dispose(资源释放)时,系统会取消该流的请求,并在活动 iterator 完全停止后完成资源释放。 `ctx.remote.$on()` 订阅一条被转发的 Host 事件。它的合法键恰好等于 Host 装配声明的转发选择,listener 类型就是事件所属包自己的 Cordis `Events` 声明,因此不存在会与之漂移的第二份签名。每个订阅归属调用方 fiber,并随该 fiber 一起消失。Client Remote 服务仅在 `connection.interactions` 为 `answer` 时把 `$events` pump 注册为 Connection generation source,无论当前是否存在 `$on` listener。选择 `none` 时,`$on()` 不可用,Client 只打开物理生命周期连接;unary 调用不等待 socket 就绪。浏览器使用 Remote mux,进程内组合使用 `connection.rpc.open`;opening `ready` 项建立 Connection generation 并提供 Host 信息。物理 carrier 失败、Remote 流故障、意外正常结束、非 ready 首项或畸形事件项都会终止该 generation,由 Connection 按持续且间隔封顶的带抖动指数退避重开。普通通知按注册顺序运行并隔离 listener 失败;Agent-scoped waterfall(瀑布式事件)允许 listener 返回结果、调用 `next()` 或拒绝,Gateway 再通过现有 HTTP 一元载体回送该结果。 diff --git a/packages/api/gateway/src/client/index.ts b/packages/api/gateway/src/client/index.ts index f0d2400dc8..3292afcfcc 100644 --- a/packages/api/gateway/src/client/index.ts +++ b/packages/api/gateway/src/client/index.ts @@ -34,7 +34,8 @@ import { type RemoteStreamOptions, } from './remote-stream.ts' -export { RemoteStreamCarrierError } from './stream-client.ts' +export { isRemoteStreamCarrierFailure, RemoteStreamCarrierError } from './stream-client.ts' +export type { RemoteStreamCarrierFailure } from './stream-client.ts' export { RemoteJournalStream } from './journal-stream.ts' export type { RemoteJournalChange, diff --git a/packages/api/gateway/src/client/journal-stream.ts b/packages/api/gateway/src/client/journal-stream.ts index ab013abdf3..2804feb0aa 100644 --- a/packages/api/gateway/src/client/journal-stream.ts +++ b/packages/api/gateway/src/client/journal-stream.ts @@ -1,7 +1,7 @@ /** Cursor, page, and live-tail coordination over a reconnecting Remote stream. */ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' -import { RemoteStreamCarrierError } from './stream-client.ts' +import { RemoteStreamCarrierError, type RemoteStreamCarrierFailure } from './stream-client.ts' import type { RemoteStream, RemoteStreamItem, @@ -75,7 +75,7 @@ export interface RemoteJournalStreamOptions) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal stream, page, or protocol failure after opening. */ readonly failed: (error: unknown) => void } diff --git a/packages/api/gateway/src/client/remote-stream.ts b/packages/api/gateway/src/client/remote-stream.ts index 00b398afd7..66b0f6544b 100644 --- a/packages/api/gateway/src/client/remote-stream.ts +++ b/packages/api/gateway/src/client/remote-stream.ts @@ -2,7 +2,7 @@ import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' -import { RemoteStreamCarrierError } from './stream-client.ts' +import { isRemoteStreamCarrierFailure, type RemoteStreamCarrierFailure } from './stream-client.ts' /** One item annotated with the physical Remote-stream generation that delivered it. */ export interface RemoteStreamItem { @@ -22,10 +22,13 @@ export interface RemoteStreamOptions { readonly name: string /** Open one physical generation of the logical stream. */ readonly open: (signal: AbortSignal) => AsyncIterable - /** Classify a normal generation end after or before its opening item was accepted. */ + /** + * Classify a normal generation end after or before its opening item was accepted; a returned error whose `code` is + * `gateway/carrier-lost` reconnects, and any other error is terminal. + */ readonly ended: (accepted: boolean) => Error /** Observe a retryable carrier loss before the supervisor waits or reopens. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void } /** @@ -129,7 +132,7 @@ export class RemoteStream implements AsyncIterable> } catch (error) { if (isAborted(this.lifetime.signal)) return if (revision !== this.revision) continue - if (!(error instanceof RemoteStreamCarrierError)) throw terminalStreamFailure(error) + if (!isRemoteStreamCarrierFailure(error)) throw terminalStreamFailure(error) this.options.carrierFailed?.(error) if (revision !== this.revision) continue attempt++ @@ -159,7 +162,7 @@ export class RemoteStream implements AsyncIterable> async function waitForRemoteStreamRetry( connection: Pick, - error: RemoteStreamCarrierError, + error: RemoteStreamCarrierFailure, attempt: number, signal: AbortSignal, ): Promise { @@ -199,7 +202,7 @@ async function waitForRemoteStreamRetry( /** * Mark a terminal escape before it crosses the stream boundary: consumers * discriminate failures by code, so an unmarked throw reads as a local bug. - * Marked failures pass through verbatim. The carrier class never escapes as a + * Marked failures pass through verbatim. A carrier failure never escapes as a * terminal outcome — it stays the retry-internal signal fed to `carrierFailed` * and the `ended(true)` retry trigger. */ diff --git a/packages/api/gateway/src/client/stream-client.ts b/packages/api/gateway/src/client/stream-client.ts index 0ada6c4055..1abe342b94 100644 --- a/packages/api/gateway/src/client/stream-client.ts +++ b/packages/api/gateway/src/client/stream-client.ts @@ -1,5 +1,5 @@ /** Client owner for the Gateway multiplexed Remote stream socket. */ -import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionWebSocket } from '@deepseek-ai/dsh-client-connection/client' import { @@ -11,8 +11,22 @@ import { import { Deque } from '@deepseek-ai/dsh-deque' import { randomUUID } from '@deepseek-ai/dsh-util-crypto' +/** + * Retryable physical Remote stream carrier failure. {@link RemoteStream} reconnects on any error whose `code` is + * `gateway/carrier-lost`, so a domain `ended` callback may return a plain `Error` carrying that code. The code is + * produced only inside this Client process; a `RemoteError` returned by the Host never counts as a carrier loss. + */ +export interface RemoteStreamCarrierFailure extends Error { + /** Stable carrier-loss code; class identity is not part of the retry decision. */ + readonly code: 'gateway/carrier-lost' +} + +const REMOTE_STREAM_CARRIER_CODE: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost' + /** Physical Remote stream socket failure that may be retried by a domain transport. */ -export class RemoteStreamCarrierError extends Error { +export class RemoteStreamCarrierError extends Error implements RemoteStreamCarrierFailure { + readonly code: RemoteStreamCarrierFailure['code'] = REMOTE_STREAM_CARRIER_CODE + /** * @param message - physical carrier failure description. * @param options - optional causal error. @@ -23,6 +37,18 @@ export class RemoteStreamCarrierError extends Error { } } +/** + * Whether a failure is a retryable carrier loss, judged by its `code` rather than its class. {@link RemoteStream} uses + * this test, and domains that classify their own failures, such as a disconnected view, reuse it. + * @param error - thrown or returned failure. + * @returns true for a locally produced `Error` whose `code` is `gateway/carrier-lost`; false for any `RemoteError`, + * which reached this Client from the Host and terminates the stream even when it carries that code. + */ +export function isRemoteStreamCarrierFailure(error: unknown): error is RemoteStreamCarrierFailure { + return error instanceof Error && remoteErrorOf(error) === undefined + && 'code' in error && error.code === REMOTE_STREAM_CARRIER_CODE +} + interface SocketWaiter { readonly revision: number resolve(socket: ConnectionWebSocket): void @@ -59,7 +85,7 @@ export class RemoteStreamMuxClient { private readonly socketClosures = new Set>() private running = false private disposed = false - private failure: RemoteStreamCarrierError | undefined + private failure: RemoteStreamCarrierFailure | undefined /** * @param openSocket - selected authenticated carrier; omission uses the browser socket. @@ -367,7 +393,7 @@ export class RemoteStreamMuxClient { () => undefined, (error: unknown) => { if (!this.running) return - const failure = error instanceof RemoteStreamCarrierError ? error + const failure = isRemoteStreamCarrierFailure(error) ? error : new RemoteStreamCarrierError('api gateway: Remote stream WebSocket failed to open', { cause: error }) if (this.revision === revision) this.failure = failure for (const waiter of [...this.waiters]) { diff --git a/packages/api/gateway/tests/control-retry.client.spec.ts b/packages/api/gateway/tests/control-retry.client.spec.ts index c818d507e7..02524e92dd 100644 --- a/packages/api/gateway/tests/control-retry.client.spec.ts +++ b/packages/api/gateway/tests/control-retry.client.spec.ts @@ -4,6 +4,7 @@ import type { ConnectionHandle } from '@deepseek-ai/dsh-api-remotes/client' import { RemoteStreamCarrierError, RemoteStream, + type RemoteStreamCarrierFailure, } from '../src/client/index.ts' const GENERATION = { id: 1, host: { home: '/home/fixture' } } @@ -118,6 +119,48 @@ describe('RemoteStream', () => { expect(carrierFailed).toHaveBeenNthCalledWith(2, repeated) }) + it('reconnects on a plain Error carrying the carrier code and stops on one without it', async () => { + const carrierLoss = Object.assign(new Error('domain stream ended'), { code: 'gateway/carrier-lost' as const }) + const carrierFailed = vi.fn<(error: RemoteStreamCarrierFailure) => void>() + const reconnecting = new RemoteStream(hostSource(true).connection, { + name: 'fixture stream', + open: scripted([{ values: ['first'] }, { values: ['second'], hold: true }]), + ended: accepted => accepted ? carrierLoss : new Error('generation ended before acceptance'), + carrierFailed, + }) + const iterator = reconnecting[Symbol.asyncIterator]() + const first = await iterator.next() + if (first.done) throw new Error('fixture generation ended early') + first.value.accept() + await expect(iterator.next()).resolves.toMatchObject({ done: false, value: { generation: 2, value: 'second' } }) + expect(carrierFailed).toHaveBeenCalledExactlyOnceWith(carrierLoss) + await reconnecting.dispose() + + const plain = new Error('domain stream ended') + const terminal = new RemoteStream(hostSource(true).connection, { + name: 'fixture stream', + open: scripted([{ values: ['first'] }, { values: ['unreached'] }]), + ended: () => plain, + }) + const stopping = terminal[Symbol.asyncIterator]() + const opened = await stopping.next() + if (opened.done) throw new Error('fixture generation ended early') + opened.value.accept() + await expect(stopping.next()).rejects.toMatchObject({ + isDSHRemoteError: true, code: 'gateway/internal', message: 'domain stream ended', cause: plain, + }) + expect(new RemoteStreamCarrierError('socket lost').code).toBe('gateway/carrier-lost') + }) + + it('terminates on a Host RemoteError even when it carries the carrier code', async () => { + const hostFailure = new RemoteError('gateway/carrier-lost' as never, 'host reused the carrier code', {} as never) + const carrierFailed = vi.fn<(error: RemoteStreamCarrierFailure) => void>() + const stream = supervisor(hostSource(true).connection, [{ terminal: hostFailure }, { values: ['unreached'] }], carrierFailed) + + await expect(stream[Symbol.asyncIterator]().next()).rejects.toBe(hostFailure) + expect(carrierFailed).not.toHaveBeenCalled() + }) + it('folds a non-Error terminal escape into a marked gateway/internal failure', async () => { const stream = new RemoteStream(hostSource(true).connection, { name: 'fixture stream', diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index e26f92ee09..e024d0c8b1 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -102,6 +102,7 @@ "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:*", "@deepseek-ai/dsh-web": "workspace:*" diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 5d91957c0a..5efb7dbeb7 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -27,6 +27,8 @@ import sessionFeedbackRemote from '@deepseek-ai/dsh-command-feedback/remote' import fileUploadsRemote from '@deepseek-ai/dsh-client-file-upload/remote' import sessionReferencesRemote from '@deepseek-ai/dsh-session-reference/remote' import subagentsRemote from '@deepseek-ai/dsh-subagent/remote' +import sessionStatusRemote from '@deepseek-ai/dsh-client-ui-session-status/remote' +export type {} from '@deepseek-ai/dsh-client-ui-session-status/remote' import sessionRemote from '@deepseek-ai/dsh-api-session-controller/remote' import jobRemote from '@deepseek-ai/dsh-api-job-controller/remote' import workspaceRemote from '@deepseek-ai/dsh-api-workspace-controller/remote' @@ -203,7 +205,8 @@ export async function apply(ctx: Context): Promise<() => Promise> { toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, - permissionPresetsRemote, subagentsRemote, sessionRemote, jobRemote, workspaceRemote, workspaceFilesRemote, terminalRemote, + permissionPresetsRemote, subagentsRemote, sessionRemote, sessionStatusRemote, jobRemote, + workspaceRemote, workspaceFilesRemote, terminalRemote, officeKitRemote, userQuestionsRemote, webRemote, ]) { disposers.push(await ctx.remote.$mount(contribution)) diff --git a/packages/api/session-controller/src/client/transport.ts b/packages/api/session-controller/src/client/transport.ts index 554eec515e..cc115f30cc 100644 --- a/packages/api/session-controller/src/client/transport.ts +++ b/packages/api/session-controller/src/client/transport.ts @@ -7,6 +7,7 @@ import { RemoteSnapshotStream, RemoteStreamCarrierError, type ClientRemote, + type RemoteStreamCarrierFailure, type RemoteJournalChange, type RemoteJournalFrame, } from '@deepseek-ai/dsh-api-gateway/client' @@ -91,7 +92,7 @@ export interface SessionControlStreamOptions { /** Apply a complete baseline or one later update. */ readonly accept: (frame: SessionControlFrame) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal business or protocol failure. */ readonly failed: (error: unknown) => void } @@ -101,7 +102,7 @@ export interface SessionEventStreamOptions { /** Apply one complete event-window change. */ readonly publish: (change: SessionJournalChange) => void /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal stream, page, or protocol failure after opening. */ readonly failed: (error: unknown) => void } diff --git a/packages/api/terminal-controller/src/client/model.ts b/packages/api/terminal-controller/src/client/model.ts index b1a87d8ae0..7ff08cb237 100644 --- a/packages/api/terminal-controller/src/client/model.ts +++ b/packages/api/terminal-controller/src/client/model.ts @@ -3,7 +3,7 @@ import { preferredShell, rememberShell } from './shell-preference.ts' import type { TerminalInventory } from './inventory.ts' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import { Deque } from '@deepseek-ai/dsh-deque' -import { RemoteStreamCarrierError, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import { isRemoteStreamCarrierFailure, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' import { RemoteError, remoteErrorOf, type RemoteResult, type RemoteStreamHandle, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -407,7 +407,7 @@ export class TerminalView { const failure = remoteErrorOf(error) const issue = failure?.code === 'terminal/view' ? failure.details.issue : failure?.code === 'terminal/limit-reached' ? 'terminalLimit' : failure?.code === 'terminal/unavailable' ? 'missingTerminal' : undefined if (!this.stopped() && issue === 'missingTerminal') this.inventory.remove(this.id) - this.patch({ phase: error instanceof RemoteStreamCarrierError ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) }) + this.patch({ phase: isRemoteStreamCarrierFailure(error) ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) }) } } diff --git a/packages/api/terminal-controller/tests/model.client.spec.ts b/packages/api/terminal-controller/tests/model.client.spec.ts index 6594514dbf..fb6790a7cf 100644 --- a/packages/api/terminal-controller/tests/model.client.spec.ts +++ b/packages/api/terminal-controller/tests/model.client.spec.ts @@ -287,6 +287,15 @@ it('classifies a discovery carrier failure as disconnected and supports explicit expect(remote.create).toHaveBeenCalledOnce() }) +it('classifies a Host RemoteError carrying the carrier code as failed, not disconnected', async () => { + const { model, remote } = fixture() + vi.mocked(remote.environment).mockRejectedValueOnce( + new RemoteError('gateway/carrier-lost' as never, 'host reused the carrier code', {} as never), + ) + await model.refresh() + expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'host reused the carrier code' }) +}) + it('retains state when disposal overtakes successful allocation or a failed discovery', async () => { for (const operation of ['creation', 'discovery'] as const) { const { model, remote } = fixture() diff --git a/packages/api/workspace-controller/src/client/index.ts b/packages/api/workspace-controller/src/client/index.ts index 3bbf4670a0..7f8246aa66 100644 --- a/packages/api/workspace-controller/src/client/index.ts +++ b/packages/api/workspace-controller/src/client/index.ts @@ -5,6 +5,7 @@ import { RemoteSnapshotStream, RemoteStreamCarrierError, type ClientRemote, + type RemoteStreamCarrierFailure, } from '@deepseek-ai/dsh-api-gateway/client' import type { WorkspaceFollowFrame, WorkspaceFollowIncrement } from '../types.ts' import type { WorkspaceFollowSink } from './model.ts' @@ -64,7 +65,7 @@ export interface WorkspaceStateStreamOptions { /** Destinations for decoded Workspace state operations. */ readonly accept: WorkspaceFollowSink /** Observe a retryable carrier loss before reconnection. */ - readonly carrierFailed?: (error: RemoteStreamCarrierError) => void + readonly carrierFailed?: (error: RemoteStreamCarrierFailure) => void /** Publish a terminal business or protocol failure. */ readonly failed: (error: unknown) => void } diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 47049ce8de..6af70f5ae7 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -276,7 +276,8 @@ - id: ui-session name: '@deepseek-ai/dsh-client-ui-session' - # Session status table behind ctx.uiSession.sessionStatus and useSessionStatus. + # Host reading records (ctx.sessionStatus) and the Session status table behind + # ctx.uiSession.sessionStatus and useSessionStatus. - id: ui-session-status name: '@deepseek-ai/dsh-client-ui-session-status' diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 008dfa67de..41d0bee797 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -37,7 +37,7 @@ The `/client` entrypoint of a UI plugin package is its public browser API, not a 1. **A UI plugin exports no values beyond what cordis loading needs** — `apply` / `inject` (and `Config` where present), plus store factories consumed type-only by components (`ReturnType`). Shared types (owner data, injected values, composed prop aliases) may also be exported. Implementation components, pure helpers, constants, and store handles stay internal. Adding any new value export requires user sign-off, not a matching consumer. 2. **Same-package tests import internals directly** — relative `../src/client/xxx.ts` from package tests, or the `./src/*` subpath where a spec lives outside the package. Never widen the public API to make a test compile. -3. **A feature plugin MUST NOT runtime-import or re-export another feature plugin's values, and MUST NOT declare `dsh.client.external` to obtain them.** Shared declarations use `import type`; behavior crosses packages through injected Cordis services, and UI crosses packages through slots. If neither fits, stop and escalate — do not add an export to unblock yourself. Shared runtime code belongs only in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package; transport and generated API assemblies keep their explicit infrastructure edges. +3. **A feature plugin MUST NOT runtime-import or re-export another feature plugin's values, and MUST NOT declare `dsh.client.external` to obtain them.** Shared declarations use `import type`; behavior crosses packages through injected Cordis services, and UI crosses packages through slots. If neither fits, stop and escalate — do not add an export to unblock yourself. Shared runtime code belongs only in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package; a feature plugin may request a `packages/api/` row's runtime values through `dsh.client.external`, and transport and generated API assemblies keep their explicit infrastructure edges. ## ctx discipline (components never see ctx) @@ -81,7 +81,7 @@ Client business code may statically read `process.env.DSH_CLIENT_*`; every refer A dynamic browser half either carries a module privately or requests the shared module-table identity. The client baseline is centralized in [`web/src/platform.ts`](web/src/platform.ts): `PLATFORM_MODULES` names shell-seeded React, Cordis, selected third-party libraries, and static Client libraries; `PRELOADED_CLIENT_EXTERNALS` is reserved for dynamic rows whose factories must arrive before shell boot and is empty when no such row exists. 1. **Baseline externals are implicit for every dynamic bundle.** Do not repeat entries from `PLATFORM_MODULES` in `dsh.client.external`; npm dependency declarations still follow the dependency rules above. -2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Only infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table. Declare the exact import specifier; only a trailing `/client` aliases the package row. +2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table; a feature plugin may request only rows under `packages/api/`. Declare the exact import specifier; only a trailing `/client` aliases the package row. 3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request. 4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. 5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 0ae9892b80..6d52c7f559 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 292a25cf1a426b56 - zh: ca765789a28289f8 + en: 45c1d8a1e1f44425 + zh: 47a5199bca1e7836 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index c7744a38b3..4efbbb0710 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -39,7 +39,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-renderer/`](ui-renderer/README.md) | Binds slot data to React and mounts the assembled application | `ctx.uiRenderer` | | [`ui-slots/`](ui-slots/README.md) | Defines typed extension Slots and reusable Component Factories | — | | [`ui-session/`](ui-session/README.md) | Adapts Session Controller state into standard Slot sources and hooks | — | -| [`ui-session-status/`](ui-session-status/README.md) | Combines running state, the effective pending interaction, and completion reminders into the Session status table behind `useSessionStatus` | `ctx.uiSession.sessionStatus` | +| [`ui-session-status/`](ui-session-status/README.md) | Keeps reading reminders in Host memory and combines running state, the effective pending interaction, and shared reminders into the Session status table behind `useSessionStatus` | `ctx.sessionStatus` / `ctx.uiSession.sessionStatus` | | [`ui-theme/`](ui-theme/README.md) | Applies the selected color theme | — | | [`ui-primitives/`](ui-primitives/README.md) | Provides shared React controls, icons, and content renderers | — | | [`ui-attachment/`](ui-attachment/README.md) | Registers composer and message-image attachment presentation | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 67fba60515..1bb3677465 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -39,7 +39,7 @@ kind: "package-group" | [`ui-renderer/`](ui-renderer/README.zh.md) | 将 slot 数据绑定到 React,并挂载组装完成的应用 | `ctx.uiRenderer` | | [`ui-slots/`](ui-slots/README.zh.md) | 定义类型化扩展 Slots 与可复用 Component Factory | — | | [`ui-session/`](ui-session/README.zh.md) | 把会话控制器状态适配为标准 Slot source 与钩子 | — | -| [`ui-session-status/`](ui-session-status/README.zh.md) | 把运行状态、生效的待交互请求和完成提醒汇总为会话状态表,并通过 `useSessionStatus` 提供 | `ctx.uiSession.sessionStatus` | +| [`ui-session-status/`](ui-session-status/README.zh.md) | 在宿主内存中保存阅读提醒,并把运行状态、生效的待交互请求和共享提醒汇总为会话状态表,通过 `useSessionStatus` 提供 | `ctx.sessionStatus` / `ctx.uiSession.sessionStatus` | | [`ui-theme/`](ui-theme/README.zh.md) | 应用所选颜色主题 | — | | [`ui-primitives/`](ui-primitives/README.zh.md) | 提供共享 React 控件、图标与内容渲染器 | — | | [`ui-attachment/`](ui-attachment/README.zh.md) | 注册输入框与消息图片的附件呈现 | — | diff --git a/packages/client/product-analytics/tests/collection.client.spec.ts b/packages/client/product-analytics/tests/collection.client.spec.ts index bdf5e7e5c5..b94a60921b 100644 --- a/packages/client/product-analytics/tests/collection.client.spec.ts +++ b/packages/client/product-analytics/tests/collection.client.spec.ts @@ -95,7 +95,7 @@ it('fails closed on stream loss and accepts a fresh policy after reconnection', const b = await setup() b.options().open(new AbortController().signal) expect(b.options().ended(true).message).toContain('policy stream ended') - b.options().carrierFailed?.(new Error('offline')) + b.options().carrierFailed?.(Object.assign(new Error('offline'), { code: 'gateway/carrier-lost' as const })) expect(b.ctx.productAnalytics.enabled).toBe(false) await b.policy(true) await b.fail() diff --git a/packages/client/ui-account-notifications/tests/apply.client.spec.ts b/packages/client/ui-account-notifications/tests/apply.client.spec.ts index ba0b42bfd2..d6c5918e68 100644 --- a/packages/client/ui-account-notifications/tests/apply.client.spec.ts +++ b/packages/client/ui-account-notifications/tests/apply.client.spec.ts @@ -297,7 +297,9 @@ it('clears notifications and stops polling when the account carrier fails', asyn const open = c.ctx.remote.$stream.bind(c.ctx.remote) let fail: (() => void) | undefined vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { - if (options.name === 'account') fail = () => { options.carrierFailed?.(new Error('connection lost')) } + if (options.name === 'account') fail = () => { + options.carrierFailed?.(Object.assign(new Error('connection lost'), { code: 'gateway/carrier-lost' as const })) + } return open(options) }) await c.reload(SELF) diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 3f894b097c..3d1d210aeb 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: d502ab38773eef34 - zh: e1f9c4edbc74c38f + en: ffbcd39a17cd2fb1 + zh: db21ca6ca1cdf853 /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 /deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: - en: 9b0b6a8505a9ebbf - zh: beb5d89f80463b3e + en: 24377b9e51d557de + zh: 9205961784386745 /deepseek-ai-dsh-client-ui-agent-team/further-exploration: en: 4d9214370681b02e zh: 4acb21b9ecf25e85 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index 7e87010dcb..24a7572af0 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, turn on **Enable agent teamwork**. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire Team row highlights on hover and toggles the selection when clicked, except for its independent information button. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The adjacent information button explains shared-task coordination and additional token use on hover, keyboard focus, or click/tap without changing the selection. Escape or an outside press dismisses the explanation. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. @@ -47,7 +47,7 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
Implementation internals — click to expand -The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. Disposing the plugin fiber removes its registrations. +The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations. The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index c0db84fe78..ba3a240d1e 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,9 +25,9 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中打开**启用智能体团队协作**。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。团队设置整行在悬停时高亮,点击可切换状态,但独立的信息按钮除外。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。旁边的信息按钮可通过悬停、键盘聚焦或点击/轻触查看共享任务协作与额外 token 消耗的说明,不改变开关状态。按 Escape 或点击外部可关闭说明。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 -会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 +会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成功的回执。失败回执仍显示 Users 图标、本地化的“智能体团队协作”标题,以及本地化的失败前缀和已记录原因的首个非空行,不翻译原因原文。展开回执可查看完整原始错误。参数无法识别或缺失时仍显示回执。 @@ -47,7 +47,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
实现细节——点击展开 -Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。销毁插件 fiber 会移除这些注册。 +Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。 Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index 75eedfb3e7..17797b2eb3 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -1,3 +1,71 @@ +.summary { + display: flex; + align-items: center; + gap: 6px; + box-sizing: border-box; + width: 100%; + height: 34px; + padding: 0 8px; + border: 0; + border-radius: var(--dsw-radius-md); + background: transparent; + color: var(--dsw-alias-label-primary); + font-family: inherit; + font-size: 13px; + font-weight: 400; + line-height: 20px; + text-align: start; + cursor: pointer; +} + +.summary:disabled { + opacity: 0.5; + cursor: default; +} + +.summary:focus-visible { + outline: none; + background: var(--dsw-alias-interactive-bg-hover); +} + +.summaryLabel { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.state, +.chevron { + flex: none; +} + +.state { + color: var(--dsw-alias-label-tertiary); +} + +.chevron { + width: 12px; + height: 12px; + color: var(--dsw-alias-menu-icon); +} + +.pane { + display: flex; + flex-direction: column; + min-width: 0; +} + +.description { + margin: 0; + padding: 4px 8px; + color: var(--dsw-alias-label-secondary); + font-size: 12px; + line-height: 18px; + overflow-wrap: anywhere; +} + .row { position: relative; display: flex; @@ -13,25 +81,14 @@ } .label { - display: inline-flex; - align-items: center; - gap: 4px; min-width: 0; + overflow-wrap: anywhere; } -.infoButton { - position: relative; - z-index: 1; - flex: none; - width: 20px; - height: 20px; - padding: 0; - color: var(--dsw-alias-label-caption); -} - -/* Extend the native switch hit target without nesting the information button. */ +/* The switch owns the whole row's pointer target. */ .row .toggle { position: static; + flex: none; } .toggle::after { @@ -41,11 +98,8 @@ border-radius: var(--dsw-radius-md); } -.row:has(.toggle:focus-visible) { - background: var(--dsw-alias-interactive-bg-hover); -} - @media (hover: hover) { + .summary:not(:disabled):hover, .row:has(.toggle:not(:disabled)):hover { background: var(--dsw-alias-interactive-bg-hover); } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index cd0d3dcafa..0033b8fdb9 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -1,7 +1,7 @@ -/** Session-owned Agent Teams selection in the model and reasoning menu. */ +/** Session-owned Agent Teams summary and settings inside the model menu. */ -import { useState } from 'react' -import { Button, IconInfoOutlineRegular, Switch, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { useId, useState } from 'react' +import { IconChevronRightOutlineRegular, Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import type {} from '@deepseek-ai/dsh-agent-team/client' @@ -9,37 +9,72 @@ import type {} from '@deepseek-ai/dsh-agent' import type { NS } from './locales.ts' import css from './TeamModeToggle.module.css' -/** Session selection callbacks supplied by the Client plugin. */ -export interface TeamModeToggleInjected { +/** Session selection callbacks supplied to the Team settings pane. */ +export interface TeamModePaneInjected { /** Save the selection; null means success, otherwise the string describes the failure. */ selectTeamMode: (enabled: boolean) => Promise /** Open a Session-targeted confirmation outside this menu. */ requestDisableConfirmation: () => void } -/** Full props of the model-menu Team switch. */ -export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> - & PropsLocale & TeamModeToggleInjected +/** Full props of the model-menu Team summary. */ +export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> & PropsLocale + +/** Full props of the model-menu Team settings pane. */ +export type TeamModePaneProps = PropsRuntime<'conversation.input.model.pane'> + & PropsLocale & TeamModePaneInjected /** - * Render the saved selection without an optimistic update. - * @param props - Session projection, menu state, localized copy, and selection callback. - * @returns the Team switch when the capability projection is available. + * Show the saved Team state and open its settings without changing the mode. + * @param props - Session projection, pane navigation, and locale. + * @returns the summary when Team mode is available on a root Session. */ export function TeamModeToggle(props: TeamModeToggleProps) { const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') if (addressedChild || listedChild) return null - return + return +} + +function RootTeamModeSummary({ useProjection, locked, openPane, t }: TeamModeToggleProps) { + const mode = useProjection('agentTeam') + if (mode === undefined) return null + return ( + + ) +} + +/** + * Present the explanation and persisted Team switch for a root Session. + * @param props - Session projections, mode operations, menu dismissal, and locale. + * @returns the Team settings content when its projection is available. + */ +export function TeamModePane(props: TeamModePaneProps) { + const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) + const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') + if (addressedChild || listedChild) return null + return } /** Read and change the selection only for root Sessions. */ -function RootTeamModeToggle({ +function RootTeamModePane({ useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, -}: TeamModeToggleProps) { +}: TeamModePaneProps) { const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) + const descriptionId = useId() if (mode === undefined) return null const select = (enabled: boolean): void => { if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { @@ -55,16 +90,12 @@ function RootTeamModeToggle({ }).finally(() => { setPending(false) }) } return ( -
- - {t('mode.label')} - - - - - +
+
+ {t('mode.label')} + +
+

{t('mode.description')}

) } diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index 0c5b29a4fb..f7bba69ff8 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -14,15 +14,16 @@ export const zh = { 'command.failed': '执行失败', 'command.failedReason': '执行失败:{reason}', trigger: '任务板', - 'mode.label': '启用智能体团队协作', - 'mode.infoLabel': '关于智能体团队协作', + 'mode.label': '开启智能体团队协作', + 'mode.on': '开启', + 'mode.off': '关闭', 'mode.description': '通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', 'mode.failed': '无法确认智能体团队协作设置已保存,请重试:{message}', - 'disable.title': '确认停用智能体团队协作?', - 'disable.description': '对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', - 'disable.warning': '停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。', + 'disable.title': '确认关闭智能体团队协作?', + 'disable.description': '对话过程中关闭智能体团队协作,将停止共享任务工具和团队协调指令。', + 'disable.warning': '关闭后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。', 'disable.cancel': '取消', - 'disable.confirm': '确认停用', + 'disable.confirm': '确认关闭', 'disable.close': '关闭', loading: '正在加载任务板…', unavailable: '任务板暂不可用', @@ -52,7 +53,8 @@ export const en = { 'command.failedReason': 'Failed: {reason}', trigger: 'Task board', 'mode.label': 'Enable agent teamwork', - 'mode.infoLabel': 'About agent teamwork', + 'mode.on': 'On', + 'mode.off': 'Off', 'mode.description': 'Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', 'mode.failed': 'Could not confirm the agent teamwork setting was saved. Try again: {message}', 'disable.title': 'Disable agent teamwork?', @@ -85,7 +87,8 @@ export const ja = { 'command.failed': '実行失敗', 'command.failedReason': '実行失敗: {reason}', 'mode.label': 'エージェント連携を有効にする', - 'mode.infoLabel': 'エージェント連携について', + 'mode.on': 'オン', + 'mode.off': 'オフ', 'mode.description': '共有タスクボードで複数のエージェントの分担と進捗を調整します。複雑なタスクでより良い結果が得られますが、その分トークンのコストも高くなります。', 'mode.failed': 'エージェント連携の設定が保存されたことを確認できませんでした。再試行してください: {message}', 'disable.title': 'エージェント連携を無効にしますか?', @@ -119,7 +122,8 @@ export const es = { 'command.failed': 'Error', 'command.failedReason': 'Error: {reason}', 'mode.label': 'Activar colaboración entre agentes', - 'mode.infoLabel': 'Acerca de la colaboración entre agentes', + 'mode.on': 'Activada', + 'mode.off': 'Desactivada', 'mode.description': 'Coordina el trabajo y el progreso de varios agentes mediante un tablero de tareas compartido, con mejores resultados en tareas complejas y un coste de tokens proporcionalmente mayor.', 'mode.failed': 'No se pudo confirmar que se guardó la configuración de colaboración entre agentes. Inténtalo de nuevo: {message}', 'disable.title': '¿Desactivar la colaboración entre agentes?', @@ -153,7 +157,8 @@ export const fr = { 'command.failed': 'Échec', 'command.failedReason': 'Échec : {reason}', 'mode.label': 'Activer la collaboration entre agents', - 'mode.infoLabel': 'À propos de la collaboration entre agents', + 'mode.on': 'Activée', + 'mode.off': 'Désactivée', 'mode.description': 'Coordonnez la répartition du travail et la progression de plusieurs agents via un tableau de tâches partagé, pour de meilleurs résultats sur les tâches complexes, avec un coût en tokens plus élevé en contrepartie.', 'mode.failed': 'Impossible de confirmer l’enregistrement du réglage de collaboration entre agents. Réessayez : {message}', 'disable.title': 'Désactiver la collaboration entre agents ?', @@ -187,7 +192,8 @@ export const de = { 'command.failed': 'Fehlgeschlagen', 'command.failedReason': 'Fehlgeschlagen: {reason}', 'mode.label': 'Agentenzusammenarbeit aktivieren', - 'mode.infoLabel': 'Über Agentenzusammenarbeit', + 'mode.on': 'Ein', + 'mode.off': 'Aus', 'mode.description': 'Koordiniert die Arbeitsteilung und den Fortschritt mehrerer Agenten über eine gemeinsame Aufgabenübersicht. Erzielt bessere Ergebnisse bei komplexen Aufgaben, bei entsprechend höheren Tokenkosten.', 'mode.failed': 'Das Speichern der Einstellung zur Agentenzusammenarbeit konnte nicht bestätigt werden. Erneut versuchen: {message}', 'disable.title': 'Agentenzusammenarbeit deaktivieren?', @@ -221,7 +227,8 @@ export const ru = { 'command.failed': 'Ошибка', 'command.failedReason': 'Ошибка: {reason}', 'mode.label': 'Включить совместную работу агентов', - 'mode.infoLabel': 'О совместной работе агентов', + 'mode.on': 'Вкл.', + 'mode.off': 'Выкл.', 'mode.description': 'Координируйте распределение работы и прогресс нескольких агентов с помощью общей доски задач: лучшие результаты в сложных задачах при соответственно более высоких затратах на токены.', 'mode.failed': 'Не удалось подтвердить сохранение настройки совместной работы агентов. Повторите попытку: {message}', 'disable.title': 'Отключить совместную работу агентов?', @@ -255,7 +262,8 @@ export const pt = { 'command.failed': 'Falha', 'command.failedReason': 'Falha: {reason}', 'mode.label': 'Ativar colaboração entre agentes', - 'mode.infoLabel': 'Sobre a colaboração entre agentes', + 'mode.on': 'Ativada', + 'mode.off': 'Desativada', 'mode.description': 'Coordene a divisão do trabalho e o progresso de vários agentes com um quadro de tarefas compartilhado, para melhores resultados em tarefas complexas, com custos de tokens proporcionalmente maiores.', 'mode.failed': 'Não foi possível confirmar que a configuração de colaboração entre agentes foi salva. Tente novamente: {message}', 'disable.title': 'Desativar a colaboração entre agentes?', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index 833267e39e..c2dec89b0a 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -11,7 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' -import { TeamModeToggle, type TeamModeToggleInjected } from './TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from './TeamModeToggle.tsx' import { TeamBoard } from './TeamBoard.tsx' import { TeamCommandRow } from './TeamCommandRow.tsx' import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' @@ -58,11 +58,14 @@ export function registerAgentTeamUi(ctx: ClientContext): void { name: 'conversation.input.model.options', id: 'agent-team', locale: NS, - inject: (sessionId): TeamModeToggleInjected => ({ + }, TeamModeToggle)) + yield scope.slots.inject('conversation.input.model.pane', () => scope.slots.register({ + name: 'conversation.input.model.pane', key: 'agent-team', locale: NS, + inject: (sessionId): TeamModePaneInjected => ({ selectTeamMode: enabled => selectTeamMode(sessionId, enabled), requestDisableConfirmation: () => { disableRequest.set({ sessionId }) }, }), - }, TeamModeToggle)) + }, TeamModePane)) }) }) ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index b4653d619f..95011ef4cf 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleInjected } from '../src/client/TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from '../src/client/TeamModeToggle.tsx' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { TeamBoard } from '../src/client/TeamBoard.tsx' @@ -63,21 +63,30 @@ describe('task-board browser plugin', () => { await b.fiber.dispose() }) - it('registers the mode switch when Agent Teams arrives and reports each execution outcome', async () => { + it('registers the summary and settings pane when Agent Teams arrives and reports each execution outcome', async () => { const b = await bench() b.ctx.slots.register({ name: 'conversation.input.model', - children: { 'conversation.input.model.options': { kind: 'list', scope: 'session' } }, + children: { + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.pane': { kind: 'keyed', scope: 'session' }, + }, } as never, () => null) const entry = () => b.ctx.slots.entries('conversation.input.model.options') .find(candidate => candidate.component === TeamModeToggle) + const page = () => b.ctx.slots.entries('conversation.input.model.pane') + .find(candidate => candidate.component === TeamModePane) expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() const setEnabled = vi.fn() new TestRemote(b.ctx, { agentTeams: { setEnabled } }) - await vi.waitFor(() => { expect(entry()).toBeDefined() }) - const injected = entry()!.inject as (sessionId: SessionId) => Record + await vi.waitFor(() => { expect(entry()).toBeDefined(); expect(page()).toBeDefined() }) + expect(entry()).toMatchObject({ options: { id: 'agent-team' }, locale: 'agent-team' }) + expect(entry()!.inject).toBeUndefined() + expect(page()).toMatchObject({ options: { key: 'agent-team' }, locale: 'agent-team' }) + const injected = page()!.inject as (sessionId: SessionId) => Record const value: object = injected(brandString('chosen-session')) - const mode = value as TeamModeToggleInjected + const mode = value as TeamModePaneInjected setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) await expect(mode.selectTeamMode(true)).resolves.toBeNull() expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', true) @@ -105,6 +114,7 @@ describe('task-board browser plugin', () => { mode.requestDisableConfirmation() await b.fiber.dispose() expect(entry()).toBeUndefined() + expect(page()).toBeUndefined() expect(overlayEntry()).toBeUndefined() expect(request.getSnapshot()).toBeNull() }) diff --git a/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx index e40889f400..1fd7191329 100644 --- a/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx @@ -49,8 +49,8 @@ it('renders nothing when no disable request exists', () => { it('shows the localized title, two paragraphs, and actions without a checkbox', () => { const input = props() render() - const dialog = within(screen.getByRole('dialog', { name: '确认停用智能体团队协作?' })) - expect(dialog.getByRole('heading', { name: '确认停用智能体团队协作?' })).toBeTruthy() + const dialog = within(screen.getByRole('dialog', { name: '确认关闭智能体团队协作?' })) + expect(dialog.getByRole('heading', { name: '确认关闭智能体团队协作?' })).toBeTruthy() expect(dialog.getByText(zh['disable.description'], { selector: 'p' })).toBeTruthy() expect(dialog.getByText(zh['disable.warning'], { selector: 'p' })).toBeTruthy() expect(dialog.getAllByRole('paragraph')).toHaveLength(2) diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index b2d401d16c..895b79f6ba 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -1,19 +1,18 @@ // @vitest-environment jsdom -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionId } from '@deepseek-ai/dsh-session' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { TeamModeToggle, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { TeamModePane, TeamModeToggle, type TeamModePaneProps, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' import { brandString } from '@deepseek-ai/dsh-brand' -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) +afterEach(cleanup) -function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TeamModeToggleProps { +type TestProps = TeamModePaneProps & TeamModeToggleProps + +function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TestProps { return { sessionId: brandString('root'), useSession: (select: (value: { subagent: object | null }) => unknown) => select({ subagent: child === 'addressed' ? {} : null }), @@ -21,69 +20,108 @@ function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => useProjection: (key: string) => key === 'modelSelection' ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } : enabled === undefined ? undefined : { enabled, tasks: [] }, - locked: false, dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + locked: false, openPane: vi.fn(), dismiss: vi.fn(), reportFailure: vi.fn(), + selectTeamMode, requestDisableConfirmation: vi.fn(), t: makeTranslate(zh), - } as TeamModeToggleProps + } as TestProps } -it('renders only available mode and waits for persisted state before displaying a new selection', async () => { - let finish!: (result: string | null) => void - const select = vi.fn(() => new Promise((resolve) => { finish = resolve })) - const view = render() +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => + [false, true].map(enabled => ({ locale, dictionary, enabled })), +))('opens Team settings from the $locale summary without changing mode (enabled: $enabled)', ({ locale, dictionary, enabled }) => { + const input = props(enabled) + render() + const summary = screen.getByRole('menuitem', { name: new RegExp(dictionary['command.title']) }) + expect(summary.textContent).toBe(dictionary['command.title'] + dictionary[enabled ? 'mode.on' : 'mode.off']) + if (locale === 'zh') expect(summary.textContent).toBe(`智能体团队协作${enabled ? '开启' : '关闭'}`) + expect(summary.getAttribute('data-model-menu-pane')).toBe('agent-team') expect(screen.queryByRole('switch')).toBeNull() - view.rerender() - const toggle = screen.getByRole('switch', { name: '启用智能体团队协作' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByText(dictionary['mode.description'])).toBeNull() + fireEvent.click(summary) + expect(input.openPane).toHaveBeenCalledExactlyOnceWith({ key: 'agent-team', title: dictionary['command.title'] }) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() +}) + +it('keeps summary state projection-owned and blocks navigation while locked', () => { + const input = props(false) + const view = render() + expect(screen.getByText('关闭')).toBeTruthy() + const lockedInput = props(true) + view.rerender() + expect(screen.getByText('开启')).toBeTruthy() + const summary = screen.getByRole('menuitem') + expect(summary.hasAttribute('disabled')).toBe(true) + fireEvent.click(summary) + expect(lockedInput.openPane).not.toHaveBeenCalled() +}) + +it('allows reading settings from the summary while model history loads', () => { + const input = props(false, undefined, undefined, 'loading') + render() + fireEvent.click(screen.getByRole('menuitem')) + expect(input.openPane).toHaveBeenCalledOnce() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it.each([false, true])('blocks repeated writes while waiting for persisted mode (enabled: %s)', async (enabled) => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const select = vi.fn(() => pending.promise) + const view = render() + const toggle = screen.getByRole('switch', { name: '开启智能体团队协作' }) + toggle.focus() fireEvent.click(toggle) - expect(select).toHaveBeenCalledWith(true) - expect(toggle.getAttribute('aria-checked')).toBe('false') + expect(select).toHaveBeenCalledExactlyOnceWith(!enabled) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) expect(toggle.hasAttribute('disabled')).toBe(true) - await act(async () => { finish(null) }) - view.rerender() - expect(toggle.getAttribute('aria-checked')).toBe('true') + fireEvent.click(toggle) + fireEvent.click(toggle) + expect(select).toHaveBeenCalledTimes(1) + await act(async () => { pending.resolve(null) }) + expect(toggle.getAttribute('aria-checked')).toBe(String(enabled)) + expect(toggle.hasAttribute('disabled')).toBe(false) + view.rerender() + expect(toggle.getAttribute('aria-checked')).toBe(String(!enabled)) }) it.each(['returned', 'error', 'string'])('reports rejected mode writes through the menu host (%s)', async (failure) => { - const p = props(false, vi.fn(async () => { + const input = props(false, vi.fn(async () => { if (failure === 'error') throw new Error('offline') if (failure === 'string') throw 'offline' return 'offline' })) - render() - await act(async () => { fireEvent.click(screen.getByRole('switch')) }) - expect(p.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) + render() + const toggle = screen.getByRole('switch') + toggle.focus() + await act(async () => { fireEvent.click(toggle) }) + expect(input.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false) }) it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => [false, true].map(locked => ({ locale, dictionary, locked })), -))('opens the $locale explanation without changing Team mode (locked: $locked)', ({ dictionary, locked }) => { - vi.stubGlobal('ResizeObserver', class { - observe() {} - unobserve() {} - disconnect() {} - }) +))('shows the full $locale explanation in the settings pane (locked: $locked)', ({ dictionary, locked }) => { const input = props(false) - render() - const info = screen.getByRole('button', { name: dictionary['mode.infoLabel'] }) - expect(info.hasAttribute('disabled')).toBe(false) - fireEvent.click(info) - const tooltip = screen.getByRole('tooltip', { hidden: true }) - expect(tooltip.textContent).toBe(dictionary['mode.description']) - expect(info.getAttribute('aria-describedby')).toBe(tooltip.id) - expect(document.body.contains(tooltip)).toBe(true) - expect(input.selectTeamMode).not.toHaveBeenCalled() - expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') - fireEvent.keyDown(info, { key: 'Escape' }) - expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() - fireEvent.click(info) - fireEvent.pointerDown(document.body) + render() + const description = screen.getByText(dictionary['mode.description'], { exact: true }) + expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(screen.queryByRole('button')).toBeNull() + const toggle = screen.getByRole('switch', { name: dictionary['mode.label'], description: dictionary['mode.description'] }) + expect(document.activeElement === toggle).toBe(!locked) + expect(toggle.compareDocumentPosition(description) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(toggle.hasAttribute('disabled')).toBe(locked) + expect(toggle.getAttribute('aria-checked')).toBe('false') expect(input.selectTeamMode).not.toHaveBeenCalled() }) -it('requests confirmation before disabling after a recorded model request', () => { +it('dismisses the menu before requesting disable confirmation after a recorded model request', () => { const input = props(true, undefined, undefined, true) - render() + render() fireEvent.click(screen.getByRole('switch')) expect(input.dismiss).toHaveBeenCalledOnce() expect(input.dismiss).toHaveBeenCalledBefore(vi.mocked(input.requestDisableConfirmation)) @@ -94,39 +132,52 @@ it('requests confirmation before disabling after a recorded model request', () = it.each([false, true])('enables directly regardless of model history (requested: %s)', async (requested) => { const input = props(false, undefined, undefined, requested) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(true) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) it('disables directly when a model is selected but no request has been recorded', async () => { const input = props(true) - render() + render() await act(async () => { fireEvent.click(screen.getByRole('switch')) }) expect(input.selectTeamMode).toHaveBeenCalledWith(false) expect(input.requestDisableConfirmation).not.toHaveBeenCalled() + expect(input.dismiss).not.toHaveBeenCalled() }) -it('waits for model history before allowing the switch to change', () => { +it('waits for model history before allowing the settings switch to change', () => { const input = props(true, undefined, undefined, 'loading') - render() + render() expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) fireEvent.click(screen.getByRole('switch')) expect(input.selectTeamMode).not.toHaveBeenCalled() expect(input.requestDisableConfirmation).not.toHaveBeenCalled() }) -it('disables selection while the Session is locked', () => { - render() - expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings pane', Component: TeamModePane }, +])('hides the $name until the Team projection is available', ({ Component }) => { + const { container } = render() + expect(container.textContent).toBe('') + expect(screen.queryByRole('menuitem')).toBeNull() + expect(screen.queryByRole('switch')).toBeNull() }) -it.each(['addressed', 'listed'] as const)('hides the switch on a child Session (%s)', (source) => { - const input = props(false, undefined, source) - const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) - render() - expect(screen.queryByRole('switch')).toBeNull() - expect(useProjection).not.toHaveBeenCalled() - expect(input.selectTeamMode).not.toHaveBeenCalled() -}) +it.each([ + { name: 'summary', Component: TeamModeToggle }, + { name: 'settings pane', Component: TeamModePane }, +].flatMap(entry => (['addressed', 'listed'] as const).map(child => ({ ...entry, child }))))( + 'hides the $name on a $child child Session', ({ Component, child }) => { + const input = props(false, undefined, child) + const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) + const { container } = render() + expect(container.textContent).toBe('') + expect(useProjection).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.openPane).not.toHaveBeenCalled() + }, +) diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index fd72dbc593..759d52d183 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -19,7 +19,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../../api/workspace-controller/tsconfig.client.json" diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index f0b4774867..67ffdadf02 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 80fc237fa5c829f7 - zh: ecff5c8526f45996 + en: b4c2e8c1f7ab4de5 + zh: 5dd0e14aa5f9d334 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: c1d14a925c92950f zh: f80f8169bc283c60 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index ec0aba0d4e..3303f8bbae 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -61,7 +61,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list slot appends controls below model and reasoning selection. Owner props expose `locked`, `reportFailure(message)`, and `dismiss()`, which closes the menu and synchronously focuses its trigger before another overlay opens; contributions read their own projections and supply narrow commands. Enabled switch buttons participate in the menu’s keyboard navigation. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPane({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.pane` slot; the invoking button's `data-model-menu-pane` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail panes share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail pane as a group named by `title`; the pane places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail pane without activating its switch. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 864d3ea9ff..1abd873ddd 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -61,7 +61,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。Owner props 提供 `locked`、`reportFailure(message)` 和 `dismiss()`,后者关闭菜单并同步聚焦触发按钮,供贡献方随后打开其他浮层;贡献方读取自身投影并提供专用命令。启用的开关按钮参与菜单键盘导航。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPane({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.pane` 的内容;入口按钮的 `data-model-menu-pane` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级面板共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级面板呈现为以 `title` 命名的分组;面板自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级面板而不激活开关。 ----- diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index 9ef7fc2e80..69d3f1d35c 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -129,6 +129,10 @@ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } +.settingsMenu { + width: min(240px, calc(100vw - 24px)); +} + .status, .empty { padding: 8px; diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 3eea3e37ad..a1510d832b 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -40,12 +40,23 @@ import { IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuControls, ModelMenuPaneRef, ModelSelectInjected } from './slots.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ -type Pane = 'root' | 'model' | 'effort' +/** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail pane. */ +type Pane = + | { kind: 'root' } + | { kind: 'model' } + | { kind: 'effort' } + | { kind: 'detail'; pane: ModelMenuPaneRef } + +/** Any pane reached by drilling from the root menu. */ +type DrilledPane = Exclude + +const ROOT_PANE: Pane = { kind: 'root' } +const MODEL_PANE: DrilledPane = { kind: 'model' } +const EFFORT_PANE: DrilledPane = { kind: 'effort' } /** One dynamic effort row; undefined means preserve the provider default. */ interface EffortChoice { @@ -63,14 +74,14 @@ interface EffortChoice { export function ModelSelect( { locked, available, directory, load, select, resolveText, t, renderSlot }: ModelSelectInjected & Pick, 'locked'> & PropsLocale<'model'> - & Omit, 'SessionProvider'>, + & Omit, 'SessionProvider'>, ) { const state = useSyncExternalStore( fn => directory.subscribe(fn), () => directory.getSnapshot(), ) const [open, setOpen] = useState(false) - const [pane, setPane] = useState('root') + const [pane, setPane] = useState(ROOT_PANE) const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) @@ -163,8 +174,13 @@ export function ModelSelect( if (menuRef.current?.contains(event.target as Node) === true) return setOpen(false) } + // WebKit touch taps on non-clickable areas dispatch pointerdown without mousedown. + document.addEventListener('pointerdown', closeOutside) document.addEventListener('mousedown', closeOutside) - return () => { document.removeEventListener('mousedown', closeOutside) } + return () => { + document.removeEventListener('pointerdown', closeOutside) + document.removeEventListener('mousedown', closeOutside) + } }, [open]) useLayoutEffect(() => { @@ -176,16 +192,22 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | 'model' | 'effort' | null>(null) + const paneFocus = useRef<'drill' | DrilledPane | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch - const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) + const intent = paneFocus.current ?? (changedSearchMode && pane.kind === 'model' ? 'drill' : null) paneFocus.current = null if (!open || intent === null) return if (intent === 'drill') { - if (pane === 'model' && showSearch && !isMobileDevice()) { + if (pane.kind === 'detail') { + // A detail pane places its own initial focus (autoFocus commits before + // this effect); otherwise the surface keeps the menu's keys reachable. + if (menuRef.current?.contains(document.activeElement) !== true) (menuRef.current ?? triggerRef.current)?.focus() + return + } + if (pane.kind === 'model' && showSearch && !isMobileDevice()) { searchRef.current?.focus() return } @@ -198,7 +220,10 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = itemRefs.current[intent === 'effort' ? 1 : 0] + const cell = intent.kind === 'detail' + ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-pane]') ?? []) + .find(button => button.dataset.modelMenuPane === intent.pane.key) + : itemRefs.current[intent.kind === 'effort' ? 1 : 0] ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() }, [open, pane, showSearch]) @@ -209,7 +234,7 @@ export function ModelSelect( }, [available, open, pane, filteredGroups]) useLayoutEffect(() => { - if (open && pane === 'model' && activeModelIndex >= 0) { + if (open && pane.kind === 'model' && activeModelIndex >= 0) { itemRefs.current[activeModelIndex]?.scrollIntoView({ block: 'nearest' }) } }, [open, pane, activeModelIndex, visibleModels]) @@ -222,7 +247,7 @@ export function ModelSelect( setQuery('') setHighlightedIndex(null) if (currentChoice === undefined) paneFocus.current = 'drill' - setPane(currentChoice === undefined ? 'model' : 'root') + setPane(currentChoice === undefined ? MODEL_PANE : ROOT_PANE) setOpen(true) reload() } @@ -234,7 +259,7 @@ export function ModelSelect( const close = (restoreFocus = false): void => { setOpen(false) - setPane('root') + setPane(ROOT_PANE) if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } @@ -243,7 +268,7 @@ export function ModelSelect( close(true) } - const drill = (next: Pane): void => { + const drill = (next: DrilledPane): void => { setQuery('') setHighlightedIndex(null) paneFocus.current = 'drill' @@ -251,9 +276,18 @@ export function ModelSelect( } /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ - const back = (from: Exclude): void => { + const back = (from: DrilledPane): void => { paneFocus.current = from - setPane('root') + setPane(ROOT_PANE) + } + + const controls: ModelMenuControls = { + locked: locked || busy, + dismiss: () => { + close() + triggerRef.current?.focus() + }, + reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, } const moveFocus = (offset: number): void => { @@ -276,12 +310,17 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (pane.kind === 'detail' || (pane.kind !== 'root' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (pane.kind === 'detail' && event.key === 'Tab') { + event.preventDefault() + close(true) + return + } + if (pane.kind === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 @@ -290,7 +329,7 @@ export function ModelSelect( } return } - if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement + if (pane.kind === 'model' && showSearch && event.target instanceof HTMLInputElement && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { if (event.key === 'Tab' && visibleModels.length === 0) return event.preventDefault() @@ -304,7 +343,7 @@ export function ModelSelect( if (event.key === 'Tab') { if (event.shiftKey) { event.preventDefault() - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (pane.kind !== 'root' && currentChoice !== undefined) back(pane) else close(true) return } @@ -323,7 +362,7 @@ export function ModelSelect( } if (focused !== triggerRef.current) return event.preventDefault() - if (pane === 'model' && showSearch) { + if (pane.kind === 'model' && showSearch) { setHighlightedIndex(null) searchRef.current?.focus() return @@ -339,6 +378,8 @@ export function ModelSelect( } const onBlur = (event: FocusEvent): void => { + // Clicking explanation text can clear focus without leaving its page. + if (pane.kind === 'detail' && event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -479,16 +520,19 @@ export function ModelSelect( {open && createPortal( - {pane === 'root' && ( + {pane.kind === 'root' && ( <> - {reasoning !== undefined && ( - )} - {renderSlot('conversation.input.model.options', { - locked: locked || busy, - dismiss: () => { - close() - triggerRef.current?.focus() - }, - reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, - })} + {renderSlot('conversation.input.model.options', { ...controls, openPane: (pane) => { drill({ kind: 'detail', pane }) } })} )} - {pane === 'model' && ( + {pane.kind === 'model' && ( <> {showSearch &&
)} - {pane === 'effort' && ( + {pane.kind === 'effort' && ( <> {state.error !== null && lastActionRef.current === 'load' && (
@@ -652,6 +689,11 @@ export function ModelSelect(
)} + {pane.kind === 'detail' && ( +
+ {renderSlot('conversation.input.model.pane', controls, { entryKey: pane.pane.key })} +
+ )} , document.body, )} diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index 224990e848..1c37307902 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -175,6 +175,7 @@ export function apply(ctx: ClientContext): void { children: { 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, 'conversation.input.model.options': { kind: 'list', scope: 'session' }, + 'conversation.input.model.pane': { kind: 'keyed', scope: 'session' }, }, inject: (sessionId): ModelSelectInjected => { const directory = models.directoryFor(sessionId) diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 39a31b673f..1aabbd0d54 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,20 +17,50 @@ export interface ModelLabelOwner { selected: boolean } +/** Data identifying a keyed contribution displayed as a detail pane of the model menu. */ +export interface ModelMenuPaneRef { + /** Registration key in conversation.input.model.pane; also marks its root button's data-model-menu-pane. */ + key: string + /** Localized accessible name of the detail pane. */ + title: string +} + +/** Selection state and feedback shared by menu option entries and detail panes. */ +export interface ModelMenuControls { + /** Whether the composer refuses changes, including while a model selection is saving. */ + locked: boolean + /** Close the menu and focus its trigger synchronously before opening another overlay. */ + dismiss: () => void + /** Report a failed selection through the menu owner's persistent toast. */ + reportFailure: (message: string) => void +} + +/** Root-menu controls for opening plugin-owned settings panes. */ +export type ModelMenuOptions = ModelMenuControls & { + /** + * Open pane.key in conversation.input.model.pane with pane.title as its localized accessible name. + * The root button's data-model-menu-pane must match pane.key for focus return. + */ + openPane: (pane: ModelMenuPaneRef) => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session options appended after model and reasoning controls in the root menu. */ 'conversation.input.model.options': { kind: 'list' scope: 'session' - owner: { - /** Whether the composer currently refuses selection changes. */ - locked: boolean - /** Close the menu and focus its trigger synchronously before opening another overlay. */ - dismiss: () => void - /** Report a failed selection through the menu owner's persistent toast. */ - reportFailure: (message: string) => void - } + owner: ModelMenuOptions + } + /** + * Plugin-owned content displayed as a model-menu detail pane. + * The pane places its own initial focus, for example with `autoFocus`; without one, + * focus stays on the menu surface, where Escape and Shift+Tab still return to the root menu. + */ + 'conversation.input.model.pane': { + kind: 'keyed' + scope: 'session' + owner: ModelMenuControls } /** * Non-interactive inline model label; selection controls remain owner-managed. diff --git a/packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx new file mode 100644 index 0000000000..b7c0a22c4d --- /dev/null +++ b/packages/client/ui-model-selection/tests/model-menu-pane.client.spec.tsx @@ -0,0 +1,97 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { ComponentProps } from 'react' +import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { ModelDirectoryState } from '../src/client/directory.ts' +import { ModelSelect } from '../src/client/ModelSelect.tsx' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +function setup(autoFocus = true) { + const directory = createSnapshotStore({ + current: { provider: 'fixture', model: 'fixture' }, routable: true, + groups: [{ id: 'fixture', name: 'Fixture', models: [{ id: 'fixture', name: 'Fixture' }] }], + failures: [], status: 'ready', pending: null, error: null, + }) + const change = vi.fn() + const select = vi.fn() + const renderSlot: ComponentProps['renderSlot'] = (name, owner, options) => { + if (name === 'conversation.input.model.options') { + const controls = owner as object as OwnerOf<'conversation.input.model.options'> + return + } + if (name === 'conversation.input.model.pane') { + const controls = owner as object as OwnerOf<'conversation.input.model.pane'> + expect(options?.entryKey).toBe('fixture') + return <>

Fixture explanation

+ } + return options?.fallback ?? null + } + render( typeof text === 'string' ? text : text.en} t={makeTranslate(en)} renderSlot={renderSlot} />) + const trigger = screen.getByRole('button', { name: /^Select model/ }) + fireEvent.click(trigger) + return { trigger, change, select, directory } +} + +it('dispatches a keyed page and returns focus to its invoking summary on Escape', () => { + const { trigger, change, select } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + const toggle = screen.getByRole('switch') + expect(document.activeElement).toBe(toggle) + expect(screen.getByRole('group', { name: 'Fixture settings' })).toBeTruthy() + fireEvent.blur(toggle, { relatedTarget: null }) + expect(screen.getByText('Fixture explanation')).toBeTruthy() + fireEvent.keyDown(toggle, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) + expect(screen.queryByRole('switch')).toBeNull() + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(change).not.toHaveBeenCalled() + expect(select).not.toHaveBeenCalled() +}) + +it('keeps focus on the page surface when the page places none, so Escape still returns', () => { + setup(false) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + const surface = screen.getByRole('group', { name: 'Fixture settings' }) + expect(document.activeElement).toBe(surface) + fireEvent.keyDown(surface, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) +}) + +it('closes a detail pane on an outside touch press that dispatches no mousedown', () => { + const { trigger } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + fireEvent.blur(screen.getByRole('switch'), { relatedTarget: null }) + fireEvent.pointerDown(screen.getByText('Fixture explanation')) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + fireEvent.pointerDown(document.body) + expect(trigger.getAttribute('aria-expanded')).toBe('false') +}) + +it.each([false, true])('closes a detail pane on Tab without changing its setting (shift: %s)', async (shiftKey) => { + const { trigger, change } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + fireEvent.keyDown(screen.getByRole('switch'), { key: 'Tab', shiftKey }) + await act(async () => {}) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(document.activeElement).toBe(trigger) + expect(change).not.toHaveBeenCalled() +}) + +it('keeps the baseline model-save lock on both summary and detail controls', () => { + const { directory } = setup() + act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) + expect(screen.getByRole('menuitem', { name: 'Fixture settings' }).hasAttribute('disabled')).toBe(true) + act(() => { directory.update((state) => { state.pending = null }) }) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +}) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 662fc787a4..3c1785b330 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,11 +18,11 @@ en: ead6be55c7c9d7cf zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 54c5085d03bf4c53 - zh: 6b5114206ca545f3 + en: 11686b52743a702d + zh: d865bb79d8f56ee1 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: 8265fa792c6fd9ec - zh: 600d2af4d5a3d183 + en: 69acdb3375548a62 + zh: c392c11faf88938f /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: en: e2649937f077d4e0 zh: 6ad604cb5adfc16b diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 5c817b94b2..84930bb4ff 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -43,7 +43,7 @@ Check this table before writing a control in a feature package. A plugin cannot | Export | What it is | |---|---| | `Button` | Clickable action; `variant` selects `primary`, `ghost`, `outline`, or `toolbar`. Outlined actions use an inset hairline. Its ref targets the native button for focus and overlay anchoring. | -| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. | +| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. Optional `autoFocus` and `describedBy` forward to the native button. | | `SegmentedControl` | Tablist of two or more equal-width segments with one sliding indicator, for switching a card or panel between a few modes; the owner holds the selection and `label` names the list. `id` seeds each tab's id (`-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | @@ -97,7 +97,7 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconMailReadOutlineRegular`/`Medium` show an open envelope; `IconMailUnreadOutlineRegular`/`Medium` show a closed envelope with an unread dot. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. It stays hidden until its first fit, prefers the requested side, then tries the opposite and perpendicular sides, sliding along the anchor without covering it when a side fits. Horizontal placements keep a 10px gap; vertical placements use `gap` (8px by default). Width and height stay within a 12px viewport margin; text wraps, and content taller than the viewport scrolls when pinned. If no side fits, a stable viewport-bounded fallback can overlap the anchor. Viewport resize refreshes the anchor coordinates; label-size changes reuse them. Fitting does not synchronously measure the bubble or trigger a React render. Touch presses dismiss unpinned hints and do not trigger hover hints, including compatibility mouse events. Mouse entry opens hints only while `(any-hover: hover)` reports an available hover-capable input, excluding iOS mouse entry caused by a tapped icon changing. Keyboard focus and explicit click-to-open explanations remain available on touch-only devices. Opt-in `openOnClick` lets an informational button pin the bubble by click or tap and associates it with the anchor description. Another click or tap, Escape, Tab, or an outside pointerdown closes it. Ordinary action buttons execute their action directly without a touch tooltip. Opt-in `onlyWhenClipped` shows the bubble only when the anchor or an HTML element inside it overflows horizontally when the bubble is about to show, so a label that repeats ellipsis-cut text appears only while it adds information. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f3e1c1719a..eb1b989a1a 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。可选的 `autoFocus` 与 `describedBy` 直接传给原生按钮。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | @@ -97,7 +97,7 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconMailReadOutlineRegular`/`Medium` 使用打开的信封,`IconMailUnreadOutlineRegular`/`Medium` 使用带未读圆点的闭合信封。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前保持隐藏,优先使用指定方向,再尝试相反方向和垂直于该方向的两侧;只要某一侧容得下,就沿锚点平移而不遮挡锚点。左右放置保留 10px 间距,上下放置使用 `gap`(默认 8px)。宽高限制在视口内并保留 12px 边距;文本自动换行,超出视口高度的内容在固定气泡后可滚动。若所有方向都放不下,则使用稳定的视口内回退位置,可能遮挡锚点。视口尺寸变化会重新读取锚点坐标,标签尺寸变化则复用坐标;定位不会同步测量气泡,也不会触发 React 渲染。 触摸按下会关闭未固定的提示,且不会触发悬停提示,包括触摸后的兼容鼠标事件。只有 `(any-hover: hover)` 表明存在可悬停的输入设备时,鼠标进入才会打开提示,从而排除 iOS 因已点击图标变化而生成的鼠标进入事件。仅有触摸输入的设备仍可使用键盘聚焦提示和显式点击打开的说明。信息按钮可显式启用 `openOnClick`,通过鼠标或触摸点击固定气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮在触摸点击时直接执行操作,不显示 Tooltip。可选的 `onlyWhenClipped` 只在气泡即将显示时锚点或其内部某个 HTML 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 980a08f6be..8816e1975a 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -13,9 +13,11 @@ import css from './Switch.module.css' * while a write is in flight, not only when a deployment locks the toggle. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. + * @param props.autoFocus - whether the control takes focus when it mounts enabled. + * @param props.describedBy - id of the element that describes the control. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, title, className, autoFocus, describedBy }: { checked: boolean onChange: (next: boolean) => void label: string @@ -24,6 +26,8 @@ export function Switch({ checked, onChange, label, disabled = false, title, clas // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). className?: string | undefined + autoFocus?: boolean + describedBy?: string | undefined }) { return (

Reason

) + const control = screen.getByRole('switch', { description: 'Reason' }) + expect(document.activeElement).toBe(control) + }) + it('keeps a caller class alongside its own so a render site can place it', () => { render( {}} />) const control = screen.getByRole('switch') diff --git a/packages/client/ui-session-status/README.i18n.yaml b/packages/client/ui-session-status/README.i18n.yaml index bdce0fb16c..c691b64c26 100644 --- a/packages/client/ui-session-status/README.i18n.yaml +++ b/packages/client/ui-session-status/README.i18n.yaml @@ -3,29 +3,35 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-session-status/README.md /: - en: 11efe93e9b428342 - zh: 56d90a359ee86ad5 + en: dc68a4aaa22727ac + zh: aef571e08a364bf1 /deepseek-ai-dsh-client-ui-session-status: en: d572f680cca905e6 zh: 7c397a1fb746b47f /deepseek-ai-dsh-client-ui-session-status/summary: - en: a3e8fe090a557c9b - zh: 782500fb80b92712 + en: 5fe776aee839b428 + zh: 5c183742a98dded0 /deepseek-ai-dsh-client-ui-session-status/table-of-contents: - en: 3e7914c761a1310c - zh: 82c46d3a4d5e6a55 -/deepseek-ai-dsh-client-ui-session-status/status-table: - en: 4c1c64a9e5aa133d - zh: 9248ed3f64a4ebc9 + en: d152484eb41ac6b4 + zh: 7b30b973a849247d +/deepseek-ai-dsh-client-ui-session-status/use-this-package: + en: fe9e33d12e5df30e + zh: 5037b80cad259f47 +/deepseek-ai-dsh-client-ui-session-status/understand-the-implementation: + en: 64919e36946e9fa8 + zh: e6b2d66e98f2bf38 +/deepseek-ai-dsh-client-ui-session-status/further-exploration: + en: e1bb29cafbeee6ec + zh: 6b9af92c1ef2b0e5 /deepseek-ai-dsh-client-ui-session-status/model-experience: - en: 687076082426c060 - zh: 5888fcd520d0e53e + en: 745f3b288309a4b3 + zh: e4150220b50a0338 /deepseek-ai-dsh-client-ui-session-status/model-experience/kv-cache-effect: - en: 99bd3bc7d244944a - zh: 0021893ed90b2686 + en: a4bc54a4825f89d2 + zh: 1a96ffe54bc0192e /deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work: - en: 52d467a078cc3486 - zh: c373685b879ad6de + en: ac174b1d3bdc68aa + zh: 6ece23133dc7dc87 /deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 - zh: e88aeb617ffb74ea + zh: 6df6019931844fb2 diff --git a/packages/client/ui-session-status/README.md b/packages/client/ui-session-status/README.md index 6973059556..7fe2368342 100644 --- a/packages/client/ui-session-status/README.md +++ b/packages/client/ui-session-status/README.md @@ -1,56 +1,105 @@ --- -description: "Client Session status table and useSessionStatus hook: running state, the effective pending interaction, and completion reminders by Session." +description: "Client Session status table and useSessionStatus hook over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one running Host." kind: "package-reference" --- + # @deepseek-ai/dsh-client-ui-session-status English | [中文](README.zh.md) ## Summary -Use this package to read each Session's running state, highest-precedence pending interaction, and completion reminder from one Client status table. Components read the table through the `useSessionStatus` root hook; Client plugins read it as `ctx.uiSession.sessionStatus`. The package has no configuration fields, Host behavior, or persistent storage. +Show each Session's running state, highest-precedence pending interaction, and read or unread reminder from one Client status table. Reminders come from reading records this package keeps in Host memory: they survive a browser refresh while the Host remains running, and connected clients share manual marks and acknowledgements, including completions that occur while every client is offline. Reading marks do not change conversation history or model requests. ## Table of Contents -- [Status table](#status-table) +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) - [Model Experience](#model-experience) - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - [Dev Note](#dev-note) ----- - -## Status table + +## Use this package -The Web bundle loads this plugin after [`dsh-client-ui-session`](../ui-session/README.md) and requires it at startup; a composition that loads ui-session without this package has no status table and no `useSessionStatus` hook. A plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession.sessionStatus'` to its `inject` list; without it, Cordis rejects the property read. A plugin whose components call `useSessionStatus` injects it as well, so the plugin unloads and reloads with the hook. The member is declared on ui-session's `UiSessionService`, the type of `ctx.uiSession`; a value annotated as the `UiSession` class does not show it. +The Web bundle's single `ui-session-status` row loads both faces: the Host reading service `ctx.sessionStatus` and, after [`dsh-client-ui-session`](../ui-session/README.md), the Client plugin, which the Web client requires at startup. A composition without this package has no status table and no `useSessionStatus` hook, and profiles without the Web bundle run no reading service. The package has no configuration fields or persistent storage. Restarting the Host or reloading this plugin discards every record: history reads as read again, and no earlier turn outcome survives. + +Use the Session row menu to **Mark as read** or **Mark as unread**. All clients connected to that Host share the result; a failed operation leaves the previous reminder visible and reports failure. A completed, failed, or cancelled turn creates an unread reminder. Existing history starts read when first observed. Opening a Session in a visible, focused main view acknowledges its loaded completion after a rendering frame. Switching the main view to a Session, including restoring it after a page reload, clears its existing manual reminder after the content arrives. Window focus and further activity in the open Session preserve manual unread. Unread reminders do not imply task success and remain independent of running and pending-interaction status. + +Components read the status table through the `useSessionStatus` root hook. A Client plugin that reads `ctx.uiSession.sessionStatus` adds `'uiSession'` and `'uiSession.sessionStatus'` to its `inject` list; without them, Cordis rejects the property read. A plugin whose components call `useSessionStatus` injects `'uiSession.sessionStatus'` as well, so the plugin unloads and reloads with the hook. The member is declared on ui-session's `UiSessionService`, the type of `ctx.uiSession`; a value annotated as the `UiSession` class does not show it. | Member | Use | |---|---| -| `getSnapshot()` | Status by Session identity; the snapshot keeps its reference until a status fact changes | -| `subscribe(listener)` | Observe published changes; a throwing listener is reported without stopping later listeners | +| `getSnapshot()` / `subscribe(listener)` | Status by Session identity; the snapshot keeps its reference until a status fact changes, and a throwing listener is reported without stopping later listeners | +| `mark(sessionId, unread)` | Mark a Session read or unread; rejects while reading is not synchronized or when the Host rejects the mark | +| `readingReady` | Whether the current Host reading baseline has arrived | -Each `SessionStatus` has three independent fields: +Each `SessionStatus` has four fields: | Field | Source | |---|---| | `running` | Host Session list baselines and `api-session/status` events; absent until either establishes it. Subagent catalog rows and retained subagent fallback rows do not establish it. | -| `pendingInteraction` | The same object `ctx.uiSession.pendingInteractions` publishes for that Session. Domain plugins keep registering requests through `ctx.uiSession.registerPendingInteraction(precedence)`. | -| `completionUnread` | A stop this Client observed while the main view did not retain the Session, including an idle event that arrives before the first list baseline. The reminder clears when the main view retains the Session, the Session runs again, or a ready list no longer contains it. | +| `pendingInteraction` | The same object `ctx.uiSession.pendingInteractions` publishes for that Session. Domain plugins register requests through `ctx.uiSession.registerPendingInteraction(precedence)`. | +| `completionUnread` | The Host reading record carries a manual unread mark, or its latest completed turn is beyond the read turn; that unacknowledged turn is not shown while the visible, focused main view retains the Session and it is open | +| `completionFailed` | The Session is unread and its latest completed turn ended with an execution error this Host observed | + +The Host face serves the `sessionStatus` Remote namespace with `mark` and `follow`; its failures use `session-status/not-found` and `session-status/unavailable`. The Client keeps its copy of the reading records private: no Client service other than `ctx.uiSession.sessionStatus` exposes them. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +Reading records live in the Host service's Map and change only from `turn/end` events and explicit marks. Each record holds `completedTurn`, `failed`, `readTurn`, and `manualUnread`. Marks do not change execution facts or flush the Session log. + +The Client submits the completed turn it has seen. The Host advances `readTurn` monotonically up to that position, bounded by its known completion; automatic acknowledgements preserve `manualUnread`. Explicit read and unread actions clear or set that flag in Host processing order. Cold menu actions check metadata without opening history. + +Only the ordered subscription updates Client records; mutation replies report success or failure. Streams send an accessible baseline followed by whole-record changes. The Client follows them through `ctx.remote.$stream` and the Gateway's `RemoteSnapshotStream` only while `ctx.remoteAccess` allows `sessionStatus/follow`, so a LiveShare viewer opens no stream and keeps `readingReady` false; a normal stream end returns an error with the Gateway's `gateway/carrier-lost` code, so the stream reconnects and the next baseline replaces the records. The existing access stream ends a reading generation when grants change, so reconnecting clients receive a fresh baseline. Disposal closes followers and discards records; pending metadata lookups cannot commit afterward. + +The Client plugin combines Session list baselines, `api-session/status` events, ui-session's pending interactions, and reading records into the status table, provided as `uiSession.sessionStatus` beneath `ctx.uiSession`. It also acknowledges the Session retained by the main view. It waits for a visible, focused window, an open Session, a rendering frame, and a loaded body that reaches the completed turn. Window focus only advances the natural read position. When the main view switches to a different Session, the plugin checks that Session's manual unread mark once the reading baseline is ready and clears an existing mark with the next acknowledgement; a replaced binding for the same Session is not a switch, and later acknowledgements keep manual marks. + +
+ +----- + + +## Further Exploration + +- [Session reading memory decision](../../../.agents/notes/implemented/feature/2026-10-23-session-reading-memory.md) — package structure, Host memory ownership, concurrency, and deferred persistence. +- [Session UI adapter](../ui-session/README.md) — the parent `ctx.uiSession` service and pending-interaction registration. +- [Workspace browser](../ui-workspace/README.md) — row menu and reminders. + +----- ## Model Experience -None, as the status table adds no tools, prompts, or Session events. +None, as reading records and the status table add no tools, prompts, or Session events. #### KV Cache effect -None; the status table does not assemble model requests. +None; reading marks and the status table do not assemble model requests. ## Known Limitations and Deferred Work -- **Completion reminders belong to one Client** — another browser tab or a page reload starts without the reminders this Client recorded. +Reading state has these operational limits: + +- **Concurrent explicit marks** — the last action processed by the Host wins. Delayed explicit read actions can clear a newer manual unread mark; there is no revision comparison. Automatic acknowledgements (`acknowledge`) never clear manual unread or read beyond their submitted position. The only automatic path that clears manual unread is the main-view switch rule above, including restoring the main view after a page reload; it applies only when that page is visible, focused, and showing the Session. +- **One Host process** — separate Host processes or machines do not synchronize with each other. +- **Host restart or plugin reload** — all reading state resets and history reads as read. A turn that failed before the restart keeps no outcome, so marking such a Session unread shows the ordinary unread reminder. Reloading the Host plugin ends every reading stream; if the replacement service is not yet serving when the Client reconnects, the Client receives a terminal error, disables reading commands, and recovers only after a page reload. Persistent reminders require the separately tracked follow-up; this package writes no read-state files. +- **Web profiles only** — the row lives in the Web bundle, so profiles without it run no reading service. +- **Metadata and transport failures** — a failed metadata lookup leaves reading state unchanged. A terminal stream or protocol failure disables reading commands until the page reloads; ordinary carrier loss reconnects automatically. +- **Unloaded and archived Sessions** — records for Sessions unloaded from memory remain until the service stops; reclaiming them requires a Session deletion lifecycle. Archived rows hide their unread styling and status, read as read, and offer no reading mark in the row menu or shortcut. +- **Main-view visibility** — main-view retention does not distinguish every settings or auxiliary panel, so acknowledgement can run, and the status table hides the open Session's unacknowledged completion, while such a panel covers the Conversation; that refinement belongs to the notification work. +- **No message counts or read receipts for other people** — the state belongs to the Host's owner and records Session-level reminders. LiveShare viewers cannot read or change it. ### Dev Note diff --git a/packages/client/ui-session-status/README.zh.md b/packages/client/ui-session-status/README.zh.md index fa79a8c760..f6b767304e 100644 --- a/packages/client/ui-session-status/README.zh.md +++ b/packages/client/ui-session-status/README.zh.md @@ -1,62 +1,111 @@ --- -description: "Client 会话状态表与 useSessionStatus hook:按会话提供运行状态、生效的待交互请求和完成提醒。" +description: "基于宿主阅读记录的 Client 会话状态表与 useSessionStatus hook:运行状态、生效的待交互请求,以及连接同一运行中宿主的前端共享的已读、未读提醒。" kind: "package-reference" --- + # @deepseek-ai/dsh-client-ui-session-status [English](README.md) | 中文 ## 概述 -使用本包可从同一张 Client 状态表读取每个 Session 的运行状态、优先级最高的待交互请求和完成提醒。组件通过根 hook `useSessionStatus` 读取该表;Client 插件以 `ctx.uiSession.sessionStatus` 读取。本包没有配置字段、Host 行为或持久化存储。 +通过同一张前端状态表显示每个会话的运行状态、优先级最高的待交互请求和已读、未读提醒。提醒来自本包保存在宿主内存中的阅读记录:只要宿主仍在运行,刷新浏览器后提醒仍然保留;已连接的前端共享手动标记和阅读确认,也能收到所有前端离线期间完成的会话提醒。阅读标记不改变对话历史或模型请求。 ## 目录 -- [状态表](#status-table) +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步阅读](#further-exploration) - [模型体验](#model-experience) -- [已知限制与暂缓事项](#known-limitations-and-deferred-work) +- [已知限制与后续工作](#known-limitations-and-deferred-work) - [开发备注](#dev-note) ----- - -## 状态表 + +## 使用本包 -Web bundle 在 [`dsh-client-ui-session`](../ui-session/README.zh.md) 之后加载本插件,并把它列为启动必需入口;只加载 ui-session、不加载本包的组合没有状态表,也没有 `useSessionStatus` hook。读取 `ctx.uiSession.sessionStatus` 的插件需要在 `inject` 列表中加入 `'uiSession.sessionStatus'`;否则 Cordis 会拒绝该属性读取。组件调用 `useSessionStatus` 的插件也注入它,使插件随该 hook 一起卸载和重新加载。该成员声明在 ui-session 的 `UiSessionService`(`ctx.uiSession` 的类型)上;标注为 `UiSession` class 的值看不到它。 +Web bundle 中唯一的 `ui-session-status` 行同时加载两个面:宿主阅读服务 `ctx.sessionStatus`,以及在 [`dsh-client-ui-session`](../ui-session/README.zh.md) 之后加载、被 Web 前端列为启动必需入口的前端插件。不加载本包的组合没有状态表,也没有 `useSessionStatus` hook;不含 Web bundle 的 profile 不运行阅读服务。本包没有配置项,也不使用持久化存储。重启宿主或重新加载本插件会丢弃全部记录:历史重新按已读处理,之前的轮次结果不再保留。 + +通过会话行菜单**标为已读**或**标为未读**,连接同一宿主的前端会共享结果;操作失败时保留原有提醒并报告失败。本轮宿主运行期间结束的轮次都会产生未读提醒,无论正常完成、失败还是取消。失败标记只适用于本轮宿主看到失败的轮次;宿主启动前就结束的失败无法得知。已有历史默认为已读。在可见且聚焦的窗口中打开会话后,主视图会在一个渲染帧之后确认已加载的完成内容。主视图切换到某个会话(包括刷新页面后恢复主视图)时,会在内容到达后清除其已有的手动提醒。窗口聚焦和在已打开会话中的其他操作都会保留手动未读。未读提醒不表示任务成功,与运行和待交互状态分别显示。 + +组件通过根 hook `useSessionStatus` 读取状态表。读取 `ctx.uiSession.sessionStatus` 的前端插件需要在 `inject` 列表中加入 `'uiSession'` 和 `'uiSession.sessionStatus'`;否则 Cordis 会拒绝该属性读取。组件调用 `useSessionStatus` 的插件也注入 `'uiSession.sessionStatus'`,使插件随该 hook 一起卸载和重新加载。该成员声明在 ui-session 的 `UiSessionService`(`ctx.uiSession` 的类型)上;标注为 `UiSession` class 的值看不到它。 | 成员 | 用途 | |---|---| -| `getSnapshot()` | 按 Session 身份索引的状态;状态事实变化前快照保持同一引用 | -| `subscribe(listener)` | 观察已发布的变化;抛错的 listener 会被报告,不会阻止后续 listener | +| `getSnapshot()` / `subscribe(listener)` | 按会话身份索引的状态;状态事实变化前快照保持同一引用,抛错的 listener 会被报告,不会阻止后续 listener | +| `mark(sessionId, unread)` | 把会话标为已读或未读;阅读状态未同步或宿主拒绝标记时拒绝 | +| `readingReady` | 是否已取得当前宿主的阅读基线 | -每个 `SessionStatus` 有三个相互独立的字段: +每个 `SessionStatus` 有四个字段: | 字段 | 来源 | |---|---| -| `running` | Host 会话列表基线和 `api-session/status` 事件;两者都未建立之前为缺省。Subagent 目录行和已保留子会话的 fallback 行不会建立它。 | -| `pendingInteraction` | `ctx.uiSession.pendingInteractions` 为该 Session 发布的同一个对象。领域插件仍通过 `ctx.uiSession.registerPendingInteraction(precedence)` 登记请求。 | -| `completionUnread` | 本 Client 在主视图未保留该 Session 时观察到的一次停止,包括首个列表基线之前到达的空闲事件。主视图保留该 Session、该 Session 再次运行,或就绪列表不再包含它时,提醒清除。 | +| `running` | 宿主会话列表基线和 `api-session/status` 事件;两者都未建立之前为缺省。Subagent 目录行和已保留子会话的 fallback 行不会建立它。 | +| `pendingInteraction` | `ctx.uiSession.pendingInteractions` 为该会话发布的同一个对象。领域插件通过 `ctx.uiSession.registerPendingInteraction(precedence)` 登记请求。 | +| `completionUnread` | 宿主阅读记录带有手动未读标记,或其最近完成的轮次超过已读轮次;可见且聚焦的主视图正在显示该会话且其已打开时,不显示尚未确认的该轮次 | +| `completionFailed` | 会话未读,且最近完成的轮次以本宿主观察到的执行错误结束 | + +宿主面通过 `sessionStatus` Remote 命名空间提供 `mark` 和 `follow`;失败使用 `session-status/not-found` 和 `session-status/unavailable`。前端保存的阅读记录副本是私有的:除 `ctx.uiSession.sessionStatus` 外,没有其他前端服务暴露这些记录。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +阅读记录放在宿主服务的 Map 中,只由 `turn/end` 事件和主动标记更新。每条记录包含 `completedTurn`、`failed`、`readTurn` 和 `manualUnread`。标记不会改变执行结果,也不会触发会话日志刷盘。 + +前端提交自己已看到的完成轮次。宿主只向前推进 `readTurn`,上限是提交位置与已知完成位置的较小值;自动确认保留 `manualUnread`。主动标为已读或未读按宿主处理顺序清除或设置该标记。冷会话的菜单操作只检查元数据,不打开历史。 + +只有有序订阅流更新前端记录,修改请求仅回复成功或失败。同步流先发送有权访问的完整快照,再推送完整记录。只有 `ctx.remoteAccess` 允许 `sessionStatus/follow` 时,前端才通过 `ctx.remote.$stream` 和 Gateway 的 `RemoteSnapshotStream` 跟随这些记录,因此 LiveShare 查看者不打开该流,`readingReady` 保持 false;流正常结束时返回带 Gateway `gateway/carrier-lost` code 的错误,因此流会重连,下一个快照替换记录。已有的访问流在授权变化时结束阅读订阅,前端重连后取得新快照。卸载会关闭订阅并清空记录,尚未返回的元数据查询不能再提交标记。 + +前端插件把会话列表基线、`api-session/status` 事件、ui-session 的待交互请求和阅读记录汇总为状态表,并以 `uiSession.sessionStatus` 的名字挂在 `ctx.uiSession` 下。它还确认主视图持有的会话。确认需要窗口可见且聚焦、会话已打开、经过一个渲染帧,且已加载的正文到达完成轮次。窗口聚焦只推进自然已读位置。主视图切换到另一个会话时,插件会在阅读基线就绪后检查该会话的手动未读标记,并在下一次确认时清除已有标记;同一会话只是更换 binding 不算切换,之后的确认保留手动标记。 + +
+ +----- + + +## 进一步阅读 + +- [会话阅读记忆决策](../../../.agents/notes/implemented/feature/2026-10-23-session-reading-memory.zh.md)——包结构、宿主内存归属、并发和暂缓的持久化。 +- [会话 UI 适配层](../ui-session/README.zh.md)——上级服务 `ctx.uiSession` 与待交互登记。 +- [工作区浏览器](../ui-workspace/README.zh.md)——会话菜单与提醒。 + +----- ## 模型体验 -无,因为状态表不添加工具、提示词或 Session 事件。 +无,阅读记录和状态表不添加工具、提示词或会话事件。 #### KV Cache 影响 -无;状态表不会组装模型请求。 +无;阅读标记和状态表不参与模型请求构建。 -## 已知限制与暂缓事项 +## 已知限制与后续工作 -- **完成提醒只属于一个 Client**——另一个浏览器标签页或刷新后的页面不会带上本 Client 记录的提醒。 +阅读状态有以下运行限制: + +- **并发主动标记**——以宿主最后处理的操作为准,不比较版本;延迟的主动已读可能清除较新的手动未读。自动确认(`acknowledge`)不会清除手动未读,也不会越过提交的阅读位置。唯一会自动清除手动未读的是上文的主视图切换规则,包括刷新后恢复主视图;它只在该页面可见、聚焦且正在显示该会话时生效。 +- **单个宿主进程**——不同宿主进程或机器之间不互相同步。 +- **宿主重启或插件重载**——全部阅读状态重置,历史按已读处理。重启前失败的轮次不保留结果,因此把这类会话标为未读时显示普通未读提醒。重载宿主插件会结束所有阅读流;前端重连时如果新服务尚未就绪,会收到终止错误并禁用阅读操作,只有刷新页面后才能恢复。持久化提醒由单独跟踪的后续需求负责;本包不写入阅读状态文件。 +- **仅 Web profile**——本包的行位于 Web bundle,不包含该行的 profile 不运行阅读服务。 +- **元信息和传输失败**——元信息查询失败不改变阅读状态。流或协议的终态失败会禁用阅读操作,直到刷新页面;普通连接中断会自动重连。 +- **已卸载和已归档的会话**——会话从内存卸载后,其记录保留到服务停止;回收记录需要会话删除生命周期。归档行隐藏未读样式和状态,按已读处理,行菜单和快捷键都不提供阅读标记。 +- **主视图可见性**——主视图保留信号不能区分所有设置或辅助面板,因此这类面板遮住对话时仍可能确认阅读,状态表也会隐藏该已打开会话尚未确认的完成轮次;该细化属于通知工作的范围。 +- **不提供消息计数或他人的阅读回执**——状态属于宿主的使用者,只记录会话级提醒。LiveShare 查看者不能读取或修改该状态。 ### 开发备注
-维护者工作上下文——点击展开 +维护者上下文——点击展开 无。 diff --git a/packages/client/ui-session-status/package.json b/packages/client/ui-session-status/package.json index be3bba1317..f6856b6ebc 100644 --- a/packages/client/ui-session-status/package.json +++ b/packages/client/ui-session-status/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-session-status", - "description": "Client Session status table: running state, the effective pending interaction, and completion reminders", + "description": "Client Session status table over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one Host", "version": "0.2.2-rc.2", "publishConfig": { "access": "public" @@ -18,17 +18,33 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts" + }, "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, "./src/*": "./src/*", "./package.json": "./package.json", "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { + "external": [ + "@deepseek-ai/dsh-api-gateway/client" + ], "inject": [ + "@deepseek-ai/dsh-api-gateway", + "@deepseek-ai/dsh-api-remote-access", "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-ui-renderer", @@ -42,20 +58,31 @@ "watch": "tsdown --watch" }, "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-deque": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.6.6" + }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-typert-registry": "workspace:*" }, "files": [ "locale/*.json", @@ -64,6 +91,11 @@ "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", "src" ] } diff --git a/packages/client/ui-session-status/src/client/acknowledge.ts b/packages/client/ui-session-status/src/client/acknowledge.ts new file mode 100644 index 0000000000..5c50563abf --- /dev/null +++ b/packages/client/ui-session-status/src/client/acknowledge.ts @@ -0,0 +1,103 @@ +/** Visible main-view acknowledgements over Host reading state. */ +import type { Context } from '@deepseek-ai/cordis' +import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +// Type-only: declares the `mainView` reference source. +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionReadModel } from './model.ts' + +/** + * Acknowledge loaded content after a rendering frame in the visible, focused main view. + * Switching the main view to a Session, including the first selection after a page load, clears that Session's + * manual reminder once its body arrives; window focus and a replaced binding for the same Session preserve it. + * Without a document there is no view to acknowledge, so nothing is installed. + * @param ctx - owning Client plugin Context. + * @param sessions - Session catalog and binding owner. + * @param reading - shared Host-confirmed reading state. + */ +export function installReadingAcknowledgements(ctx: Context, sessions: Pick, reading: Pick): void { + if (typeof document === 'undefined') return + let selected: SessionId | undefined + let binding: SessionBinding | undefined + let releaseBinding = (): void => {} + // The entered Session whose manual reminder the next acknowledgement clears; settled against a ready baseline. + let entered: SessionId | undefined + let attemptedTurn: number | undefined + let frame: number | undefined + let active = true + let pending: Promise | undefined + const visible = (): boolean => document.visibilityState === 'visible' && document.hasFocus() + const schedule = (): void => { + if (!active || frame !== undefined || !visible()) return + frame = requestAnimationFrame(() => { + frame = undefined + acknowledge() + }) + } + const acknowledge = (): void => { + const snapshot = reading.state.getSnapshot() + const record = selected === undefined ? undefined : snapshot.items[selected] + if (!visible() || !snapshot.ready || binding?.session.getSnapshot().openState !== 'open') return + if (record === undefined || pending !== undefined || attemptedTurn === record.completedTurn) return + const clearing = entered === record.sessionId + if (!clearing && record.completedTurn <= record.readTurn) return + const received = record.completedTurn === 0 || binding.eventSource.getSnapshot().entries.some(({ event }) => + (event.type === 'turn/end' && event.data.turn >= record.completedTurn) + || (event.type === 'turn/start' && event.data.turn > record.completedTurn)) + if (!received) return + attemptedTurn = record.completedTurn + entered = undefined + pending = reading.acknowledge(record.sessionId, record.completedTurn, clearing).catch((error: unknown) => { + console.error('[session-status] Reading acknowledgement could not be confirmed. Reopen the Session to refresh its state:', error) + }).finally(() => { pending = undefined; schedule() }) + } + const settleEntry = (): void => { + const snapshot = reading.state.getSnapshot() + if (snapshot.ready && entered !== undefined && !snapshot.items[entered]?.manualUnread) entered = undefined + } + const update = (): void => { + const list = sessions.list.getSnapshot() + const id = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0)?.id + const next = id === undefined ? undefined : sessions.binding(id) + if (id !== selected || next !== binding) { + releaseBinding() + if (id !== selected) { + entered = id + settleEntry() + } + selected = id + binding = next + attemptedTurn = undefined + const releaseSession = next?.session.subscribe(schedule) + const releaseEvents = next?.eventSource.subscribe(schedule) + releaseBinding = () => { releaseSession?.(); releaseEvents?.() } + } + schedule() + } + const focus = (): void => { + attemptedTurn = undefined + schedule() + } + ctx.effect(() => { + const releaseList = sessions.list.subscribe(update) + const releaseReading = reading.state.subscribe(() => { + settleEntry() + schedule() + }) + document.addEventListener('visibilitychange', focus) + window.addEventListener('focus', focus) + window.addEventListener('blur', focus) + update() + return async () => { + active = false + releaseList() + releaseReading() + releaseBinding() + document.removeEventListener('visibilitychange', focus) + window.removeEventListener('focus', focus) + window.removeEventListener('blur', focus) + if (frame !== undefined) cancelAnimationFrame(frame) + await pending + } + }, 'session-status: visible reading acknowledgement') +} diff --git a/packages/client/ui-session-status/src/client/index.ts b/packages/client/ui-session-status/src/client/index.ts index 588d5a2ba7..3d77cd11b2 100644 --- a/packages/client/ui-session-status/src/client/index.ts +++ b/packages/client/ui-session-status/src/client/index.ts @@ -1,21 +1,24 @@ -/** Client Session status plugin: the `uiSession.sessionStatus` service and the `useSessionStatus` root hook. */ +/** Client Session status plugin: the `uiSession.sessionStatus` service, the `useSessionStatus` root hook, and reading. */ import type { Context } from '@deepseek-ai/cordis' // Type-only: declares the `sessions` Controller service. import type {} from '@deepseek-ai/dsh-api-session-controller/client' // Type-only service merge for ctx.slots. import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { installReading } from './read.ts' import { UiSessionStatus } from './status.ts' export type { SessionStatus, SessionStatusSnapshot, UiSessionStatus, UseSessionStatus } from './status.ts' -/** Required Controller, Remote, renderer, and Session UI services. */ -export const inject = ['remote', 'sessions', 'slots', 'uiSession'] +/** Required Controller, Remote, generated reading namespace, access, renderer, and Session UI services. */ +export const inject = ['remote', 'remote.sessionStatus', 'remoteAccess', 'sessions', 'slots', 'uiSession'] /** - * Install `ctx.uiSession.sessionStatus` and publish it through the `useSessionStatus` root hook. + * Install `ctx.uiSession.sessionStatus`, publish it through the `useSessionStatus` root hook, and follow Host reading + * records into it. * @param ctx - Client root context. */ export function apply(ctx: Context): void { const status = new UiSessionStatus(ctx, ctx.sessions, ctx.uiSession.pendingInteractions) ctx.slots.provideRoot({ hooks: { sessionStatus: status } }) + installReading(ctx, status) } diff --git a/packages/client/ui-session-status/src/client/model.ts b/packages/client/ui-session-status/src/client/model.ts new file mode 100644 index 0000000000..9fe7e7f96e --- /dev/null +++ b/packages/client/ui-session-status/src/client/model.ts @@ -0,0 +1,73 @@ +/** React-free Client copy of the Host reading records; internal to the Session status plugin. */ +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/remote' +import type { SessionReadAction, SessionReadState } from '../types.ts' + +/** Reading records retained during reconnection; mutations require a ready baseline. */ +export interface SessionReadSnapshot { + readonly items: Readonly> + readonly ready: boolean +} + +/** Projects the ordered Host stream; mutation responses never replace reading records. */ +export class SessionReadModel { + /** Current reading records and baseline readiness, published synchronously on every change. */ + readonly state: SnapshotStore = createSnapshotStore( + { items: {}, ready: false }, { flush: 'sync' }, + ) + + /** @param remote - generated `sessionStatus` Remote methods. */ + constructor(private readonly remote: Pick) {} + + /** + * Replace the complete projection for a new connection. + * @param items - complete authoritative baseline for the new stream generation. + */ + replace(items: readonly SessionReadState[]): void { + this.state.set({ items: Object.fromEntries(items.map(item => [item.sessionId, item])), ready: true }) + } + + /** + * Accept the next committed record from the ordered subscription. + * @param item - Committed whole-record change. + */ + accept(item: SessionReadState): void { + const snapshot = this.state.getSnapshot() + this.state.set({ ...snapshot, items: { ...snapshot.items, [item.sessionId]: item } }) + } + + /** Retain the last projection while disabling writes until a new baseline. */ + disconnected(): void { + this.state.set({ ...this.state.getSnapshot(), ready: false }) + } + + /** + * Mark the Session through the latest completion known to this Client, without optimistically changing it. + * @param sessionId - known Session identity. + * @param unread - requested reminder state. + * @throws when no current baseline exists or the Host or carrier rejects; reconnect to refresh an unknown outcome. + */ + async mark(sessionId: SessionId, unread: boolean): Promise { + const throughTurn = this.state.getSnapshot().items[sessionId]?.completedTurn ?? 0 + await this.send(sessionId, unread ? { type: 'unread' } : { type: 'read', throughTurn }) + } + + /** + * Acknowledge content received by the visible Session view. + * @param sessionId - Known Session identity. + * @param throughTurn - Latest completed turn received in the Session body. + * @param clearManual - Clear the manual reminder of a Session the main view switched to. + */ + async acknowledge(sessionId: SessionId, throughTurn: number, clearManual: boolean): Promise { + await this.send(sessionId, { type: clearManual ? 'read' : 'acknowledge', throughTurn }) + } + + private async send(sessionId: SessionId, action: SessionReadAction): Promise { + const snapshot = this.state.getSnapshot() + if (!snapshot.ready) throw new Error('Reading state is unavailable. Reload the page to reconnect.') + const result = await this.remote.mark(sessionId, action) + if (!result.ok) throw result.error + } +} diff --git a/packages/client/ui-session-status/src/client/read.ts b/packages/client/ui-session-status/src/client/read.ts new file mode 100644 index 0000000000..16b21b958c --- /dev/null +++ b/packages/client/ui-session-status/src/client/read.ts @@ -0,0 +1,62 @@ +/** Host reading records installed under the Session status table: the access-gated stream and acknowledgements. */ +import type { Context } from '@deepseek-ai/cordis' +import { RemoteSnapshotStream, type RemoteStreamCarrierFailure } from '@deepseek-ai/dsh-api-gateway/client' +// Type-only: declares the `remoteAccess` Client service. +import type {} from '@deepseek-ai/dsh-api-remote-access/client' +// Type-only: declares the `sessions` Controller service. +import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionReadFrame } from '../types.ts' +import { installReadingAcknowledgements } from './acknowledge.ts' +import type { UiSessionStatus } from './status.ts' + +type SessionReadBaseline = Extract +type SessionReadChange = Extract + +const CARRIER_LOST: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost' + +/** + * Follow Host reading records into the status table's reading model and acknowledge reading in the visible main view. + * The stream runs only while the current Peer may follow it, so a LiveShare viewer opens no stream and keeps + * `readingReady` false; carrier reconnection replaces the complete reading baseline. + * @param ctx - Client root context with `remote`, `remoteAccess`, and `sessions`. + * @param status - status table whose reading model receives the records. + */ +export function installReading(ctx: Context, status: UiSessionStatus): void { + const reading = status.reading + installReadingAcknowledgements(ctx, ctx.sessions, reading) + // Each access grant runs one stream. Disposal stops failure reports and carrier retries at once, but a frame + // already handed to the consumer can still arrive, so a revoked or superseded stream's frames are discarded. + let active: object | undefined + const granted = (): boolean => active !== undefined + ctx.remoteAccess.whenAccess('sessionStatus/follow', function* () { + const token = {} + active = token + const current = (): boolean => active === token + const stream = ctx.remote.$stream({ + name: 'Session reading state', + open: signal => ctx.remote.sessionStatus.follow(signal), + carrierFailed: () => { reading.disconnected() }, + ended: (): RemoteStreamCarrierFailure => Object.assign( + new Error('Session reading state stream ended'), { code: CARRIER_LOST }, + ), + }) + const control = new RemoteSnapshotStream(stream, { + name: 'Session reading state', + isSnapshot: (frame): frame is SessionReadBaseline => frame.type === 'baseline', + replace: (frame) => { if (current()) reading.replace(frame.items) }, + update: (frame) => { if (current()) reading.accept(frame.state) }, + failed: (error) => { + reading.disconnected() + console.error('[session-status] Reminders could not be synchronized. Reload the page to reconnect:', error) + }, + }) + control.start() + yield async () => { + active = undefined + reading.disconnected() + await control.dispose() + // A later grant owns readiness once it starts; otherwise reading stays unavailable. + if (!granted()) reading.disconnected() + } + }) +} diff --git a/packages/client/ui-session-status/src/client/status.ts b/packages/client/ui-session-status/src/client/status.ts index 0e514f9033..80aeaf35cc 100644 --- a/packages/client/ui-session-status/src/client/status.ts +++ b/packages/client/ui-session-status/src/client/status.ts @@ -1,13 +1,16 @@ -/** Client Session status table: running state, the effective pending interaction, and completion reminders. */ +/** Client Session status table: running state, the effective pending interaction, and shared reading reminders. */ import { Service, type Context } from '@deepseek-ai/cordis' -import type { ISessions, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' +import type { ISessions, SessionBinding, SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' import { notifySubscribers } from '@deepseek-ai/dsh-client-store' import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only service merge for ctx.slots. +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' // Retains ui-session's Context and Slot prop declarations for every consumer of this face. export type {} from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { SessionReadModel } from './model.ts' /** Independent UI status facts for one Session identity. */ export interface SessionStatus { @@ -15,8 +18,13 @@ export interface SessionStatus { readonly running: boolean | undefined /** Highest-precedence domain request currently awaiting user interaction. */ readonly pendingInteraction: SessionPendingInteraction | undefined - /** Whether an observed stop outside the main view still needs acknowledgement. */ + /** + * Host-confirmed unread completion or explicit unread mark; an unacknowledged completion of the open Session the + * visible, focused main view retains is not shown until the view leaves it. + */ readonly completionUnread: boolean + /** Latest unread completion ended with an execution error this Host observed. */ + readonly completionFailed: boolean } /** Current UI status indexed by Session identity. */ @@ -39,37 +47,57 @@ declare module '@deepseek-ai/dsh-client-ui-session/client' { /** * Session status table provided as the `uiSession.sessionStatus` service and read as `ctx.uiSession.sessionStatus`. - * Completion reminders live only in this Client; the [status table reference](../../README.md#status-table) states - * when each field is set and cleared. + * Completion reminders come from the Host reading records shared by every Client of one Host; the + * [package reference](../../README.md#use-this-package) states when each field is set and cleared. */ export class UiSessionStatus extends Service implements HostObservable { private readonly running = new Map() - private readonly completionUnread = new Set() private statusSnapshot: SessionStatusSnapshot = new Map() + private viewedBinding: SessionBinding | undefined + private viewedOpenState: string | undefined + private releaseViewed = (): void => {} private readonly statusListeners = new Set<() => void>() + /** + * Package-internal Client copy of the Host reading records, which the reading installer follows into. + * @internal + */ + readonly reading: SessionReadModel + /** Whether reading marks can be sent: the current Host reading baseline has arrived. */ + readonly readingReady: HostObservable /** - * @param ctx - Client root context. - * @param sessions - Controller-owned Session catalog. + * @param ctx - Client root context; its generated `sessionStatus` Remote namespace sends reading marks. + * @param sessions - Controller-owned Session catalog and bindings. * @param pendingInteractions - effective pending request by Session, published by ui-session. */ constructor( ctx: Context, - private readonly sessions: Pick, + private readonly sessions: Pick, private readonly pendingInteractions: HostObservable>, ) { super(ctx, 'uiSession.sessionStatus') + const reading = new SessionReadModel(ctx.remote.sessionStatus) + this.reading = reading + this.readingReady = { + getSnapshot: () => reading.state.getSnapshot().ready, + subscribe: listener => reading.state.subscribe(listener), + } ctx.effect(() => { const disposeStatus = sessions.list.subscribe(() => { this.reconcileStatus() }) const disposeRemoteStatus = ctx.remote.$on('api-session/status', (sessionId, running) => { this.observeRunning(sessionId, running) }) const disposePending = pendingInteractions.subscribe(() => { this.publishStatus() }) + const disposeReading = reading.state.subscribe(() => { this.publishStatus() }) + const disposeView = watchViewVisibility(() => { this.publishStatus() }) this.reconcileStatus() return () => { disposeStatus() disposeRemoteStatus() disposePending() + disposeReading() + disposeView() + this.releaseViewed() } }, 'session-status: Session status table') } @@ -90,13 +118,18 @@ export class UiSessionStatus extends Service implements HostObservable { this.statusListeners.delete(listener) } } + /** + * Mark one Session read or unread through the latest completion known to this Client. + * @param sessionId - known Session identity. + * @param unread - requested reminder state. + * @throws when reading is not synchronized or the Host or carrier rejects; reconnect to refresh an unknown outcome. + */ + async mark(sessionId: SessionId, unread: boolean): Promise { + await this.reading.mark(sessionId, unread) + } + private observeRunning(sessionId: SessionId, running: boolean): void { - const previous = this.running.get(sessionId) - const beforeBaseline = this.sessions.list.getSnapshot().phase === 'pending' this.running.set(sessionId, running) - if (running) this.completionUnread.delete(sessionId) - else if ((previous === true || (previous === undefined && beforeBaseline)) - && !this.isMain(sessionId)) this.completionUnread.add(sessionId) this.publishStatus() } @@ -110,37 +143,55 @@ export class UiSessionStatus extends Service implements HostObservable 0 + /** Follow the main-view Session's binding, whose open state decides whether its natural reminder is hidden. */ + private followMainView(list: SessionListState): void { + const id = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0)?.id + const binding = id === undefined ? undefined : this.sessions.binding(id) + if (binding === this.viewedBinding) return + this.releaseViewed() + this.viewedBinding = binding + this.viewedOpenState = binding?.session.getSnapshot().openState + // Session snapshots change with every streamed event; only the open state affects the table. + this.releaseViewed = binding?.session.subscribe(() => { + const openState = binding.session.getSnapshot().openState + if (openState === this.viewedOpenState) return + this.viewedOpenState = openState + this.publishStatus() + }) ?? (() => {}) } private publishStatus(): void { const pending = this.pendingInteractions.getSnapshot() + const reading = this.reading.state.getSnapshot().items + const list = this.sessions.list.getSnapshot() + // The visible, focused main view acknowledges its open Session's completions; hiding them meanwhile avoids a flash. + const viewing = viewVisible() && this.viewedOpenState === 'open' ? this.viewedBinding?.sessionId : undefined const ids = new Set([ - ...(Object.keys(this.sessions.list.getSnapshot().byId) as SessionId[]), + ...(Object.keys(list.byId) as SessionId[]), ...this.running.keys(), ...pending.keys(), - ...this.completionUnread, + ...(Object.keys(reading) as SessionId[]), ]) const next = new Map() for (const id of ids) { + const record = reading[id] + const unread = record !== undefined + && (record.manualUnread || (id !== viewing && record.completedTurn > record.readTurn)) next.set(id, { running: this.running.get(id), pendingInteraction: pending.get(id), - completionUnread: this.completionUnread.has(id), + completionUnread: unread, + completionFailed: unread && record.failed, }) } if (sameSessionStatus(this.statusSnapshot, next)) return @@ -149,6 +200,28 @@ export class UiSessionStatus extends Service implements HostObservable void): () => void { + if (typeof document === 'undefined') return () => {} + document.addEventListener('visibilitychange', changed) + window.addEventListener('focus', changed) + window.addEventListener('blur', changed) + return () => { + document.removeEventListener('visibilitychange', changed) + window.removeEventListener('focus', changed) + window.removeEventListener('blur', changed) + } +} + function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean { if (left.size !== right.size) return false for (const [id, status] of left) { @@ -156,7 +229,8 @@ function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnap if (candidate === undefined || candidate.running !== status.running || candidate.pendingInteraction !== status.pendingInteraction - || candidate.completionUnread !== status.completionUnread) return false + || candidate.completionUnread !== status.completionUnread + || candidate.completionFailed !== status.completionFailed) return false } return true } diff --git a/packages/client/ui-session-status/src/feed.ts b/packages/client/ui-session-status/src/feed.ts new file mode 100644 index 0000000000..ef66255734 --- /dev/null +++ b/packages/client/ui-session-status/src/feed.ts @@ -0,0 +1,58 @@ +/** Cancellation-owned queue for a reading-state follow generation. */ +import { Deque } from '@deepseek-ai/dsh-deque' +import type { SessionReadFrame } from './types.ts' + +type ChangedFrame = Extract + +/** One follower's ordered committed updates. */ +export class SessionReadFollower { + private readonly frames = new Deque() + private wake: (() => void) | undefined + private readonly lifetime = new AbortController() + private failure: Error | undefined + + /** Aborts when this follower closes, including while its consumer is paused. */ + get signal(): AbortSignal { return this.lifetime.signal } + + /** + * Enqueue one update for an active follower. + * @param frame - committed whole-record replacement. + */ + push(frame: ChangedFrame): void { + if (this.signal.aborted) return + this.frames.pushBack(frame) + this.wake?.() + } + + /** + * Wake the reader and end this generation, preserving the first close reason. + * Queued frames are discarded; the next generation supplies a complete baseline. + * @param failure - terminal stream failure, when present. + */ + close(failure?: Error): void { + if (this.signal.aborted) return + this.failure = failure + this.lifetime.abort() + this.wake?.() + } + + /** + * Consume queued changes until cancellation, teardown, or stream failure. + * @param signal - Remote generation lifetime. + * @returns ordered updates; rejects with the first terminal stream failure. + */ + async *read(signal: AbortSignal): AsyncIterable { + const abort = (): void => { this.close() } + signal.addEventListener('abort', abort, { once: true }) + try { + while (!signal.aborted && !this.signal.aborted) { + const frame = this.frames.popFront() + if (frame !== undefined) yield frame + else await new Promise((resolve) => { this.wake = resolve }) + } + if (this.failure !== undefined) throw this.failure + } finally { + signal.removeEventListener('abort', abort) + } + } +} diff --git a/packages/client/ui-session-status/src/index.ts b/packages/client/ui-session-status/src/index.ts index cb1b451cca..e6f80992f7 100644 --- a/packages/client/ui-session-status/src/index.ts +++ b/packages/client/ui-session-status/src/index.ts @@ -1,4 +1,146 @@ -/** Host loader entry for the browser-only Session status plugin. */ +/** Host-authoritative Session reading records, kept in memory, and their Remote service. */ +import { Context, Service } from '@deepseek-ai/cordis' +import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-api-remote-access' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-persistence' +import { SessionReadFollower } from './feed.ts' +import type { SessionReadRecord } from './spec.ts' +import type { SessionReadAction, SessionReadFrame, SessionReadState } from './types.ts' -/** Provides no Host-side behavior. */ -export function apply(): void {} +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Host owner of the in-memory Session reading records behind the `sessionStatus` Remote namespace. */ + sessionStatus: SessionStatusService + } +} + +const emptyRecord: SessionReadRecord = { + completedTurn: 0, failed: false, readTurn: 0, manualUnread: false, +} + +/** Shared owner reading records; no reading operation changes model history. */ +export class SessionStatusService extends TypertRemoteService { + static inject = ['remoteAccess', 'sessions', 'sessionPersistence', 'typert'] + + private readonly records = new Map() + private closing = false + private readonly followers = new Set() + + /** @param ctx - Host services supplying Session events and metadata. */ + constructor(ctx: Context) { + super(ctx, 'sessionStatus', { namespace: 'sessionStatus' }) + } + + protected [Service.init](): void { + this.ctx.effect(() => () => { + this.closing = true + for (const follower of this.followers) follower.close() + this.followers.clear() + this.records.clear() + }, 'session-status: close followers and discard records') + // History recorded before this service started is read: only a turn that + // ends while it runs can raise a reminder. A `turn/end` replayed from a + // restored or forked log reaches no listener, so it raises none either. + this.ctx.on('session/event', (session, event) => { + if (event.type !== 'turn/end') return + this.complete(session.id, event.data.turn, event.data.reason.kind === 'error') + }) + } + + /** + * Update one Session; read positions advance only through Client-observed completions. + * @param sessionId - Session identity. + * @param action - Explicit reminder change or automatic read-position acknowledgement. + * @throws RemoteError when closing, the Session is missing, or its metadata cannot be read. + */ + @Remote + async mark(sessionId: SessionId, action: SessionReadAction): Promise { + this.assertOpen() + const sessions = this.ctx.sessions + if (sessions.get(sessionId) === undefined) { + let exists: boolean + try { + exists = await this.ctx.sessionPersistence.stat(sessionId) !== undefined + } catch (cause) { + throw this.unavailable(cause) + } + this.assertOpen() + if (!exists) throw new RemoteError('session-status/not-found', 'Session no longer exists', { sessionId }) + } + const record = this.records.get(sessionId) ?? emptyRecord + const next = { ...record, + manualUnread: action.type === 'acknowledge' ? record.manualUnread : action.type === 'unread', + readTurn: action.type === 'unread' ? record.readTurn + : Math.max(record.readTurn, Math.min(action.throughTurn, record.completedTurn)) } + this.records.set(sessionId, next) + this.publish(sessionId, next) + } + + /** + * Follow accessible reading records; every connection starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline and whole-record changes, filtered by Session access. + * @throws RemoteError when the service is closing. + */ + @Remote({ mode: 'stream' }) + async *follow(signal: AbortSignal): AsyncIterable { + this.assertOpen() + signal.throwIfAborted() + const allowed = (id: SessionId): boolean => this.ctx.remoteAccess.allows({ kind: 'session', id }) + const follower = new SessionReadFollower() + const access = this.followAccess(follower, AbortSignal.any([signal, follower.signal])) + this.followers.add(follower) + try { + yield { type: 'baseline', items: [...this.records.entries()] + .filter(([id]) => allowed(id)).map(([id, record]) => this.view(id, record)) } + for await (const frame of follower.read(signal)) { + if (allowed(frame.state.sessionId)) yield frame + } + } finally { + this.followers.delete(follower) + follower.close() + await access + } + } + + private async followAccess(follower: SessionReadFollower, signal: AbortSignal): Promise { + try { + for await (const frame of this.ctx.remoteAccess.follow(signal)) { + if (frame.type !== 'baseline') break + } + } catch (cause) { + follower.close(this.unavailable(cause)) + } finally { + follower.close() + } + } + + private assertOpen(): void { + if (this.closing) throw this.unavailable(new Error('Session status service is closing')) + } + + private complete(sessionId: SessionId, turn: number, failed: boolean): void { + const next: SessionReadRecord = { ...(this.records.get(sessionId) ?? emptyRecord), completedTurn: turn, failed } + this.records.set(sessionId, next) + this.publish(sessionId, next) + } + + private view(sessionId: SessionId, record: SessionReadRecord): SessionReadState { + return { sessionId, completedTurn: record.completedTurn, failed: record.failed, + readTurn: record.readTurn, manualUnread: record.manualUnread } + } + + private publish(sessionId: SessionId, record: SessionReadRecord): void { + const state = this.view(sessionId, record) + for (const follower of this.followers) follower.push({ type: 'changed', state }) + } + + private unavailable(cause: unknown): RemoteError { + return new RemoteError('session-status/unavailable', 'Reading state could not be updated. Try the operation again; reload the page if synchronization is unavailable.', {}, { cause }) + } +} + +export default SessionStatusService diff --git a/packages/client/ui-session-status/src/spec.ts b/packages/client/ui-session-status/src/spec.ts new file mode 100644 index 0000000000..1d9d8e21c6 --- /dev/null +++ b/packages/client/ui-session-status/src/spec.ts @@ -0,0 +1,5 @@ +/** Host-owned reading record, reset when the service is reloaded. */ +import type { SessionReadState } from './types.ts' + +/** Reading fields stored per Session, without the map key. */ +export type SessionReadRecord = Omit diff --git a/packages/client/ui-session-status/src/types.ts b/packages/client/ui-session-status/src/types.ts new file mode 100644 index 0000000000..901322bb58 --- /dev/null +++ b/packages/client/ui-session-status/src/types.ts @@ -0,0 +1,32 @@ +/** Browser-safe Session reading state and Remote requests. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** Host-confirmed reading state for one Session; turn numbers survive log-format migrations. */ +export interface SessionReadState { + readonly sessionId: SessionId + /** Latest turn that ended while this Host served the Session; 0 when none did. */ + readonly completedTurn: number + /** Whether {@link SessionReadState.completedTurn} ended with an execution error; older history reads as success. */ + readonly failed: boolean + readonly readTurn: number + readonly manualUnread: boolean +} + +/** Explicit marks replace the manual reminder; automatic acknowledgements only advance the read position. */ +export type SessionReadAction = + | { readonly type: 'unread' } + | { readonly type: 'read' | 'acknowledge'; readonly throughTurn: number } + +/** Reconnect baseline followed by complete replacement records. */ +export type SessionReadFrame = + | { readonly type: 'baseline'; readonly items: readonly SessionReadState[] } + | { readonly type: 'changed'; readonly state: SessionReadState } + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface RemoteErrorDetailsMap { + /** The requested Session does not exist. */ + 'session-status/not-found': { readonly sessionId: SessionId } + /** Reading state could not be updated; the previous value remains visible. */ + 'session-status/unavailable': {} + } +} diff --git a/packages/client/ui-session-status/tests/access.client.spec.ts b/packages/client/ui-session-status/tests/access.client.spec.ts new file mode 100644 index 0000000000..370c05258d --- /dev/null +++ b/packages/client/ui-session-status/tests/access.client.spec.ts @@ -0,0 +1,157 @@ +/** The reading stream follows the current Peer's access to `sessionStatus/follow`. */ +import { Context } from '@deepseek-ai/cordis' +import type { AccessEffect, RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' +import { whenAllowed } from '@deepseek-ai/dsh-api-remote-access/src/client/when-allowed.ts' +import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import { apply, inject } from '../src/client/index.ts' +import type { UiSessionStatus } from '../src/client/status.ts' +import type { SessionReadFrame, SessionReadState } from '../src/types.ts' + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) + +/** A stream whose frames the test hands to the consumer; disposal does not withdraw a frame already handed over. */ +function drivenStream() { + const queue: (SessionReadFrame | undefined)[] = [] + let wake: (() => void) | undefined + const state = { finished: false } + let generation = 1 + const signal = new AbortController().signal + const stream = { + signal, + restart: () => {}, + dispose: async () => {}, + async* [Symbol.asyncIterator]() { + try { + for (;;) { + while (queue.length === 0) await new Promise((resolve) => { wake = resolve }) + const value = queue.shift() + if (value === undefined) return + yield { generation, value, signal, accept: () => {} } + } + } finally { + state.finished = true + } + }, + } + const push = (value: SessionReadFrame | undefined) => { + queue.push(value) + wake?.() + } + return { stream, push, end: () => { push(undefined) }, reconnect: () => { generation++ }, state } +} + +const record = (id: string): SessionReadState => ({ + sessionId: id as SessionId, completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, +}) + +async function harness(initiallyAllowed: boolean, driven = false) { + const ctx = new Context() + roots.push(ctx) + const opened: AbortSignal[] = [] + const follow = (signal: AbortSignal): AsyncIterable => { + opened.push(signal) + return (async function* () { + yield { type: 'baseline', items: [] } + await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + })() + } + const remote = new TestRemote(ctx, { sessionStatus: { follow, mark: vi.fn() } }) + const streams: ReturnType[] = [] + if (driven) { + Object.assign(remote, { $stream: () => { + const next = drivenStream() + streams.push(next) + return next.stream + } }) + } + const allowed = createSnapshotStore(initiallyAllowed, { flush: 'sync' }) + const requested: RemoteEndpoint[] = [] + ctx.provide('remoteAccess', { + whenAccess: (action: RemoteEndpoint, callback: () => AccessEffect) => { + requested.push(action) + return whenAllowed(ctx, allowed, callback, 'test access') + }, + } as never) + ctx.provide('sessions', { + list: createSnapshotStore({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }), + binding: () => undefined, + } as never) + ctx.provide('slots', { provideRoot: () => () => {} } as never) + ctx.provide('uiSession', { + pendingInteractions: createSnapshotStore>(new Map()), + } as never) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + await ctx.plugin({ inject, apply }).await() + const status = ctx.get('uiSession.sessionStatus') as UiSessionStatus + const ready = () => status.readingReady.getSnapshot() + return { ctx, opened, allowed, requested, report, ready, status, streams } +} + +it('opens no reading stream and reports nothing while the Peer may not follow reading records', async () => { + const b = await harness(false) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.requested).toEqual(['sessionStatus/follow']) + expect(b.opened).toEqual([]) + expect(b.ready()).toBe(false) + await expect(b.status.mark('s1' as SessionId, true)).rejects.toThrow('Reading state is unavailable') + expect(b.report).not.toHaveBeenCalled() +}) + +it('starts the stream when access is granted and stops it when access is revoked', async () => { + const b = await harness(false) + b.allowed.set(true) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + expect(b.opened).toHaveLength(1) + b.allowed.set(false) + expect(b.ready()).toBe(false) + await vi.waitFor(() => { expect(b.opened[0]!.aborted).toBe(true) }) + b.allowed.set(true) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + expect(b.opened).toHaveLength(2) + expect(b.report).not.toHaveBeenCalled() +}) + +it('discards frames a revoked stream still delivers and leaves reading unavailable', async () => { + const b = await harness(true, true) + const first = b.streams[0]! + first.push({ type: 'baseline', items: [] }) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + b.allowed.set(false) + expect(b.ready()).toBe(false) + first.reconnect() + first.push({ type: 'baseline', items: [record('late')] }) + first.push({ type: 'changed', state: record('later') }) + first.end() + await vi.waitFor(() => { expect(first.state.finished).toBe(true) }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.ready()).toBe(false) + expect(b.status.getSnapshot().size).toBe(0) +}) + +it('keeps a quick re-grant\'s records and readiness while the revoked stream drains', async () => { + const b = await harness(true, true) + const first = b.streams[0]! + first.push({ type: 'baseline', items: [] }) + await vi.waitFor(() => { expect(b.ready()).toBe(true) }) + b.allowed.set(false) + b.allowed.set(true) + const second = b.streams[1]! + second.push({ type: 'baseline', items: [record('granted')] }) + await vi.waitFor(() => { expect(b.status.getSnapshot().get('granted' as SessionId)?.completionUnread).toBe(true) }) + first.push({ type: 'changed', state: record('revoked') }) + first.end() + await vi.waitFor(() => { expect(first.state.finished).toBe(true) }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(b.ready()).toBe(true) + expect([...b.status.getSnapshot().keys()]).toEqual(['granted']) + second.end() +}) diff --git a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts new file mode 100644 index 0000000000..4475586682 --- /dev/null +++ b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts @@ -0,0 +1,291 @@ +// @vitest-environment jsdom +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { AgentContext, SessionBinding, SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { FixtureSession, type SessionFixtureSnapshot } from '@deepseek-ai/dsh-client-test-runtime' +import { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import { installReadingAcknowledgements } from '../src/client/acknowledge.ts' +import type { SessionReadSnapshot } from '../src/client/model.ts' +import type { SessionReadState } from '../src/types.ts' + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +interface HarnessOptions { + /** Manual reminder of the initial record. */ + readonly manual?: boolean + /** Completed turn of the initial record, also delivered to the body. */ + readonly completedTurn?: number + /** Whether the main view retains the Session at install time. */ + readonly selected?: boolean + /** Whether the reading baseline is ready at install time. */ + readonly ready?: boolean +} + +function harness({ manual = false, completedTurn = 1, selected = true, ready = true }: HarnessOptions = {}) { + const ctx = new Context() + roots.push(ctx) + const id = SessionId('viewed') + const state = createSnapshotStore({ ready, items: { [id]: { + sessionId: id, completedTurn, failed: false, readTurn: 0, manualUnread: manual, + } } }, { flush: 'sync' }) + const lifecycle = createSnapshotStore({ + sessionId: id, pendingSubmissions: [], running: false, subagent: null, removed: false, + openState: 'open', openError: null, hasMore: false, loadingOlder: false, promptError: null, + historyLoadStatus: 'idle', historyWasPartial: false, + blank: false, lastAgentError: null, promptAttempted: false, awaitingFirstTurn: false, + }, { flush: 'sync' }) + const session = new FixtureSession(id, lifecycle, {}) + const body = (turn: number) => { session.eventSource.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(turn), time: 0, data: { turn, reason: { kind: 'completed' } }, + } }) } + if (completedTurn > 0) body(completedTurn) + const row = (mainView: boolean) => ({ + id, displayTitle: 'Viewed', retainedBy: mainView ? { mainView: 1 } : {}, running: false, blank: false, updatedAt: 1, + }) + const list = createSnapshotStore({ + ids: [id], phase: 'ready', projectionsBySession: {}, byId: { [id]: row(selected) }, + }, { flush: 'sync' }) + const bind = (): SessionBinding => ({ sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext }) + let binding = bind() + const mark = vi.fn(async (_id: typeof id, _throughTurn: number, _clearManual: boolean) => {}) + let frame: FrameRequestCallback | undefined + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frame = callback; return 1 }) + vi.stubGlobal('cancelAnimationFrame', () => { frame = undefined }) + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true) + const visible = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') + installReadingAcknowledgements(ctx, { list, binding: () => binding }, { state, acknowledge: mark }) + const paint = async () => { + const callback = frame + frame = undefined + callback?.(0) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + } + /** Replace the record with the given fields over the current one. */ + const record = (patch: Partial) => { + const current = state.getSnapshot() + state.set({ ready: true, items: { [id]: { ...current.items[id]!, ...patch } } }) + } + /** Move the main view to or away from the Session. */ + const select = (on: boolean) => { list.update((draft) => { draft.byId[id] = row(on) }) } + /** Replace the binding of the still-selected Session. */ + const rebind = () => { + binding = bind() + list.set({ ...list.getSnapshot() }) + } + return { ctx, id, state, body, lifecycle, list, mark, paint, focus, visible, session, record, select, rebind } +} + +it('waits for a focused visible main view and an open Session before acknowledging', async () => { + const b = harness() + b.visible.mockReturnValue('hidden') + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.visible.mockReturnValue('visible') + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + document.dispatchEvent(new Event('visibilitychange')) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('clears a manual reminder after the main view switches to its Session and the body arrives', async () => { + const b = harness({ manual: true, selected: false }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.select(true) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('preserves a manual mark made in the open Session until the main view leaves and returns', async () => { + const b = harness() + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + b.record({ readTurn: 1, manualUnread: true }) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.select(false) + b.select(true) + await b.paint() + expect(b.mark).toHaveBeenLastCalledWith(b.id, 1, true) +}) + +it('preserves a manual reminder when the window regains focus or visibility', async () => { + const b = harness() + await b.paint() + b.record({ readTurn: 1, manualUnread: true }) + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + document.dispatchEvent(new Event('visibilitychange')) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('treats the initial selection as an entry and clears its manual reminder once a late baseline arrives', async () => { + const b = harness({ manual: true, ready: false }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.record({ manualUnread: true }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('does not treat a replaced binding for the same Session as an entry', async () => { + const b = harness() + await b.paint() + b.record({ readTurn: 1, manualUnread: true }) + b.rebind() + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('acknowledges an earlier manual mark before any turn has completed', async () => { + const b = harness({ manual: true, completedTurn: 0 }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 0, true) +}) + +it('does not read a new completion before its content arrives, or after disposal', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + await b.ctx.fiber.dispose() + await b.paint() + expect(b.mark).not.toHaveBeenCalled() +}) + +it('acknowledges later body progress without clearing manual unread again', async () => { + const b = harness({ manual: true, completedTurn: 0 }) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.body(1) + b.record({ completedTurn: 1, manualUnread: true }) + await b.paint() + expect(b.mark.mock.calls).toEqual([[b.id, 0, true], [b.id, 1, false]]) +}) + +it('retains unread after acknowledgement failure and retries on a new view entry', async () => { + const b = harness() + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + b.mark.mockRejectedValueOnce(new Error('offline')) + await b.paint() + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + expect(report).toHaveBeenCalled() + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(2) +}) + +it('does not acknowledge an unselected or unknown record and tolerates unrelated list updates', async () => { + const b = harness() + const selected = b.list.getSnapshot() + b.list.set({ ...selected, byId: {} }) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.state.set({ ready: true, items: {} }) + b.list.set(selected) + await b.paint() + b.list.set({ ...selected }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + await b.ctx.fiber.dispose() +}) + +it('waits for the body to reach the completed turn before acknowledging', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + b.body(2) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 2, false) +}) + +it('preserves a manual mark received while the entered Session is loading', async () => { + const b = harness() + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.record({ manualUnread: true }) + await b.paint() + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).not.toHaveBeenCalledWith(b.id, 1, true) +}) + +it('keeps a pending entry across window blur and clears after the body loads', async () => { + const b = harness({ manual: true }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + await b.paint() + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + b.lifecycle.update((draft) => { draft.openState = 'open' }) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, true) +}) + +it('retains an entry while a natural acknowledgement is pending', async () => { + const b = harness() + let resolve!: () => void + b.mark.mockImplementationOnce(() => new Promise((settle) => { resolve = settle })) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) + b.record({ manualUnread: true }) + b.select(false) + b.select(true) + await b.paint() + expect(b.mark).toHaveBeenCalledTimes(1) + resolve() + await b.paint() + await b.paint() + expect(b.mark).toHaveBeenLastCalledWith(b.id, 1, true) +}) + +it('drops an entry after another client clears the manual reminder', async () => { + const b = harness({ manual: true }) + b.lifecycle.update((draft) => { draft.openState = 'loading' }) + b.record({ manualUnread: false }) + b.record({ manualUnread: true }) + b.lifecycle.update((draft) => { draft.openState = 'open' }) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 1, false) +}) + +it('acknowledges a completed turn only after the body advances to the next turn', async () => { + const b = harness() + b.record({ completedTurn: 2, readTurn: 1 }) + const start = (turn: number) => { b.session.eventSource.replace([{ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(turn), time: 0, data: { turn }, + } }], true) } + start(2) + await b.paint() + expect(b.mark).not.toHaveBeenCalled() + start(3) + await b.paint() + expect(b.mark).toHaveBeenCalledExactlyOnceWith(b.id, 2, false) +}) diff --git a/packages/client/ui-session-status/tests/model.client.spec.ts b/packages/client/ui-session-status/tests/model.client.spec.ts new file mode 100644 index 0000000000..f5db380693 --- /dev/null +++ b/packages/client/ui-session-status/tests/model.client.spec.ts @@ -0,0 +1,87 @@ +import { expect, it, vi } from 'vitest' +import { RemoteError, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SessionReadModel } from '../src/client/model.ts' +import type { SessionReadState } from '../src/types.ts' + +const id = SessionId('reading') +const record = (completedTurn: number, manualUnread = false): SessionReadState => ({ + sessionId: id, completedTurn, failed: false, readTurn: 0, manualUnread, +}) + +it('replaces reconnect baselines and rejects actions without a current baseline', async () => { + const mark = vi.fn() + const model = new SessionReadModel({ mark }) + await expect(model.mark(id, false)).rejects.toThrow('Reload the page') + model.replace([record(1)]) + model.accept(record(2)) + expect(model.state.getSnapshot().items[id]?.completedTurn).toBe(2) + model.disconnected() + expect(model.state.getSnapshot()).toMatchObject({ ready: false }) + model.replace([]) + expect(model.state.getSnapshot()).toEqual({ items: {}, ready: true }) +}) + +it('keeps newer pushed unread marks when an older read response arrives', async () => { + const response = Promise.withResolvers<{ ok: true; value: undefined }>() + const mark = vi.fn(() => response.promise) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + const pending = model.mark(id, false) + model.accept(record(3, true)) + response.resolve({ ok: true, value: undefined }) + await pending + expect(mark).toHaveBeenCalledWith(id, { type: 'read', throughTurn: 1 }) + expect(model.state.getSnapshot().items[id]).toEqual(record(3, true)) +}) + +it('keeps a replaced baseline when an earlier operation completes and preserves records on failure', async () => { + const response = Promise.withResolvers<{ ok: true; value: undefined }>() + const mark = vi.fn(() => response.promise) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + const pending = model.mark(id, true) + model.disconnected() + model.replace([]) + response.resolve({ ok: true, value: undefined }) + await pending + expect(model.state.getSnapshot().items).toEqual({}) + mark.mockRejectedValueOnce(new Error('offline')) + await expect(model.mark(id, true)).rejects.toThrow('offline') + expect(model.state.getSnapshot().items).toEqual({}) +}) + +it('sends explicit marks and body acknowledgements with their observed positions', async () => { + const mark = vi.fn(async () => ({ ok: true, value: undefined })) + const model = new SessionReadModel({ mark }) + model.replace([]) + await model.mark(id, false) + await model.mark(id, true) + await model.acknowledge(id, 2, false) + await model.acknowledge(id, 3, true) + expect(mark.mock.calls).toEqual([ + [id, { type: 'read', throughTurn: 0 }], + [id, { type: 'unread' }], + [id, { type: 'acknowledge', throughTurn: 2 }], + [id, { type: 'read', throughTurn: 3 }], + ]) + expect(model.state.getSnapshot().items).toEqual({}) +}) + +it('reports business rejection and disables writes without losing reminders', async () => { + const error = new RemoteError('session-status/unavailable', 'Storage unavailable', {}) + const mark = vi.fn(async () => ({ ok: false, error })) + const model = new SessionReadModel({ mark }) + model.replace([record(1)]) + await expect(model.mark(id, false)).rejects.toBe(error) + expect(model.state.getSnapshot().items[id]).toEqual(record(1)) + model.disconnected() + expect(model.state.getSnapshot()).toMatchObject({ ready: false }) +}) + +it('accepts the first pushed record for a newly visible Session', () => { + const model = new SessionReadModel({ mark: vi.fn() }) + model.replace([]) + model.accept(record(1)) + expect(model.state.getSnapshot().items[id]).toEqual(record(1)) +}) diff --git a/packages/client/ui-session-status/tests/status-controller.client.spec.ts b/packages/client/ui-session-status/tests/status-controller.client.spec.ts index 3a7e2543ab..13ce251f13 100644 --- a/packages/client/ui-session-status/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session-status/tests/status-controller.client.spec.ts @@ -1,5 +1,6 @@ /** Session status across the real Controller catalog, ui-session pending interactions, and the status service. */ -import { expect, vi } from 'vitest' +import { expect, onTestFinished, vi } from 'vitest' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { ok } from '@deepseek-ai/dsh-remote-mock' import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import { SESSION_FORMAT_VERSION, type SessionId } from '@deepseek-ai/dsh-session/types' @@ -11,6 +12,39 @@ const it = createClientTest({ roster: webApp.closure(['@deepseek-ai/dsh-client-u const parentId = 'status-parent' as SessionId const childId = 'status-child' as SessionId +it('reports a failed completion as an error reminder until it is read', async ({ mock, start }) => { + const record = (turn: number, readTurn: number, failed = false) => ({ + sessionId: parentId, completedTurn: turn, failed, readTurn, manualUnread: false, + }) + mock.remote.session.list.mockResolvedValue(ok({ items: [{ + sessionId: parentId, updatedAt: 1, running: false, blank: false, agentAvailable: true, + }] })) + mock.stream('sessionStatus/follow', (_request, stream) => { + stream.push({ type: 'baseline', items: [record(1, 0, true)] }) + }) + const client = await start() + const sessions = client.ctx.sessions + const status = () => client.ctx.uiSession.sessionStatus.getSnapshot().get(parentId) + await sessions.refresh() + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: true }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 0) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: false }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 2, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: false, completionFailed: false }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(3, 2, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: true, completionFailed: true }) }) + + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(3, 3, true) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status()).toMatchObject({ completionUnread: false, completionFailed: false }) }) +}) + it('preserves unlisted child status through metadata updates and main view acknowledgement', async ({ mock, start }) => { mock.remote.session.list.mockResolvedValue(ok({ items: [{ sessionId: parentId, updatedAt: 1, running: false, blank: false, agentAvailable: true, @@ -53,11 +87,20 @@ it('preserves unlisted child status through metadata updates and main view ackno mock.streams.push('$events', { type: 'emit', event: 'api-session/status', args: [childId, false] }) await mock.streams.drained('$events') await client.flush() + mock.streams.push('sessionStatus/follow', { type: 'changed', state: { + sessionId: childId, completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, + } }) + await mock.streams.drained('sessionStatus/follow') + await client.flush() expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: true }) using reference = sessions.retain(childId, { source: 'mainView' }) await reference.ready expect(sessions.list.getSnapshot().ids).not.toContain(childId) + mock.streams.push('sessionStatus/follow', { type: 'changed', state: { + sessionId: childId, completedTurn: 1, failed: false, readTurn: 1, manualUnread: false, + } }) + await mock.streams.drained('sessionStatus/follow') await vi.waitFor(() => { expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: false }) }) @@ -76,3 +119,43 @@ it('reports the effective ui-session pending interaction as the same request obj remove() expect(status.getSnapshot().get(parentId)?.pendingInteraction).toBeUndefined() }) + +it('applies ordered whole-record reading changes after the baseline', async ({ mock, start }) => { + const record = (completedTurn: number, readTurn: number) => ({ + sessionId: parentId, completedTurn, failed: false, readTurn, manualUnread: false, + }) + mock.stream('sessionStatus/follow', (_request, stream) => { + stream.push({ type: 'baseline', items: [record(1, 0)] }) + }) + const client = await start() + const status = client.ctx.uiSession.sessionStatus + await vi.waitFor(() => { expect(status.getSnapshot().get(parentId)?.completionUnread).toBe(true) }) + expect(status.readingReady.getSnapshot()).toBe(true) + mock.streams.push('sessionStatus/follow', { type: 'changed', state: record(2, 2) }) + await mock.streams.drained('sessionStatus/follow') + await vi.waitFor(() => { expect(status.getSnapshot().get(parentId)?.completionUnread).toBe(false) }) +}) + +it('retains reminders after a stream ends, replaces the reconnect baseline, and reports terminal failure', async ({ mock, start }) => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { report.mockRestore() }) + let generation = 0 + mock.stream('sessionStatus/follow', (_request, stream) => { + generation++ + stream.push({ type: 'baseline', items: [{ + sessionId: parentId, completedTurn: generation, failed: generation === 2, readTurn: 0, + manualUnread: false, + }] }) + if (generation === 1) stream.end() + else stream.fail(new RemoteError('session-status/unavailable', 'Reading storage unavailable', {})) + }) + const client = await start() + const status = client.ctx.uiSession.sessionStatus + await vi.waitFor(() => { + expect(status.getSnapshot().get(parentId)).toMatchObject({ completionUnread: true, completionFailed: true }) + expect(status.readingReady.getSnapshot()).toBe(false) + }) + expect(generation).toBe(2) + await expect(status.mark(parentId, false)).rejects.toThrow('Reload the page') + expect(report).toHaveBeenCalledWith(expect.stringContaining('Reminders could not be synchronized'), expect.any(Error)) +}) diff --git a/packages/client/ui-session-status/tests/status-view.client.spec.ts b/packages/client/ui-session-status/tests/status-view.client.spec.ts new file mode 100644 index 0000000000..ef03c22f15 --- /dev/null +++ b/packages/client/ui-session-status/tests/status-view.client.spec.ts @@ -0,0 +1,109 @@ +// @vitest-environment jsdom +/** Natural reminders of the Session the visible, focused main view retains. */ +import { Context } from '@deepseek-ai/cordis' +import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, expect, it, vi } from 'vitest' +import type { SessionReadSnapshot } from '../src/client/model.ts' +import { UiSessionStatus } from '../src/client/status.ts' +import type { SessionReadState } from '../src/types.ts' + +const viewed = 'viewed' as SessionId +const other = 'other' as SessionId +const roots: Context[] = [] + +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + vi.restoreAllMocks() +}) + +function bench() { + const ctx = new Context() + roots.push(ctx) + ctx.provide('remote', { $on: () => () => {} } as never) + const row = (id: SessionId, mainView: boolean) => ({ + id, displayTitle: id, running: false, retainedBy: mainView ? { mainView: 1 } : {}, blank: false, updatedAt: 1, + }) + const list = createSnapshotStore({ + ids: [viewed, other], phase: 'ready', projectionsBySession: {}, + byId: { [viewed]: row(viewed, true), [other]: row(other, false) }, + }) + const record = (id: SessionId, value: Partial): SessionReadState => ({ + sessionId: id, completedTurn: 1, failed: true, readTurn: 0, manualUnread: false, ...value, + }) + const opened = (id: SessionId) => ({ + sessionId: id, session: createSnapshotStore<{ readonly openState: string; readonly running?: boolean }>({ openState: 'open' }), + }) + const bindings = new Map([viewed, other].map(id => [id, opened(id)])) + const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true) + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') + const service = new UiSessionStatus(ctx, { list, binding: (id: SessionId) => bindings.get(id) as never }, + createSnapshotStore>(new Map())) + const reading: { set(value: SessionReadSnapshot): void } = service.reading.state + reading.set({ ready: true, items: { [viewed]: record(viewed, {}), [other]: record(other, {}) } }) + const status = (id: SessionId) => service.getSnapshot().get(id) + const view = (id: SessionId) => { + list.update((draft) => { + for (const key of [viewed, other]) draft.byId[key] = row(key, key === id) + }) + } + const openState = (id: SessionId, state: string) => { bindings.get(id)!.session.set({ openState: state }) } + const snapshot = (id: SessionId, value: { readonly openState: string; readonly running?: boolean }) => { + bindings.get(id)!.session.set(value) + } + return { ctx, reading, record, focus, visibility, status, view, openState, service, snapshot } +} + +it('hides the natural reminder of the viewed Session until the window loses focus or visibility', () => { + const b = bench() + expect(b.status(viewed)).toMatchObject({ completionUnread: false, completionFailed: false }) + expect(b.status(other)).toMatchObject({ completionUnread: true, completionFailed: true }) + + b.focus.mockReturnValue(false) + window.dispatchEvent(new Event('blur')) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.focus.mockReturnValue(true) + window.dispatchEvent(new Event('focus')) + expect(b.status(viewed)?.completionUnread).toBe(false) + + b.visibility.mockReturnValue('hidden') + document.dispatchEvent(new Event('visibilitychange')) + expect(b.status(viewed)?.completionUnread).toBe(true) +}) + +it('keeps a manual reminder of the viewed Session visible', () => { + const b = bench() + b.reading.set({ ready: true, items: { [viewed]: b.record(viewed, { readTurn: 1, manualUnread: true }) } }) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) +}) + +it('shows an unacknowledged completion again after the main view switches to another Session', () => { + const b = bench() + b.view(other) + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + expect(b.status(other)).toMatchObject({ completionUnread: false, completionFailed: false }) +}) + +it('shows the natural reminder of the viewed Session until that Session is open', () => { + const b = bench() + b.openState(viewed, 'loading') + expect(b.status(viewed)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.openState(viewed, 'error') + expect(b.status(viewed)?.completionUnread).toBe(true) + b.openState(viewed, 'open') + expect(b.status(viewed)).toMatchObject({ completionUnread: false, completionFailed: false }) +}) + +it('does not rebuild the table when the viewed Session snapshot changes without an open-state change', () => { + const b = bench() + const before = b.service.getSnapshot() + const changed = vi.fn() + b.service.subscribe(changed) + const rebuild = vi.spyOn(b.service.reading.state, 'getSnapshot') + b.snapshot(viewed, { openState: 'open', running: true }) + expect(rebuild).not.toHaveBeenCalled() + expect(b.service.getSnapshot()).toBe(before) + expect(changed).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-session-status/tests/status.client.spec.ts b/packages/client/ui-session-status/tests/status.client.spec.ts index 9257f7afe7..01abc42679 100644 --- a/packages/client/ui-session-status/tests/status.client.spec.ts +++ b/packages/client/ui-session-status/tests/status.client.spec.ts @@ -4,9 +4,10 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { afterEach, describe, expect, it, vi } from 'vitest' +import type { SessionReadSnapshot } from '../src/client/model.ts' import { apply } from '../src/client/index.ts' import { UiSessionStatus } from '../src/client/status.ts' -import { apply as nodeApply } from '../src/index.ts' +import type { SessionReadState } from '../src/types.ts' const sessionId = (value: string): SessionId => value as SessionId const pendingQuestion = (id: SessionId) => ({ key: 'question:1', kind: 'question', sessionId: id }) as SessionPendingInteraction @@ -21,16 +22,33 @@ function bench() { const ctx = new Context() roots.push(ctx) let statusListener: ((id: SessionId, running: boolean) => void) | undefined + const remoteMark = vi.fn(async () => ({ ok: true as const, value: undefined })) ctx.provide('remote', { $on: (_event: string, listener: (id: SessionId, running: boolean) => void) => { statusListener = listener return () => { if (statusListener === listener) statusListener = undefined } }, + sessionStatus: { mark: remoteMark }, } as never) const list = createSnapshotStore({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }) - const sessions: Pick = { list } + const sessions: Pick = { list, binding: () => undefined } const pending = createSnapshotStore>(new Map()) - const status = () => new UiSessionStatus(ctx, sessions, pending) + // The status table owns its reading model; this facade drives the most recently created one with a ready baseline. + let latest: UiSessionStatus | undefined + const model = () => { + if (latest === undefined) throw new Error('no status table was created') + return latest.reading.state + } + const reading = { + set: (value: SessionReadSnapshot) => { model().set(value) }, + getSnapshot: () => model().getSnapshot(), + } + const create = (scope: Context = ctx, catalog: Pick = sessions) => { + latest = new UiSessionStatus(scope, catalog, pending) + latest.reading.replace([]) + return latest + } + const status = () => create() const row = (id: SessionId) => { list.update((draft) => { if (!draft.ids.includes(id)) draft.ids.push(id) @@ -46,10 +64,16 @@ function bench() { if (statusListener === undefined) throw new Error('api-session/status is not subscribed') statusListener(id, running) } - return { ctx, list, pending, status, row, setMainView, emitStatus, subscribed: () => statusListener !== undefined } + const record = (id: SessionId, value: Partial): SessionReadState => ({ + sessionId: id, completedTurn: 0, failed: false, readTurn: 0, manualUnread: false, ...value, + }) + return { + ctx, list, pending, reading, remoteMark, create, status, row, setMainView, emitStatus, record, + subscribed: () => statusListener !== undefined, + } } -describe('Session running status and completion reminders', () => { +describe('Session running status', () => { it('keeps synthetic-row status unknown until an event or Host baseline establishes it', () => { const b = bench() const id = sessionId('catalog-only') @@ -58,19 +82,17 @@ describe('Session running status and completion reminders', () => { }) const service = b.status() expect(service.getSnapshot().get(id)?.running).toBeUndefined() - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) b.emitStatus(id, true) b.list.update((draft) => { draft.byId[id]!.displayTitle = 'Renamed child' }) expect(service.getSnapshot().get(id)?.running).toBe(true) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) b.list.update((draft) => { draft.ids.push(id) }) expect(service.getSnapshot().get(id)?.running).toBe(false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) }) - it('records non-main completions and lets main-view activity acknowledge them', () => { + it('publishes running changes from list rows and status events, and skips unchanged status', () => { const b = bench() const id = sessionId('s1') b.row(id) @@ -79,41 +101,20 @@ describe('Session running status and completion reminders', () => { const off = service.subscribe(changed) expect(service.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: false, + running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, }) b.list.update((draft) => { draft.byId[id]!.running = true }) expect(service.getSnapshot().get(id)?.running).toBe(true) - b.list.update((draft) => { draft.byId[id]!.running = false }) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - b.setMainView(id, 1) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.setMainView(id, 0) - - b.emitStatus(id, true) b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - - b.setMainView(id, 1) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.emitStatus(id, true) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - - b.setMainView(id, 0) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) - b.emitStatus(id, true) - b.emitStatus(id, false) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) - b.emitStatus(id, true) - expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + expect(service.getSnapshot().get(id)?.running).toBe(false) expect(changed).toHaveBeenCalled() + const calls = changed.mock.calls.length + b.emitStatus(id, false) + expect(changed).toHaveBeenCalledTimes(calls) off() }) - it('records an idle event before the initial catalog baseline and retires absent status later', () => { + it('records an event before the initial catalog baseline and retires absent status later', () => { const b = bench() const id = sessionId('early') b.list.update((draft) => { draft.phase = 'pending' }) @@ -121,9 +122,7 @@ describe('Session running status and completion reminders', () => { b.emitStatus(id, false) expect(service.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: true, + running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, }) b.list.update((draft) => { draft.phase = 'ready' }) expect(service.getSnapshot().has(id)).toBe(false) @@ -148,6 +147,69 @@ describe('Session running status and completion reminders', () => { }) }) +describe('Session reading reminders', () => { + it('derives unread and failed reminders from Host reading records', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + b.emitStatus(id, true) + b.emitStatus(id, false) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, failed: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: true }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2 }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: false }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2, readTurn: 2, failed: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: false, completionFailed: false }) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 2, readTurn: 2, manualUnread: true }) } }) + expect(service.getSnapshot().get(id)).toMatchObject({ completionUnread: true, completionFailed: false }) + }) + + it('preserves a Host reminder through main view selection and running changes', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1 }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.setMainView(id, 1) + b.emitStatus(id, true) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, readTurn: 1, manualUnread: true }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1, readTurn: 1 }) } }) + expect(service.getSnapshot().get(id)?.completionUnread).toBe(false) + }) + + it('retains a shared reminder for a Session that left the catalog', () => { + const b = bench() + const id = sessionId('evicted') + const service = b.status() + b.emitStatus(id, true) + b.reading.set({ ready: true, items: { [id]: b.record(id, { completedTurn: 1 }) } }) + b.list.set({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }) + expect(service.getSnapshot().get(id)).toMatchObject({ running: undefined, completionUnread: true }) + }) + + it('reports reading readiness and forwards explicit marks', async () => { + const b = bench() + const service = b.status() + const ready = vi.fn() + const off = service.readingReady.subscribe(ready) + expect(service.readingReady.getSnapshot()).toBe(true) + b.reading.set({ ...b.reading.getSnapshot(), ready: false }) + expect(service.readingReady.getSnapshot()).toBe(false) + expect(ready).toHaveBeenCalled() + off() + b.reading.set({ ...b.reading.getSnapshot(), ready: true }) + const mark = vi.spyOn(service.reading, 'mark') + await service.mark(sessionId('s1'), true) + expect(mark).toHaveBeenCalledExactlyOnceWith(sessionId('s1'), true) + expect(b.remoteMark).toHaveBeenCalledExactlyOnceWith(sessionId('s1'), { type: 'unread' }) + }) +}) + describe('Session status pending interactions', () => { it('carries the exact effective request object and adds Sessions known only by their request', () => { const b = bench() @@ -161,10 +223,12 @@ describe('Session status pending interactions', () => { const question = { key: 'question:1', kind: 'question', sessionId: unlisted } as SessionPendingInteraction b.pending.set(new Map([[listed, approval], [unlisted, question]])) - expect(service.getSnapshot().get(listed)).toEqual({ running: false, pendingInteraction: approval, completionUnread: false }) + expect(service.getSnapshot().get(listed)).toEqual({ + running: false, pendingInteraction: approval, completionUnread: false, completionFailed: false, + }) expect(service.getSnapshot().get(listed)?.pendingInteraction).toBe(approval) expect(service.getSnapshot().get(unlisted)).toEqual({ - running: undefined, pendingInteraction: question, completionUnread: false, + running: undefined, pendingInteraction: question, completionUnread: false, completionFailed: false, }) expect(changed).toHaveBeenCalledOnce() @@ -196,7 +260,7 @@ describe('Session status pending interactions', () => { let service: UiSessionStatus | undefined const fiber = b.ctx.plugin({ apply(scope: Context) { - service = new UiSessionStatus(scope, { list: b.list }, b.pending) + service = b.create(scope) }, }) await fiber.await() @@ -209,6 +273,7 @@ describe('Session status pending interactions', () => { expect(b.subscribed()).toBe(false) b.row(sessionId('later')) b.pending.set(new Map([[sessionId('later'), pendingQuestion(sessionId('later'))]])) + b.reading.set({ ready: true, items: { [sessionId('later')]: b.record(sessionId('later'), { completedTurn: 1 }) } }) expect(service.getSnapshot()).toBe(before) }) }) @@ -217,9 +282,10 @@ describe('session-status apply', () => { it('provides the status service under ctx.uiSession and publishes it as the root useSessionStatus source', () => { const b = bench() const provideRoot = vi.fn() - b.ctx.provide('sessions', { list: b.list } as never) b.ctx.provide('slots', { provideRoot } as never) b.ctx.provide('uiSession', { pendingInteractions: b.pending } as never) + b.ctx.provide('sessions', { list: b.list, binding: () => undefined } as never) + b.ctx.provide('remoteAccess', { whenAccess: () => () => {} } as never) apply(b.ctx) @@ -227,13 +293,8 @@ describe('session-status apply', () => { const root = provideRoot.mock.calls[0]![0] as { hooks: { sessionStatus: UiSessionStatus } } expect(Object.keys(root)).toEqual(['hooks']) expect(Object.keys(root.hooks)).toEqual(['sessionStatus']) - expect(root.hooks.sessionStatus).toBeInstanceOf(UiSessionStatus) const provided: unknown = b.ctx.get('uiSession.sessionStatus') if (!(provided instanceof UiSessionStatus)) throw new Error('uiSession.sessionStatus is not provided') - expect(provided.getSnapshot()).toBe(root.hooks.sessionStatus.getSnapshot()) - }) - - it('keeps the Host loader half inert', () => { - expect(() => { nodeApply() }).not.toThrow() + expect(root.hooks.sessionStatus.getSnapshot()).toBe(provided.getSnapshot()) }) }) diff --git a/packages/client/ui-session-status/tests/status.host.spec.ts b/packages/client/ui-session-status/tests/status.host.spec.ts new file mode 100644 index 0000000000..bcb23c74d4 --- /dev/null +++ b/packages/client/ui-session-status/tests/status.host.spec.ts @@ -0,0 +1,345 @@ +import { Context } from '@deepseek-ai/cordis' +import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import Projections from '@deepseek-ai/dsh-session-projection' +import RemoteAccess from '@deepseek-ai/dsh-api-remote-access' +import Typert from '@deepseek-ai/dsh-typert-registry' +import { Peer } from '@deepseek-ai/dsh-client-connection' +import { afterEach, expect, it, vi } from 'vitest' +import { remoteMethods, type RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' +import SessionStatusService from '../src/index.ts' +import { SessionReadFollower } from '../src/feed.ts' +import type { SessionReadState, SessionReadFrame } from '../src/types.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + 'reading-test': { readonly kind: 'reading-test' } + } +} + +const roots: Context[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) +}) + +async function harness(before?: (ctx: Context) => void) { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(Projections) + await ctx.plugin(Typert) + await ctx.plugin(RemoteAccess) + const stat = vi.fn(async (_id: SessionId): Promise => undefined) + ctx.provide('sessionPersistence', { stat } as never) + const allows = vi.spyOn(ctx.remoteAccess, 'allows').mockReturnValue(true) + before?.(ctx) + const fiber = ctx.plugin(SessionStatusService) + await fiber + return { ctx, service: ctx.sessionStatus, allows, stat, fiber } +} + +function end(session: Session, turn: number): readonly SessionEvent[] { + return [session.append('turn/start', { turn }), + session.append('turn/end', { turn, reason: { kind: 'completed' } })] +} + +async function nextFrame(iterator: AsyncIterator): Promise { + const result = await iterator.next() + if (result.done) throw new Error('reading stream ended') + return result.value +} + +async function baseline(service: SessionStatusService): Promise { + const abort = new AbortController() + const iterator = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + const frame = await nextFrame(iterator) + if (frame?.type !== 'baseline') throw new Error('missing reading baseline') + return frame.items + } finally { + abort.abort() + await iterator.return?.() + } +} + +it('raises no reminder for history recorded before the service started', async () => { + const { ctx, service } = await harness((context) => { + end(context.sessions.create(SessionId('history')), 7) + }) + expect(await baseline(service)).toEqual([]) + end(ctx.sessions.get(SessionId('history'))!, 8) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 8, readTurn: 0 })]) +}) + +it('raises no reminder for a Session restored from stored history', async () => { + const { ctx, service } = await harness() + ctx.sessions.create(SessionId('restored'), { seed: end(Session.create(SessionId('seed')), 7) }) + expect(await baseline(service)).toEqual([]) +}) + +it('records whether the completing turn failed', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('failed')) + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'boom', code: 'UNKNOWN' } } }) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, failed: true })]) + session.append('turn/start', { turn: 2 }) + session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 2, failed: false })]) +}) + +it('broadcasts explicit marks to both frontends and keeps later completions unread', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('shared')) + end(session, 1) + const abort = new AbortController() + const left = service.follow(abort.signal)[Symbol.asyncIterator]() + const right = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + const opening = await nextFrame(left) + await right.next() + if (opening?.type !== 'baseline') throw new Error('missing baseline') + await service.mark(session.id, { type: 'read', throughTurn: opening.items[0]!.completedTurn }) + const read = { sessionId: session.id, completedTurn: 1, failed: false, readTurn: 1, manualUnread: false } + expect(await left.next()).toMatchObject({ value: { type: 'changed', state: read } }) + expect(await right.next()).toMatchObject({ value: { type: 'changed', state: read } }) + await service.mark(session.id, { type: 'unread' }) + end(session, 2) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 1 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2, manualUnread: true }]) + await service.mark(session.id, { type: 'read', throughTurn: 1 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2 }]) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 9 }) + await service.mark(session.id, { type: 'acknowledge', throughTurn: 0 }) + expect(await baseline(service)).toEqual([{ ...read, completedTurn: 2, readTurn: 2 }]) + } finally { + abort.abort() + await Promise.all([left.return?.(), right.return?.()]) + } +}) + +it('filters the baseline and increments by Session access and rejects missing Sessions', async () => { + const { ctx, service, allows } = await harness() + const visible = ctx.sessions.create(SessionId('visible')) + const hidden = ctx.sessions.create(SessionId('hidden')) + end(visible, 1) + end(hidden, 1) + await baseline(service) + allows.mockImplementation(resource => resource.kind !== 'session' || resource.id !== hidden.id) + expect(await baseline(service)).toEqual([expect.objectContaining({ sessionId: visible.id })]) + const marker = remoteMethods(service).find(method => method.method === 'mark') + expect(marker?.resources).toBeUndefined() + const abort = new AbortController() + const iterator = service.follow(abort.signal)[Symbol.asyncIterator]() + try { + await nextFrame(iterator) + const next = nextFrame(iterator) + end(hidden, 2) + end(visible, 2) + expect(await next).toMatchObject({ type: 'changed', state: { sessionId: visible.id, completedTurn: 2 } }) + } finally { + abort.abort() + await iterator.return?.() + } + await expect(service.mark(SessionId('missing'), { type: 'unread' })) + .rejects.toMatchObject({ code: 'session-status/not-found' }) +}) + +it('marks cold history without opening it', async () => { + const { ctx, service, stat } = await harness() + const id = SessionId('cold') + stat.mockResolvedValue({}) + await service.mark(id, { type: 'unread' }) + expect(ctx.sessions.get(id)).toBeUndefined() + expect(await baseline(service)).toEqual([ + { sessionId: id, completedTurn: 0, failed: false, readTurn: 0, manualUnread: true }, + ]) +}) + +it('closes an idle follower when its Host owner is disposed', async () => { + const { ctx, service } = await harness() + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + const pending = iterator.next() + await ctx.fiber.dispose() + expect(await pending).toMatchObject({ done: true }) +}) + +it('cancels its access watcher even when a consumer pauses after the baseline', async () => { + const { ctx, service, fiber } = await harness() + const follow = ctx.remoteAccess.follow.bind(ctx.remoteAccess) + let stopped = false + vi.spyOn(ctx.remoteAccess, 'follow').mockImplementation(async function* (signal) { + try { yield* follow(signal) } finally { stopped = true } + }) + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + await fiber.dispose() + await vi.waitFor(() => { expect(stopped).toBe(true) }) + await iterator.return?.() +}) + +it('ignores late updates after a follower closes and wakes a cancelled reader', async () => { + const follower = new SessionReadFollower() + const abort = new AbortController() + const iterator = follower.read(abort.signal)[Symbol.asyncIterator]() + const pending = iterator.next() + abort.abort() + follower.push({ type: 'changed', state: { + sessionId: SessionId('closed'), completedTurn: 1, failed: false, readTurn: 0, manualUnread: false, + } }) + expect(await pending).toMatchObject({ done: true }) +}) + +it('preserves the first follower failure even when cancellation follows immediately', async () => { + const follower = new SessionReadFollower() + const abort = new AbortController() + const iterator = follower.read(abort.signal)[Symbol.asyncIterator]() + const pending = iterator.next() + const error = new Error('failed') + follower.close(error) + abort.abort() + follower.close() + await expect(pending).rejects.toBe(error) +}) + +it('keeps the first completion unread after a live zero-turn Session is marked unread then read', async () => { + const { ctx, service } = await harness() + const session = ctx.sessions.create(SessionId('first-turn')) + await service.mark(session.id, { type: 'unread' }) + await service.mark(session.id, { type: 'read', throughTurn: 0 }) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it('restarts filtered followers on access changes so new grants receive a baseline', async () => { + const { ctx, allows } = await harness() + allows.mockRestore() + const session = ctx.sessions.create(SessionId('new-grant')) + end(session, 1) + const principal = { kind: 'reading-test' } as const + let granted = false + ctx.remoteAccess.registerPolicy('reading-test', { bindings: () => granted ? [{ + role: { name: 'reader', resource: 'session', actions: ['sessionStatus/follow'] }, + resource: { kind: 'session', id: session.id }, + }] : [] }) + const abort = new AbortController() + const invocation: RemoteInvocation = { + request: { namespace: 'sessionStatus', method: 'follow', args: {} }, service: 'sessionStatus', + peer: new Peer(ctx, { principal }), signal: abort.signal, + uplink: (): AsyncIterable => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }), + } + const scoped = ctx.extend({ invocation }).sessionStatus + const iterator = scoped.follow(abort.signal)[Symbol.asyncIterator]() + try { + expect(await nextFrame(iterator)).toEqual({ type: 'baseline', items: [] }) + const ended = iterator.next() + granted = true + ctx.remoteAccess.invalidate(principal) + expect(await ended).toMatchObject({ done: true }) + expect(await baseline(scoped)).toEqual([expect.objectContaining({ sessionId: session.id, completedTurn: 1 })]) + } finally { + abort.abort() + await iterator.return?.() + } +}) + +it('reports a failed access stream without leaving its reading follower open', async () => { + const { ctx, service } = await harness() + vi.spyOn(ctx.remoteAccess, 'follow').mockImplementation(async function* () { + yield { type: 'baseline', owner: true } + throw new Error('access stream failed') + }) + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + await expect(iterator.next()).rejects.toMatchObject({ code: 'session-status/unavailable' }) +}) + +it('discards every record when the service reloads', async () => { + const { ctx, service, fiber } = await harness() + const session = ctx.sessions.create(SessionId('restart')) + end(session, 1) + await service.mark(session.id, { type: 'unread' }) + await fiber.dispose() + await ctx.plugin(SessionStatusService) + expect(await baseline(ctx.sessionStatus)).toEqual([]) +}) + +it('records completions without waiting for or triggering a Session flush', async () => { + const { ctx, service } = await harness() + const flush = vi.fn(() => { throw new Error('unavailable disk') }) + ctx.on('session/flush', flush) + const session = ctx.sessions.create(SessionId('memory-only')) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) + expect(flush).not.toHaveBeenCalled() +}) + +it('rechecks a Session opened while its metadata lookup is pending', async () => { + const { ctx, service, stat } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('opening') + const mark = service.mark(id, { type: 'read', throughTurn: 0 }) + const session = ctx.sessions.create(id) + pending.resolve({}) + await expect(mark).resolves.toBeUndefined() + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it('keeps a completion unread when an earlier read position arrives after metadata lookup', async () => { + const { ctx, service, stat } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('opening-completed') + const mark = service.mark(id, { type: 'read', throughTurn: 0 }) + end(ctx.sessions.create(id), 1) + pending.resolve({}) + await expect(mark).resolves.toBeUndefined() + expect(await baseline(service)).toEqual([expect.objectContaining({ completedTurn: 1, readTurn: 0 })]) +}) + +it.each(['service', 'Host'] as const)('discards pending marks without waiting for metadata during %s teardown', async (owner) => { + const { ctx, service, stat, fiber } = await harness() + const pending = Promise.withResolvers() + stat.mockReturnValueOnce(pending.promise) + const id = SessionId('closing') + const iterator = service.follow(new AbortController().signal)[Symbol.asyncIterator]() + await nextFrame(iterator) + const closed = iterator.next() + const mark = service.mark(id, { type: 'unread' }) + const rejected = expect(mark).rejects.toMatchObject({ code: 'session-status/unavailable' }) + let disposed = false + const disposal = (owner === 'Host' ? ctx.fiber.dispose() : fiber.dispose()).then(() => { disposed = true }) + try { + expect(await closed).toMatchObject({ done: true }) + await vi.waitFor(() => { expect(disposed).toBe(true) }) + await expect(service.mark(id, { type: 'read', throughTurn: 0 })) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + await expect(service.follow(new AbortController().signal)[Symbol.asyncIterator]().next()) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + } finally { + pending.resolve({}) + await Promise.allSettled([rejected, disposal]) + await iterator.return?.() + } + await rejected + expect(disposed).toBe(true) +}) + +it('keeps other readers available after a metadata failure', async () => { + const { ctx, service, stat } = await harness() + stat.mockRejectedValueOnce(new Error('metadata unavailable')) + await expect(service.mark(SessionId('failed'), { type: 'unread' })) + .rejects.toMatchObject({ code: 'session-status/unavailable' }) + const session = ctx.sessions.create(SessionId('healthy')) + end(session, 1) + expect(await baseline(service)).toEqual([expect.objectContaining({ sessionId: session.id, completedTurn: 1 })]) +}) + +it('keeps arbitrary Session ids distinct without filesystem restrictions', async () => { + const { ctx, service } = await harness() + const ids = ['thread.42', 'user/1', '..', 'a'.repeat(200), '\ud800', '\ufffd'].map(SessionId) + for (const id of ids) end(ctx.sessions.create(id), 1) + expect((await baseline(service)).map(record => record.sessionId).sort()).toEqual([...ids].sort()) +}) diff --git a/packages/client/ui-session-status/tsconfig.client.json b/packages/client/ui-session-status/tsconfig.client.json new file mode 100644 index 0000000000..0e04c23729 --- /dev/null +++ b/packages/client/ui-session-status/tsconfig.client.json @@ -0,0 +1,47 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../api/remote-access/tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-session-status/tsconfig.host.json b/packages/client/ui-session-status/tsconfig.host.json new file mode 100644 index 0000000000..4b8c8637f5 --- /dev/null +++ b/packages/client/ui-session-status/tsconfig.host.json @@ -0,0 +1,34 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/spec.ts", + "src/types.ts", + "src/feed.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../api/remote-access/tsconfig.host.json" + }, + { + "path": "../../session/session-persistence" + }, + { + "path": "../../util/deque" + } + ] +} diff --git a/packages/client/ui-session-status/tsconfig.json b/packages/client/ui-session-status/tsconfig.json index 4c10ff072a..2a0b0e33f7 100644 --- a/packages/client/ui-session-status/tsconfig.json +++ b/packages/client/ui-session-status/tsconfig.json @@ -1,36 +1,7 @@ { - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, - { - "path": "../../api/session-controller/tsconfig.client.json" - }, - { - "path": "../../core/session" - }, - { - "path": "../store" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-session" - }, - { - "path": "../ui-slots" - } + { "path": "./tsconfig.host.json" }, + { "path": "./tsconfig.client.json" } ] } diff --git a/packages/client/ui-session-status/tsdown.config.ts b/packages/client/ui-session-status/tsdown.config.ts index 7aa03cebc1..620261533c 100644 --- a/packages/client/ui-session-status/tsdown.config.ts +++ b/packages/client/ui-session-status/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle(import.meta.dirname, ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-sidebar/README.i18n.yaml b/packages/client/ui-sidebar/README.i18n.yaml index 6ce4278621..5847e07229 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -51,8 +51,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-sidebar/known-limitations-and-deferred-work: - en: 9738f4cd887876d0 - zh: 95a646deba4a6489 + en: f31345fa08c77f91 + zh: e2639d597353207f /deepseek-ai-dsh-client-ui-sidebar/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index ea682c7e41..43cfe45193 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -127,7 +127,6 @@ These limits define what the shell owns versus what its occupants own; they are - **Session state-dot rendering is owned by ui-workspace** — no done/error notification sources are available to this shell. - **Workspace browser behavior is composition-owned** — grouping, ordering, search, and row state belong to ui-workspace, not this shell. -- **"New task completed" unread marking is local viewing state** — completion-time > last-seen never reaches the host. - **Copying the local-build version is mouse-only** — keyboard activation of the brand starts a session. - **Only wheel and trackpad input crosses the navigation boundary in one gesture** — touch drags keep native nested scrolling and stop where the viewport reaches its end; browsers without scroll-state container queries scroll the section first. Wheel steps split in JavaScript run on the main thread without smooth-scrolling animation or overscroll bounce. diff --git a/packages/client/ui-sidebar/README.zh.md b/packages/client/ui-sidebar/README.zh.md index 58ccbebef2..2f0c507119 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -127,7 +127,6 @@ root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区 - **Session 状态点渲染由 ui-workspace 持有**:本外壳没有可用的 done/error 通知数据源。 - **Workspace 浏览行为由组合持有**:分组、排序、搜索与行状态都属于 ui-workspace,不属于此外壳。 -- **「New task completed」未读标记是本地查看状态**:完成时间 > 上次查看时间这一事实永远不会到达宿主。 - **复制本地构建版本号仅支持鼠标**:键盘激活品牌会新建会话。 - **只有滚轮和触控板输入能在一次手势中越过导航边界**:触摸拖动保持浏览器原生的嵌套滚动,在视口滚到底时停止;不支持滚动状态容器查询的浏览器会先滚动区块。由 JavaScript 分配的滚轮步进在主线程执行,没有平滑滚动动画,也没有越界回弹。 diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 660db73fd5..7ff86bb02c 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -449,7 +449,7 @@ describe('SubagentHeaderLineage', () => { const input = props(catalog({ entries: [{ id: CHILD, mode: 'continuable', label: 'worker', activity: 'inactive' }] })) const initial = input.useSessions(state => state) const statuses: SessionStatusSnapshot = new Map([[CHILD, { - running: true, completionUnread: false, pendingInteraction: undefined, + running: true, completionUnread: false, completionFailed: false, pendingInteraction: undefined, }]]) render( select({ ...initial, ids: [] })} diff --git a/packages/client/ui-subagent/tsconfig.json b/packages/client/ui-subagent/tsconfig.json index cbf78e252c..1478265add 100644 --- a/packages/client/ui-subagent/tsconfig.json +++ b/packages/client/ui-subagent/tsconfig.json @@ -12,7 +12,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../../../vendor/cordis" diff --git a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx index 84f1d6045d..84255d3e45 100644 --- a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx +++ b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx @@ -885,14 +885,14 @@ describe('WorkflowRunPanel', () => { byId: { ...listState().byId, [CHILD_ID]: { ...listState().byId[CHILD_ID]!, running: false } }, }) const openSession = vi.fn() - let statuses = new Map([[CHILD_ID, { running: true, pendingInteraction: undefined, completionUnread: false }]]) + let statuses = new Map([[CHILD_ID, { running: true, pendingInteraction: undefined, completionUnread: false, completionFailed: false }]]) const props: WorkflowRunPanelProps = { ...panelProps(data, sessions, openSession), useSessionStatus: select => select(statuses), } const view = render() fireEvent.click(screen.getByRole('button', { name: '打开 worker' })) expect(openSession).toHaveBeenCalledWith({ parentSessionId: PARENT_ID, childSessionId: CHILD_ID, mode: 'one-shot' }) - statuses = new Map([[CHILD_ID, { running: false, pendingInteraction: undefined, completionUnread: false }]]) + statuses = new Map([[CHILD_ID, { running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false }]]) view.rerender() expect(screen.queryByRole('button', { name: '打开 worker' })).toBeNull() }) diff --git a/packages/client/ui-workflow-run/tsconfig.json b/packages/client/ui-workflow-run/tsconfig.json index f48fbe28f0..786a9f9b06 100644 --- a/packages/client/ui-workflow-run/tsconfig.json +++ b/packages/client/ui-workflow-run/tsconfig.json @@ -18,7 +18,7 @@ "path": "../../api/session-controller/tsconfig.client.json" }, { - "path": "../ui-session-status" + "path": "../ui-session-status/tsconfig.client.json" }, { "path": "../store" diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index e8365eb4c0..7e4bc36aea 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-workspace/use-this-package: - en: 9226c42c2559fbf0 - zh: 5527f59aa379c9fd + en: c24ee36a92dcb08e + zh: 1383bbf4d2579e97 /deepseek-ai-dsh-client-ui-workspace/use-this-package/reordering-and-view-options: en: 55054408b8593c70 zh: 9fdf9861a48abba3 @@ -27,11 +27,11 @@ en: 148f2ab562fecc09 zh: 9ba7c07999705b31 /deepseek-ai-dsh-client-ui-workspace/use-this-package/managing-sessions: - en: 29b6b357fc6be99a - zh: 182996efed35029c + en: 0515aae59aa89cce + zh: 83b150ab0e233d8a /deepseek-ai-dsh-client-ui-workspace/use-this-package/pending-interactions: - en: 9fb88260380bf093 - zh: 3bace2b96ecd4a82 + en: 27089341ac2cbcc4 + zh: 63d818a53a7c20e9 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: en: 249d9552d8bef805 zh: 405b1c636cba8e0b @@ -42,8 +42,8 @@ en: 868904dbfb5713f8 zh: 35d3c285ed770885 /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions: - en: 511408e373ff8c70 - zh: 7ae3b396171821a4 + en: d309a8bc5085616b + zh: 66152a89d58cb7cb /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions/packaged-client-plugin: en: 36934671b80b11ae zh: 8e0aea6162e35e77 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index fb4c55b2d2..00eea4ac7a 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -31,6 +31,8 @@ Use the sidebar to browse Workspaces and their Sessions, reorder them, and start History rows without a stored title use the localized unnamed label (未命名 / Untitled), rather than a directory name. The current blank row remains New Session; other blank rows remain hidden. Rename drafts use the stored title, or start empty when unnamed; unnamed rows do not offer title copying. +**Mark as read / Mark as unread** in each Session menu saves shared reading state on the Host; archived Sessions read as read and offer neither. Unread reminders survive browser reloads while the Host runs, and reset on Host restart or plugin reload, appear alongside live activity, and do not imply successful completion. Window focus confirms natural unread content. Manual unread stays until the main view switches to the Session or an explicit read mark arrives, and automatic confirmation always waits for the content to arrive. See [Session status](../ui-session-status/README.md) for synchronization and lifetime limits. + Without hover, Workspace actions appear only while expanded, Session More buttons stay visible, and search-result actions remain visible. Toolbar tooltips render outside the sidebar so its drawer animation does not crop them. Search and rename inputs use 16px text with a coarse pointer; a fine pointer keeps their compact sizes. ### Reordering and view options @@ -67,11 +69,13 @@ Archive commits without a confirmation dialog for a quiet Session and retains th Session update times use the tertiary label color, including on archived rows. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start. -The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. The navigation drawer allows these commands; other dialogs follow the command’s modal restrictions. Rename requires a nonblank main Conversation with no other modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. +The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, Archive session, and Toggle read/unread. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. The navigation drawer allows these commands; other dialogs follow the command’s modal restrictions. Rename requires a nonblank main Conversation with no other modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. + +Toggle read/unread uses Command+Shift+U on macOS and Control+Shift+U on Windows in both Desktop and Web. Linux leaves it unbound for customization. It targets the nonblank main Conversation, requires synchronized reading state and permission, and does not run behind another main panel or a modal. Menu actions target their own row. Successful and stale reading changes remain silent; only a failed write raises a toast. ### Pending interactions -Session rows render the runtime's live `pendingInteraction` classification: approvals report **Waiting for approval**, plan reviews report **Plan awaiting review**, and ordinary questions report **Waiting for answer**. While an interaction is pending, the row uses the shared warning dot and replaces its trailing update time with **Approval**, **Plan review**, or **Answer**; the full status and relative time remain in hover details. Pending interaction takes precedence over the shared ongoing loader; a finished-but-unviewed Session uses done, while idle remains dot-free in the row and uses the shared idle dot in its hover details. The leading seat renders only while the row's primary status is idle — no pending interaction, no own or descendant activity, and no unviewed completion — so an occupant there never appears beside the row's own status dot. An archived row keeps that cell blank: it shows neither a status dot nor the seat, and its live status appears on the hover card only. +Session rows render the runtime's live `pendingInteraction` classification: approvals report **Waiting for approval**, plan reviews report **Plan awaiting review**, and ordinary questions report **Waiting for answer**. While an interaction is pending, the row uses the shared warning dot and replaces its trailing update time with **Approval**, **Plan review**, or **Answer**; the full status and relative time remain in hover details. Pending interaction takes precedence over the shared ongoing loader, which takes precedence over unread reminders. A failed turn uses a red reminder; other ended turns, including cancellation, use green. Opening the Session or marking it read clears either reminder. Marking a Session unread preserves its title weight and any pending-interaction dot. Idle remains dot-free in the row and uses the shared idle dot in its hover details. The leading seat renders only while the row's primary status is idle — no pending interaction, no own or descendant activity, and no unviewed completion — so an occupant there never appears beside the row's own status dot. An archived row keeps that cell blank: it shows neither a status dot nor the seat, and its live status appears on the hover card only. ### Active Schedule markers @@ -121,9 +125,9 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session row actions -Built-in Session menu actions register structured contributions through `ctx.contextMenus`: pin (100), rename (200), fork (300), copy ID (450), and archive (600). Native directory reveal belongs to ui-open-in-app (500). Rename, fork, and archive associate existing command IDs for live shortcut display; clicks retain their captured Session and invoke the existing business callback. Pin and archive also retain their hover-button Slot entries. +Built-in Session menu actions register structured contributions through `ctx.contextMenus`: pin (100), rename (200), read/unread (250), fork (300), copy ID (450), and archive (600). Native directory reveal belongs to ui-open-in-app (500). Rename, read/unread, fork, and archive associate existing command IDs for live shortcut display; clicks retain their captured Session and invoke the existing business callback. Pin and archive also retain their hover-button Slot entries. -The legacy `sidebar.workspaces.session.menu.item` Slot remains for external React entries. It receives `sessionId`, `displayTitle`, and `useMenuOpenState` for dismissal. Legacy entries retain their own order and render together before Archive; their priority no longer replaces built-in data actions. New contributions use the [menu service](../ui-context-menu/README.md). Built-in visibility tracks permissions and pin/archive membership while open; dialogs and notices remain frame-wide overlays. +The legacy `sidebar.workspaces.session.menu.item` Slot remains for external React entries. It receives `sessionId`, `displayTitle`, and `useMenuOpenState` for dismissal. Legacy entries retain their own order and render together before Archive; their priority no longer replaces built-in data actions. New contributions use the [menu service](../ui-context-menu/README.md). Built-in visibility tracks permissions and pin/archive membership while open; the reading action also tracks reminders and synchronization readiness. Dialogs and notices remain frame-wide overlays. The existing notice overlay dispatches `workspace.toast` by notice kind. Keyed registrations inject localized display mappings and their own actions; only archive notices subscribe to the viewing filter. They render the package-local `workspace.toast.content` Factory, which reuses the Toast primitive once for all presentations. The existing notice state, display sequence, latest-notice replacement, and dismissal remain shared; locale or filter changes do not restart the same notice's timer. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 2037167c1c..0075ba3c0d 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -31,6 +31,8 @@ kind: "package-reference" 未保存标题的历史会话显示本地化名称「未命名 / Untitled」,不使用目录名兜底。当前空会话仍显示「新会话」,其他空会话仍隐藏。重命名草稿使用已保存标题,无标题时留空;无标题行不提供标题复制。 +会话菜单中的**标为已读/标为未读**将阅读状态保存到宿主,并同步给各前端;已归档的会话按已读处理,不提供这两项。宿主运行期间刷新浏览器会保留未读提醒,宿主重启或插件重载则会重置,可与运行状态同时出现,不表示任务成功。窗口聚焦只确认自然未读。手动未读会保留到主视图切换到该会话或主动标为已读,自动确认始终等待正文到达。同步和生命周期的限制见[会话状态](../ui-session-status/README.zh.md)。 + 无 hover 时,工作区操作仅在展开时显示,会话的更多按钮始终显示,搜索结果操作保持可见。工具栏的提示气泡在侧边栏外渲染,避免被抽屉动画裁切。使用粗指针时,搜索和重命名输入框采用 16px 字号;精细指针下保留紧凑字号。 ### 重排序与视图选项 @@ -67,11 +69,13 @@ Session 行内的 Rename 操作打开一个以该行显示标题预填的对话 会话更新时间使用 tertiary 文本色,包括已归档行。标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。 -快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。导航抽屉允许这些命令,其他对话框遵循命令的模态限制。重命名要求主区域正在显示非空会话,且没有其他模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 +快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话、归档会话和切换已读/未读。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。导航抽屉允许这些命令,其他对话框遵循命令的模态限制。重命名要求主区域正在显示非空会话,且没有其他模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 + +切换已读/未读在 macOS 的 Desktop 和 Web 中使用 Command+Shift+U,在 Windows 使用 Control+Shift+U;Linux 默认不绑定,可自行配置。快捷键操作主区域显示的非空会话,要求阅读状态已同步且具有操作权限;切换到其他主面板或打开模态对话框时不可用。菜单操作始终针对所在行。成功修改及并发导致的过期请求都不弹提示,只有保存失败时显示 toast。 ### 待处理交互 -Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**等待审批**,计划审阅显示**计划待审**,普通问题显示**等待回答**。交互待处理期间,该行使用共享 warning 橙点,并以**待批准**、**计划待审**或**待回答**替换尾部更新时间;悬停详情仍保留完整状态和相对时间。待处理交互的优先级高于共享 ongoing loading;已完成但未查看的 Session 使用 done,idle 在行内不显示点,在悬停详情中使用共享 idle 灰点。 行首 seat 仅在该行的主状态为 idle 时渲染——没有待处理交互、没有自身或后代活动、也没有未查看的完成提醒——因此该处的占用方不会与行自身的状态点同时出现。归档行该格整体留空:既不显示状态点也不挂 seat,其活动状态只出现在悬浮卡片上。 +Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示**等待审批**,计划审阅显示**计划待审**,普通问题显示**等待回答**。交互待处理期间,该行使用共享 warning 橙点,并以**待批准**、**计划待审**或**待回答**替换尾部更新时间;悬停详情仍保留完整状态和相对时间。待处理交互优先于共享 ongoing loading,后者优先于未读提醒。失败的轮次显示红点,其他结束的轮次(含主动取消)显示绿点。打开会话或标为已读会清除这两种提醒。标为未读不会改变标题字重或已有的待处理交互点。idle 在行内不显示点,在悬停详情中使用共享 idle 灰点。行首 seat 仅在该行的主状态为 idle 时渲染——没有待处理交互、没有自身或后代活动、也没有未查看的完成提醒——因此该处的占用方不会与行自身的状态点同时出现。归档行该格整体留空:既不显示状态点也不挂 seat,其活动状态只出现在悬浮卡片上。 ### 活动 Schedule 标识 @@ -122,9 +126,9 @@ Session 行可通过 Tab 聚焦,使用不带修饰键的 Enter 或空格打开 ### Session 行 action -内置 Session 菜单动作通过 `ctx.contextMenus` 注册结构化贡献:置顶(100)、重命名(200)、分支(300)、复制 ID(450)和归档(600)。本机目录定位由 ui-open-in-app 提供(500)。重命名、分支和归档关联已有命令 ID,以显示实时快捷键;点击仍针对捕获的 Session 调用现有业务回调。置顶和归档同时保留悬停按钮 Slot 条目。 +内置 Session 菜单动作通过 `ctx.contextMenus` 注册结构化贡献:置顶(100)、重命名(200)、已读/未读(250)、分支(300)、复制 ID(450)和归档(600)。本机目录定位由 ui-open-in-app 提供(500)。重命名、已读/未读、分支和归档关联已有命令 ID,以显示实时快捷键;点击仍针对捕获的 Session 调用现有业务回调。置顶和归档同时保留悬停按钮 Slot 条目。 -旧 `sidebar.workspaces.session.menu.item` Slot 保留给外部 React 条目,提供 `sessionId`、`displayTitle` 和用于关闭菜单的 `useMenuOpenState`。旧条目保持彼此顺序,集中显示在归档之前;其 priority 不再替换内置数据动作。新贡献使用[菜单服务](../ui-context-menu/README.zh.md)。内置动作在菜单打开时持续响应权限和置顶/归档状态;对话框与提示仍为应用级浮层。 +旧 `sidebar.workspaces.session.menu.item` Slot 保留给外部 React 条目,提供 `sessionId`、`displayTitle` 和用于关闭菜单的 `useMenuOpenState`。旧条目保持彼此顺序,集中显示在归档之前;其 priority 不再替换内置数据动作。新贡献使用[菜单服务](../ui-context-menu/README.zh.md)。内置动作在菜单打开时持续响应权限和置顶/归档状态;阅读动作还会响应未读提醒和同步就绪状态。对话框与提示仍为应用级浮层。 现有通知浮层按通知 kind 分派 `workspace.toast`。各 keyed 注册注入本地化展示映射与自己的操作,只有归档通知订阅查看筛选状态。它们渲染包内的 `workspace.toast.content` Factory,所有展示共用一处 Toast primitive。现有通知状态、显示序号、最新提示替换及关闭逻辑仍共享;语言或筛选变化不会重新启动同一条提示的计时。 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 7e53a43400..ffa5850cb8 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -320,6 +320,7 @@ export type SessionRowActionProps = export type RowToast = | { kind: 'archived'; sessionId: SessionId; message?: string; tone?: 'success' | 'warning' } | { kind: 'stoppedAndArchived'; sessionId: SessionId; message?: string; tone?: 'success' | 'warning' } + | { kind: 'readingFailed' } | { kind: 'sessionIdCopied' } | { kind: 'sessionIdCopyFailed' } | { kind: 'pinFailed' } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 425fcbf712..5d95282a59 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -1,4 +1,4 @@ -import { IconEditOutlineRegular, IconTrashOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconUnarchiveOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, IconCopyOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconEditOutlineRegular, IconTrashOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconUnarchiveOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, IconCopyOutlineRegular, IconMailReadOutlineRegular, IconMailUnreadOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { SessionMenu } from './session-actions/SessionMenu.tsx' import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** @@ -137,7 +137,7 @@ const NS = 'workspace' */ export const inject = ['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', - 'uiSession.sessionStatus', + 'uiSession', 'uiSession.sessionStatus', ] /** @@ -196,6 +196,9 @@ export function apply(ctx: Context): void { // Registry-global sets as Sets, rebuilt only when the Workspace snapshot changes. const pinnedSet = derive(workspaces.list, snapshot => new Set(snapshot.pinnedSessionIds)) const archivedSet = derive(workspaces.list, snapshot => new Set(snapshot.archivedSessionIds)) + const markSession = (sessionId: SessionId, unread: boolean): void => { + ctx.uiSession.sessionStatus.mark(sessionId, unread).catch(() => { notify({ kind: 'readingFailed' }) }) + } // Plugin-private facts the row actions and their overlay surfaces share: // the pending rename request and the notice on display. Each business // writes through its own injected callback and the surface reads through @@ -262,7 +265,7 @@ export function apply(ctx: Context): void { unarchiveSession, }) installWorkspaceShortcuts(ctx, uiWorkspace, shortcutControls, archiveInjected().archiveSession, - (reason) => { notify({ kind: 'shortcutForkFailed', reason }) }) + (reason) => { notify({ kind: 'shortcutForkFailed', reason }) }, markSession) const archiveConfirmInjected = (): SessionArchiveConfirmInjected => ({ hooks: { archiveRequest }, settleSessionArchive: () => { archiveRequest.set(null) }, @@ -323,6 +326,7 @@ export function apply(ctx: Context): void { 'workspace.pin': IconPinOutlineRegular, 'workspace.unpin': IconPinFillRegular, 'workspace.archive': IconArchiveOutlineRegular, 'workspace.unarchive': IconUnarchiveOutlineRegular, 'workspace.fork': IconBranchOutlineRegular, 'workspace.copy': IconCopyOutlineRegular, + 'workspace.markRead': IconMailReadOutlineRegular, 'workspace.markUnread': IconMailUnreadOutlineRegular, })) yield ctx.slots.register({ name: 'contextMenu.icon', key }, Icon) }) ctx.effect(() => ctx.contextMenus.register({ @@ -390,6 +394,7 @@ export function apply(ctx: Context): void { }, SessionMenu)) registerSessionMenus(ctx, { ...pinInjected(), ...archiveInjected(), ...renameInjected(), ...forkInjected(), ...sessionIdInjected(), + markSession, }) ctx.slots.inject('sidebar.workspaces.session.row.action', function* () { yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'archive', order: 100, locale: NS, inject: archiveInjected }, ArchiveSessionRowButton) diff --git a/packages/client/ui-workspace/src/client/locales.ts b/packages/client/ui-workspace/src/client/locales.ts index 7420f4547b..bcdb692951 100644 --- a/packages/client/ui-workspace/src/client/locales.ts +++ b/packages/client/ui-workspace/src/client/locales.ts @@ -13,6 +13,11 @@ export const zh = { 'session.new': '新会话', 'session.untitled': '未命名', 'shortcut.noSession': '请先选择一个会话', + 'shortcut.closeDialog': '请先关闭打开的对话框', + 'shortcut.closePanel': '请先关闭打开的面板,返回会话', + 'shortcut.archivedReading': '已归档的会话没有未读提醒', + 'shortcut.toggleRead': '切换已读/未读', + 'shortcut.readingUnavailable': '当前无法修改阅读状态,请刷新页面以重新连接', 'shortcut.noPicker': '目录选择器不可用', 'shortcut.directoryBusy': '正在选择或添加工作区', 'shortcut.noCompletedTurn': '当前会话没有已结束的轮次', @@ -114,7 +119,11 @@ export const zh = { 'status.compact.approval': '待审批', 'status.compact.planReview': '计划待审', 'status.compact.answer': '待回答', - 'status.completed': '已完成', + 'status.unread': '未读', + 'status.failed': '运行出错', + 'menu.markRead': '标为已读', + 'menu.markUnread': '标为未读', + 'toast.readingFailed': '未能确认阅读状态,请重试', 'hover.created': '创建于 {time}', 'hover.copied': '已复制', 'date.ymd': '{y}年{m}月{d}日', @@ -139,6 +148,11 @@ export const en = { 'session.new': 'New Session', 'session.untitled': 'Untitled', 'shortcut.noSession': 'Select a session first', + 'shortcut.closeDialog': 'Close the open dialog first', + 'shortcut.closePanel': 'Close the open panel to return to the session', + 'shortcut.archivedReading': 'Archived sessions have no unread reminders', + 'shortcut.toggleRead': 'Toggle read/unread', + 'shortcut.readingUnavailable': 'Reading state is unavailable. Reload the page to reconnect.', 'shortcut.noPicker': 'Directory picker unavailable', 'shortcut.directoryBusy': 'Selecting or adding a workspace', 'shortcut.noCompletedTurn': 'This session has no completed turn', @@ -240,7 +254,11 @@ export const en = { 'status.compact.approval': 'Approval', 'status.compact.planReview': 'Plan review', 'status.compact.answer': 'Answer', - 'status.completed': 'Completed', + 'status.unread': 'Unread', + 'status.failed': 'Run failed', + 'menu.markRead': 'Mark as read', + 'menu.markUnread': 'Mark as unread', + 'toast.readingFailed': 'Could not confirm reading state. Try again.', 'hover.created': 'Created {time}', 'hover.copied': 'Copied', 'date.ymd': '{y}-{m}-{d}', @@ -262,6 +280,11 @@ export const ja = { 'session.new': '新しいセッション', 'session.untitled': '無題', 'shortcut.noSession': '先にセッションを選択してください', + 'shortcut.closeDialog': '先に開いているダイアログを閉じてください', + 'shortcut.closePanel': '開いているパネルを閉じてセッションに戻ってください', + 'shortcut.archivedReading': 'アーカイブ済みのセッションには未読の通知がありません', + 'shortcut.toggleRead': '既読・未読を切り替え', + 'shortcut.readingUnavailable': '現在、既読状態を変更できません。ページを再読み込みして接続し直してください。', 'shortcut.noPicker': 'ディレクトリピッカーを利用できません', 'shortcut.directoryBusy': 'ワークスペースを選択または追加しています', 'shortcut.noCompletedTurn': 'このセッションには完了したターンがありません', @@ -363,7 +386,11 @@ export const ja = { 'status.compact.approval': '承認', 'status.compact.planReview': '計画レビュー', 'status.compact.answer': '回答', - 'status.completed': '完了', + 'status.unread': '未読', + 'status.failed': '実行エラー', + 'menu.markRead': '既読にする', + 'menu.markUnread': '未読にする', + 'toast.readingFailed': '既読状態を確認できませんでした。再試行してください。', 'hover.created': '作成日時 {time}', 'hover.copied': 'コピーしました', 'date.ymd': '{y}-{m}-{d}', @@ -385,6 +412,11 @@ export const es = { 'session.new': 'Nueva sesión', 'session.untitled': 'Sin título', 'shortcut.noSession': 'Seleccione una sesión primero', + 'shortcut.closeDialog': 'Cierre primero el cuadro de diálogo abierto', + 'shortcut.closePanel': 'Cierre el panel abierto para volver a la sesión', + 'shortcut.archivedReading': 'Las sesiones archivadas no tienen avisos de no leído', + 'shortcut.toggleRead': 'Alternar leído/no leído', + 'shortcut.readingUnavailable': 'El estado de lectura no está disponible. Recarga la página para volver a conectarte.', 'shortcut.noPicker': 'Selector de directorio no disponible', 'shortcut.directoryBusy': 'Seleccionar o agregar un espacio de trabajo', 'shortcut.noCompletedTurn': 'Esta sesión no tiene turno completo', @@ -486,7 +518,11 @@ export const es = { 'status.compact.approval': 'Aprobación', 'status.compact.planReview': 'Revisión del plan', 'status.compact.answer': 'respuesta', - 'status.completed': 'Completado', + 'status.unread': 'No leído', + 'status.failed': 'La ejecución ha fallado', + 'menu.markRead': 'Marcar como leído', + 'menu.markUnread': 'Marcar como no leído', + 'toast.readingFailed': 'No se pudo confirmar el estado de lectura. Inténtalo de nuevo.', 'hover.created': 'Creado {time}', 'hover.copied': 'Copiado', 'date.ymd': '{y}-{m}-{d}', @@ -508,6 +544,11 @@ export const fr = { 'session.new': 'Nouvelle séance', 'session.untitled': 'Sans titre', 'shortcut.noSession': "Sélectionnez d'abord une session", + 'shortcut.closeDialog': "Fermez d'abord la boîte de dialogue ouverte", + 'shortcut.closePanel': 'Fermez le panneau ouvert pour revenir à la session', + 'shortcut.archivedReading': "Les sessions archivées n'ont pas de rappel non lu", + 'shortcut.toggleRead': 'Basculer lu/non lu', + 'shortcut.readingUnavailable': 'Le statut de lecture est indisponible. Rechargez la page pour vous reconnecter.', 'shortcut.noPicker': 'Sélecteur de répertoire indisponible', 'shortcut.directoryBusy': "Sélection ou ajout d'un espace de travail", 'shortcut.noCompletedTurn': "Cette session n'a pas de tour terminé", @@ -609,7 +650,11 @@ export const fr = { 'status.compact.approval': 'Approbation', 'status.compact.planReview': 'Révision des plans', 'status.compact.answer': 'Réponse', - 'status.completed': 'Terminé', + 'status.unread': 'Non lu', + 'status.failed': 'Échec de l’exécution', + 'menu.markRead': 'Marquer comme lu', + 'menu.markUnread': 'Marquer comme non lu', + 'toast.readingFailed': 'Impossible de confirmer le statut de lecture. Réessayez.', 'hover.created': 'Créé {time}', 'hover.copied': 'Copié', 'date.ymd': '{y}-{m}-{d}', @@ -631,6 +676,11 @@ export const de = { 'session.new': 'Neue Sitzung', 'session.untitled': 'Ohne Titel', 'shortcut.noSession': 'Wählen Sie zunächst eine Sitzung aus', + 'shortcut.closeDialog': 'Schließen Sie zuerst den geöffneten Dialog', + 'shortcut.closePanel': 'Schließen Sie das geöffnete Panel, um zur Sitzung zurückzukehren', + 'shortcut.archivedReading': 'Archivierte Sitzungen haben keine Ungelesen-Hinweise', + 'shortcut.toggleRead': 'Gelesen/ungelesen umschalten', + 'shortcut.readingUnavailable': 'Der Lesestatus ist nicht verfügbar. Lade die Seite neu, um die Verbindung wiederherzustellen.', 'shortcut.noPicker': 'Verzeichnisauswahl nicht verfügbar', 'shortcut.directoryBusy': 'Auswählen oder Hinzufügen eines Arbeitsbereichs', 'shortcut.noCompletedTurn': 'Diese Sitzung hat keine abgeschlossene Runde', @@ -732,7 +782,11 @@ export const de = { 'status.compact.approval': 'Zustimmung', 'status.compact.planReview': 'Planüberprüfung', 'status.compact.answer': 'Antwort', - 'status.completed': 'Abgeschlossen', + 'status.unread': 'Ungelesen', + 'status.failed': 'Ausführung fehlgeschlagen', + 'menu.markRead': 'Als gelesen markieren', + 'menu.markUnread': 'Als ungelesen markieren', + 'toast.readingFailed': 'Der Lesestatus konnte nicht bestätigt werden. Versuche es erneut.', 'hover.created': 'Erstellt {time}', 'hover.copied': 'Kopiert', 'date.ymd': '{y}-{m}-{d}', @@ -754,6 +808,11 @@ export const ru = { 'session.new': 'Новая сессия', 'session.untitled': 'Без названия', 'shortcut.noSession': 'Сначала выберите сеанс', + 'shortcut.closeDialog': 'Сначала закройте открытое диалоговое окно', + 'shortcut.closePanel': 'Закройте открытую панель, чтобы вернуться к сеансу', + 'shortcut.archivedReading': 'У архивных сеансов нет напоминаний о непрочитанном', + 'shortcut.toggleRead': 'Переключить прочитано/не прочитано', + 'shortcut.readingUnavailable': 'Статус прочтения недоступен. Перезагрузите страницу для повторного подключения.', 'shortcut.noPicker': 'Выбор каталога недоступен.', 'shortcut.directoryBusy': 'Выбор или добавление рабочего пространства', 'shortcut.noCompletedTurn': 'В этой сессии нет завершенных ходов', @@ -855,7 +914,11 @@ export const ru = { 'status.compact.approval': 'Одобрение', 'status.compact.planReview': 'Обзор плана', 'status.compact.answer': 'Ответ', - 'status.completed': 'Завершено', + 'status.unread': 'Не прочитано', + 'status.failed': 'Ошибка выполнения', + 'menu.markRead': 'Отметить как прочитанное', + 'menu.markUnread': 'Отметить как непрочитанное', + 'toast.readingFailed': 'Не удалось подтвердить статус прочтения. Повторите попытку.', 'hover.created': 'Создано {time}', 'hover.copied': 'Скопировано', 'date.ymd': '{y}-{m}-{d}', @@ -877,6 +940,11 @@ export const pt = { 'session.new': 'Nova sessão', 'session.untitled': 'Sem título', 'shortcut.noSession': 'Selecione uma sessão primeiro', + 'shortcut.closeDialog': 'Feche primeiro a caixa de diálogo aberta', + 'shortcut.closePanel': 'Feche o painel aberto para voltar à sessão', + 'shortcut.archivedReading': 'Sessões arquivadas não têm avisos de não lido', + 'shortcut.toggleRead': 'Alternar lido/não lido', + 'shortcut.readingUnavailable': 'O estado de leitura está indisponível. Recarregue a página para voltar a conectar.', 'shortcut.noPicker': 'Seletor de diretório indisponível', 'shortcut.directoryBusy': 'Selecionando ou adicionando um espaço de trabalho', 'shortcut.noCompletedTurn': 'Esta sessão não tem turno concluído', @@ -978,7 +1046,11 @@ export const pt = { 'status.compact.approval': 'Aprovação', 'status.compact.planReview': 'Revisão do plano', 'status.compact.answer': 'Resposta', - 'status.completed': 'Concluído', + 'status.unread': 'Não lido', + 'status.failed': 'Falha na execução', + 'menu.markRead': 'Marcar como lido', + 'menu.markUnread': 'Marcar como não lido', + 'toast.readingFailed': 'Não foi possível confirmar o estado de leitura. Tente novamente.', 'hover.created': 'Criado {time}', 'hover.copied': 'Copiado', 'date.ymd': '{y}-{m}-{d}', diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx index 04b56cb10c..e2094eeabf 100644 --- a/packages/client/ui-workspace/src/client/rows/Rows.tsx +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -382,7 +382,7 @@ interface SessionStatus { * outranks completion reminders. */ function sessionStatuses( - node: Pick, + node: Pick, t: RowTranslate, ): readonly [SessionStatus, ...SessionStatus[]] { const subagents: SessionStatus | undefined = node.runningSubagentCount === 0 @@ -423,13 +423,17 @@ function sessionStatuses( /* v8 ignore next -- closed PendingInteractionStatus union */ default: return assertNever(node.pendingInteraction) } - if (pending !== undefined) return subagents === undefined ? [pending] : [pending, subagents] + const completion: SessionStatus = node.failed + ? { state: 'error', label: t('status.failed') } + : { state: 'done', label: t('status.unread') } + const unread: SessionStatus[] = node.completed ? [completion] : [] + if (pending !== undefined) return subagents === undefined ? [pending, ...unread] : [pending, subagents, ...unread] if (node.running) { const primary: SessionStatus = { state: 'ongoing', label: t('status.running') } - return subagents === undefined ? [primary] : [primary, subagents] + return subagents === undefined ? [primary, ...unread] : [primary, subagents, ...unread] } - if (subagents !== undefined) return [subagents] - if (node.completed) return [{ state: 'done', label: t('status.completed') }] + if (subagents !== undefined) return [subagents, ...unread] + if (node.completed) return [completion] return [{ state: 'idle', label: t('status.idle') }] } @@ -468,10 +472,9 @@ function SessionHoverContent({ node, cwd, now, renderSlot, t }: { renderSlot: RowRenderSlots t: RowTranslate }) { - // On archived rows the archived line already says the session is inactive, - // so resting statuses (idle/completed) drop; live activity still shows. - const statuses = sessionStatuses(node, t) - .filter(status => !(node.archived && (status.state === 'done' || status.state === 'idle'))) + // Archived rows show live activity but suppress idle and unread reminders. + const statuses = sessionStatuses(node.archived ? { ...node, completed: false } : node, t) + .filter(status => !(node.archived && status.state === 'idle')) return (
{displayTitle(node, t)}
@@ -701,8 +704,8 @@ export function SessionNodeItem({ }} > {/* Pending interaction and own or descendant activity outrank the - finished-but-unviewed reminder, which returns after activity stops - and is cleared by opening the session. Archived rows keep the slot + unread reminder, which returns after activity stops + and clears after the visible content is acknowledged. Archived rows keep the slot blank — the grayed row carries the archived look — and their live status stays on the hover card only. */} diff --git a/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx b/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx index f312e0233f..a1b94ce8ac 100644 --- a/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/context-menus.tsx @@ -2,13 +2,17 @@ import type { Context } from '@deepseek-ai/cordis' import type { RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { MenuContribution, ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { ArchiveSessionInjected, ForkSessionInjected, PinSessionInjected, RenameSessionInjected, SessionIdInjected, } from '../contract/slots.ts' type Actions = Omit & ForkSessionInjected & RenameSessionInjected & SessionIdInjected + & { readonly markSession: (sessionId: SessionId, unread: boolean) => void } /** * Register built-in actions while retaining the legacy Slot for external components. @@ -22,11 +26,12 @@ export function registerSessionMenus(ctx: Context, actions: Actions): void { order: number, endpoints: readonly RemoteEndpoint[], resolve: MenuContribution<'session'>['resolve'], + sources: readonly ObservableSnapshot[] = [], ): void => { ctx.effect(() => ctx.contextMenus.register({ id: `session.${id}`, target: 'session', order, observe: ({ sessionId }) => [ - ctx.workspaces.list, ctx.locale, + ctx.workspaces.list, ctx.locale, ...sources, ...endpoints.map(action => ctx.remoteAccess.source('session', sessionId, action)), ], resolve, @@ -48,6 +53,18 @@ export function registerSessionMenus(ctx: Context, actions: Actions): void { id: 'rename', label: t('rename'), icon: { key: 'workspace.rename' }, commandId: 'session.rename' as ShortcutCommandId, run: () => { actions.requestSessionRename(target.sessionId, target.displayTitle) }, }] : []) + register('read-state', 250, ['sessionStatus/mark'], (target) => { + // Archived rows hide reminders and read as read, so they offer no reading mark. + if (archived(target) || !allowed(target, 'sessionStatus/mark')) return [] + const status = ctx.uiSession.sessionStatus + const unread = status.getSnapshot().get(target.sessionId)?.completionUnread === true + return [{ + id: 'mark', label: t(unread ? 'menu.markRead' : 'menu.markUnread'), + icon: { key: unread ? 'workspace.markRead' : 'workspace.markUnread' }, + commandId: 'session.toggleRead' as ShortcutCommandId, disabled: !status.readingReady.getSnapshot(), + run: () => { actions.markSession(target.sessionId, !unread) }, + }] + }, [ctx.uiSession.sessionStatus, ctx.uiSession.sessionStatus.readingReady]) register('fork', 300, ['session/fork'], target => allowed(target, 'session/fork') ? [{ id: 'fork', label: t('menu.fork'), icon: { key: 'workspace.fork' }, commandId: 'session.fork' as ShortcutCommandId, run: () => { actions.forkSession(target.sessionId) }, diff --git a/packages/client/ui-workspace/src/client/shortcuts.ts b/packages/client/ui-workspace/src/client/shortcuts.ts index 180c13fbcb..5fe67dd8c8 100644 --- a/packages/client/ui-workspace/src/client/shortcuts.ts +++ b/packages/client/ui-workspace/src/client/shortcuts.ts @@ -54,6 +54,7 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { * @param controls - browser-owned opening requests. * @param archiveSession - shared archive action, including running-work confirmation and notices. * @param reportForkFailure - publish a classified failure through the frame-wide notice channel. + * @param markSession - shared reading action; only failed writes raise a notice. */ export function installWorkspaceShortcuts( ctx: Context, @@ -61,6 +62,7 @@ export function installWorkspaceShortcuts( controls: ReturnType, archiveSession: (sessionId: SessionId) => void, reportForkFailure: (reason: 'unavailable' | 'failed') => void, + markSession: (sessionId: SessionId, unread: boolean) => void, ): void { const t = ctx.locale.bind('workspace') const current = () => Object.values(ctx.sessions.list.getSnapshot().byId) @@ -115,4 +117,30 @@ export function installWorkspaceShortcuts( archiveSession(target.id) } } }) + ctx.effect(() => ctx.shortcuts.register({ + id: 'session.toggleRead' as ShortcutCommandId, + label: () => t('shortcut.toggleRead'), aliases: ['mark as read', 'mark as unread', 'toggle unread'], + defaults: { + 'desktop:macos': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'desktop:windows': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'web:macos': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + 'web:windows': { code: 'KeyU', modifiers: ['primary', 'shift'] }, + }, + regions: ['page', 'editable'], modals: [], + resolve: (context) => { + const target = current() + if (target === undefined || target.blank) return { status: 'blocked', reason: t('shortcut.noSession') } + // Like the row menu, a Peer that may not mark reading has no reading command. + if (!ctx.remoteAccess.source('session', target.id, 'sessionStatus/mark').getSnapshot()) return { status: 'pass' } + if (context.modal !== null) return { status: 'blocked', reason: t('shortcut.closeDialog') } + if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return { status: 'blocked', reason: t('shortcut.closePanel') } + if (ctx.workspaces.list.getSnapshot().archivedSessionIds.includes(target.id)) { + return { status: 'blocked', reason: t('shortcut.archivedReading') } + } + const status = ctx.uiSession.sessionStatus + if (!status.readingReady.getSnapshot()) return { status: 'blocked', reason: t('shortcut.readingUnavailable') } + const unread = status.getSnapshot().get(target.id)?.completionUnread === true + return { status: 'handled', run: () => { markSession(target.id, !unread) } } + }, + }), 'ui-workspace: session.toggleRead') } diff --git a/packages/client/ui-workspace/src/client/toast/register.ts b/packages/client/ui-workspace/src/client/toast/register.ts index 51a3a6ca09..3ba0eb141b 100644 --- a/packages/client/ui-workspace/src/client/toast/register.ts +++ b/packages/client/ui-workspace/src/client/toast/register.ts @@ -21,6 +21,13 @@ export function registerToasts( }) ctx.slots.registerFactory({ name: 'workspace.toast.content', scope: 'root' }, WorkspaceToast) ctx.slots.inject('workspace.toast', function* () { + yield ctx.slots.register({ + name: 'workspace.toast', key: 'readingFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'readingFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.readingFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ name: 'workspace.toast', key: 'sessionIdCopied', locale: 'workspace', inject: (): ToastDisplayInjected<'sessionIdCopied'> => ({ diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 993c00dbf6..8684ee4238 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -52,8 +52,10 @@ export interface SessionNode { running: boolean /** Running direct children in the loaded subagent catalog. */ runningSubagentCount: number - /** Finished running while not selected and not yet opened (the green "done" reminder dot). */ + /** Host-confirmed unread completion or explicit unread mark. */ completed: boolean + /** Latest unread completion ended with an execution error. */ + failed: boolean /** In the registry-global pin set: leads its section, reorderable only among pinned rows. */ pinned: boolean /** In the registry-global archive set: shown grayed in place and not openable. */ @@ -95,8 +97,10 @@ export interface SearchResultNode { running: boolean /** Running direct children in the loaded subagent catalog. */ runningSubagentCount: number - /** Finished running while not selected and not yet opened (the green "done" reminder dot). */ + /** Host-confirmed unread completion or explicit unread mark. */ completed: boolean + /** Latest unread completion ended with an execution error. */ + failed: boolean /** In the registry-global archive set: shown grayed and not openable. */ archived: boolean snippet?: string @@ -401,6 +405,7 @@ function sessionNode( running: status?.running ?? s.running, runningSubagentCount: runningChildCount(list, s.id, statuses), completed: status?.completionUnread === true, + failed: status?.completionFailed === true, pinned: !archived.has(s.id) && pinned.has(s.id), archived: archived.has(s.id), updatedAt: s.updatedAt, @@ -605,6 +610,7 @@ export function deriveSearchResults( ? {} : { pendingInteraction }), completed: status?.completionUnread === true, + failed: status?.completionFailed === true, archived: archived.has(summary.id), ...match === undefined ? {} : { snippet: match.snippet }, } diff --git a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx index 51ce69fdfb..1adc908ff6 100644 --- a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx @@ -9,8 +9,9 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, screen } from '@testing-library/react' -import type { TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' +import type { AccessEffect, RemoteEndpoint, TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' import { ClientAccessState } from '@deepseek-ai/dsh-api-remote-access/src/client/state.ts' +import { whenAllowed } from '@deepseek-ai/dsh-api-remote-access/src/client/when-allowed.ts' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -48,6 +49,8 @@ async function bench(access: ClientAccessState, options: { ungroupedSession?: Se apply(ctx) { ctx.provide('remoteAccess', { source: (kind: TypertResourceKind, id: string, action: string) => access.resource(kind, id, action), + whenAccess: (action: RemoteEndpoint, callback: () => AccessEffect) => + whenAllowed(ctx, access.global(action), callback, `access-assembly: ${action}`), }) ctx.slots.provideRoot({ keyedHooks: { remoteAccess: action => access.global(action) } }) }, diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index efe3751dc6..c5828af449 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -31,6 +31,7 @@ import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' import { apply as hostApply } from '../src/index.ts' import { SECTION_HOOK_CONTEXT, SECTION_INJECT } from './section-scroller.client.ts' +import { provideSessionStatus } from './session-status.client.ts' const sid = (id: string) => id as SessionId const summary = (id: string, updatedAt: number): SessionSummary => ({ @@ -70,7 +71,7 @@ async function bench(access: 'fake' | 'static' = 'fake') { onTestFinished(() => { menuRegistry.dispose() }) ctx.provide('contextMenus', { register: menuRegistry.register.bind(menuRegistry), resolve: menuRegistry.resolve.bind(menuRegistry), active: createSnapshotStore(null), open: vi.fn(), close: vi.fn() } as never) ctx.provide('uiConversation', {}) - ctx.provide('uiSession.sessionStatus', createSnapshotStore(new Map()) as never) + const status = provideSessionStatus(ctx) await ctx.plugin(SlotRegistry).await() const accessSource = vi.fn((_kind: string, _id: string, _action: string): HostObservable => ALLOWED) const stopGuard = vi.fn() @@ -169,7 +170,8 @@ async function bench(access: 'fake' | 'static' = 'fake') { locale.setLocale('zh') ctx.provide('locale', locale) return { - ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, accessSource, whenResourceAccess, stopGuard, + ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, accessSource, + whenResourceAccess, stopGuard, status, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, workspacesSubscribe, initializeDefault, history, scope, sessionOf, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, @@ -222,6 +224,7 @@ function sessionMenuActions(ctx: Context) { forkSession: (sessionId: SessionId) => { select('session.fork/fork', sessionId) }, requestSessionRename: (sessionId: SessionId, title: string) => { select('session.rename/rename', sessionId, title) }, copySessionId: async (sessionId: SessionId) => { select('session.id/copy', sessionId); await settled() }, + toggleRead: (sessionId: SessionId) => { select('session.read-state/mark', sessionId) }, } } @@ -243,7 +246,7 @@ describe('ui-workspace apply', () => { it('declares the services it drives', () => { expect(inject).toEqual(['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', - 'uiSession.sessionStatus', + 'uiSession', 'uiSession.sessionStatus', ]) }) @@ -345,6 +348,7 @@ describe('ui-workspace apply', () => { const rowToastEntry = entry(b.slots, 'shell.overlay', 'workspace.row-toast') expect(rowToastEntry.store).toBeUndefined() expect(b.slots.entries('workspace.toast').map(row => row.options.key)).toEqual([ + 'readingFailed', 'sessionIdCopied', 'sessionIdCopyFailed', 'pinFailed', 'unpinFailed', 'archivedNotOpenable', 'defaultWorkspaceFailed', 'shortcutForkFailed', 'createFailed', 'forkRequiresOpen', 'archived', 'stoppedAndArchived', ]) @@ -362,6 +366,36 @@ describe('ui-workspace apply', () => { } }) + it('marks cold Sessions silently and reports only failed writes', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const action = sessionMenuActions(b.ctx) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const menu = b.ctx.contextMenus.resolve({ kind: 'session', value: { sessionId: sid('cold'), displayTitle: 'Cold' } }) + const readAction = () => menu.source.getSnapshot().find(item => item.id === 'session.read-state/mark') + expect(readAction()?.disabled).toBe(false) + b.status.readingReady.set(false) + expect(readAction()?.disabled).toBe(true) + menu.dispose() + b.status.readingReady.set(true) + for (const unread of [true, false]) { + b.status.setUnread(sid('cold'), !unread) + b.status.mark.mockResolvedValueOnce(undefined) + action.toggleRead(sid('cold')) + await Promise.resolve() + expect(b.status.mark).toHaveBeenLastCalledWith(sid('cold'), unread) + expect(toast.hooks.toast.getSnapshot()).toBeNull() + } + b.status.table.set(new Map()) + action.toggleRead(sid('cold')) + await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'readingFailed' }) }) + expect(b.status.mark).toHaveBeenLastCalledWith(sid('cold'), true) + expect(b.retain).not.toHaveBeenCalled() + expect(b.binding).not.toHaveBeenCalled() + }) + it.each([true, false])('copies an ID directly without loading its Session (clipboard accepted: %s)', async (accepted) => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 8e747090c6..fedc107546 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -123,7 +123,7 @@ describe('session rename through the assembled browser', () => { fireEvent.click(trigger) await view.findByRole('menuitem', { name: '置顶会话' }) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '置顶会话', '重命名', '分叉会话', '复制 Session ID', 'Export action', 'Last action', '归档会话', + '置顶会话', '重命名', '标为未读', '分叉会话', '复制 Session ID', 'Export action', 'Last action', '归档会话', ]) expect(view.getAllByRole('separator')).toHaveLength(3) const last = view.getByRole('menuitem', { name: 'Last action' }) diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 0cc4cac028..ad2e5f248d 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -112,7 +112,7 @@ describe('Workspace and Session hover handoff', () => { }) const session: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -175,7 +175,7 @@ describe('native row drag previews', () => { }} onToggle={vi.fn()} onCreate={vi.fn()} drag={drag} t={t} /> : ) const row = screen.getByRole('treeitem') stubRect(row) @@ -238,7 +238,7 @@ describe('native row drag previews', () => { const image = start() rerender() expect(row.getAttribute('draggable')).toBe('false') fireEvent.dragEnd(row) @@ -265,7 +265,7 @@ describe('workspace browser rows', () => { it('keeps the leading status cell in the hierarchy-free flat list', () => { const idle: SessionNode = { id: sid('flat'), title: 'Flat Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const view = render() // The cell is the row's first element and holds nothing while the row is @@ -288,7 +288,7 @@ describe('workspace browser rows', () => { workspace: 'Workspace context', running: true, runningSubagentCount: 0, - completed: false, + completed: false, failed: false, archived: false, snippet: 'matching message excerpt', } @@ -308,7 +308,7 @@ describe('workspace browser rows', () => { it('withholds the search-result restore control while the Session access excludes unarchiving', () => { const result: SearchResultNode = { id: sid('archived-result'), title: 'Archived', workspace: 'Project', - running: false, runningSubagentCount: 0, completed: false, archived: true, + running: false, runningSubagentCount: 0, completed: false, failed: false, archived: true, } const denied = vi.fn(() => false) const view = render( { ] as const)('shows %s ahead of running in search results', (pendingInteraction, label) => { const result: SearchResultNode = { id: sid(pendingInteraction), title: 'Needs input', workspace: 'Project', - pendingInteraction, running: true, runningSubagentCount: 0, completed: false, archived: false, + pendingInteraction, running: true, runningSubagentCount: 0, completed: false, failed: false, archived: false, } render() @@ -364,7 +364,7 @@ describe('workspace browser rows', () => { it('renders and opens a selected running Session row', () => { const node: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: true, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const onOpen = vi.fn() render( @@ -382,7 +382,7 @@ describe('workspace browser rows', () => { it('keeps a row.action entry click in the strip, so a plain button does not open the row', () => { const node: SessionNode = { id: sid('session'), title: 'Session', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const onOpen = vi.fn() const pluginAction = vi.fn() @@ -404,7 +404,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('clipped'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -476,7 +476,7 @@ describe('workspace browser rows', () => { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false }))) try { const node: SessionNode = { id: sid('context-crawl'), title: 'A long Session title', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false } + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false } const props = { node, currentId: undefined, now: 0, onOpen: vi.fn(), t } const view = render() const row = screen.getByRole('treeitem') @@ -501,7 +501,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('reduced-motion'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -530,7 +530,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('instant-return'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, - running: false, runningSubagentCount: 0, completed: false, updatedAt: 0, + running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render( @@ -559,12 +559,12 @@ describe('workspace browser rows', () => { } }) - it('shows the green done dot only on a finished, unviewed session (live activity wins the slot)', () => { + it('shows the green unread dot only on an unread session (live activity wins the slot)', () => { const renderRow = (over: Partial) => render( , @@ -575,27 +575,51 @@ describe('workspace browser rows', () => { const plain = renderRow({}) expect(stateDot(plain)).toBeNull() plain.unmount() - // Completed while unviewed: the green done dot. const done = renderRow({ completed: true }) expect(done.container.querySelector('[data-state="done"]')).not.toBeNull() done.unmount() - // Running wins the slot: the animated ongoing dot, no done dot. - const running = renderRow({ completed: true, running: true }) + // Running wins the slot: the ongoing dot takes precedence over the unread dot. + const running = renderRow({ completed: true, failed: false, running: true }) expect(running.container.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(running.container.querySelector('[data-state="done"]')).toBeNull() running.unmount() // Descendant activity also wins until the last running descendant stops. - const delegated = renderRow({ completed: true, runningSubagentCount: 1 }) + const delegated = renderRow({ completed: true, failed: false, runningSubagentCount: 1 }) expect(delegated.container.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(delegated.container.querySelector('[data-state="done"]')).toBeNull() }) + it('shows a red unread failure and removes it after the Session is read', () => { + const node = { + id: sid('failed'), title: 'Failed', blank: false, running: false, + runningSubagentCount: 0, completed: true, failed: true, updatedAt: 0, pinned: false, archived: false, + } + const view = render() + expect(view.container.querySelector('[data-state="error"]')).not.toBeNull() + expect(view.container.querySelector('[data-state="done"]')).toBeNull() + expect(screen.getByText('运行出错')).toBeTruthy() + view.rerender() + expect(view.container.querySelector('[data-state]')).toBeNull() + }) + + it.each(['approval', 'plan-review', 'question'] as const)( + 'keeps the yellow %s dot when the session is unread', (pendingInteraction) => { + render() + const row = screen.getByRole('treeitem') + expect(row.querySelector('[data-state="warning"]')).not.toBeNull() + expect(row.querySelector('[data-state="done"]')).toBeNull() + }, + ) + it('shows descendant activity without describing an idle parent as running', () => { vi.useFakeTimers() try { const node: SessionNode = { id: sid('owner'), title: 'Delegating', blank: false, running: false, - runningSubagentCount: 2, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 2, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -616,7 +640,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('owner'), title: 'Delegating', blank: false, running: true, - runningSubagentCount: 1, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 1, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -636,7 +660,7 @@ describe('workspace browser rows', () => { it('keeps child activity as a secondary status while user attention is primary', () => { const node: SessionNode = { id: sid('owner'), title: 'Needs input', blank: false, pendingInteraction: 'question', - running: false, runningSubagentCount: 1, completed: false, updatedAt: 0, pinned: false, archived: false, + running: false, runningSubagentCount: 1, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -646,11 +670,11 @@ describe('workspace browser rows', () => { expect(screen.getByText('1 个子智能体运行中')).toBeTruthy() }) - it('shows the green done dot on a finished search result row', () => { + it('shows the green unread dot on an unread search result row', () => { render( { it('session row drags and renames from its title only while its access snapshot allows each', () => { const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const drag: RowDragProps = { active: false, marker: null, start: vi.fn(), end: vi.fn(), hover: vi.fn(), drop: vi.fn(), @@ -901,7 +925,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('s-blank'), title: 'ignored', blank: true, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const rendered = vi.fn() const renderSlot: RowRenderSlot = (name: RowSlotName) => { rendered(name); return null } @@ -927,7 +951,7 @@ describe('workspace browser rows', () => { describe('Session hover-card working directory', () => { const located: SessionNode = { id: sid('s-cwd'), title: 'Located', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, cwd: '/home/u/project', } function hoverCard(node: SessionNode): void { @@ -962,7 +986,7 @@ describe('workspace browser rows', () => { const renderFactorySlot = vi.fn(renderMenuButton) const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const target = { kind: 'session', value: { sessionId: node.id, displayTitle: 'One' } } render( { : null const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const trigger = screen.getByRole('button', { name: '会话“One”的操作' }) @@ -1012,7 +1036,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('more-hover'), title: 'More hover', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } render() const row = screen.getByRole('treeitem') @@ -1037,7 +1061,7 @@ describe('workspace browser rows', () => { try { const node: SessionNode = { id: sid('action-hover'), title: 'Action hover', blank: false, running: false, - runningSubagentCount: 0, completed: false, updatedAt: 0, pinned: false, archived: false, + runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false, } const renderSlot: RowRenderSlot = (name: RowSlotName) => name === 'sidebar.workspaces.session.row.action' ?