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 a1044d0181..802e66d820 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 @@ -18,17 +18,17 @@ en: 821989170ad76994 zh: 0ed142bea166fc3a /agent-note-client-session-conversation-and-ui-ownership-layers/layering-principles/ui-adapters-own-react-integration: - en: 4d032e048364fb97 - zh: 82a435531efdaa78 + en: 4caab5487c8545f8 + zh: 77fa93f76b6fb65f /agent-note-client-session-conversation-and-ui-ownership-layers/layering-principles/slot-scopes-and-standard-props-are-separate: en: b6f585ca87e1fc6f zh: 53fd58c3e93cf17c /agent-note-client-session-conversation-and-ui-ownership-layers/package-ownership: - en: 2fc4b50a651b1847 - zh: 7dceeecb9c58e838 + en: 89f75f7cc2fe0e6c + zh: e50974fad3baf69c /agent-note-client-session-conversation-and-ui-ownership-layers/overall-data-flow: - en: e7c11e82db080dd4 - zh: 5a8a501a128366d6 + en: 002d9f406580684b + zh: a86742c6c943ac85 /agent-note-client-session-conversation-and-ui-ownership-layers/session-controller-client: en: b88f651b1bfb8b5e zh: b88f651b1bfb8b5e @@ -48,8 +48,8 @@ en: 860315b96703371d zh: 860315b96703371d /agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/service-responsibilities: - en: d075ba28fd37bff2 - zh: e2d430d1f3e89b15 + en: 40e598676f2d7f46 + zh: acc8e028978a5419 /agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/standard-source-registration: en: e4be6d4b1d79b342 zh: 7cb0e8c0f6358b50 @@ -60,8 +60,8 @@ en: 5d9bdb1f784f97f2 zh: a4b3de7a21b84fce /agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/pending-interactions: - en: 85e358a03ffac4ba - zh: 54b1d5ed6197f2c2 + en: 54b65fef1667278f + zh: cf46a8ad738a0a55 /agent-note-client-session-conversation-and-ui-ownership-layers/workspace-controller-and-ui-workspace: en: 45e5f41550e62a3d zh: d4e6d8f5b397bb51 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 0d2f19cff1..4ef7434535 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 @@ -57,7 +57,7 @@ Each standard hook belongs to the `ui-*` package closest to its data semantics. | `useSessions` | `client/ui-session` | Session Controller global list | | `useSession` | `client/ui-session` | Bound Session snapshot | | `useProjection` | `client/ui-session` | Bound Session keyed projection | -| `useSessionStatus` | `client/ui-session` | Running, effective pending request, and unread completion | +| `useSessionStatus` | `client/ui-session-status` | Running, effective pending request, and unread completion | | `useSessionRetainInfo` | `client/ui-session` | Read-only Controller reference-source counts | | `useWorkspaces` | `client/ui-workspace` | Workspace Controller list | | `useConversation` | `client/ui-conversation` | Conversation binding snapshot | @@ -80,7 +80,8 @@ 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 unified UI status | Session transport, reference ownership, Conversation assembly, Approval/Question results | +| `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-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 | @@ -120,7 +121,7 @@ Session data reaches the UI through this path: Workspace data enters the Workspace Controller from `ctx.remote.workspace`, then `ui-workspace` exposes it as `useWorkspaces`. `ui-workspace` reads explicit targets for cross-domain navigation and owns the main-area reference without making it a default business Context. -Approval and Question arrive from the Host waterfall through `ctx.remote.$on` at their respective UI owners. Each owner publishes a Pending object; `ui-session.sessionStatus` supplies the same effective object to Workspace indicators and Conversation composer selection. +Approval and Question arrive from the Host waterfall through `ctx.remote.$on` at their respective UI owners. Each owner publishes a Pending object through `ui-session`; `ctx.uiSession.sessionStatus` from `ui-session-status` supplies the same effective object to Workspace indicators and Conversation composer selection. ## Session Controller Client @@ -178,9 +179,9 @@ This cleanup does not require the Session Controller to know the roster of upper - supplies `SessionProvider` rendering semantics; - supplies built-in Session snapshot, projection, and sessionId sources; - accepts Session-scoped source contributions from other domain packages; -- aggregates domain-owned pending interactions with running and completion-reminder facts in `sessionStatus`. +- selects each Session's effective domain-owned pending interaction and publishes it read-only as `pendingInteractions`. -It does not own Session transport, event folding, Conversation targets, or concrete business results. +It does not own Session transport, event folding, Conversation targets, or concrete business results. `client/ui-session-status` combines the effective pending interactions with running and completion-reminder facts in the `uiSession.sessionStatus` service, read as `ctx.uiSession.sessionStatus`. ### Standard source registration @@ -221,7 +222,7 @@ Concurrent objects with the same key are rejected; replacement requests use a ne `ui-session` selects each Session's effective object using domain precedence. Higher precedence wins; at equal precedence, the later valid object in traversal order wins. -The pending aggregate is private to `ui-session`; its effective request appears unchanged as `sessionStatus.getSnapshot().get(id)?.pendingInteraction`. `useSessionStatus` is the public UI read face. +The pending aggregate is private to `ui-session`; `pendingInteractions` exposes each Session's effective request read-only, and the same object appears as `ctx.uiSession.sessionStatus.getSnapshot().get(id)?.pendingInteraction`. `useSessionStatus` is the public UI read face. Session navigation state and composer takeover read the same effective object. They do not maintain separate status maps or takeover rosters. 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 fdb2420eff..cf3b65492d 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 @@ -57,7 +57,7 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把 | `useSessions` | `client/ui-session` | Session Controller 全局列表 | | `useSession` | `client/ui-session` | 已绑定会话快照 | | `useProjection` | `client/ui-session` | 已绑定会话的键控投影 | -| `useSessionStatus` | `client/ui-session` | 运行状态、有效待处理请求和未读完成提醒 | +| `useSessionStatus` | `client/ui-session-status` | 运行状态、有效待处理请求和未读完成提醒 | | `useSessionRetainInfo` | `client/ui-session` | 控制器的只读引用来源计数 | | `useWorkspaces` | `client/ui-workspace` | Workspace Controller 列表 | | `useConversation` | `client/ui-conversation` | Conversation binding snapshot | @@ -80,7 +80,8 @@ 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` 与统一 UI 状态 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果 | +| `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与有效待处理交互 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果、统一 UI 状态 | +| `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 | @@ -120,7 +121,7 @@ Session 数据按以下路径进入 UI: Workspace 数据由 `ctx.remote.workspace` 进入 Workspace 控制器,再由 `ui-workspace` 通过 `useWorkspaces` 提供。`ui-workspace` 为跨领域导航读取显式目标并持有主区域引用,不把它变为默认业务 Context。 -Approval 与 Question 通过 `ctx.remote.$on` 从 Host waterfall 到达各自的 UI owner。各 owner 发布 Pending 对象;`ui-session.sessionStatus` 向 Workspace 标识和 Conversation composer 选择提供同一个有效对象。 +Approval 与 Question 通过 `ctx.remote.$on` 从 Host waterfall 到达各自的 UI owner。各 owner 通过 `ui-session` 发布 Pending 对象;`ui-session-status` 提供的 `ctx.uiSession.sessionStatus` 向 Workspace 标识和 Conversation composer 选择提供同一个有效对象。 ## Session Controller Client @@ -178,9 +179,9 @@ Session Controller 对外提供三个互不替代的读取面: - 提供 `SessionProvider` 的呈现语义; - 内建 session snapshot、projection 和 sessionId source; - 接收其他领域 package 的 Session-scoped source contribution; -- 在 `sessionStatus` 中组合领域持有的待处理交互、运行事实和完成提醒。 +- 为每个会话选出领域持有的有效待处理交互,并以只读的 `pendingInteractions` 发布。 -它不拥有 Session transport、event folding、Conversation target 或具体业务结果。 +它不拥有 Session transport、event folding、Conversation target 或具体业务结果。`client/ui-session-status` 在 `uiSession.sessionStatus` 服务中把有效待处理交互与运行事实、完成提醒组合起来,以 `ctx.uiSession.sessionStatus` 读取。 ### 标准 source 注册 @@ -221,7 +222,7 @@ Contribution roster 变化会重建已 materialize 的 binding 并发布新的 s `ui-session` 使用各 domain 的 precedence 选出每个 Session 当前生效的对象。较高 precedence 胜出,相同 precedence 下后遍历到的有效对象胜出。 -待处理聚合是 `ui-session` 的私有实现;其有效请求原样出现在 `sessionStatus.getSnapshot().get(id)?.pendingInteraction` 中。`useSessionStatus` 是公开 UI 读取接口。 +待处理聚合是 `ui-session` 的私有实现;`pendingInteractions` 以只读方式提供每个会话的有效请求,同一个对象原样出现在 `ctx.uiSession.sessionStatus.getSnapshot().get(id)?.pendingInteraction` 中。`useSessionStatus` 是公开 UI 读取接口。 Session 导航状态和 composer takeover 必须读取同一个 effective object,不得分别维护 status map 或 takeover roster。 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 f1173f2864..12ad701c1e 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 @@ -12,8 +12,8 @@ en: a15c7c13f167e5ac zh: 63bcc2ef60c2f344 /agent-note-client-session-references-reference-sources-and-ui-status/decision/scope-and-ownership: - en: 3f04f9c2b7b0fc2b - zh: ebfcbac3de8463a3 + en: 9ff7f15985d06986 + zh: fe27ef687594c124 /agent-note-client-session-references-reference-sources-and-ui-status/decision/addresses-bindings-and-references: en: 3743abc8bca00348 zh: d79e6a9311f0a2fe @@ -24,8 +24,8 @@ en: e2de83d10542f93b zh: 3855b38fc8c48ea3 /agent-note-client-session-references-reference-sources-and-ui-status/decision/unified-ui-session-status: - en: 2d75aef5cf5f1fc8 - zh: 87a7051f24f9871a + en: 07ea04b9ca50dd8f + zh: e025fcea4c9f0fb9 /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 83f2ec688b..ac8eb95cf7 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 @@ -21,7 +21,8 @@ Client Session objects, Agent-scoped Client Contexts, references, consumer-sourc | Owner | Responsibility | | --- | --- | | Client Session Controller | Catalog, live generations, references, source counts, bindings, history windows, and existing Session control state | -| `ui-session` | Explicit Session Provider integration and the unified UI status source | +| `ui-session` | Explicit Session Provider integration and the effective pending-interaction source | +| `ui-session-status` | The unified UI status source | | View or operation | Its own reference, target, source identifier, and release point | | Workspace UI | Main-area target and reference, navigation, persisted target, and creation flow | | UI composition boundary | Supplies an owner-provided reference to one explicit `SessionProvider` | @@ -89,7 +90,7 @@ Window-level consumers may inspect source markers. Session business operations s ### Unified UI Session status -`ui-session` owns a React-free `sessionStatus` source and exposes it through the standard `useSessionStatus` hook. The snapshot is indexed by Session identity and supplies one UI status record per known Session. It combines these independent facts rather than reducing them to one mutually exclusive phase: +`ui-session-status` owns the React-free `uiSession.sessionStatus` service, read as `ctx.uiSession.sessionStatus`, and exposes it through the standard `useSessionStatus` hook. The snapshot is indexed by Session identity and supplies one UI status record per known Session. It combines these independent facts rather than reducing them to one mutually exclusive phase: | Field | Value | Meaning and owner | | --- | --- | --- | @@ -99,7 +100,7 @@ Window-level consumers may inspect source markers. Session business operations s 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. 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. +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: 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 542def8a76..3a4168f4c4 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 @@ -21,7 +21,8 @@ Client Session 对象、Agent 作用域的 Client Context、引用、使用方 | 所有者 | 职责 | | --- | --- | | Client Session Controller | 目录、活跃代、引用、来源计数、binding、历史窗口与既有 Session 控制状态 | -| `ui-session` | 显式 Session Provider 集成与统一 UI 状态来源 | +| `ui-session` | 显式 Session Provider 集成与有效待处理交互来源 | +| `ui-session-status` | 统一 UI 状态来源 | | 视图或操作 | 自己的引用、目标、来源标识与释放时机 | | Workspace UI | 主区域目标与引用、导航、持久目标及创建流程 | | UI 组合边界 | 将所有者提供的引用交给一个明确的 `SessionProvider` | @@ -89,7 +90,7 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源 ### 统一的 UI Session 状态 -`ui-session` 拥有不依赖 React 的 `sessionStatus` 来源,通过标准 `useSessionStatus` 钩子公开。快照按 Session 身份索引,为每个已知 Session 提供一条 UI 状态记录。它组合下列独立事实,不将它们压缩成互斥的单一阶段: +`ui-session-status` 拥有不依赖 React 的 `uiSession.sessionStatus` 服务,以 `ctx.uiSession.sessionStatus` 读取,并通过标准 `useSessionStatus` 钩子公开。快照按 Session 身份索引,为每个已知 Session 提供一条 UI 状态记录。它组合下列独立事实,不将它们压缩成互斥的单一阶段: | 字段 | 取值 | 含义与所有者 | | --- | --- | --- | @@ -99,7 +100,7 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源 来源计数以 `SessionListState.byId[id].retainedBy` 为准;UI 状态读取它以执行确认策略,不维护另一套引用注册表。标题、Workspace 关联、历史、队列和投影数据保留在各自的既有所有者中。 -待处理领域保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。 +待处理领域在 `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 已消失。更新规则如下: diff --git a/apps/web/tests/expected/forge-panel/extension-annotations.expected.md b/apps/web/tests/expected/forge-panel/extension-annotations.expected.md new file mode 100644 index 0000000000..dcb20c165d --- /dev/null +++ b/apps/web/tests/expected/forge-panel/extension-annotations.expected.md @@ -0,0 +1,126 @@ +- img "变更请求状态:需要处理" +- text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 +- button "提交评审" +- button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 6" [checked] + - radio "接口 1" + - radio "实现 2" + - radio "测试 3" +- button "全部 6 个文件" +- switch "隐藏测试文件" +- button "筛选透镜": 透镜 +- button "笔记 2" [pressed] +- progressbar "已审阅的文件": 已审阅 0 / 6 +- text: +8 −2 +- button "刷新变更" +- button "全部折叠" +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- button "将文件树移到右侧" [expanded] +- region "全部 6 个文件": + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" + - button "panel.md 的更多操作" + - strong: 笔记 + - text: 已看过此文件 + - button "移除" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. + - button "收起 schema.json" [expanded] + - text: docs/schema.json 新文件 +1 −0 + - checkbox "将 schema.json 标记为已审阅" + - button "schema.json 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ { \"type\": \"object\" }" + - button "收起 zh.json" [expanded] + - text: locale/zh.json 新文件 +1 −0 + - checkbox "将 zh.json 标记为已审阅" + - button "zh.json 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ { \"title\": \"面板\" }" + - button "收起 panel.spec.ts" [expanded] + - text: src/panel.spec.ts 新文件 +1 −0 + - checkbox "将 panel.spec.ts 标记为已审阅" + - button "panel.spec.ts 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ it('shows the panel', () => {})" + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - strong: 笔记 + - text: Check the quoted value + - button "移除" + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" + - button "收起 package.json" [expanded] + - text: package.json 新文件 +1 −0 + - checkbox "将 package.json 标记为已审阅" + - button "package.json 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ { \"name\": \"demo\" }" +- separator "调整文件树宽度" +- navigation "全部 6 个文件": + - textbox "筛选文件…" + - button "docs" [expanded] + - button "docs/panel.md": panel.md +2 −0 + - button "docs/schema.json": schema.json +1 −0 + - button "locale" [expanded] + - button "locale/zh.json": zh.json +1 −0 + - button "src" [expanded] + - button "src/panel.spec.ts": panel.spec.ts +1 −0 + - button "src/panel.ts": panel.ts +2 −2 + - button "package.json": package.json +1 −0 diff --git a/apps/web/tests/expected/forge-panel/extension-lens.expected.md b/apps/web/tests/expected/forge-panel/extension-lens.expected.md new file mode 100644 index 0000000000..e1ec761358 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/extension-lens.expected.md @@ -0,0 +1,81 @@ +- img "变更请求状态:需要处理" +- text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 +- button "提交评审" +- button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 1" [checked] + - radio "接口 0" + - radio "实现 1" + - radio "测试 0" +- button "全部 1 个文件" +- switch "隐藏测试文件" +- button "筛选透镜:导出": 导出 1 +- button "笔记 0" [pressed] +- progressbar "已审阅的文件": 已审阅 0 / 1 +- text: +2 −2 +- button "刷新变更" +- button "全部折叠" +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- button "将文件树移到右侧" [expanded] +- region "全部 1 个文件": + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" +- separator "调整文件树宽度" +- navigation "全部 1 个文件": + - textbox "筛选文件…" + - button "src" [expanded] + - button "src/panel.ts": panel.ts +2 −2 diff --git a/apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js b/apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js new file mode 100644 index 0000000000..102c1240b7 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js @@ -0,0 +1,117 @@ +/** + * Client half of the forge extension fixture: the title of the Host lens, and notes pinned through every forge slot — + * a comment form action pins a line note, a file menu row pins a file note, each note shows as a line annotation, a + * toolbar toggle hides them, and a card button opens the change request's changes view with the lens chosen. + */ +window.__ModuleLoader__.load({ + id: '@fixture/forge-extension', + factory(require) { + const React = require('react') + const { Button, MenuItemButton, Tooltip } = require('@deepseek-ai/dsh-client-ui-primitives') + const h = React.createElement + const NS = 'fixtureForge' + return { + inject: ['slots', 'locale', 'forgeChanges'], + apply(ctx) { + ctx.effect(() => ctx.locale.register(NS, { + zh: { + lens: '导出', pin: '钉为笔记', pinFile: '钉上文件笔记', fileNote: '已看过此文件', notes: '笔记 {count}', toggle: '显示或隐藏笔记', + note: '笔记', remove: '移除', open: '打开导出视图', + }, + en: { + lens: 'Exports', pin: 'Pin as note', pinFile: 'Pin a file note', fileNote: 'Looked at this file', notes: 'Notes {count}', + toggle: 'Show or hide notes', note: 'Note', remove: 'Remove', open: 'Open the exports view', + }, + })) + const t = ctx.locale.bind(NS) + ctx.effect(() => ctx.forgeChanges.describeLens({ id: 'fixture/exports', title: () => t('lens') })) + + // Notes of each changes view by address; the observable a view reads publishes nothing while its notes hide. + const views = new Map() + let sequence = 0 + const viewOf = (target) => { + const address = ctx.forgeChanges.address(target) + let view = views.get(address) + if (view === undefined) { + const listeners = new Set() + const state = { notes: [], shown: true, snapshot: new Map() } + const publish = () => { + const byPath = new Map() + if (state.shown) { + for (const note of state.notes) byPath.set(note.path, [...(byPath.get(note.path) ?? []), note.annotation]) + } + state.snapshot = byPath + for (const listener of [...listeners]) listener() + } + view = { + state, + observable: { + getSnapshot: () => state.snapshot, + subscribe: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } }, + }, + add(path, place, text) { + sequence += 1 + state.notes = [...state.notes, { path, text, annotation: { key: `note-${sequence}`, place, version: 1 } }] + publish() + }, + remove(key) { + state.notes = state.notes.filter(note => note.annotation.key !== key) + publish() + }, + toggle() { + state.shown = !state.shown + publish() + }, + textOf: key => state.notes.find(note => note.annotation.key === key)?.text ?? '', + listeners, + } + views.set(address, view) + } + return view + } + ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'fixture-notes', observe: target => viewOf(target).observable })) + + function useNotes(target) { + const view = viewOf(target) + React.useSyncExternalStore(view.observable.subscribe, view.observable.getSnapshot) + return view + } + function NotesToggle({ target, form, close }) { + const view = useNotes(target) + const label = t('notes', { count: view.state.notes.length }) + if (form === 'menu') return h(MenuItemButton, { onSelect: () => { view.toggle(); close() } }, label) + return h(Tooltip, { label: t('toggle'), side: 'bottom' }, + h('button', { type: 'button', 'data-fixture-notes-toggle': '', 'aria-pressed': view.state.shown, onClick: () => { view.toggle() }, + style: { height: 28, padding: '0 8px', border: 0, borderRadius: 8, background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer' } }, label)) + } + function PinNote({ target, selection, empty, busy, send }) { + return h(Button, { size: 'sm', variant: 'outline', disabled: empty || busy, 'data-fixture-pin': '', + onClick: () => { send(async (body) => { viewOf(target).add(selection.path, { side: selection.side, startLine: selection.startLine, endLine: selection.endLine }, body); return undefined }) } }, + t('pin')) + } + function NoteBody({ target, annotation }) { + const view = useNotes(target) + return h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px' }, 'data-fixture-note': annotation.key }, + h('strong', { style: { fontWeight: 500 } }, t('note')), + h('span', { style: { flex: 1, minWidth: 0 } }, view.textOf(annotation.key)), + h(Button, { size: 'sm', variant: 'outline', onClick: () => { view.remove(annotation.key) } }, t('remove'))) + } + function PinFileNote({ target, file, dismiss }) { + return h(MenuItemButton, { onSelect: () => { viewOf(target).add(file.path, 'file', t('fileNote')); dismiss() } }, t('pinFile')) + } + function OpenExports({ url, ref, sessionId }) { + if (ref === null) return null + return h(Tooltip, { label: t('open'), side: 'top' }, + h('button', { type: 'button', 'aria-label': t('open'), 'data-fixture-open-exports': '', + onClick: () => { ctx.forgeChanges.open({ sessionId, source: { kind: 'change', url } }, { lens: 'fixture/exports' }) }, + style: { width: 24, height: 24, border: 0, borderRadius: 6, background: 'transparent', color: 'inherit', cursor: 'pointer' } }, '⎇')) + } + ctx.slots.inject('forge.changes.toolbar', () => ctx.slots.register({ name: 'forge.changes.toolbar', id: 'fixture-notes', locale: NS }, NotesToggle)) + ctx.slots.inject('forge.diff.comment.actions', () => ctx.slots.register({ name: 'forge.diff.comment.actions', id: 'fixture-notes', locale: NS }, PinNote)) + ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register({ name: 'forge.diff.line.annotation', key: 'fixture-notes', locale: NS }, NoteBody)) + ctx.slots.inject('forge.changes.file.menu', () => ctx.slots.register({ name: 'forge.changes.file.menu', id: 'fixture-notes', locale: NS }, PinFileNote)) + ctx.slots.inject('forge.change-request.card.actions', () => ctx.slots.register({ name: 'forge.change-request.card.actions', id: 'fixture-notes', locale: NS }, OpenExports)) + }, + } + }, +}) diff --git a/apps/web/tests/fixtures/plugins/fixture-forge-extension/cordis.patch.yml b/apps/web/tests/fixtures/plugins/fixture-forge-extension/cordis.patch.yml new file mode 100644 index 0000000000..7d1de129bc --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-forge-extension/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: fixture-forge-extension + name: '@fixture/forge-extension' diff --git a/apps/web/tests/fixtures/plugins/fixture-forge-extension/index.js b/apps/web/tests/fixtures/plugins/fixture-forge-extension/index.js new file mode 100644 index 0000000000..2b23936b82 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-forge-extension/index.js @@ -0,0 +1,27 @@ +/** Host half of the forge extension fixture: a filter lens that keeps the files whose new side has `export` lines, about those lines. */ +export const name = '@fixture/forge-extension' +export const inject = ['forgePanel'] + +/** @param {import('@deepseek-ai/cordis').Context} ctx */ +export function apply(ctx) { + ctx.forgePanel.registerLens({ + id: 'fixture/exports', + version: '1', + async classify(input, signal) { + const files = {} + let done = 0 + for (const file of input.files) { + const text = await input.text('new', file.path, signal) + done += 1 + input.progress(done, input.files.length) + if (text === null) continue + const ranges = [] + text.split('\n').forEach((line, index) => { + if (/^export\b/.test(line)) ranges.push({ start: index + 1, end: index + 1 }) + }) + if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } } + } + return { files } + }, + }) +} diff --git a/apps/web/tests/fixtures/plugins/fixture-forge-extension/package.json b/apps/web/tests/fixtures/plugins/fixture-forge-extension/package.json new file mode 100644 index 0000000000..96e72088f6 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-forge-extension/package.json @@ -0,0 +1,22 @@ +{ + "name": "@fixture/forge-extension", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "index.js", + "exports": { + ".": "./index.js", + "./client": "./client.js" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-experimental-client-ui-forge" + ] + } + } +} diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 98a8ceed8e..138ca12506 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -26,6 +26,8 @@ declare global { } const BUNDLE = fileURLToPath(new URL('../../../packages/experimental/forge-bundle', import.meta.url)) +/** A plugin that uses the forge extension API: a Host lens, line annotations, and every forge slot. */ +const EXTENSION = fileURLToPath(new URL('./fixtures/plugins/fixture-forge-extension', import.meta.url)) const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v4.jsonl', import.meta.url)) const EXPECTED = fileURLToPath(new URL('./expected/forge-panel', import.meta.url)) const MODE = webSnapshotMode() @@ -471,11 +473,19 @@ interface PanelLaunch { * Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace. * @param failureShot - name of the screenshot saved when the test fails. * @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup through `bash` or a PTC program. - * @param options - desktop transport, checkout branch, browser input, sandbox runner availability, and diff output limit. + * @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, and + * whether the extension fixture plugin loads. * @returns the scaffold, page, and checkout. */ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' | 'ptc-reference' = 'normal', - options: { desktop?: 'darwin' | 'win32'; branch?: string; hasTouch?: boolean; missingSandbox?: boolean; maxDiffBytes?: number } = {}): Promise { + options: { + desktop?: 'darwin' | 'win32' + branch?: string + hasTouch?: boolean + missingSandbox?: boolean + maxDiffBytes?: number + extension?: boolean + } = {}): Promise { const { desktop } = options const resources: { scaffold?: WebScaffold; browser?: Browser } = {} const root = await mkdtemp(join(tmpdir(), 'dsh-forge-panel-')) @@ -517,7 +527,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' ] })) } const scaffold = await launchWebScaffold({ - profile: { packages: [{ dir: BUNDLE, enabled: true }] }, + profile: { packages: [{ dir: BUNDLE, enabled: true }, ...options.extension === true ? [{ dir: EXTENSION, enabled: true }] : []] }, extraOverlayPath: overlay, replayFixture: FIXTURE, ...scenario !== 'normal' ? { replayOverride: override } : {}, @@ -1946,6 +1956,65 @@ async function shownPaths(view: ReturnType): Promise<(string | return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))) } +it.skipIf(MODE === 'record')('lets a plugin filter the changes by its lens, annotate lines and files, and act from the toolbar, comment form, and card', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-extension', 'normal', { extension: true }) + await writeReviewFixture(root) + // The plugin's lens keeps the export lines; past line 9 the head's src/panel.ts has none, so its second hunk folds. + const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record + contents[`src/panel.ts@${HEAD7}`] = `${Array.from({ length: 20 }, (_, index) => index < 9 ? panelLine(index + 1, 'new') + : panelLine(index + 1, 'new').replace(/^export /, '')).join('\n')}\n` + await writeFile(join(root, 'contents.json'), JSON.stringify(contents)) + const { settled } = await sendPrompt(page, scaffold) + const session = scaffold.ctx.sessions.get(await settled) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + + // The card button the plugin adds opens the changes view with its lens chosen. + await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '打开导出视图', exact: true }).click() + await page.getByRole('button', { name: '全屏', exact: true }).click() + const view = page.locator('[data-forge-changes="change"]') + const lens = view.locator('[data-forge-filter-lens]') + await expect.poll(() => lens.getAttribute('data-forge-filter-lens'), { timeout: 20_000 }).toBe('fixture/exports') + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['src/panel.ts']) + await expect.poll(() => lens.textContent()).toBe('导出1') + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + const fold = panel.locator('[data-forge-lens-fold]') + await expect.poll(() => fold.textContent()).toBe('另有 1 处与「导出」无关的改动已折叠展开') + await fold.click() + await expect.poll(() => fold.count()).toBe(0) + await panel.locator('[data-review-code][data-new-line="15"]').waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'extension-lens.expected.md'), + await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + + await lens.click() + await page.getByRole('menuitem', { name: '不使用透镜', exact: true }).click() + await expect.poll(() => shownPaths(view)).toHaveLength(6) + + // The comment form's plugin button pins the comment as a line note; the toolbar toggle hides and shows the notes. + await panel.getByRole('button', { name: '选择第 R2 行', exact: true }).click() + await panel.getByRole('button', { name: '添加评论', exact: true }).click() + await panel.getByRole('textbox', { name: '留下评论…', exact: true }).fill('Check the quoted value') + await panel.getByRole('button', { name: '钉为笔记', exact: true }).click() + const note = panel.locator('[data-forge-annotation^="fixture-notes/"]') + await expect.poll(() => note.textContent()).toBe('笔记Check the quoted value移除') + const toggle = view.locator('[data-fixture-notes-toggle]') + await expect.poll(() => toggle.textContent()).toBe('笔记 1') + await toggle.click() + await expect.poll(() => note.count()).toBe(0) + await toggle.click() + await expect.poll(() => note.count()).toBe(1) + + // The file menu's plugin row pins a note on the whole file. + const docs = view.locator('[data-forge-diff-file="docs/panel.md"]') + await docs.getByRole('button', { name: 'panel.md 的更多操作', exact: true }).click() + await page.getByRole('menuitem', { name: '钉上文件笔记', exact: true }).click() + await expect.poll(() => docs.locator('[data-forge-annotation^="fixture-notes/"]').textContent()).toBe('笔记已看过此文件移除') + await compareOrRefreshGolden(join(EXPECTED, 'extension-annotations.expected.md'), + await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) +}) + it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => { const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers') await writeReviewFixture(root) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index cb969a6156..5a4576282b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1101,7 +1101,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:483`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1148,6 +1148,14 @@ export interface Config { * request's update time does not change when a thread is resolved. */ reviewRefreshMs?: number + /** Deadline in milliseconds for one lens `classify` call. */ + lensTimeoutMs?: number + /** Most UTF-8 bytes of file text one lens `classify` call may read. */ + maxLensReadBytes?: number + /** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */ + maxCachedLensBytes?: number + /** Most line annotations a changes view shows in one file, across every annotation source. */ + maxAnnotationsPerFile?: number } ``` @@ -1213,7 +1221,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -5121,6 +5129,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-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 aade14ce04..b6515259e8 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1103,7 +1103,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:483`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1150,6 +1150,14 @@ export interface Config { * request's update time does not change when a thread is resolved. */ reviewRefreshMs?: number + /** Deadline in milliseconds for one lens `classify` call. */ + lensTimeoutMs?: number + /** Most UTF-8 bytes of file text one lens `classify` call may read. */ + maxLensReadBytes?: number + /** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */ + maxCachedLensBytes?: number + /** Most line annotations a changes view shows in one file, across every annotation source. */ + maxAnnotationsPerFile?: number } ``` @@ -1215,7 +1223,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -5123,6 +5131,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-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/cookbook/extension-cookbook.i18n.yaml b/docs/cookbook/extension-cookbook.i18n.yaml index ff778ef2c5..38b6d95941 100644 --- a/docs/cookbook/extension-cookbook.i18n.yaml +++ b/docs/cookbook/extension-cookbook.i18n.yaml @@ -17,6 +17,9 @@ /cookbook-extension-plugin-shapes/an-external-protocol-driver: en: fc5e0d074214eaaf zh: aac2bf67d6e7b30a +/cookbook-extension-plugin-shapes/a-forge-review-extension: + en: 63267f9317969d16 + zh: 9a0ce54da348509a /cookbook-extension-plugin-shapes/runnable-wirings: en: f0a28d07c0bb4d1b zh: 840962f512cb4031 diff --git a/docs/cookbook/extension-cookbook.md b/docs/cookbook/extension-cookbook.md index 7e960a85f5..2e737467ba 100644 --- a/docs/cookbook/extension-cookbook.md +++ b/docs/cookbook/extension-cookbook.md @@ -91,6 +91,49 @@ export function apply(ctx: Context) { } ``` +## A forge review extension + +Change request review opens to plugins through the [forge extension API](../subsystems/forge.md#extension-api). A Host plugin registers a filter lens, which keeps some of the files a changes view shows and names the lines it is about: + +```ts +import type { Context } from '@deepseek-ai/cordis' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { ForgeLensId } from '@deepseek-ai/dsh-experimental-client-ui-forge' + +export const name = 'exports-lens' +export const inject = ['forgePanel'] + +export function apply(ctx: Context) { + // An effect of this plugin's fiber: unloading the plugin withdraws the lens and aborts its runs. + ctx.forgePanel.registerLens({ + id: brandString('example/exports'), + version: '1', + async classify(input, signal) { + const files: Record = {} + for (const file of input.files) { + const lines = (await input.text('new', file.path, signal))?.split('\n') ?? [] + const ranges = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : []) + if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } } + } + return { files } + }, + }) +} +``` + +A Client plugin names that lens and adds line annotations; `notesOf` returns one stable observable per view, and `NoteBody` is a module-scope component that draws one annotation inside the frame the view draws. The forge tests' [fixture plugin](../../apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js) also uses the toolbar, file menu, comment form, and card slots. + +```ts ignore-check +export const inject = ['forgeChanges', 'slots'] + +export function apply(ctx: Context) { + ctx.effect(() => ctx.forgeChanges.describeLens({ id: brandString('example/exports'), title: () => 'Exports' })) + ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'example-notes', observe: target => notesOf(target) })) + ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register( + { name: 'forge.diff.line.annotation', key: 'example-notes' }, NoteBody)) +} +``` + ## Runnable wirings Shipped applications contribute profile layers through `packages/bundle/*/cordis.patch.yml`, and the product `dsh` launcher owns Web, ACP, SDK, and one-shot headless execution through named profiles. Optional user-facing overlays live under `apps/cli/config/examples/`; profile integration tests live under `apps/cli/tests/profiles/`, while package-specific Loader compositions stay with their package tests. diff --git a/docs/cookbook/extension-cookbook.zh.md b/docs/cookbook/extension-cookbook.zh.md index 04eaa40533..c255eb78fe 100644 --- a/docs/cookbook/extension-cookbook.zh.md +++ b/docs/cookbook/extension-cookbook.zh.md @@ -93,6 +93,49 @@ export function apply(ctx: Context) { } ``` +## Forge 评审扩展 + +变更请求评审经由 [forge 扩展 API](../subsystems/forge.zh.md#extension-api) 向插件开放。Host 插件注册一个筛选透镜,它保留变更视图所显示文件中的一部分,并给出它关心的行: + +```ts +import type { Context } from '@deepseek-ai/cordis' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { ForgeLensId } from '@deepseek-ai/dsh-experimental-client-ui-forge' + +export const name = 'exports-lens' +export const inject = ['forgePanel'] + +export function apply(ctx: Context) { + // An effect of this plugin's fiber: unloading the plugin withdraws the lens and aborts its runs. + ctx.forgePanel.registerLens({ + id: brandString('example/exports'), + version: '1', + async classify(input, signal) { + const files: Record = {} + for (const file of input.files) { + const lines = (await input.text('new', file.path, signal))?.split('\n') ?? [] + const ranges = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : []) + if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } } + } + return { files } + }, + }) +} +``` + +Client 插件给这个透镜起名并添加行注解;`notesOf` 为每个视图返回一个稳定的可观察对象,`NoteBody` 是模块级组件,在视图所画的外框中绘制一条注解。forge 测试的[夹具插件](../../apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js)还用到了工具栏、文件菜单、评论框和卡片的 slot。 + +```ts ignore-check +export const inject = ['forgeChanges', 'slots'] + +export function apply(ctx: Context) { + ctx.effect(() => ctx.forgeChanges.describeLens({ id: brandString('example/exports'), title: () => 'Exports' })) + ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'example-notes', observe: target => notesOf(target) })) + ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register( + { name: 'forge.diff.line.annotation', key: 'example-notes' }, NoteBody)) +} +``` + ## 可运行的组装示例 交付应用通过 `packages/bundle/*/cordis.patch.yml` 提供 profile 层,产品 `dsh` 启动器通过具名 profile 负责 Web、ACP、SDK 与一次性 headless 执行。可选的用户 overlay 位于 `apps/cli/config/examples/`;profile 集成测试位于 `apps/cli/tests/profiles/`,包专属 Loader 组合则留在对应包的测试目录中。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 4103ecd11d..aa42c78c51 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,7 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b55b06e507..bdda966741 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,7 +49,8 @@ | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 623e1664ff..64461120cc 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -193,6 +193,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_status["client-ui-session-status"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"] @@ -1521,6 +1522,7 @@ flowchart TD pkg_client_test_runtime --> pkg_client_ui_conversation pkg_client_test_runtime --> pkg_client_ui_renderer pkg_client_test_runtime --> pkg_client_ui_session + pkg_client_test_runtime --> pkg_client_ui_session_status pkg_client_test_runtime --> pkg_client_ui_settings pkg_client_test_runtime --> pkg_client_ui_slots pkg_client_test_runtime --> pkg_client_web @@ -1634,6 +1636,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-status`](../packages/client/ui-session-status) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | | [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — | @@ -1928,7 +1931,7 @@ flowchart TD | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | +| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fd754de0b4..d483b75dd1 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -195,6 +195,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_status["client-ui-session-status"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"] @@ -1523,6 +1524,7 @@ flowchart TD pkg_client_test_runtime --> pkg_client_ui_conversation pkg_client_test_runtime --> pkg_client_ui_renderer pkg_client_test_runtime --> pkg_client_ui_session + pkg_client_test_runtime --> pkg_client_ui_session_status pkg_client_test_runtime --> pkg_client_ui_settings pkg_client_test_runtime --> pkg_client_ui_slots pkg_client_test_runtime --> pkg_client_web @@ -1636,6 +1638,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-status`](../packages/client/ui-session-status) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | | [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — | @@ -1930,7 +1933,7 @@ flowchart TD | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | +| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 9702f4429c..d8461f092c 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -24,5 +24,8 @@ en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: 0e0348e9a38215ed - zh: affcc0231e15d682 + en: 7dcefe2825490257 + zh: 38cec4d1ae3b0d6e +/forges/extension-api: + en: f35345e482e84f4f + zh: 2ecb7d9498decb31 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index d153e4f634..cc8922729a 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -101,6 +101,12 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Find the merge base of commits `base` and `head` in the change request's repository, as a full object name: the + * commit whose files the old side of a change request's diff shows. Omission declares that the provider cannot name + * it, so readers of the old side get `unsupported`. + */ + mergeBase?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise /** * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a @@ -928,6 +934,11 @@ interface ForgePanelWorktree { interface ForgePanelChangeRequest extends SessionChangeRequest { /** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */ readonly snapshot: ChangeRequestSnapshot | null + /** + * Number of review changes `forge/review-changed` announced for the change request since the panel host started; it + * grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it. + */ + readonly reviewRevision: number } ``` @@ -1187,6 +1198,120 @@ interface ForgeLocalChanges { } ``` + + +## Extension API + +Other plugins extend change request review through the services above and five more extension points; each registration returns its disposer and ends with the plugin that made it. The surface is experimental and pre-stable like the rest of this capability. Adding an optional field, method, slot, event, error code, or defaulted Config key is compatible; removing or renaming a type, method, slot, owner prop, event, Config key, or the `dsh-resource://forge-changes/` address, or narrowing what one means, needs an [upgrade guide](../../.agents/skills/dsh-create-upgrade-guide/SKILL.md). None of these extension points sends anything to a model: a plugin that shows forge data, lens results, or annotations to a model does so through its own tool results or `agent.inject()`, which the Session log records. + +| Extension point | Service Definition | Service Provider | Consumer | +|---|---|---|---| +| Review data | `ctx.forge` and the `forge/review-changed` event | The forge providers | The panel host and other Host plugins | +| Filter lenses | `ctx.forgePanel.registerLens` | Host plugins | The changes view through `changesLens` | +| Changes view face | `ctx.forgeChanges` | The forge panel's Client plugin | Client plugins that open views, name lenses, and add annotations | +| Slots | `forge.changes.toolbar`, `forge.changes.file.menu`, `forge.diff.line.annotation`, `forge.diff.comment.actions`, `forge.change-request.card.actions` | Client plugins | The changes view and the change request card | +| Session data | The `forgeChangeRequests` and `forgeWorktree` projections | forge-session and the forge panel | Client plugins through `useProjection`, Host plugins through `ctx.forgeSession.changeRequests` or `ctx.sessionProjections.snapshot` | + +`ctx.forge` announces `forge/review-changed` after a review write, a submitted review, or a viewed mark the host accepted, whichever plugin made it; an outcome that is unknown, refused, stale, or unsupported is not announced. The panel host then drops the threads it keeps for the change request and raises `reviewRevision` on its entries, so an open changes view reads the threads and the viewed marks again without a refresh. + +```ts type-equiv +/** + * One review change the host accepted, which `forge/review-changed` announces: a write to the threads or the pending + * review, a submitted review, or a viewed mark. Each names the head commit the change was made against. + */ +type ForgeReviewChange = + | { readonly kind: 'write'; readonly write: ForgeReviewWrite['kind']; readonly headSha: string } + | { readonly kind: 'submit'; readonly headSha: string } + | { readonly kind: 'viewed'; readonly path: string; readonly viewed: boolean; readonly headSha: string } +``` + +A Host plugin registers a filter lens with `ctx.forgePanel.registerLens(lens)`, and a Client plugin names it with `ctx.forgeChanges.describeLens({ id, title })`; a lens without a description shows its identity. A lens filters the shown files and does not place them in layers: the changes view shows the files that both the chosen layer and the chosen lens keep, the test switch still hides test files, and a lens cannot move a file to another layer. Hunks that meet none of a kept file's `ranges` fold into one row the reader can expand. The view asks for the chosen lens only, through the streaming Remote `changesLens`, which reads the same files as the view, refuses other files with `forgePanel/lens-stale`, and runs `classify` within `lensTimeoutMs` and `maxLensReadBytes`; results are kept up to `maxCachedLensBytes`. `text` reads a local old side at the fork point, HEAD, the index, or the parent of the first chosen commit, and a change request's old side at the chosen commits' parent or at the merge base its provider names through the optional `mergeBase`. + +```ts type-equiv +/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */ +interface ForgeLens { + /** Identity the plugin chooses; one registration holds an id at a time. */ + readonly id: ForgeLensId + /** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */ + readonly version: string + /** + * Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the + * registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result. + */ + classify(input: ForgeLensInput, signal: AbortSignal): Promise +} +``` + +```ts type-equiv +/** What one `classify` call receives. */ +interface ForgeLensInput { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order, with the layer the panel gave it. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to + * null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not + * in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot + * locate, and when the read fails. + */ + text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise + /** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */ + progress(done: number, total: number): void +} +``` + +```ts type-equiv +/** The files a lens keeps, by path; a file the result does not name is filtered out. */ +interface ForgeLensResult { + readonly files: Readonly> +} +``` + +```ts type-equiv +/** What a lens keeps of one file. */ +interface ForgeLensKeep { + /** + * Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand. + * Omitted: every hunk of the file shows. + */ + readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] } +} +``` + +`ctx.forgeChanges` also mints and reads changes addresses, names the tab `kinds`, and opens a view with `open(target, { path, lens })` in the Session the sidebar shows. `registerAnnotations(source)` adds line annotations: the source observes each view's annotations by path, and its `forge.diff.line.annotation` entry, keyed by the source's identity, draws each one inside a frame the view draws. Annotations stack on the row of their last line after the comment form, the browser drafts, and the host threads, in the column of their side; whole-file annotations come first, and those written on another `digest` follow the file in their own section. A file shows at most `maxAnnotationsPerFile`, and a file that draws its lines draws no annotation before its section comes within reach of the scrollport. The owner props of every slot live in [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts). + +```ts type-equiv +/** Where one line annotation sits in a file of a changes view. */ +interface ForgeLineAnnotation { + /** Identity within its source, stable across updates; it keys the drawn entry. */ + readonly key: string + /** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */ + readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file' + /** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */ + readonly digest?: string + /** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */ + readonly version: string | number +} +``` + +```ts type-equiv +/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */ +interface ForgeAnnotationSource { + /** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */ + readonly id: string + /** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number + /** + * Observe the annotations of one view, by path. The changes view calls it once per view and source registration; + * the source republishes through the same observable whenever the annotations change. + * @param target - the view's Session and source. + * @returns annotations by repository-relative path. + */ + observe(target: ChangesTarget): HostObservable> +} +``` + @@ -1355,7 +1480,7 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P /** * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then * poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls - * it as a stale read does. + * it as a stale read does; a write the host took is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param write - the write and the head commit the user saw. * @param signal - cancellation of the write. @@ -1379,7 +1504,8 @@ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): /** * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still - * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved + * mark is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - the file, its mark, and the head commit the user saw. * @param signal - cancellation of the request. @@ -1410,7 +1536,21 @@ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * Publish one comment or a completed review, then refresh the watched status. + * Find the merge base of two commits of a change request's repository: the commit whose files the old side of the + * change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`. + * @param ref - change request served by a registered provider. + * @param base - full object name of the base commit. + * @param head - full object name of the head commit. + * @param signal - cancellation of the read. + * @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider + * cannot name merge bases. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + +/** + * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced + * with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - explicitly selected commit, comments, and review decision. * @param signal - request cancellation. @@ -1658,6 +1798,40 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending + * the registration aborts its running classifications and waits for them. + * @param lens - the lens. + * @returns the disposer that unregisters the lens and waits for its classifications to stop. + * @throws when another registration holds `lens.id`. + */ +registerLens(lens: ForgeLens): () => Promise + +/** + * Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts + * after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns the registered lenses and the annotation limit, in publication order. + */ +@Remote({ mode: 'stream' }) async *extensions(signal: AbortSignal): AsyncIterable + +/** + * Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens + * runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until + * `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files + * are those `changeRequestDiff` reads. + * @param session - Session whose checkout or binding the view shows. + * @param request - the view's source, the version of the files it shows, and the lens. + * @param signal - ends the classification. + * @returns progress frames, then one result frame. + * @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends; + * `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and + * when local files changed while the lens ran; + * `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers + * over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files. + */ +@Remote({ mode: 'stream' }) async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable + /** * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the * whole change request. @@ -1971,5 +2145,25 @@ Announces a provider registration or withdrawal after the registry changes. List 'forge/providers-changed'(forge: string): void | Promise ``` +Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts) + + + +#### `forge/review-changed` — parallel + +Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. Listener failures are logged without preventing other listeners from running. + +```ts cordis-catalog +/** + * Announces a review change the host accepted through this service: a thread or pending-review write, a submitted + * review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. + * Listener failures are logged without preventing other listeners from running. + * @param ref - change request the change went to. + * @param change - what changed and the head commit it was made against. + * @mode parallel + */ +'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise +``` + Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts) diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 707adff7b9..167f4ba646 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -101,6 +101,12 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Find the merge base of commits `base` and `head` in the change request's repository, as a full object name: the + * commit whose files the old side of a change request's diff shows. Omission declares that the provider cannot name + * it, so readers of the old side get `unsupported`. + */ + mergeBase?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise /** * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a @@ -930,6 +936,11 @@ interface ForgePanelWorktree { interface ForgePanelChangeRequest extends SessionChangeRequest { /** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */ readonly snapshot: ChangeRequestSnapshot | null + /** + * Number of review changes `forge/review-changed` announced for the change request since the panel host started; it + * grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it. + */ + readonly reviewRevision: number } ``` @@ -1189,6 +1200,120 @@ interface ForgeLocalChanges { } ``` + + +## 扩展 API + +其他插件通过上面的服务和另外五个扩展点扩展变更请求评审;每次注册都返回 disposer,并随做出注册的插件一起结束。与这一能力的其余部分一样,这些接口处于实验阶段,尚未稳定。新增可选字段、方法、slot、事件、错误码或带默认值的 Config 键是兼容的;删除或改名类型、方法、slot、owner props、事件、Config 键或 `dsh-resource://forge-changes/` 地址,或收窄其含义,需要写[升级指南](../../.agents/skills/dsh-create-upgrade-guide/SKILL.md)。这些扩展点都不向模型发送任何内容:插件要让模型看到 forge 数据、透镜结果或注解,须经由它自己的工具结果或 `agent.inject()`,Session log 会记录它们。 + +| 扩展点 | Service Definition | Service Provider | Consumer | +|---|---|---|---| +| 评审数据 | `ctx.forge` 与 `forge/review-changed` 事件 | 各 forge 提供方 | 面板 Host 与其他 Host 插件 | +| 筛选透镜 | `ctx.forgePanel.registerLens` | Host 插件 | 经 `changesLens` 使用它的变更视图 | +| 变更视图接口 | `ctx.forgeChanges` | forge 面板的 Client 插件 | 打开视图、给透镜起名、添加注解的 Client 插件 | +| Slot | `forge.changes.toolbar`、`forge.changes.file.menu`、`forge.diff.line.annotation`、`forge.diff.comment.actions`、`forge.change-request.card.actions` | Client 插件 | 变更视图与变更请求卡片 | +| Session 数据 | `forgeChangeRequests` 与 `forgeWorktree` 投影 | forge-session 与 forge 面板 | Client 插件经 `useProjection` 读取,Host 插件经 `ctx.forgeSession.changeRequests` 或 `ctx.sessionProjections.snapshot` 读取 | + +托管平台接受一次评审写入、一次评审提交或一个已审阅标记后,`ctx.forge` 发出 `forge/review-changed`,无论是哪个插件做的;结果未知、被拒绝、已过时或不支持时不发出。面板 Host 随后丢弃为该变更请求保留的讨论,并让对应条目的 `reviewRevision` 加一,因此已打开的变更视图无需刷新就会重新读取讨论和已审阅标记。 + +```ts type-equiv +/** + * One review change the host accepted, which `forge/review-changed` announces: a write to the threads or the pending + * review, a submitted review, or a viewed mark. Each names the head commit the change was made against. + */ +type ForgeReviewChange = + | { readonly kind: 'write'; readonly write: ForgeReviewWrite['kind']; readonly headSha: string } + | { readonly kind: 'submit'; readonly headSha: string } + | { readonly kind: 'viewed'; readonly path: string; readonly viewed: boolean; readonly headSha: string } +``` + +Host 插件用 `ctx.forgePanel.registerLens(lens)` 注册筛选透镜,Client 插件用 `ctx.forgeChanges.describeLens({ id, title })` 给它起名;没有名字的透镜显示其身份。透镜筛选显示的文件,不给文件分层:变更视图显示所选分层与所选透镜都保留的文件,测试文件开关仍然隐藏测试文件,透镜也不能把文件移到另一层。被保留文件中与 `ranges` 都不相交的 hunk 折叠成一行,读者可以展开。视图只请求所选的透镜,经流式 Remote `changesLens` 进行:它读取与视图相同的文件,文件不同时以 `forgePanel/lens-stale` 拒绝,并在 `lensTimeoutMs` 与 `maxLensReadBytes` 之内运行 `classify`;结果最多保留 `maxCachedLensBytes`。`text` 在分叉点、HEAD、暂存区或第一个所选提交的父提交上读取本地变更的旧侧,在所选提交的父提交上,或在提供方经可选的 `mergeBase` 给出的合并基准上读取变更请求的旧侧。 + +```ts type-equiv +/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */ +interface ForgeLens { + /** Identity the plugin chooses; one registration holds an id at a time. */ + readonly id: ForgeLensId + /** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */ + readonly version: string + /** + * Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the + * registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result. + */ + classify(input: ForgeLensInput, signal: AbortSignal): Promise +} +``` + +```ts type-equiv +/** What one `classify` call receives. */ +interface ForgeLensInput { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order, with the layer the panel gave it. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to + * null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not + * in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot + * locate, and when the read fails. + */ + text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise + /** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */ + progress(done: number, total: number): void +} +``` + +```ts type-equiv +/** The files a lens keeps, by path; a file the result does not name is filtered out. */ +interface ForgeLensResult { + readonly files: Readonly> +} +``` + +```ts type-equiv +/** What a lens keeps of one file. */ +interface ForgeLensKeep { + /** + * Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand. + * Omitted: every hunk of the file shows. + */ + readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] } +} +``` + +`ctx.forgeChanges` 还可以生成和解析变更视图地址,给出标签的 `kinds`,并用 `open(target, { path, lens })` 在侧栏所显示的 Session 中打开视图。`registerAnnotations(source)` 添加行注解:数据源按路径观察每个视图的注解,它在 `forge.diff.line.annotation` 中按数据源身份登记的条目,负责绘制视图所画外框里的内容。注解放在其最后一行之后,位于评论框、浏览器草稿和托管平台讨论之后,落在所在一侧的那一栏;整个文件的注解排在最前,写在另一个 `digest` 上的注解在文件之后单独成段。每个文件最多显示 `maxAnnotationsPerFile` 条;逐行绘制的文件在文件段进入可视区附近之前不绘制注解。所有 slot 的 owner props 见 [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts)。 + +```ts type-equiv +/** Where one line annotation sits in a file of a changes view. */ +interface ForgeLineAnnotation { + /** Identity within its source, stable across updates; it keys the drawn entry. */ + readonly key: string + /** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */ + readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file' + /** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */ + readonly digest?: string + /** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */ + readonly version: string | number +} +``` + +```ts type-equiv +/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */ +interface ForgeAnnotationSource { + /** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */ + readonly id: string + /** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number + /** + * Observe the annotations of one view, by path. The changes view calls it once per view and source registration; + * the source republishes through the same observable whenever the annotations change. + * @param target - the view's Session and source. + * @returns annotations by repository-relative path. + */ + observe(target: ChangesTarget): HostObservable> +} +``` + @@ -1357,7 +1482,7 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P /** * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then * poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls - * it as a stale read does. + * it as a stale read does; a write the host took is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param write - the write and the head commit the user saw. * @param signal - cancellation of the write. @@ -1381,7 +1506,8 @@ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): /** * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still - * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved + * mark is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - the file, its mark, and the head commit the user saw. * @param signal - cancellation of the request. @@ -1412,7 +1538,21 @@ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * Publish one comment or a completed review, then refresh the watched status. + * Find the merge base of two commits of a change request's repository: the commit whose files the old side of the + * change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`. + * @param ref - change request served by a registered provider. + * @param base - full object name of the base commit. + * @param head - full object name of the head commit. + * @param signal - cancellation of the read. + * @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider + * cannot name merge bases. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + +/** + * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced + * with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - explicitly selected commit, comments, and review decision. * @param signal - request cancellation. @@ -1660,6 +1800,40 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending + * the registration aborts its running classifications and waits for them. + * @param lens - the lens. + * @returns the disposer that unregisters the lens and waits for its classifications to stop. + * @throws when another registration holds `lens.id`. + */ +registerLens(lens: ForgeLens): () => Promise + +/** + * Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts + * after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns the registered lenses and the annotation limit, in publication order. + */ +@Remote({ mode: 'stream' }) async *extensions(signal: AbortSignal): AsyncIterable + +/** + * Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens + * runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until + * `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files + * are those `changeRequestDiff` reads. + * @param session - Session whose checkout or binding the view shows. + * @param request - the view's source, the version of the files it shows, and the lens. + * @param signal - ends the classification. + * @returns progress frames, then one result frame. + * @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends; + * `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and + * when local files changed while the lens ran; + * `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers + * over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files. + */ +@Remote({ mode: 'stream' }) async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable + /** * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the * whole change request. @@ -1973,5 +2147,25 @@ Announces a provider registration or withdrawal after the registry changes. List 'forge/providers-changed'(forge: string): void | Promise ``` +Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts) + + + +#### `forge/review-changed` — parallel + +Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. Listener failures are logged without preventing other listeners from running. + +```ts cordis-catalog +/** + * Announces a review change the host accepted through this service: a thread or pending-review write, a submitted + * review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. + * Listener failures are logged without preventing other listeners from running. + * @param ref - change request the change went to. + * @param change - what changed and the head commit it was made against. + * @mode parallel + */ +'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise +``` + Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts) diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 7d02bb4794..5f34f8ce71 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -18,8 +18,8 @@ en: 278b2eee160be413 zh: d6e0fd1e9f4a4b27 /web-client-slots/framework-provided-hooks: - en: c9f8d836214623ae - zh: 76dec55006396535 + en: e1090f50013a2483 + zh: fd8db6ff6d4d0936 /web-client-slots/developer-provided-injection: en: 3481dfa6cd3097da zh: acbd6f06a7da1752 diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index 820bd90171..dea9b7cbec 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -106,7 +106,8 @@ The shipped adapters add these standard props. They are available according to t | Availability | Props | Owner | |---|---|---| -| every scope | `useSessions`, `useSessionStatus`, `useSessionRetainInfo`, `useSessionAccess` | `ui-session` | +| every scope | `useSessions`, `useSessionRetainInfo`, `useSessionAccess` | `ui-session` | +| every scope | `useSessionStatus` | `ui-session-status` | | every scope | `useWorkspaces`, `useWorkspaceAccess` | `ui-workspace` | | every scope | `useRemoteAccess` (the `global` resource) | `api-remote-access` | | every scope | `usePanelInfo` | `ui-layout` | diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 69456901eb..ecb1455470 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -108,7 +108,8 @@ hoc entry 是以必填 `id` 和可选 `key` 寻址的一层。不带 `key` 的 | 可用范围 | Props | Owner | |---|---|---| -| 所有 scope | `useSessions`、`useSessionStatus`、`useSessionRetainInfo`、`useSessionAccess` | `ui-session` | +| 所有 scope | `useSessions`、`useSessionRetainInfo`、`useSessionAccess` | `ui-session` | +| 所有 scope | `useSessionStatus` | `ui-session-status` | | 所有 scope | `useWorkspaces`、`useWorkspaceAccess` | `ui-workspace` | | 所有 scope | `useRemoteAccess`(`global` 资源) | `api-remote-access` | | 所有作用域 | `usePanelInfo` | `ui-layout` | diff --git a/docs/subsystems/web-client.i18n.yaml b/docs/subsystems/web-client.i18n.yaml index f201ba2f7e..4ff473259e 100644 --- a/docs/subsystems/web-client.i18n.yaml +++ b/docs/subsystems/web-client.i18n.yaml @@ -24,8 +24,8 @@ en: c063711f8247c240 zh: 5e54758bbaf1670c /web-client-architecture/conversation-and-presentation: - en: 9a22492f0d4359c6 - zh: 55d449e383e88f62 + en: f37ba948a8838fb0 + zh: df19542d87860221 /web-client-architecture/data-paths: en: a254278432416473 zh: 567c2d3c6a20b304 diff --git a/docs/subsystems/web-client.md b/docs/subsystems/web-client.md index 93f2fbdf1d..fbdaecf3d5 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`, `useSessionStatus`, `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. 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 completion reminders. 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. diff --git a/docs/subsystems/web-client.zh.md b/docs/subsystems/web-client.zh.md index 3c0c0da5bb..50ef3f9146 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`、`useSessionStatus`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。领域 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。 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 new file mode 100644 index 0000000000..b2225275ad --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/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/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 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 new file mode 100644 index 0000000000..c4fdfe189a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md @@ -0,0 +1,28 @@ +--- +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." +--- + +# Session status moves to `@deepseek-ai/dsh-client-ui-session-status` + +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. + +`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`. + +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. + +This affects Client plugins and tests that import the three status types, 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. +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. 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 new file mode 100644 index 0000000000..8403fc5f48 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md @@ -0,0 +1,28 @@ +--- +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 服务。" +--- + +# 会话状态移到 `@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。 + +`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`。 + +待交互仍归 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 插件和测试。 + +## 迁移 + +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`。 +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. 确认插件通过类型检查,并且会话行仍显示运行或等待标记。 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index e842d8e3e1..47049ce8de 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -276,6 +276,10 @@ - id: ui-session name: '@deepseek-ai/dsh-client-ui-session' + # Session status table behind ctx.uiSession.sessionStatus and useSessionStatus. + - id: ui-session-status + name: '@deepseek-ai/dsh-client-ui-session-status' + # Unified resource model: protocol providers behind the useResource hook. - id: resources name: '@deepseek-ai/dsh-client-resources' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index eccc864be4..3d630df1e0 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -110,6 +110,7 @@ "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", "@deepseek-ai/dsh-client-ui-secret-mask": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-agent-loop": "workspace:*", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index f77d3835d7..0ae9892b80 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: 2165938f26300774 - zh: 5f739534a8509545 + en: 292a25cf1a426b56 + zh: ca765789a28289f8 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 3047a181c1..c7744a38b3 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -39,6 +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-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 e327a717d9..67fba60515 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -39,6 +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-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/ui-chat/package.json b/packages/client/ui-chat/package.json index 76ab087eaa..99b09c1836 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -75,6 +75,7 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-browser": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:*", diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 4cd6d1bb24..71e5dc672e 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -28,7 +28,7 @@ import type { } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import { SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { KeyedSnapshotSelectorHook, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' import { allowAllAccess, bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' diff --git a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx index ca6d67f0f3..e13eb58f65 100644 --- a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { allowAllAccess, bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index 330dad8d18..3b9b445457 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -35,6 +35,7 @@ "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-session", + "@deepseek-ai/dsh-client-ui-session-status", "@deepseek-ai/dsh-client-ui-settings", "@deepseek-ai/dsh-client-ui-workspace", "@deepseek-ai/dsh-client-ui-context-menu" @@ -67,6 +68,7 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 37420f7fc2..4f292f0ece 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -12,6 +12,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { ShortcutCommandId, ShortcutFixedCommand } from '@deepseek-ai/dsh-client-shortcuts/client' import { UiConversation } from './conversation/assembly.ts' @@ -58,9 +59,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -/** Services required by the Conversation plugin. */ +/** + * Services required by the Conversation plugin. `uiSession.sessionStatus` provides the `useSessionStatus` hook the + * Conversation shell renders with, so the plugin unloads and reloads with it. + */ export const inject = [ - 'slots', 'sessions', 'fileUpload', 'uiSession', 'uiWorkspace', 'locale', 'configForms', + 'slots', 'sessions', 'fileUpload', 'uiSession', 'uiSession.sessionStatus', 'uiWorkspace', 'locale', 'configForms', ] /** Conversation runtime configuration. */ diff --git a/packages/client/ui-conversation/src/client/stop-shortcut.ts b/packages/client/ui-conversation/src/client/stop-shortcut.ts index b410a06918..f9b7520073 100644 --- a/packages/client/ui-conversation/src/client/stop-shortcut.ts +++ b/packages/client/ui-conversation/src/client/stop-shortcut.ts @@ -11,7 +11,7 @@ import { StopSequence } from './stop-sequence.ts' * @param shortcuts - window keyboard arbitration and validated sequence interval. * @param sessions - live Session identities and lifecycle sources. * @param openTurn - stable current-turn source for a live Session binding. - * @param uiSession - current pending-interaction status. + * @param uiSession - effective pending interaction of each Session. * @param cancel - scoped stop operation that preserves Queue and reports failures. * @returns disposer releasing the input subscription, pending watches and expiry timer. */ @@ -47,7 +47,7 @@ export function installStopShortcut( const session = binding.session.getSnapshot() if (!session.running || session.removed || (session.subagent !== null && session.subagent.address.mode !== 'continuable') - || uiSession.sessionStatus.getSnapshot().get(sessionId)?.pendingInteraction !== undefined) return undefined + || uiSession.pendingInteractions.getSnapshot().get(sessionId) !== undefined) return undefined return turnSource.getSnapshot() } const turn = currentTurn() @@ -58,7 +58,7 @@ export function installStopShortcut( const changed = (): void => { if (sessions.binding(sessionId) !== binding || currentTurn() !== turn) reset() } - const disposers = [turnSource.subscribe(changed), binding.session.subscribe(changed), uiSession.sessionStatus.subscribe(changed)] + const disposers = [turnSource.subscribe(changed), binding.session.subscribe(changed), uiSession.pendingInteractions.subscribe(changed)] unwatch = () => { for (const dispose of disposers) dispose() } }) return () => { off(); reset() } diff --git a/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx b/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx index 3106eeb495..5f203d14d9 100644 --- a/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx +++ b/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx @@ -6,7 +6,7 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { allowAllAccess, bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { EnterBehaviorRow } from '../src/client/settings/EnterBehaviorRow.tsx' import type { EnterBehaviorRowProps } from '../src/client/settings/EnterBehaviorRow.tsx' diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index dd7143f188..cca80d2934 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -16,7 +16,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { allowAllAccess, bindSnapshotSelector, conversationSnapshot, sessionSnapshot, } from '@deepseek-ai/dsh-client-test-runtime' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SubmitAttachment, SubmitOutcome } from '../src/client/contract/input.ts' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index aed6c05c2a..1f73eaf740 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -29,7 +29,7 @@ import type { import { allowAllAccess, bindSnapshotSelector, conversationSnapshot, makeTranslate, sessionSnapshot, SlotTestRuntime, } from '@deepseek-ai/dsh-client-test-runtime' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { DraftAttachmentId } from '../src/client/contract/input.ts' diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 713c74df88..7c048d5ee9 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -20,7 +20,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { allowAllAccess, bindSnapshotSelector, conversationSnapshot, makeTranslate, } from '@deepseek-ai/dsh-client-test-runtime' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { InputState } from '../src/client/contract/input.ts' import { zh } from '../src/client/locales.ts' diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 6f599b2d22..e8c20dde27 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -12,7 +12,7 @@ import { allowAllAccess, bindSnapshotSelector, makeTranslate, RemoteError, sessionSnapshot as sessionFixture, } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' diff --git a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts index 73dd206b6c..f1f93856f1 100644 --- a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts +++ b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts @@ -137,6 +137,17 @@ describe('fixed stop routing', () => { expect(b.cancel).toHaveBeenCalledOnce() }) + it("keeps this Session's double-Escape sequence when another Session gains a pending interaction", async () => { + const b = await bench() + const publish = b.runtime.ctx.uiSession.registerPendingInteraction(() => 0) + b.press() + const remove = publish({ kind: 'approval', key: 'request-other', sessionId: 's2' as SessionId }, async () => {}) + b.press() + await Promise.resolve() + expect(b.cancel).toHaveBeenCalledOnce() + remove() + }) + it('excludes terminal, iframe, approval and inert descendants even inside Conversation', async () => { const b = await bench() for (const [tag, attribute] of [['div', 'class'], ['iframe', ''], ['div', 'data-approval-key'], ['div', 'inert']]) { diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index c75fd6b50d..fd72dbc593 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -18,6 +18,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../ui-session-status" + }, { "path": "../../api/workspace-controller/tsconfig.client.json" }, diff --git a/packages/client/ui-session-status/README.i18n.yaml b/packages/client/ui-session-status/README.i18n.yaml new file mode 100644 index 0000000000..bdce0fb16c --- /dev/null +++ b/packages/client/ui-session-status/README.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for README.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 packages/client/ui-session-status/README.md +/: + en: 11efe93e9b428342 + zh: 56d90a359ee86ad5 +/deepseek-ai-dsh-client-ui-session-status: + en: d572f680cca905e6 + zh: 7c397a1fb746b47f +/deepseek-ai-dsh-client-ui-session-status/summary: + en: a3e8fe090a557c9b + zh: 782500fb80b92712 +/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 +/deepseek-ai-dsh-client-ui-session-status/model-experience: + en: 687076082426c060 + zh: 5888fcd520d0e53e +/deepseek-ai-dsh-client-ui-session-status/model-experience/kv-cache-effect: + en: 99bd3bc7d244944a + zh: 0021893ed90b2686 +/deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work: + en: 52d467a078cc3486 + zh: c373685b879ad6de +/deepseek-ai-dsh-client-ui-session-status/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/client/ui-session-status/README.md b/packages/client/ui-session-status/README.md new file mode 100644 index 0000000000..6973059556 --- /dev/null +++ b/packages/client/ui-session-status/README.md @@ -0,0 +1,63 @@ +--- +description: "Client Session status table and useSessionStatus hook: running state, the effective pending interaction, and completion reminders by Session." +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. + +## Table of Contents + +- [Status table](#status-table) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Status table + +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. + +| 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 | + +Each `SessionStatus` has three independent 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. | + + +## Model Experience + +None, as the status table adds no tools, prompts, or Session events. + +#### KV Cache effect + +None; the status table does 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. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/ui-session-status/README.zh.md b/packages/client/ui-session-status/README.zh.md new file mode 100644 index 0000000000..fa79a8c760 --- /dev/null +++ b/packages/client/ui-session-status/README.zh.md @@ -0,0 +1,63 @@ +--- +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) +- [模型体验](#model-experience) +- [已知限制与暂缓事项](#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 的值看不到它。 + +| 成员 | 用途 | +|---|---| +| `getSnapshot()` | 按 Session 身份索引的状态;状态事实变化前快照保持同一引用 | +| `subscribe(listener)` | 观察已发布的变化;抛错的 listener 会被报告,不会阻止后续 listener | + +每个 `SessionStatus` 有三个相互独立的字段: + +| 字段 | 来源 | +|---|---| +| `running` | Host 会话列表基线和 `api-session/status` 事件;两者都未建立之前为缺省。Subagent 目录行和已保留子会话的 fallback 行不会建立它。 | +| `pendingInteraction` | `ctx.uiSession.pendingInteractions` 为该 Session 发布的同一个对象。领域插件仍通过 `ctx.uiSession.registerPendingInteraction(precedence)` 登记请求。 | +| `completionUnread` | 本 Client 在主视图未保留该 Session 时观察到的一次停止,包括首个列表基线之前到达的空闲事件。主视图保留该 Session、该 Session 再次运行,或就绪列表不再包含它时,提醒清除。 | + + +## 模型体验 + +无,因为状态表不添加工具、提示词或 Session 事件。 + +#### KV Cache 影响 + +无;状态表不会组装模型请求。 + +## 已知限制与暂缓事项 + + + +- **完成提醒只属于一个 Client**——另一个浏览器标签页或刷新后的页面不会带上本 Client 记录的提醒。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/client/ui-session-status/locale/de.json b/packages/client/ui-session-status/locale/de.json new file mode 100644 index 0000000000..ecae7fda9a --- /dev/null +++ b/packages/client/ui-session-status/locale/de.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Sitzungsstatus" + } +} diff --git a/packages/client/ui-session-status/locale/en.json b/packages/client/ui-session-status/locale/en.json new file mode 100644 index 0000000000..fe1fd31399 --- /dev/null +++ b/packages/client/ui-session-status/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Session status" + } +} diff --git a/packages/client/ui-session-status/locale/es.json b/packages/client/ui-session-status/locale/es.json new file mode 100644 index 0000000000..b72cf90667 --- /dev/null +++ b/packages/client/ui-session-status/locale/es.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Estado de la sesión" + } +} diff --git a/packages/client/ui-session-status/locale/fr.json b/packages/client/ui-session-status/locale/fr.json new file mode 100644 index 0000000000..0c28b2cd64 --- /dev/null +++ b/packages/client/ui-session-status/locale/fr.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Statut de la session" + } +} diff --git a/packages/client/ui-session-status/locale/ja.json b/packages/client/ui-session-status/locale/ja.json new file mode 100644 index 0000000000..8a346e88b5 --- /dev/null +++ b/packages/client/ui-session-status/locale/ja.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "セッションの状態" + } +} diff --git a/packages/client/ui-session-status/locale/pt.json b/packages/client/ui-session-status/locale/pt.json new file mode 100644 index 0000000000..3530cb1df7 --- /dev/null +++ b/packages/client/ui-session-status/locale/pt.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Estado da sessão" + } +} diff --git a/packages/client/ui-session-status/locale/ru.json b/packages/client/ui-session-status/locale/ru.json new file mode 100644 index 0000000000..6277db877a --- /dev/null +++ b/packages/client/ui-session-status/locale/ru.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Статус сеанса" + } +} diff --git a/packages/client/ui-session-status/locale/zh.json b/packages/client/ui-session-status/locale/zh.json new file mode 100644 index 0000000000..2d9703a9f7 --- /dev/null +++ b/packages/client/ui-session-status/locale/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "会话状态" + } +} diff --git a/packages/client/ui-session-status/package.json b/packages/client/ui-session-status/package.json new file mode 100644 index 0000000000..be3bba1317 --- /dev/null +++ b/packages/client/ui-session-status/package.json @@ -0,0 +1,69 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-session-status", + "description": "Client Session status table: running state, the effective pending interaction, and completion reminders", + "version": "0.2.2-rc.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-session-status" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-api-session-controller", + "@deepseek-ai/dsh-client-ui-renderer", + "@deepseek-ai/dsh-client-ui-session" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "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:*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ] +} diff --git a/packages/client/ui-session-status/src/client/index.ts b/packages/client/ui-session-status/src/client/index.ts new file mode 100644 index 0000000000..588d5a2ba7 --- /dev/null +++ b/packages/client/ui-session-status/src/client/index.ts @@ -0,0 +1,21 @@ +/** Client Session status plugin: the `uiSession.sessionStatus` service and the `useSessionStatus` root hook. */ +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 { 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'] + +/** + * Install `ctx.uiSession.sessionStatus` and publish it through the `useSessionStatus` root hook. + * @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 } }) +} diff --git a/packages/client/ui-session-status/src/client/status.ts b/packages/client/ui-session-status/src/client/status.ts new file mode 100644 index 0000000000..0e514f9033 --- /dev/null +++ b/packages/client/ui-session-status/src/client/status.ts @@ -0,0 +1,162 @@ +/** Client Session status table: running state, the effective pending interaction, and completion reminders. */ +import { Service, type Context } from '@deepseek-ai/cordis' +import type { ISessions, 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' +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' + +/** Independent UI status facts for one Session identity. */ +export interface SessionStatus { + /** Latest known running state; absent until a baseline or event establishes it. */ + 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. */ + readonly completionUnread: boolean +} + +/** Current UI status indexed by Session identity. */ +export type SessionStatusSnapshot = ReadonlyMap +/** Selector hook over the unified Session UI status snapshot. */ +export type UseSessionStatus = SnapshotSelectorHook + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface GlobalStandardProps { + useSessionStatus: UseSessionStatus + } +} + +declare module '@deepseek-ai/dsh-client-ui-session/client' { + interface UiSessionService { + /** Session status table; a plugin that reads it injects `uiSession.sessionStatus`. */ + readonly sessionStatus: UiSessionStatus + } +} + +/** + * 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. + */ +export class UiSessionStatus extends Service implements HostObservable { + private readonly running = new Map() + private readonly completionUnread = new Set() + private statusSnapshot: SessionStatusSnapshot = new Map() + private readonly statusListeners = new Set<() => void>() + + /** + * @param ctx - Client root context. + * @param sessions - Controller-owned Session catalog. + * @param pendingInteractions - effective pending request by Session, published by ui-session. + */ + constructor( + ctx: Context, + private readonly sessions: Pick, + private readonly pendingInteractions: HostObservable>, + ) { + super(ctx, 'uiSession.sessionStatus') + 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() }) + this.reconcileStatus() + return () => { + disposeStatus() + disposeRemoteStatus() + disposePending() + } + }, 'session-status: Session status table') + } + + /** + * Read the current status table; the reference changes only when a status fact changes. + * @returns status by Session identity. + */ + readonly getSnapshot: () => SessionStatusSnapshot = () => this.statusSnapshot + + /** + * Observe status table changes; a throwing listener is reported without stopping later listeners. + * @param listener - called after each published change. + * @returns unsubscribe. + */ + readonly subscribe: (listener: () => void) => () => void = (listener) => { + this.statusListeners.add(listener) + return () => { this.statusListeners.delete(listener) } + } + + 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() + } + + private reconcileStatus(): void { + const list = this.sessions.list.getSnapshot() + const present = new Set(Object.keys(list.byId) as SessionId[]) + // Subagent catalog rows and retained subagent fallback rows do not establish Host running state. + for (const id of list.ids) { + const row = list.byId[id] as SessionSummary + const previous = this.running.get(id) + if (previous === undefined) this.running.set(id, row.running) + else if (previous !== row.running) this.observeRunning(id, row.running) + } + for (const id of present) { + if (this.isMain(id)) this.completionUnread.delete(id) + } + if (list.phase === 'ready') { + for (const id of this.running.keys()) { + if (present.has(id)) continue + this.running.delete(id) + this.completionUnread.delete(id) + } + } + this.publishStatus() + } + + private isMain(sessionId: SessionId): boolean { + return (this.sessions.list.getSnapshot().byId[sessionId]?.retainedBy.mainView ?? 0) > 0 + } + + private publishStatus(): void { + const pending = this.pendingInteractions.getSnapshot() + const ids = new Set([ + ...(Object.keys(this.sessions.list.getSnapshot().byId) as SessionId[]), + ...this.running.keys(), + ...pending.keys(), + ...this.completionUnread, + ]) + const next = new Map() + for (const id of ids) { + next.set(id, { + running: this.running.get(id), + pendingInteraction: pending.get(id), + completionUnread: this.completionUnread.has(id), + }) + } + if (sameSessionStatus(this.statusSnapshot, next)) return + this.statusSnapshot = next + notifySubscribers(this.statusListeners, '[session-status] Session status') + } +} + +function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean { + if (left.size !== right.size) return false + for (const [id, status] of left) { + const candidate = right.get(id) + if (candidate === undefined + || candidate.running !== status.running + || candidate.pendingInteraction !== status.pendingInteraction + || candidate.completionUnread !== status.completionUnread) return false + } + return true +} diff --git a/packages/client/ui-session-status/src/index.ts b/packages/client/ui-session-status/src/index.ts new file mode 100644 index 0000000000..cb1b451cca --- /dev/null +++ b/packages/client/ui-session-status/src/index.ts @@ -0,0 +1,4 @@ +/** Host loader entry for the browser-only Session status plugin. */ + +/** Provides no Host-side behavior. */ +export function apply(): void {} diff --git a/packages/client/ui-session-status/tests/consumer-lifecycle.client.spec.tsx b/packages/client/ui-session-status/tests/consumer-lifecycle.client.spec.tsx new file mode 100644 index 0000000000..168b7ac405 --- /dev/null +++ b/packages/client/ui-session-status/tests/consumer-lifecycle.client.spec.tsx @@ -0,0 +1,42 @@ +// @vitest-environment jsdom +/** Plugins that render `useSessionStatus` follow the status table's plugin lifecycle in the real Loader and renderer. */ +import { act } from '@testing-library/react' +import { expect, onTestFinished, vi } from 'vitest' +import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' + +const STATUS = '@deepseek-ai/dsh-client-ui-session-status' +const WORKSPACE = '@deepseek-ai/dsh-client-ui-workspace' +const CONVERSATION = '@deepseek-ai/dsh-client-ui-conversation' + +const it = createClientTest({ roster: webApp.closure([WORKSPACE, CONVERSATION]) }, { mount: true }) + +it('unloads hook consumers with the status table and renders them again after it reloads', async ({ start }) => { + const errors = vi.spyOn(console, 'error') + onTestFinished(() => { errors.mockRestore() }) + const client = await start() + const entry = (name: string) => [...client.ctx.loader.entries()].find(candidate => candidate.options.name === name) + // Each consumer provides its own service only while its plugin is active. + const consumers = () => [client.ctx.get('uiWorkspace') !== undefined, client.ctx.get('uiConversation') !== undefined] + const slotText = (name: string) => client.container!.querySelector(`[data-slot="${name}"]`)?.textContent ?? '' + const status = entry(STATUS) + if (status === undefined) throw new Error(`${STATUS} is not in the roster`) + + expect(consumers()).toEqual([true, true]) + expect(slotText('sidebar.workspaces')).toContain('Workspaces') + expect(slotText('main.conversation')).toContain('Choose a workspace to start') + + await act(async () => { await status.update({ disabled: true }) }) + await client.flush() + + expect(consumers()).toEqual([false, false]) + expect(slotText('sidebar.workspaces')).not.toContain('Workspaces') + expect(slotText('main.conversation')).not.toContain('Choose a workspace to start') + + await act(async () => { await status.update({ disabled: false }) }) + await client.flush() + + expect(consumers()).toEqual([true, true]) + expect(slotText('sidebar.workspaces')).toContain('Workspaces') + expect(slotText('main.conversation')).toContain('Choose a workspace to start') + expect(errors).not.toHaveBeenCalled() +}, 60_000) diff --git a/packages/client/ui-session/tests/status-controller.client.spec.ts b/packages/client/ui-session-status/tests/status-controller.client.spec.ts similarity index 61% rename from packages/client/ui-session/tests/status-controller.client.spec.ts rename to packages/client/ui-session-status/tests/status-controller.client.spec.ts index e2e75adede..3a7e2543ab 100644 --- a/packages/client/ui-session/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session-status/tests/status-controller.client.spec.ts @@ -1,11 +1,13 @@ -/** Running-state ownership across the real Controller catalog and UI status source. */ +/** Session status across the real Controller catalog, ui-session pending interactions, and the status service. */ import { expect, vi } from 'vitest' 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' import type { SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types' +import type { SessionPendingInteractionBase } from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '../src/client/index.ts' -const it = createClientTest({ roster: webApp.closure(['@deepseek-ai/dsh-client-ui-session']) }) +const it = createClientTest({ roster: webApp.closure(['@deepseek-ai/dsh-client-ui-session-status']) }) const parentId = 'status-parent' as SessionId const childId = 'status-child' as SessionId @@ -29,37 +31,48 @@ it('preserves unlisted child status through metadata updates and main view ackno }) const client = await start() const sessions = client.ctx.sessions - const ui = client.ctx.uiSession + const status = client.ctx.uiSession.sessionStatus await sessions.refresh() await sessions.refreshProjections(parentId) await client.flush() expect(sessions.list.getSnapshot().ids).toEqual([parentId]) expect(sessions.binding(childId)).toBeUndefined() - expect(ui.sessionStatus.getSnapshot().get(childId)).toMatchObject({ running: undefined, completionUnread: false }) + expect(status.getSnapshot().get(childId)).toMatchObject({ running: undefined, completionUnread: false }) mock.streams.push('$events', { type: 'emit', event: 'api-session/status', args: [childId, true] }) await mock.streams.drained('$events') await client.flush() - expect(ui.sessionStatus.getSnapshot().get(childId)).toMatchObject({ running: true, completionUnread: false }) + expect(status.getSnapshot().get(childId)).toMatchObject({ running: true, completionUnread: false }) mock.streams.push('$events', { type: 'emit', event: 'api-session/activity', args: [parentId, 2] }) await mock.streams.drained('$events') await client.flush() expect(sessions.list.getSnapshot().byId[parentId]?.updatedAt).toBe(2) - expect(ui.sessionStatus.getSnapshot().get(childId)).toMatchObject({ running: true, completionUnread: false }) + expect(status.getSnapshot().get(childId)).toMatchObject({ running: true, completionUnread: false }) mock.streams.push('$events', { type: 'emit', event: 'api-session/status', args: [childId, false] }) await mock.streams.drained('$events') await client.flush() - expect(ui.sessionStatus.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: true }) + 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) await vi.waitFor(() => { - expect(ui.sessionStatus.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: false }) + expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: false }) }) reference.release() await client.flush() - expect(ui.sessionStatus.getSnapshot().get(childId)?.completionUnread).toBe(false) + expect(status.getSnapshot().get(childId)?.completionUnread).toBe(false) +}) + +it('reports the effective ui-session pending interaction as the same request object', async ({ start }) => { + const client = await start() + const status = client.ctx.uiSession.sessionStatus + const publish = client.ctx.uiSession.registerPendingInteraction(() => 0) + const request = { key: 'approval:1', kind: 'approval', sessionId: parentId } + const remove = publish(request, async () => {}) + expect(status.getSnapshot().get(parentId)?.pendingInteraction).toBe(request) + remove() + expect(status.getSnapshot().get(parentId)?.pendingInteraction).toBeUndefined() }) diff --git a/packages/client/ui-session-status/tests/status.client.spec.ts b/packages/client/ui-session-status/tests/status.client.spec.ts new file mode 100644 index 0000000000..9257f7afe7 --- /dev/null +++ b/packages/client/ui-session-status/tests/status.client.spec.ts @@ -0,0 +1,239 @@ +import { Context } from '@deepseek-ai/cordis' +import type { ISessions, 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, describe, expect, it, vi } from 'vitest' +import { apply } from '../src/client/index.ts' +import { UiSessionStatus } from '../src/client/status.ts' +import { apply as nodeApply } from '../src/index.ts' + +const sessionId = (value: string): SessionId => value as SessionId +const pendingQuestion = (id: SessionId) => ({ key: 'question:1', kind: 'question', sessionId: id }) as SessionPendingInteraction +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) + let statusListener: ((id: SessionId, running: boolean) => void) | undefined + ctx.provide('remote', { + $on: (_event: string, listener: (id: SessionId, running: boolean) => void) => { + statusListener = listener + return () => { if (statusListener === listener) statusListener = undefined } + }, + } as never) + const list = createSnapshotStore({ ids: [], byId: {}, phase: 'ready', projectionsBySession: {} }) + const sessions: Pick = { list } + const pending = createSnapshotStore>(new Map()) + const status = () => new UiSessionStatus(ctx, sessions, pending) + const row = (id: SessionId) => { + list.update((draft) => { + if (!draft.ids.includes(id)) draft.ids.push(id) + draft.byId[id] = { id, displayTitle: id, running: false, retainedBy: {}, blank: false, updatedAt: 1 } + }) + } + const setMainView = (id: SessionId, count: number) => { + list.update((draft) => { + draft.byId[id] = { ...draft.byId[id]!, retainedBy: count === 0 ? {} : { mainView: count } } + }) + } + const emitStatus = (id: SessionId, running: boolean) => { + 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 } +} + +describe('Session running status and completion reminders', () => { + it('keeps synthetic-row status unknown until an event or Host baseline establishes it', () => { + const b = bench() + const id = sessionId('catalog-only') + b.list.update((draft) => { + draft.byId[id] = { id, displayTitle: id, running: false, retainedBy: {}, blank: false, updatedAt: 0 } + }) + 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) + }) + + it('records non-main completions and lets main-view activity acknowledge them', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + const changed = vi.fn() + const off = service.subscribe(changed) + + expect(service.getSnapshot().get(id)).toEqual({ + running: false, + pendingInteraction: undefined, + completionUnread: 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(changed).toHaveBeenCalled() + off() + }) + + it('records an idle 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' }) + const service = b.status() + + b.emitStatus(id, false) + expect(service.getSnapshot().get(id)).toEqual({ + running: false, + pendingInteraction: undefined, + completionUnread: true, + }) + b.list.update((draft) => { draft.phase = 'ready' }) + expect(service.getSnapshot().has(id)).toBe(false) + }) + + it('keeps the snapshot reference until a status fact changes', () => { + const b = bench() + const id = sessionId('s1') + b.row(id) + const service = b.status() + const changed = vi.fn() + service.subscribe(changed) + const before = service.getSnapshot() + + b.emitStatus(id, false) + b.list.update((draft) => { draft.byId[id]!.displayTitle = 'Renamed' }) + expect(service.getSnapshot()).toBe(before) + expect(changed).not.toHaveBeenCalled() + b.emitStatus(id, true) + expect(service.getSnapshot()).not.toBe(before) + expect(changed).toHaveBeenCalledOnce() + }) +}) + +describe('Session status pending interactions', () => { + it('carries the exact effective request object and adds Sessions known only by their request', () => { + const b = bench() + const listed = sessionId('listed') + const unlisted = sessionId('unlisted') + b.row(listed) + const service = b.status() + const changed = vi.fn() + service.subscribe(changed) + const approval = { key: 'approval:1', kind: 'approval', sessionId: listed } as SessionPendingInteraction + 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)?.pendingInteraction).toBe(approval) + expect(service.getSnapshot().get(unlisted)).toEqual({ + running: undefined, pendingInteraction: question, completionUnread: false, + }) + expect(changed).toHaveBeenCalledOnce() + + b.pending.set(new Map([[listed, approval], [unlisted, question]])) + expect(changed).toHaveBeenCalledOnce() + b.pending.set(new Map()) + expect(service.getSnapshot().get(listed)?.pendingInteraction).toBeUndefined() + expect(service.getSnapshot().has(unlisted)).toBe(false) + expect(changed).toHaveBeenCalledTimes(2) + }) + + it('contains a failing status subscriber and continues dispatch', () => { + const b = bench() + const service = b.status() + const failure = new Error('status subscriber failed') + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + service.subscribe(() => { throw failure }) + const after = vi.fn() + service.subscribe(after) + + b.pending.set(new Map([[sessionId('s1'), pendingQuestion(sessionId('s1'))]])) + + expect(after).toHaveBeenCalledOnce() + expect(report).toHaveBeenCalledWith('[session-status] Session status subscriber failed:', failure) + }) + + it('stops following its sources when its plugin unloads', async () => { + const b = bench() + let service: UiSessionStatus | undefined + const fiber = b.ctx.plugin({ + apply(scope: Context) { + service = new UiSessionStatus(scope, { list: b.list }, b.pending) + }, + }) + await fiber.await() + if (service === undefined) throw new Error('UiSessionStatus did not start') + expect(b.subscribed()).toBe(true) + const before = service.getSnapshot() + + await fiber.dispose() + + expect(b.subscribed()).toBe(false) + b.row(sessionId('later')) + b.pending.set(new Map([[sessionId('later'), pendingQuestion(sessionId('later'))]])) + expect(service.getSnapshot()).toBe(before) + }) +}) + +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) + + apply(b.ctx) + + expect(provideRoot).toHaveBeenCalledOnce() + 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() + }) +}) diff --git a/packages/client/ui-session-status/tsconfig.json b/packages/client/ui-session-status/tsconfig.json new file mode 100644 index 0000000000..4c10ff072a --- /dev/null +++ b/packages/client/ui-session-status/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "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" + } + ] +} diff --git a/packages/client/ui-session-status/tsdown.config.ts b/packages/client/ui-session-status/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-session-status/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-session/README.i18n.yaml b/packages/client/ui-session/README.i18n.yaml index 3a3d92d9d5..1ca425e341 100644 --- a/packages/client/ui-session/README.i18n.yaml +++ b/packages/client/ui-session/README.i18n.yaml @@ -9,14 +9,17 @@ en: 22464c74746de6c2 zh: 171a244a493a277e /deepseek-ai-dsh-client-ui-session/summary: - en: 75428e0474a073a4 - zh: 18f1db4b4c5302e5 + en: 164c245872687c87 + zh: 80ad1ecfbc78c3f5 /deepseek-ai-dsh-client-ui-session/table-of-contents: - en: 12e1ffc25a2d6695 - zh: 321156dea1356e55 + en: 2abfd2105ed73a78 + zh: 042ec2f41ac7d1b6 /deepseek-ai-dsh-client-ui-session/access-hooks: - en: 7bf4bca5607248fa - zh: 665d5c4e9cd29f68 + en: 9b32047bba740867 + zh: 3b08b927c99a162c +/deepseek-ai-dsh-client-ui-session/sub-services: + en: 7d3c27551c090dd6 + zh: 9de5063e62818570 /deepseek-ai-dsh-client-ui-session/model-experience: en: cb2d4451e8bf8520 zh: 6d3adbb930d90c59 diff --git a/packages/client/ui-session/README.md b/packages/client/ui-session/README.md index 4c3928b35d..f3a39e7803 100644 --- a/packages/client/ui-session/README.md +++ b/packages/client/ui-session/README.md @@ -8,13 +8,14 @@ English | [中文](README.zh.md) ## Summary -Use this package to expose Session catalog, retain information, and unified UI status through standard Slot hooks. It materializes per-`SessionBinding` hooks and props, while `SessionProvider` can inherit an outer binding or bind an explicit `SessionReference`. It owns process-local pending-interaction and completion-reminder policy without owning Controller transport, history, or references. +Use this package to expose the Session catalog and retain information through standard Slot hooks. It materializes per-`SessionBinding` hooks and props, while `SessionProvider` can inherit an outer binding or bind an explicit `SessionReference`. It owns process-local pending-interaction policy without owning Controller transport, history, or references. -Running status comes from Host list baselines or status events. Subagent catalog rows and retained subagent fallback rows do not establish running status; main view references still acknowledge completions. +Domain plugins publish requests awaiting the user through `ctx.uiSession.registerPendingInteraction(precedence)`, and `ctx.uiSession.pendingInteractions` exposes each Session's highest-precedence request read-only. The Session status table and `useSessionStatus` belong to [`dsh-client-ui-session-status`](../ui-session-status/README.md). ## Table of Contents - [Access Hooks](#access-hooks) +- [Sub-services](#sub-services) - [Model Experience](#model-experience) - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - [Dev Note](#dev-note) @@ -26,6 +27,11 @@ Running status comes from Host list baselines or status events. Subagent catalog The package injects the Client `remoteAccess` service and publishes Session access Hooks over its `source()`: the root `useSessionAccess(sessionId, action)` answers on one Session resource, and the Session-scope `useAccess(action)` answers on the bound Session's resource; the `global` resource's answer is a different Hook, `useRemoteAccess(action)`, so neither shadows the other. `ctx.uiSession.whenAccess(sessionId, action, callback)` is the JS counterpart of `useSessionAccess`: it keeps the callback's effects installed while the current Peer may call `action` on that Session, with the semantics of `ctx.remoteAccess.whenAccess`. The SessionMaybe-scope `useAccess(action)` returns `undefined` while no Session is bound, which callers treat as not allowed; a decision on the `global` resource reads `useRemoteAccess` instead. Snapshot semantics belong to [`dsh-api-remote-access`](../../api/remote-access/README.md#client-face). + +## Sub-services + +`ctx.uiSession` has the type `UiSessionService`. A package that provides a sub-service `x` as the Cordis service `uiSession.x`, read as `ctx.uiSession.x`, merges the member `x` into that interface; [`dsh-client-ui-session-status`](../ui-session-status/README.md) provides `ctx.uiSession.sessionStatus` this way. + ## Model Experience diff --git a/packages/client/ui-session/README.zh.md b/packages/client/ui-session/README.zh.md index fb63e227cd..1934621ddd 100644 --- a/packages/client/ui-session/README.zh.md +++ b/packages/client/ui-session/README.zh.md @@ -8,13 +8,14 @@ kind: "package-reference" ## 概述 -使用本包可通过标准 Slot 钩子公开 Session catalog、retain 信息与统一 UI 状态。它按 `SessionBinding` 物化钩子和 prop,而 `SessionProvider` 可以继承外围 binding 或绑定显式 `SessionReference`。它拥有进程本地的 pending-interaction 与完成提醒策略,但不拥有 Controller transport、历史或 reference。 +使用本包可通过标准 Slot 钩子公开 Session catalog 与 retain 信息。它按 `SessionBinding` 物化钩子和 prop,而 `SessionProvider` 可以继承外围 binding 或绑定显式 `SessionReference`。它拥有进程本地的 pending-interaction 策略,但不拥有 Controller transport、历史或 reference。 -运行状态来自 Host 列表基线或状态事件。Subagent 目录行和已保留子会话的 fallback 行不会建立运行状态;主视图引用仍会确认完成提醒。 +领域插件通过 `ctx.uiSession.registerPendingInteraction(precedence)` 发布等待用户处理的请求,`ctx.uiSession.pendingInteractions` 以只读方式提供每个 Session 优先级最高的请求。会话状态表与 `useSessionStatus` 归 [`dsh-client-ui-session-status`](../ui-session-status/README.zh.md) 所有。 ## 目录 - [访问 Hook](#access-hooks) +- [子服务](#sub-services) - [模型体验](#model-experience) - [已知限制与暂缓事项](#known-limitations-and-deferred-work) - [开发备注](#dev-note) @@ -26,6 +27,11 @@ kind: "package-reference" 本包注入 Client `remoteAccess` 服务,并在其 `source()` 之上发布会话访问 Hook:根作用域的 `useSessionAccess(sessionId, action)` 回答某一个 Session 资源上的访问,Session 作用域的 `useAccess(action)` 回答所绑定 Session 资源上的访问;`global` 资源上的答案是另一个 Hook `useRemoteAccess(action)`,两者互不遮蔽。`ctx.uiSession.whenAccess(sessionId, action, callback)` 是 `useSessionAccess` 在 JS 侧的对应:当前 Peer 能在该 Session 上调用 `action` 期间保持回调的效果,语义同 `ctx.remoteAccess.whenAccess`。SessionMaybe 作用域的 `useAccess(action)` 在未绑定 Session 时返回 `undefined`,调用方将其视为不允许;需要 `global` 资源上的判断时读 `useRemoteAccess`。快照语义归 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md#client-face)。 + +## 子服务 + +`ctx.uiSession` 的类型是 `UiSessionService`。以 Cordis 服务 `uiSession.x` 提供子服务 `x`、并以 `ctx.uiSession.x` 读取的包,把成员 `x` 声明合并进该接口;[`dsh-client-ui-session-status`](../ui-session-status/README.zh.md) 就以这种方式提供 `ctx.uiSession.sessionStatus`。 + ## 模型体验 diff --git a/packages/client/ui-session/package.json b/packages/client/ui-session/package.json index 9fb6bda901..8aa051aca0 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -30,7 +30,6 @@ "client": { "inject": [ "@deepseek-ai/dsh-api-remote-access", - "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-ui-renderer" ], @@ -48,13 +47,11 @@ "devDependencies": { "@deepseek-ai/cordis": "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-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@deepseek-ai/dsh-remote-mock": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "react": "^18.2.0" diff --git a/packages/client/ui-session/src/client/index.ts b/packages/client/ui-session/src/client/index.ts index 860a82287c..6725d14037 100644 --- a/packages/client/ui-session/src/client/index.ts +++ b/packages/client/ui-session/src/client/index.ts @@ -7,11 +7,9 @@ import type { SessionReference, SessionRetainInfo, SessionSnapshot, - SessionSummary, UseProjection, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type {} from '@deepseek-ai/dsh-api-remotes/client' import type { AccessEffect, RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' import { notifySubscribers } from '@deepseek-ai/dsh-client-store' import { WeakMapWithValues } from '@deepseek-ai/dsh-util-values' @@ -56,21 +54,6 @@ export type SessionPendingInteraction = ? SessionPendingInteractionBase : SessionPendingInteractionMap[keyof SessionPendingInteractionMap] -/** Independent UI status facts for one Session identity. */ -export interface SessionStatus { - /** Latest known running state; absent until a baseline or event establishes it. */ - 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. */ - readonly completionUnread: boolean -} - -/** Current UI status indexed by Session identity. */ -export type SessionStatusSnapshot = ReadonlyMap -/** Selector hook over the unified Session UI status snapshot. */ -export type UseSessionStatus = SnapshotSelectorHook - /** Selector hook for explicit or surrounding-Provider Session reference counts. */ export interface UseSessionRetainInfo { /** @@ -157,7 +140,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface GlobalStandardProps { /** Session list and current selection. */ useSessions: UseSessions - useSessionStatus: UseSessionStatus useSessionRetainInfo: UseSessionRetainInfo /** Whether the current Peer may call `action` on one Session resource. */ useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean @@ -195,10 +177,17 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { declare module '@deepseek-ai/cordis' { interface Context { /** Session Controller adapter and session-scoped source registry. */ - uiSession: UiSession + uiSession: UiSessionService } } +/** + * Type of `ctx.uiSession`: the {@link UiSession} service plus the sub-services other Client packages provide beneath + * it. A package declares its sub-service `x`, provided as the Cordis service `uiSession.x` and read as + * `ctx.uiSession.x`, by merging a member into this interface; Typert analysis rejects members merged into the class. + */ +export interface UiSessionService extends UiSession {} + type SessionSourceRoster = readonly string[] | undefined type StandardMemberKind = 'hook' | 'keyed hook' | 'prop' @@ -288,19 +277,19 @@ export class UiSession extends Service { private readonly current: BindingSource private readonly pendingDomains: RuntimePendingDomain[] = [] private pendingSnapshot: ReadonlyMap = new Map() - private readonly running = new Map() - private readonly completionUnread = new Set() - private statusSnapshot: SessionStatusSnapshot = new Map() - private readonly statusListeners = new Set<() => void>() + private readonly pendingListeners = new Set<() => void>() private mainRetainId: SessionId | undefined private disposeMainRetain = (): void => {} private active = true - /** Root source combining running, pending-interaction, and completion-reminder facts. */ - readonly sessionStatus: HostObservable = { - getSnapshot: () => this.statusSnapshot, + /** + * Read-only view of every Session's highest-precedence pending interaction. The snapshot keeps its + * reference until an effective request changes; a throwing listener is reported without stopping later listeners. + */ + readonly pendingInteractions: HostObservable> = { + getSnapshot: () => this.pendingSnapshot, subscribe: (listener) => { - this.statusListeners.add(listener) - return () => { this.statusListeners.delete(listener) } + this.pendingListeners.add(listener) + return () => { this.pendingListeners.delete(listener) } }, } /** Renderer-facing adapter for `session` and `session-maybe` scopes. */ @@ -325,17 +314,10 @@ export class UiSession extends Service { ctx.effect(() => { const disposeList = sessions.list.subscribe(() => { this.publishMain() }) - const disposeStatus = sessions.list.subscribe(() => { this.reconcileStatus() }) - const disposeRemoteStatus = ctx.remote.$on('api-session/status', (sessionId, running) => { - this.observeRunning(sessionId, running) - }) this.publishMain() - this.reconcileStatus() return () => { this.active = false disposeList() - disposeStatus() - disposeRemoteStatus() this.disposeMainRetain() const records = [...this.bindings.values] this.bindings.clear() @@ -502,64 +484,7 @@ export class UiSession extends Service { ) if (samePendingInteractions(this.pendingSnapshot, projected)) return this.pendingSnapshot = projected - this.publishStatus() - } - - 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() - } - - private reconcileStatus(): void { - const list = this.sessions.list.getSnapshot() - const present = new Set(Object.keys(list.byId) as SessionId[]) - // Subagent catalog rows and retained subagent fallback rows do not establish Host running state. - for (const id of list.ids) { - const row = list.byId[id] as SessionSummary - const previous = this.running.get(id) - if (previous === undefined) this.running.set(id, row.running) - else if (previous !== row.running) this.observeRunning(id, row.running) - } - for (const id of present) { - if (this.isMain(id)) this.completionUnread.delete(id) - } - if (list.phase === 'ready') { - for (const id of this.running.keys()) { - if (present.has(id)) continue - this.running.delete(id) - this.completionUnread.delete(id) - } - } - this.publishStatus() - } - - private isMain(sessionId: SessionId): boolean { - return (this.sessions.list.getSnapshot().byId[sessionId]?.retainedBy.mainView ?? 0) > 0 - } - - private publishStatus(): void { - const ids = new Set([ - ...(Object.keys(this.sessions.list.getSnapshot().byId) as SessionId[]), - ...this.running.keys(), - ...this.pendingSnapshot.keys(), - ...this.completionUnread, - ]) - const next = new Map() - for (const id of ids) { - next.set(id, { - running: this.running.get(id), - pendingInteraction: this.pendingSnapshot.get(id), - completionUnread: this.completionUnread.has(id), - }) - } - if (sameSessionStatus(this.statusSnapshot, next)) return - this.statusSnapshot = next - notifySubscribers(this.statusListeners, '[ui-session] Session status') + notifySubscribers(this.pendingListeners, '[ui-session] pending interactions') } private createMaterializedBinding(owner: SessionBinding): MaterializedBinding { @@ -685,8 +610,8 @@ function claimStandardProp(kind: StandardMemberKind, name: string, finalProps: S finalProps.add(propName) } -/** Required Controller, renderer, Remote, and access services. */ -export const inject = ['sessions', 'slots', 'remote', 'remoteAccess'] +/** Required Controller, renderer, and access services. */ +export const inject = ['sessions', 'slots', 'remoteAccess'] /** * Install the Session root source and scoped adapter. @@ -697,7 +622,6 @@ export function apply(ctx: Context): void { ctx.slots.provideRoot({ hooks: { sessions: ctx.sessions.list, - sessionStatus: service.sessionStatus, }, keyedHooks: { sessionRetainInfo: key => ctx.sessions.retainInfo(key as SessionId), @@ -715,18 +639,6 @@ export function apply(ctx: Context): void { }) } -function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean { - if (left.size !== right.size) return false - for (const [id, status] of left) { - const candidate = right.get(id) - if (candidate === undefined - || candidate.running !== status.running - || candidate.pendingInteraction !== status.pendingInteraction - || candidate.completionUnread !== status.completionUnread) return false - } - return true -} - function samePendingInteractions( left: ReadonlyMap, right: ReadonlyMap, diff --git a/packages/client/ui-session/tests/ui-session.client.spec.ts b/packages/client/ui-session/tests/ui-session.client.spec.ts index 6afbe4be49..ac7fb9bc42 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -31,7 +31,6 @@ interface SessionsBench { reference(binding: SessionBinding): SessionReference setMainView(id: SessionId, count: number): void setRetainInfo(id: SessionId, count: number): void - emitStatus(id: SessionId, running: boolean): void release(id: SessionId): Promise } @@ -41,15 +40,6 @@ const roots: Context[] = [] function createSessionsBench(ctx: Context): SessionsBench { roots.push(ctx) - let statusListener: ((id: SessionId, running: boolean) => void) | undefined - ctx.provide('remote', { - $on: (_event: string, listener: (id: SessionId, running: boolean) => void) => { - statusListener = listener - return () => { - if (statusListener === listener) statusListener = undefined - } - }, - } as never) const list = createSnapshotStore({ ids: [], byId: {}, @@ -171,10 +161,6 @@ function createSessionsBench(ctx: Context): SessionsBench { retainedBy: count === 0 ? {} : { mainView: count }, }) }, - emitStatus(id, running) { - if (statusListener === undefined) throw new Error('api-session/status is not subscribed') - statusListener(id, running) - }, async release(id) { bindings.delete(id) const scopeCtx = scopes.get(id) @@ -521,90 +507,6 @@ describe('UiSession bindings', () => { }) }) -describe('UiSession status', () => { - it('keeps synthetic-row status unknown until an event or Host baseline establishes it', () => { - const ctx = new Context() - const bench = createSessionsBench(ctx) - const id = sessionId('catalog-only') - bench.list.update((draft) => { - draft.byId[id] = { id, displayTitle: id, running: false, retainedBy: {}, blank: false, updatedAt: 0 } - }) - const service = createUiSession(ctx, bench) - expect(service.sessionStatus.getSnapshot().get(id)?.running).toBeUndefined() - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - - bench.emitStatus(id, true) - bench.list.update((draft) => { draft.byId[id]!.displayTitle = 'Renamed child' }) - expect(service.sessionStatus.getSnapshot().get(id)?.running).toBe(true) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - - bench.list.update((draft) => { draft.ids.push(id) }) - expect(service.sessionStatus.getSnapshot().get(id)?.running).toBe(false) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(true) - }) - - it('records non-main completions and lets main-view activity acknowledge them', () => { - const ctx = new Context() - const bench = createSessionsBench(ctx) - const id = sessionId('s1') - bench.binding(id) - const service = createUiSession(ctx, bench) - const changed = vi.fn() - const off = service.sessionStatus.subscribe(changed) - - expect(service.sessionStatus.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: false, - }) - bench.list.update((draft) => { draft.byId[id]!.running = true }) - expect(service.sessionStatus.getSnapshot().get(id)?.running).toBe(true) - bench.list.update((draft) => { draft.byId[id]!.running = false }) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(true) - bench.setMainView(id, 1) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - bench.setMainView(id, 0) - - bench.emitStatus(id, true) - bench.emitStatus(id, false) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(true) - - bench.setMainView(id, 1) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - bench.emitStatus(id, true) - bench.emitStatus(id, false) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - - bench.setMainView(id, 0) - bench.emitStatus(id, false) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - bench.emitStatus(id, true) - bench.emitStatus(id, false) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(true) - bench.emitStatus(id, true) - expect(service.sessionStatus.getSnapshot().get(id)?.completionUnread).toBe(false) - expect(changed).toHaveBeenCalled() - off() - }) - - it('records an idle event before the initial catalog baseline and retires absent status later', () => { - const ctx = new Context() - const bench = createSessionsBench(ctx) - const id = sessionId('early') - bench.list.update((draft) => { draft.phase = 'pending' }) - const service = createUiSession(ctx, bench) - - bench.emitStatus(id, false) - expect(service.sessionStatus.getSnapshot().get(id)).toEqual({ - running: false, - pendingInteraction: undefined, - completionUnread: true, - }) - bench.list.update((draft) => { draft.phase = 'ready' }) - expect(service.sessionStatus.getSnapshot().has(id)).toBe(false) - }) -}) - describe('UiSession pending interactions', () => { it('publishes the highest-precedence exact object and removes each source independently', async () => { const ctx = new Context() @@ -612,7 +514,7 @@ describe('UiSession pending interactions', () => { const service = createUiSession(ctx, bench) const id = sessionId('s1') const listener = vi.fn() - const off = service.sessionStatus.subscribe(listener) + const off = service.pendingInteractions.subscribe(listener) const registerApproval = service.registerPendingInteraction( () => 0, ) @@ -631,26 +533,31 @@ describe('UiSession pending interactions', () => { const background = { key: 'background:1', kind: 'background', sessionId: id } const delegate = (): Promise => Promise.resolve() const removeApproval = registerApproval(approval, delegate) - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(approval) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(approval) const removeDuplicate = registerApproval(duplicate, delegate) - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(duplicate) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(duplicate) const removeQuestion = registerQuestion(question, delegate) - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(question) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(question) const removePlan = registerQuestion(plan, delegate) - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(plan) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(plan) + listener.mockClear() + const effective = service.pendingInteractions.getSnapshot() const removeBackground = registerBackground(background, delegate) - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(plan) + expect(service.pendingInteractions.getSnapshot()).toBe(effective) removeBackground() removeQuestion() - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(plan) + expect(service.pendingInteractions.getSnapshot()).toBe(effective) + expect(listener).not.toHaveBeenCalled() removePlan() - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(duplicate) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(duplicate) + expect(listener).toHaveBeenCalledOnce() removeDuplicate() - expect(service.sessionStatus.getSnapshot().get(id)?.pendingInteraction).toBe(approval) + expect(service.pendingInteractions.getSnapshot().get(id)).toBe(approval) removeApproval() removeApproval() - expect(service.sessionStatus.getSnapshot().has(id)).toBe(false) + expect(service.pendingInteractions.getSnapshot().has(id)).toBe(false) + expect(listener).toHaveBeenCalledTimes(3) off() await ctx.fiber.dispose() }) @@ -670,15 +577,15 @@ describe('UiSession pending interactions', () => { const failure = new Error('pending subscriber failed') const report = vi.spyOn(console, 'error').mockImplementation(() => {}) - service.sessionStatus.subscribe(() => { throw failure }) + service.pendingInteractions.subscribe(() => { throw failure }) const after = vi.fn() - service.sessionStatus.subscribe(after) + service.pendingInteractions.subscribe(after) remove() expect(after).toHaveBeenCalledOnce() expect(report).toHaveBeenCalledWith( - '[ui-session] Session status subscriber failed:', + '[ui-session] pending interactions subscriber failed:', failure, ) }) @@ -698,7 +605,7 @@ describe('UiSession pending interactions', () => { let disposed = false const disposal = ctx.fiber.dispose().then(() => { disposed = true }) await vi.waitFor(() => { expect(delegate).toHaveBeenCalledOnce() }) - expect(service.sessionStatus.getSnapshot()).toEqual(new Map()) + expect(service.pendingInteractions.getSnapshot()).toEqual(new Map()) expect(disposed).toBe(false) remove() remove() @@ -745,7 +652,6 @@ describe('ui-session apply', () => { expect(slots.provideRoot).toHaveBeenCalledWith({ hooks: { sessions: bench.sessions.list, - sessionStatus: ctx.uiSession.sessionStatus, }, keyedHooks: { sessionRetainInfo: retainInfoMatcher, sessionAccess: sessionAccessMatcher }, }) diff --git a/packages/client/ui-session/tsconfig.json b/packages/client/ui-session/tsconfig.json index e38563a19b..6fa6b47b4c 100644 --- a/packages/client/ui-session/tsconfig.json +++ b/packages/client/ui-session/tsconfig.json @@ -11,9 +11,6 @@ { "path": "../../../vendor/cordis" }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, { "path": "../../api/remote-access/tsconfig.client.json" }, diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index 9f008dd598..8f17675697 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -37,6 +37,7 @@ "@deepseek-ai/dsh-client-ui-primitives", "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-session-status", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -70,6 +71,7 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", "@deepseek-ai/dsh-agent-team": "workspace:*" }, diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index b44d4f8e55..d6fe29b2d8 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -12,6 +12,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' @@ -31,8 +32,11 @@ export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' -/** Required services for subagent presentation and navigation. */ -export const inject = ['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight'] +/** + * Required services for subagent presentation and navigation. `uiSession.sessionStatus` provides the + * `useSessionStatus` hook the lineage header renders with, so the plugin unloads and reloads with it. + */ +export const inject = ['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight', 'uiSession.sessionStatus'] /** Claim the composer when the child mode does not allow follow-ups. */ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatch | null { diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index 83c5839e8d..4dae089f5a 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -88,6 +88,7 @@ async function fullBench(sessions: SessionSummary[]) { }, } as never) ctx.provide('remote', { $on: () => () => {} } as never) + ctx.provide('uiSession.sessionStatus', createSnapshotStore(new Map()) as never) ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) await provideSlotFaces(ctx) await ctx.plugin({ inject: localeInject, apply: applyLocale }).await() @@ -107,7 +108,7 @@ const FAMILY: SessionSummary[] = [ describe('apply', () => { it('declares the services it binds', () => { - expect(inject).toEqual(['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight']) + expect(inject).toEqual(['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight', 'uiSession.sessionStatus']) }) it('keeps the root catalog extension available when optional Sidebar services arrive', async () => { 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 a70f41295e..660db73fd5 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -9,7 +9,7 @@ import type { import type { SubagentAddress, SubagentCatalogEntry } from '@deepseek-ai/dsh-subagent/client' import type { TeamProjection, TeamTaskId, TeamTaskView } from '@deepseek-ai/dsh-agent-team/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogActionProps, type SubagentHeaderLineageProps, diff --git a/packages/client/ui-subagent/tsconfig.json b/packages/client/ui-subagent/tsconfig.json index 293725f30b..cbf78e252c 100644 --- a/packages/client/ui-subagent/tsconfig.json +++ b/packages/client/ui-subagent/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../ui-session-status" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index a0d6689e43..cb5a30a729 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -76,6 +76,7 @@ "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@tanstack/react-virtual": "3.14.10", diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index e0ee44c80a..57c07402a6 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -33,7 +33,7 @@ import type { } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import { ConversationSession, ConversationSessionHeader, type ConversationSessionHeaderProps, type ConversationSessionProps, diff --git a/packages/client/ui-workflow-run/package.json b/packages/client/ui-workflow-run/package.json index c097a340a7..3ed8a3bfbd 100644 --- a/packages/client/ui-workflow-run/package.json +++ b/packages/client/ui-workflow-run/package.json @@ -35,6 +35,7 @@ "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-session", + "@deepseek-ai/dsh-client-ui-session-status", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -68,6 +69,7 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-tool-workflow": "workspace:*", diff --git a/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx b/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx index 059cf803cb..c5aa6fd3c5 100644 --- a/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx +++ b/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx @@ -10,7 +10,7 @@ import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots import type { SessionListState, SessionTarget } from '@deepseek-ai/dsh-api-session-controller/client' import { shallowEqual } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { WorkflowRunKey } from './locales.ts' import type { WorkflowRunMemberData, WorkflowRunPhaseData, WorkflowRunStatus, diff --git a/packages/client/ui-workflow-run/src/client/index.ts b/packages/client/ui-workflow-run/src/client/index.ts index 648dbd1f46..a65d9e01cf 100644 --- a/packages/client/ui-workflow-run/src/client/index.ts +++ b/packages/client/ui-workflow-run/src/client/index.ts @@ -7,6 +7,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { WorkflowRunPanel, type WorkflowRunInjected } from './WorkflowRunPanel.tsx' import { en, ja, es, fr, de, ru, pt, NS, type WorkflowRunKey, zh } from './locales.ts' @@ -19,8 +20,11 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -/** Required services for Definition, keyed renderer, navigation, and copy. */ -export const inject = ['uiConversation', 'uiWorkspace', 'slots', 'sessions', 'locale'] +/** + * Required services for Definition, keyed renderer, navigation, and copy. `uiSession.sessionStatus` provides the + * `useSessionStatus` hook the run panel renders with, so the plugin unloads and reloads with it. + */ +export const inject = ['uiConversation', 'uiWorkspace', 'slots', 'sessions', 'locale', 'uiSession.sessionStatus'] /** Register the workflow Definition, dictionary, and keyed Chat renderer. */ export function apply(ctx: ClientContext): void { 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 9ba88045d8..84f1d6045d 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 @@ -940,6 +940,7 @@ describe('plugin lifecycle', () => { ctx.provide('sessions', sessions) const openSession = vi.fn(async () => {}) ctx.provide('uiWorkspace', { openSession } as never) + ctx.provide('uiSession.sessionStatus', createSnapshotStore(new Map()) as never) const conversationEvents = new UiConversation(ctx, ctx.sessions).events ctx.slots.register({ name: 'root', diff --git a/packages/client/ui-workflow-run/tsconfig.json b/packages/client/ui-workflow-run/tsconfig.json index 2f3c83a425..f48fbe28f0 100644 --- a/packages/client/ui-workflow-run/tsconfig.json +++ b/packages/client/ui-workflow-run/tsconfig.json @@ -17,6 +17,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../ui-session-status" + }, { "path": "../store" }, diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index e67c5242a6..0ae2e2565d 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -40,6 +40,7 @@ "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-session", + "@deepseek-ai/dsh-client-ui-session-status", "@deepseek-ai/dsh-client-ui-sidebar", "@deepseek-ai/dsh-client-ui-context-menu" ], @@ -71,6 +72,7 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 9b64c6332e..425fcbf712 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -39,6 +39,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' // Type-only: pulls the Session root standard-hook merge. import type {} from '@deepseek-ai/dsh-client-ui-session/client' +// Type-only: pulls the useSessionStatus root standard-hook merge. +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import { type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected, type SessionArchiveConfirmInjected, type SessionArchiveConfirmRequest, @@ -130,9 +132,12 @@ const NS = 'workspace' * (loading/prefetch metadata, never apply sequencing) and neither owner * provides a waitable service. apply therefore depends on each slot * declaration through `slots.inject()` instead of assuming order. + * `uiSession.sessionStatus` provides the `useSessionStatus` hook the browser rows render with, so the plugin unloads + * and reloads with it. */ export const inject = ['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', + 'uiSession.sessionStatus', ] /** diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 054c584d4b..993c00dbf6 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -9,7 +9,7 @@ import { import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot, -} from '@deepseek-ai/dsh-client-ui-session/client' +} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { assertNever } from '@deepseek-ai/dsh-util-values' import { workspaceTitleOf } from '@deepseek-ai/dsh-util-workspace-path' diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index d6c18cd763..efe3751dc6 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -70,6 +70,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) await ctx.plugin(SlotRegistry).await() const accessSource = vi.fn((_kind: string, _id: string, _action: string): HostObservable => ALLOWED) const stopGuard = vi.fn() @@ -242,6 +243,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', ]) }) diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index bb180fb209..ba02053e36 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -12,7 +12,7 @@ import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { GlobalStandardProps, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' diff --git a/packages/client/ui-workspace/tests/tree.client.spec.ts b/packages/client/ui-workspace/tests/tree.client.spec.ts index b754980ca5..bd62b40952 100644 --- a/packages/client/ui-workspace/tests/tree.client.spec.ts +++ b/packages/client/ui-workspace/tests/tree.client.spec.ts @@ -3,9 +3,8 @@ import type { SessionListState, SessionProjectionMap, SessionSummary, } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' -import type { - SessionPendingInteraction, SessionStatus, SessionStatusSnapshot, -} from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SessionProjectionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' diff --git a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx index 5df4923b4f..0c36940ed6 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx @@ -10,9 +10,8 @@ import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-sess import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' -import type { - SessionPendingInteraction, SessionStatus, SessionStatusSnapshot, -} from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' diff --git a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx index e39f7cf81c..3302f38d85 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.client.spec.tsx @@ -10,7 +10,7 @@ import type { import type {} from '@deepseek-ai/dsh-client-locale/client' import { allowAllAccess, bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { DirectoryFlowOwnerProps, WorkspacePickerProps } from '../src/client/contract/slots.ts' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' import { zh } from '../src/client/locales.ts' diff --git a/packages/client/ui-workspace/tsconfig.json b/packages/client/ui-workspace/tsconfig.json index 2fce88ba2d..71bc07a1e2 100644 --- a/packages/client/ui-workspace/tsconfig.json +++ b/packages/client/ui-workspace/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../ui-session-status" + }, { "path": "../../preset/agent-preset-registry" }, diff --git a/packages/client/web/src/boot-client.ts b/packages/client/web/src/boot-client.ts index 9ad95f3770..2dffd17e65 100644 --- a/packages/client/web/src/boot-client.ts +++ b/packages/client/web/src/boot-client.ts @@ -18,7 +18,8 @@ export type EntryStateLabel = (typeof STATE_LABELS)[keyof typeof STATE_LABELS] | * The list is global rather than page or profile metadata. A name absent from * the boot manifest does not affect startup; a listed entry that is present * must activate. The list covers the module system, Session control, the - * renderer and application frame, and the Session view with its sidebar. It is + * renderer and application frame, the Session view with its sidebar, and the + * Session status table those views read through `useSessionStatus`. It is * the minimum fatal set: an entry that a listed entry waits on leaves it * inactive, so that entry's failure also rejects startup. */ @@ -28,6 +29,7 @@ const requiredClientEntryNames = new Set([ '@deepseek-ai/dsh-client-ui-renderer', '@deepseek-ai/dsh-client-ui-layout', '@deepseek-ai/dsh-client-ui-session', + '@deepseek-ai/dsh-client-ui-session-status', '@deepseek-ai/dsh-client-ui-chat', '@deepseek-ai/dsh-client-ui-sidebar', ]) diff --git a/packages/client/web/tests/boot-client.client.spec.ts b/packages/client/web/tests/boot-client.client.spec.ts index e362670b1a..b143dc8473 100644 --- a/packages/client/web/tests/boot-client.client.spec.ts +++ b/packages/client/web/tests/boot-client.client.spec.ts @@ -11,6 +11,7 @@ import { FIBER_STATE } from '../src/loader-status.ts' const BOOTSTRAP_ID = '@deepseek-ai/dsh-client-modules' const REQUIRED_ID = '@deepseek-ai/dsh-client-ui-chat' const OTHER_REQUIRED_ID = '@deepseek-ai/dsh-client-ui-layout' +const SESSION_STATUS_ID = '@deepseek-ai/dsh-client-ui-session-status' function graphOf(ids: readonly string[]): WebBootGraph { const entries: WebBootEntry[] = ids.map(id => ({ id, url: `/${id}.js`, rev: '1' })) @@ -131,6 +132,33 @@ describe('bootClient', () => { ) }) + it('rejects startup when the Session status row cannot be imported', async () => { + const { modules } = modulesOf(graphOf(['seeded']), { seeded: { apply: () => {} } }) + const manifest = parseBootManifest(graphOf(['seeded', SESSION_STATUS_ID])) + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + + await expect(bootClient({ ctx, modules, manifest })).rejects.toThrow( + `web boot: 1 required entry did not activate\n${SESSION_STATUS_ID} (required): import failed (see console for the import error)`, + ) + }) + + it('rejects startup when the Session status row fails to apply', async () => { + const { modules } = modulesOf(graphOf([SESSION_STATUS_ID]), { + [SESSION_STATUS_ID]: { apply: () => { throw new Error('status table failed') } }, + }) + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + + await expect(bootClient({ ctx, modules, manifest: modules.manifest })).rejects.toThrow( + `web boot: 1 required entry did not activate\n${SESSION_STATUS_ID} (required): failed: Error: status table failed`, + ) + }) + it('rejects a required row whose module exports no plugin and names it', async () => { const { modules } = modulesOf(graphOf([REQUIRED_ID]), { [REQUIRED_ID]: { default: 'invalid' } }) const ctx = new Context() diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 61b61e6dc9..8a27462ed9 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: c3fa707a638717e4 - zh: dfeba8a57c58a8aa + en: 6e11f578c23bf7f5 + zh: 3dc895e6955f9b96 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: c9541603ea971f46 - zh: 15c41326e3fb29e4 + en: 8a32164b43695f96 + zh: c5659ca104118d3b /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 913b4dd2cc8f2a40 - zh: 2794e247c0063717 + en: 4cc0215ddd1aa565 + zh: 5a39cbdafc70fce9 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 2d95507268..5efe782f10 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -42,12 +42,13 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. - **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. +- **Extension API** — Other plugins extend the changes view through the [extension API](../../../docs/subsystems/forge.md#extension-api). A Host plugin registers a filter lens with `ctx.forgePanel.registerLens`, and a Client plugin names it with `ctx.forgeChanges.describeLens`; the toolbar then offers a Lens menu after Hide test files, which keeps the files of the chosen layer that the chosen lens keeps, counts each lens's files once it ran, and folds the hunks a kept file's lens is not about into a row that shows them. A running lens shows its progress on the menu button; a failed, refused, or interrupted run says why and offers Retry and Clear lens, and a lens whose plugin unloads stops filtering with a toast. While no lens is chosen, the menu folds into the More menu with the test switch. `ctx.forgeChanges` also opens a view with a file and a lens chosen and registers line annotation sources, whose notes stack after the comments and threads of their last line, in the column of their side, whole-file notes first and notes on an earlier change last, at most `maxAnnotationsPerFile` in a file. Plugins add toolbar tools, which fold into the More menu first, file menu rows, comment form buttons after Add to input, and card head buttons through the `forge.changes.toolbar`, `forge.changes.file.menu`, `forge.diff.comment.actions`, and `forge.change-request.card.actions` slots. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, and `maxAnnotationsPerFile` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the GitHub split button starts the user's pending review on GitHub with the comment, or adds the comment to it; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately, which GitHub refuses while the user has a pending review, so the menu is then absent. Agent references and published comments remain beside their code. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. On the user's own pull request, which GitHub lets its author only comment on, Approve and Request changes are unavailable. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. @@ -70,7 +71,7 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old or the reader refreshes the view, since resolving a GitHub thread leaves the update time unchanged. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old or the reader refreshes the view, since resolving a GitHub thread leaves the update time unchanged. Each `forge/review-changed` drops the read kept for its change request and raises `reviewRevision` on the panel entries that bind it, so an open view reads the threads and the viewed marks again after another plugin's write. `registerLens` keeps lenses by identity, and `extensions` streams their identities with `maxAnnotationsPerFile`. `changesLens` reads the files as `localDiff` or `changeRequestDiff` does, refuses files whose `lensVersion` differs from the request with `forgePanel/lens-stale`, and runs `classify` with a signal that aborts on cancellation, withdrawal, or `lensTimeoutMs`, counting the UTF-8 bytes `text` returns against `maxLensReadBytes`. Old sides come from `git show` at the fork point, the first chosen commit's parent, the index, or HEAD for local changes, and through `fileText` at the chosen commits' parent or at the provider's `mergeBase` of `baseSha` and the head for a change request. Results are kept by files, lens, and lens version up to `maxCachedLensBytes` as JSON; a failure maps to `forgePanel/lens-failed`, and a withdrawn lens to `forgePanel/lens-missing`. `changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it. @@ -155,6 +156,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. - **Viewed files on the code host** — GitHub keeps one viewed mark per file and user, not one per commit, so marks in a view of chosen commits stay in this browser, and another browser or device starts without them. A file beyond the provider's `maxViewedFiles` shows no mark from GitHub until it is marked in this view. - **Review thread writes** — a write through one changes view shows in other open views of the change request at their next status, or after `reviewRefreshMs` for a resolve, which does not change the pull request's update time. GitHub keeps one pending review per user and pull request. A comment draft an earlier version kept in the browser can join the pending review only while its file and lines still match the shown diff; otherwise it can only be edited or deleted. A comment on chosen commits can only be added to the input. Minimized comments show like others, and avatars load from the code host's image server in the browser. +- **Extensions** — a lens runs only once it is chosen, and its result applies to the files the view showed when it asked; reading the old side of a whole change request needs a provider that names merge bases. Line annotations stay out of the thread list, the unresolved counts, and thread navigation. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index c7f9d4b994..0ca82f2ea3 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -42,12 +42,13 @@ kind: "package-reference" - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 - **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 +- **扩展 API**——其他插件通过[扩展 API](../../../docs/subsystems/forge.zh.md#extension-api)扩展变更视图。Host 插件用 `ctx.forgePanel.registerLens` 注册筛选透镜,Client 插件用 `ctx.forgeChanges.describeLens` 给它起名;工具栏随后在“隐藏测试文件”之后提供“透镜”菜单:只保留所选分层中被所选透镜保留的文件,透镜运行过之后显示它保留的文件数,并把被保留文件中透镜不关心的 hunk 折叠成一行,点开即显示。透镜运行时,菜单按钮显示进度;运行失败、被拒绝或中断时说明原因,并提供“重试”和“清除透镜”;透镜所在的插件卸载后停止筛选,并弹出提示。没有选透镜时,菜单与测试文件开关一起收进“更多”菜单。`ctx.forgeChanges` 还可以打开选定了文件和透镜的视图,并注册行注解数据源:注解放在其最后一行的评论和讨论之后、所在一侧的那一栏,整个文件的注解排在最前,写在较早改动上的注解排在最后,每个文件最多显示 `maxAnnotationsPerFile` 条。插件可以通过 `forge.changes.toolbar`、`forge.changes.file.menu`、`forge.diff.comment.actions` 与 `forge.change-request.card.actions` 这些 slot 添加工具栏工具(最先收进“更多”菜单)、文件菜单项、放在“添加到输入框”之后的评论框按钮,以及卡片头部按钮。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes` 与 `maxAnnotationsPerFile` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 “全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,GitHub 分段按钮会用这条评论在 GitHub 上开始用户的待提交评审,或把评论加入其中;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时 GitHub 会拒绝单条评论,因此这时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。在用户自己的 PR 上,GitHub 只允许作者评论,因此“批准”和“请求更改”不可用。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 @@ -70,7 +71,7 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后,或读者刷新视图时,重新读取,因为解决 GitHub 讨论不会改变更新时间。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后,或读者刷新视图时,重新读取,因为解决 GitHub 讨论不会改变更新时间。每个 `forge/review-changed` 都会丢弃对应变更请求保留的读取结果,并让绑定它的面板条目的 `reviewRevision` 加一,因此其他插件写入后,已打开的视图会重新读取讨论和已审阅标记。`registerLens` 按身份保存透镜,`extensions` 流式发送这些身份和 `maxAnnotationsPerFile`。`changesLens` 像 `localDiff` 或 `changeRequestDiff` 一样读取文件,文件的 `lensVersion` 与请求不同时以 `forgePanel/lens-stale` 拒绝;它运行 `classify` 时传入的 signal 会在取消、透镜撤销或超过 `lensTimeoutMs` 时中止,并把 `text` 返回的 UTF-8 字节数计入 `maxLensReadBytes`。本地变更的旧侧在分叉点、第一个所选提交的父提交、暂存区或 HEAD 上经 `git show` 读取;变更请求的旧侧经 `fileText` 在所选提交的父提交上读取,或在提供方给出的 `baseSha` 与 head 的 `mergeBase` 上读取。结果按文件、透镜和透镜版本保留,按 JSON 计最多 `maxCachedLensBytes`;失败映射为 `forgePanel/lens-failed`,透镜已撤销映射为 `forgePanel/lens-missing`。 `changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。 @@ -155,6 +156,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 - **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 - **评审讨论的写入**——在一个变更视图中的写操作,会在该变更请求的其他已打开视图收到下一次状态时显示;解决讨论不会改变 pull request 的更新时间,要等到 `reviewRefreshMs` 之后才显示。GitHub 每个用户在每个 pull request 上只保留一个待提交评审。早期版本保存在浏览器中的评论草稿,只有其文件和行仍与所显示的 diff 一致时才能加入待提交评审,否则只能编辑或删除。对所选提交的评论只能添加到输入框。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 +- **扩展**——透镜只在被选中后运行,结果作用于发出请求时视图所显示的文件;读取整个变更请求的旧侧需要能给出合并基准的提供方。行注解不进入讨论列表、未解决数和讨论导航。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 755e0192e0..e9793caed3 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -117,7 +117,8 @@ "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-session-query": "workspace:*", "@deepseek-ai/dsh-api-remote-access": "workspace:*", - "@types/picomatch": "^4.0.3" + "@types/picomatch": "^4.0.3", + "@deepseek-ai/dsh-brand": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 4e455c1037..dcb1c7ed76 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -21,6 +21,7 @@ import { ChecksRow, IssuesRow, MergeRow, ReviewRow, RowParts, ThreadGlyph, type import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' +import type { ForgeChangeRequestCardActionsProps } from './slots.ts' import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' import css from './ForgeTab.module.css' @@ -47,6 +48,8 @@ export interface ChangeRequestActions extends OverviewActions { readonly readChecks?: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined /** Open the changes view of the change request. */ readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined + /** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */ + readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined } /** Props of one change request card. */ @@ -395,6 +398,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc )} + {actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })} + : } + + }> + {lensRun.run.code === 'forgePanel/lens-stale' ? t('filterLens.stale', { lens: chosenChoice.title }) + : lensRun.run.code === 'forgePanel/lens-interrupted' ? t('filterLens.interrupted', { lens: chosenChoice.title }) + : t('filterLens.failed', { lens: chosenChoice.title, message: lensRun.run.message })} + + )} {data?.kind === 'change' && data.viewed?.kind === 'failed' && ( {t('retry')}}> {t('viewed.readFailed', { message: data.viewed.message })} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index fc25c20ebc..a46d46a4ef 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -29,6 +29,7 @@ import { FileLabel } from './FileLabel.tsx' import type { ForgePanelKey, NS } from './locales.ts' import type { ViewedState } from './viewed-files.ts' import type { SectionReach } from './section-reach.ts' +import type { SourcedAnnotation } from './annotations.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -65,6 +66,12 @@ export interface DiffFileHandlers { readonly nextThread: (path: string) => void /** Tells each expanded section when it comes within reach of the scrollport, which draws its lines. */ readonly reach: SectionReach + /** Draw the content of one line annotation through its source's `forge.diff.line.annotation` entry. */ + readonly annotation: (path: string, item: SourcedAnnotation) => ReactNode + /** Draw the plugin rows of a file's menu through `forge.changes.file.menu`. */ + readonly fileMenu: (file: ForgeDiffFile, dismiss: () => void) => ReactNode + /** Show the hunks the chosen lens folds in a file. */ + readonly unfold: (path: string) => void } /** Props of one file section. */ @@ -103,6 +110,12 @@ export interface DiffFileProps { readonly threads?: FileThreads | undefined /** Whether the section draws its lines at once, as the target of a thread jump, whose card must exist to be centered. */ readonly drawNow?: boolean | undefined + /** Line annotations of the file in stacking order, or undefined for none; the view keeps their identity. */ + readonly annotations?: readonly SourcedAnnotation[] | undefined + /** Most annotations the file shows, the rest counted below them, or undefined to show none while the limit is unknown. */ + readonly annotationLimit?: number | undefined + /** Indexes of the hunks the chosen lens folds with the lens's title, or undefined for none; the view keeps their identity. */ + readonly folded?: { readonly hunks: ReadonlySet; readonly lens: string } | undefined /** Actions shared by every section of the view. */ readonly handlers: DiffFileHandlers /** Forge panel copy. */ @@ -135,6 +148,7 @@ type SideSpans = ReadonlyMap | undefined /** A segment ready to draw: collapsed lines, or rows with the tokens of each side. */ type Prepared = | { readonly kind: 'gap'; readonly index: number; readonly count: number | null } + | { readonly kind: 'folded'; readonly hunks: readonly number[] } | { readonly kind: 'rows'; readonly rows: readonly DiffRow[]; readonly old: SideSpans; readonly new: SideSpans } /** Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. */ @@ -180,13 +194,66 @@ function rangeKey(item: ReviewSelection): string { return `${item.comment.side}${item.comment.startLine}-${item.comment.endLine}` } +/** A file's annotations as it shows them: on lines, on the whole file, written on an earlier change, and how many the limit leaves out. */ +interface FileAnnotations { + readonly lines: readonly SourcedAnnotation[] + readonly file: readonly SourcedAnnotation[] + readonly outdated: readonly SourcedAnnotation[] + readonly hidden: number +} + +const NO_ANNOTATIONS: FileAnnotations = { lines: [], file: [], outdated: [], hidden: 0 } + +/** Group the first `limit` annotations of a file by where they show; none show while the limit is unknown. */ +function groupAnnotations( + file: ForgeDiffFile, items: readonly SourcedAnnotation[] | undefined, limit: number | undefined, +): FileAnnotations { + if (items === undefined || items.length === 0 || limit === undefined) return NO_ANNOTATIONS + const lines: SourcedAnnotation[] = [] + const whole: SourcedAnnotation[] = [] + const outdated: SourcedAnnotation[] = [] + for (const item of items.slice(0, limit)) { + const { place, digest } = item.annotation + if (digest !== undefined && digest !== file.digest) outdated.push(item) + else if (place === 'file') whole.push(item) + else lines.push(item) + } + return { lines, file: whole, outdated, hidden: Math.max(0, items.length - limit) } +} + +/** Whether a line of one side falls in one of the hunks. */ +function inHunks(file: ForgeDiffFile, hunks: readonly number[], side: 'L' | 'R', line: number): boolean { + return hunks.some((index) => { + const hunk = file.hunks[index] + /* v8 ignore next -- folded indexes name hunks of the file */ + if (hunk === undefined) return false + const start = side === 'L' ? hunk.oldStart : hunk.newStart + return line >= start && line < start + (side === 'L' ? hunk.oldLines : hunk.newLines) + }) +} + +/** The saved comments and plugin annotations the lines of a file place. */ +interface LinesNotes { + readonly comments: FileReviewState + readonly annotations: readonly SourcedAnnotation[] +} + +/** One annotation's frame, which holds the content its source's slot entry draws. */ +function Annotation({ path, item, handlers }: { + readonly path: string + readonly item: SourcedAnnotation + readonly handlers: DiffFileHandlers +}): ReactNode { + return
{handlers.annotation(path, item)}
+} + function pairKind(pair: SplitRow): 'context' | 'change' { return pair.left !== null && pair.left.kind === 'context' ? 'context' : 'change' } /** The hunks of one file with their collapsed and expanded unchanged lines. */ -function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, t }: Pick & { readonly comments: FileReviewState }): ReactNode { +function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, folded, annotations, t }: Pick & LinesNotes): ReactNode { const lines = typeof text === 'object' ? text : undefined const columns = split && file.additions > 0 && file.deletions > 0 const singleSide = file.status === 'added' ? 'R' : file.status === 'deleted' ? 'L' : null @@ -194,6 +261,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme for (const hunk of file.hunks) maximum = Math.max(maximum, hunk.oldStart + hunk.oldLines - 1, hunk.newStart + hunk.newLines - 1) const style: CSSProperties & { '--forge-number-width': string } = { '--forge-number-width': `calc(${Math.max(2, String(maximum).length)}ch + 12px)` } const highlighter = useCodeHighlighter(languageForPath(file.path)) + const foldLens = folded === undefined ? '' : folded.lens const [selection, setSelection] = useState(null) // Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range. const chosen = useRef(null) @@ -271,9 +339,19 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme window.removeEventListener('pointercancel', finish) } }, [selecting, nativeSelection]) - const prepared = useMemo(() => segmentsOf(file, lines, open).map((segment): Prepared => segment.kind === 'gap' + // A hunk that holds an open comment form or a comment saved in this browser stays drawn: folding it would move the form, + // which loses its text, and show the saved comment as written on lines the diff no longer has. + const foldHunks = useMemo(() => { + if (folded === undefined) return undefined + const holds = (index: number): boolean => editors.some(item => inHunks(file, [index], item.comment.side, item.comment.endLine)) + || (review !== undefined && comments.threads.some(thread => reviewMatches(thread.selection, review.source, file) + && inHunks(file, [index], thread.selection.comment.side, thread.selection.comment.endLine))) + return new Set([...folded.hunks].filter(index => !holds(index))) + }, [folded, editors, review, comments.threads, file]) + const prepared = useMemo(() => segmentsOf(file, lines, open, foldHunks).map((segment): Prepared => segment.kind !== 'rows' ? segment - : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), [file, lines, open, highlighter]) + : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), + [file, lines, open, foldHunks, highlighter]) // Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection. const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => { /* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */ @@ -366,6 +444,16 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme const unplaced = new Set(threads === undefined ? [] : threads.lines.map(item => ({ ...item, actions: threads.actions }))) const threadCard = (item: LineThread & { readonly actions: ThreadActions }): ReactNode => + // Plugin annotations follow the host threads on the row of their last line, or the collapsed or folded lines that hold it. + const unplacedNotes = new Set(annotations) + const annotationOf = (item: SourcedAnnotation): ReactNode => + + const lastLine = (item: SourcedAnnotation): { readonly side: 'L' | 'R'; readonly line: number } => { + const place = item.annotation.place + /* v8 ignore next -- only line annotations reach the lines */ + if (place === 'file') return { side: 'R', line: 0 } + return { side: place.side, line: place.endLine } + } // The editors, the saved comments, then the host threads whose ranges end on this side's line. const commentsAt = (side: 'L' | 'R', line: number | null): ReactNode[] => { const nodes: ReactNode[] = [] @@ -388,6 +476,12 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme nodes.push(threadCard(item)) unplaced.delete(item) } + for (const item of unplacedNotes) { + const at = lastLine(item) + if (at.side !== side || at.line !== line) continue + nodes.push(annotationOf(item)) + unplacedNotes.delete(item) + } return nodes } const editorOf = (item: ReviewSelection, actions: ReviewActions): ReactNode => @@ -418,6 +512,30 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme rows.push(threadCard(item)) unplaced.delete(item) } + for (const item of unplacedNotes) { + const at = lastLine(item) + if (gapOf(file, at.side, at.line) !== segment.index) continue + rows.push(annotationOf(item)) + unplacedNotes.delete(item) + } + } else if (segment.kind === 'folded') { + rows.push() + for (const item of unplaced) { + if (!inHunks(file, segment.hunks, item.place.side, item.place.endLine)) continue + rows.push(threadCard(item)) + unplaced.delete(item) + } + for (const item of unplacedNotes) { + const place = lastLine(item) + if (!inHunks(file, segment.hunks, place.side, place.line)) continue + rows.push(annotationOf(item)) + unplacedNotes.delete(item) + } } else if (columns) { for (const [index, pair] of splitRows(segment.rows).entries()) { rows.push(
) - const lineThreads = threads?.lines.map(item => ) + const lineThreads = <> + {threads?.lines.map(item => + )} + {notes.lines.map(item => )} + if (file.binary) return <>

{t('diff.binary')}

{records}{lineThreads} if (file.oversized) return <>

{t('diff.fileTooLarge')}

{records}{lineThreads} if (file.hunks.length === 0) return <>{records}{lineThreads} @@ -490,16 +612,27 @@ function Content(props: DiffFileProps): ReactNode { {records}{lineThreads} ) } - return + return } /** Host threads on the whole file, the lines, then the host threads that later commits made outdated. */ function Body(props: DiffFileProps): ReactNode { - const { threads, t } = props + const { file, threads, handlers, t } = props + const notes = groupAnnotations(file, props.annotations, props.annotationLimit) + const frame = (item: SourcedAnnotation): ReactNode => + return <> {threads?.file.map(thread => )} - + {notes.file.map(frame)} + {threads !== undefined && } + {notes.outdated.length > 0 && ( +
+
{t('annotation.outdated', { count: String(notes.outdated.length) })}
+ {notes.outdated.map(frame)} +
+ )} + {notes.hidden > 0 &&

{t('annotation.hidden', { count: String(notes.hidden) })}

} } @@ -543,6 +676,7 @@ function FileMenu({ name, file, handlers, t }: { {t(action.label)} ))} + {menuOpen &&
{handlers.fileMenu(file, () => { setMenuOpen(false) })}
} ) } diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx index 20eec63c19..a636d40cc9 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx @@ -4,7 +4,8 @@ import { useEffect, useState, type ReactNode } from 'react' import { Button, IconBranchOutlineRegular, IconCopyOutlineRegular, IconFolderCloseRegular, IconWarningTriangleOutlineRegular, StateDot, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from './slots.ts' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' @@ -68,6 +69,7 @@ export interface ForgeTabInjected { /** Full props of the tab body. */ export type ForgeTabProps = Pick, 'useTabInfo' | 'sessionId'> + & Pick, 'renderSlot'> & InjectFace & PropsLocale @@ -167,7 +169,7 @@ function SignIn({ state, copyText, t }: { export function ForgeTab({ useTabInfo, sessionId, usePanel, useHost, useLocale, reconnect, refresh, remove, markReady, merge, readChecks, restore, rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, copyPath, - reportVisible, createChangeRequest, t, + reportVisible, createChangeRequest, renderSlot, t, }: ForgeTabProps): ReactNode { const snapshot = usePanel(current => current) const home = useHost(facts => facts.home) @@ -200,6 +202,7 @@ export function ForgeTab({ openLink, copyLink: copyText, retry: startRefresh, remove, markReady, merge, readChecks, rerunChecks, requestReviews, reviewerCandidates, updateBranch, viewChanges: (entry) => { viewChanges({ kind: 'change', url: entry.url }) }, + renderActions: owner => renderSlot('forge.change-request.card.actions', owner), } const local = state.local !== null && state.local.files.length > 0 ? state.local : null const expanded = chosen ?? defaultExpanded(state.changeRequests) diff --git a/packages/experimental/client-ui-forge/src/client/LensFilter.module.css b/packages/experimental/client-ui-forge/src/client/LensFilter.module.css new file mode 100644 index 0000000000..848cea6332 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/LensFilter.module.css @@ -0,0 +1,87 @@ +/* The filter lens menu trigger, which shares the toolbar trigger's geometry and turns tinted while a lens is chosen. */ + +.trigger { + display: inline-flex; + flex: none; + align-items: center; + gap: 4px; + max-width: 220px; + height: 28px; + padding: 0 6px 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-secondary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +.trigger[data-active] { + background: var(--dsw-alias-state-business-tertiary); + color: var(--dsw-alias-state-business-primary); +} + +@media (hover: hover) { + .trigger:not([data-active]):hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.count { + flex: none; + font-size: 12px; + opacity: 0.8; +} + +.spin { + flex: none; + animation: lens-spin 0.9s linear infinite; +} + +@media (prefers-reduced-motion: reduce) { + .spin { + animation: none; + } +} + +@keyframes lens-spin { + to { + transform: rotate(360deg); + } +} + +.row { + display: flex; + align-items: center; + gap: 16px; + width: 100%; +} + +.rowLabel { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.rowCount { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; +} diff --git a/packages/experimental/client-ui-forge/src/client/LensFilter.tsx b/packages/experimental/client-ui-forge/src/client/LensFilter.tsx new file mode 100644 index 0000000000..7269ae9bf4 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/LensFilter.tsx @@ -0,0 +1,105 @@ +/** The changes toolbar's filter lens menu: the Host's lenses with the files each keeps among the shown files. */ + +import { useState, type ReactNode } from 'react' +import { IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconLoadingOutlineRegular, Menu, type MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { LensRun } from './lens-filter.ts' +import type { NS } from './locales.ts' +import css from './LensFilter.module.css' + +/** One lens the view offers. */ +export interface LensChoice { + /** Identity of the Host lens. */ + readonly id: string + /** Title in the current language, or the identity when no Client plugin describes it. */ + readonly title: string + /** Files the lens keeps among the shown files, or null before it ran for them. */ + readonly count: number | null +} + +/** Menu row identity of choosing no lens. */ +export const NO_LENS = 'lens:none' + +/** + * Menu row identity of choosing a lens. + * @param id - the lens identity. + * @returns the row identity. + */ +export function lensRowId(id: string): string { + return `lens:${id}` +} + +/** + * Read the lens a menu row chooses. + * @param row - a row identity. + * @returns the lens identity, null for no lens, or undefined for a row that chooses no lens. + */ +export function lensOfRow(row: string): string | null | undefined { + if (row === NO_LENS) return null + return row.startsWith('lens:') ? row.slice('lens:'.length) : undefined +} + +/** + * The rows that choose a lens: a heading, No lens, and each lens with its count. + * @param lenses - the lenses offered. + * @param t - forge panel copy. + * @returns the menu entries. + */ +export function lensEntries(lenses: readonly LensChoice[], t: PropsLocale['t']): MenuEntry[] { + return [ + { type: 'label', id: 'lens:heading', text: t('filterLens.heading') }, + { id: NO_LENS, label: t('filterLens.none') }, + ...lenses.map((lens): MenuEntry => ({ + id: lensRowId(lens.id), + label: {lens.title}{lens.count ?? '—'}, + })), + ] +} + +/** + * Render the lens menu button: Lens while none is chosen; the chosen lens's title, tinted, with the files it keeps, or + * its progress while it runs. + * @param props - the offered lenses, the chosen one, its run, the choose action, whether the owning tab is visible, and copy. + * @returns the trigger with its portalled menu. + */ +export function LensFilterMenu({ lenses, chosen, run, choose, visible, t }: PropsLocale & { + readonly lenses: readonly LensChoice[] + readonly chosen: LensChoice | null + readonly run: LensRun + readonly choose: (lens: string | null) => void + readonly visible: boolean +}): ReactNode { + const [open, setOpen] = useState(false) + let status: ReactNode = null + if (run.kind === 'running') { + status = <> + + {run.done !== null && run.total !== null && {t('filterLens.progress', { done: String(run.done), total: String(run.total) })}} + + } else if (chosen?.count !== null && chosen?.count !== undefined) { + status = {chosen.count} + } + return ( + { setOpen(false) }} + onSelect={(row) => { + setOpen(false) + const lens = lensOfRow(row) + /* v8 ignore next -- the menu offers only rows that choose a lens */ + if (lens === undefined) return + choose(lens) + }} + anchor={( + + )} /> + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 694dc51bea..bb9589f05d 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -7,6 +7,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ReviewQueue } from './review-queue.ts' import { reviewRange, type ReviewSelection, type ReviewSource } from './review.ts' import type { NS } from './locales.ts' +import type { ForgeCommentActionsProps } from './slots.ts' import css from './ReviewComposer.module.css' /** Actions supplied by the owning changes tab. */ @@ -29,6 +30,8 @@ export interface ReviewActions { readonly publish?: (selection: ReviewSelection) => Promise /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ readonly queue?: (selection: ReviewSelection) => Promise + /** Draw the buttons plugins add to the form through `forge.diff.comment.actions`. */ + readonly renderActions?: (owner: Omit) => ReactNode } /** @@ -115,6 +118,15 @@ export function ReviewComposer({ selection, actions, close, visible = true, t }: if (actions.addToInput(selected)) { actions.onQuoted?.(selected); close() } else setError(t('review.inputFailed')) }}>{t('review.addToInput')} + {actions.renderActions?.({ + selection: { + path: selection.comment.path, side: selection.comment.side, + startLine: selection.comment.startLine, endLine: selection.comment.endLine, + }, + empty, + busy, + send: (deliver) => { void send(async () => await deliver(body.current)) }, + })} {visible && actions.queue !== undefined && { void send(actions.queue) }} menuLabel={t('review.githubActions')} diff --git a/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx b/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx index 4ba29ee705..6ccc1239a3 100644 --- a/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx @@ -6,6 +6,7 @@ import { IconEllipsisOutlineRegular, Menu, Tooltip, type MenuEntry } from '@deep import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { NS } from './locales.ts' import { foldOf } from './toolbar-fold.ts' +import { lensEntries, lensOfRow, NO_LENS, type LensChoice } from './LensFilter.tsx' import css from './ChangesTab.module.css' /** Toolbar state and actions the menu repeats. */ @@ -23,11 +24,16 @@ export interface ViewOptions { readonly hideTests: boolean | undefined readonly toggleTests: () => void readonly refresh: () => void + /** Lenses the menu offers while the lens menu folds, empty while a lens is chosen and its menu stays in the row. */ + readonly lenses: readonly LensChoice[] + readonly chooseLens: (lens: string | null) => void + /** Draw the `MenuItemButton` rows of plugin toolbar entries, which fold first; `close` closes the menu. */ + readonly plugins: (close: () => void) => ReactNode } /** * Render the More button and its menu, which lists the controls of the toolbar's fold level when it opens (see - * `observeToolbarFold`); the toolbar's styles hide the button while nothing folds. + * `observeToolbarFold`), then the rows of plugin toolbar entries; the toolbar's styles hide the button while nothing folds. * @param props - the toolbar state and actions, whether the owning tab is visible, and copy. * @returns the button and its portalled menu. */ @@ -45,10 +51,17 @@ export function ViewOptionsMenu({ options, visible, t }: PropsLocale { id: 'wrap', label: t('diff.wrapAria') }, ) if (fold >= 2 && options.hideTests !== undefined) entries.push({ type: 'separator', id: 'tests-separator' }, { id: 'tests', label: t('tests.hide') }) + if (fold >= 2 && options.lenses.length > 0) entries.push({ type: 'separator', id: 'lens-separator' }, ...lensEntries(options.lenses, t)) if (fold >= 3) entries.push({ type: 'separator', id: 'refresh-separator' }, { id: 'refresh', label: t('diff.refresh') }) } - const selected = [options.split && 'split', options.wrap && 'wrap', options.hideTests === true && 'tests'].filter(item => item !== false) + const selected = [options.split && 'split', options.wrap && 'wrap', options.hideTests === true && 'tests', options.lenses.length > 0 && NO_LENS] + .filter(item => item !== false) const run = (id: string): void => { + const lens = lensOfRow(id) + if (lens !== undefined) { + options.chooseLens(lens) + return + } switch (id) { case 'expansion': options.toggleExpansion(); break case 'split': options.toggleSplit(); break @@ -74,6 +87,8 @@ export function ViewOptionsMenu({ options, visible, t }: PropsLocale - )} /> + )}> + {fold !== null &&
{options.plugins(() => { setFold(null) })}
} +
) } diff --git a/packages/experimental/client-ui-forge/src/client/annotations.ts b/packages/experimental/client-ui-forge/src/client/annotations.ts new file mode 100644 index 0000000000..6fc9d36462 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/annotations.ts @@ -0,0 +1,105 @@ +/** + * Line annotations of one changes view: every source's annotations merged by path, and where each one shows in a + * file's lines. + */ + +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { ChangesTarget } from './changes-address.ts' +import type { ForgeAnnotationSource, ForgeLineAnnotation } from './changes-service.ts' + +/** One annotation with the source that draws it. */ +export interface SourcedAnnotation { + /** Identity of the source, the key of its `forge.diff.line.annotation` entry. */ + readonly source: string + readonly annotation: ForgeLineAnnotation +} + +/** Annotations of one view by path, in source order and then each source's order. */ +export type ViewAnnotations = ReadonlyMap + +const EMPTY: ViewAnnotations = new Map() + +/** Whether two lists hold the same annotations of the same sources at the same versions in the same order. */ +function sameList(a: readonly SourcedAnnotation[], b: readonly SourcedAnnotation[]): boolean { + return a.length === b.length && a.every((item, index) => { + const other = b[index] + return other !== undefined && item.source === other.source && item.annotation.key === other.annotation.key + && item.annotation.version === other.annotation.version + }) +} + +/** + * The merged annotations of one view. It observes each registered source while a reader subscribes, starting with + * the first reader and stopping after the last; a file whose annotations did not change keeps its list, so its section + * does not draw again. + */ +export class AnnotationView implements HostObservable { + private snapshot: ViewAnnotations = EMPTY + private readonly listeners = new Set<() => void>() + /** The followed sources in stacking order, each with its observable for this view and its unsubscribe. */ + private followed: readonly { readonly source: ForgeAnnotationSource; readonly values: ReturnType; readonly stop: () => void }[] = [] + private stopSources: (() => void) | undefined + + /** + * @param sources - the registered sources. + * @param target - the view's Session and source. + */ + constructor(private readonly sources: HostObservable, private readonly target: ChangesTarget) {} + + readonly getSnapshot = (): ViewAnnotations => this.snapshot + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + if (this.listeners.size === 1) { + this.stopSources = this.sources.subscribe(() => { this.sync() }) + this.sync() + } + return () => { + this.listeners.delete(listener) + if (this.listeners.size > 0) return + this.stopSources?.() + this.stopSources = undefined + for (const entry of this.followed) entry.stop() + this.followed = [] + } + } + + /** Follow the sources registered now, observing each new one once and releasing each withdrawn one, then merge. */ + private sync(): void { + const next = this.sources.getSnapshot().map(source => this.followed.find(entry => entry.source === source) ?? this.follow(source)) + for (const entry of this.followed) { + if (!next.includes(entry)) entry.stop() + } + this.followed = next + this.merge() + } + + private follow(source: ForgeAnnotationSource): (typeof this.followed)[number] { + const values = source.observe(this.target) + return { source, values, stop: values.subscribe(() => { this.merge() }) } + } + + private merge(): void { + const lists = new Map() + for (const { source, values } of this.followed) { + for (const [path, annotations] of values.getSnapshot()) { + const list = lists.get(path) ?? [] + for (const annotation of annotations) list.push({ source: source.id, annotation }) + if (list.length > 0) lists.set(path, list) + } + } + let changed = lists.size !== this.snapshot.size + const next = new Map() + for (const [path, list] of lists) { + const previous = this.snapshot.get(path) + if (previous !== undefined && sameList(previous, list)) next.set(path, previous) + else { + next.set(path, list) + changed = true + } + } + if (!changed) return + this.snapshot = next + for (const listener of [...this.listeners]) listener() + } +} diff --git a/packages/experimental/client-ui-forge/src/client/changes-address.ts b/packages/experimental/client-ui-forge/src/client/changes-address.ts index de9c62bda3..7c15d499c5 100644 --- a/packages/experimental/client-ui-forge/src/client/changes-address.ts +++ b/packages/experimental/client-ui-forge/src/client/changes-address.ts @@ -39,11 +39,13 @@ export interface ChangesTarget { export interface ChangesParams { /** File to scroll to, by its path in the diff. */ readonly path?: string + /** Identity of the filter lens to choose. */ + readonly lens?: string } declare module '@deepseek-ai/dsh-client-ui-sidebar-right/client' { interface SidebarRightResourceParamsMap { - /** The file a changes tab scrolls to. */ + /** The file a changes tab scrolls to and the lens it chooses. */ 'forge-changes': ChangesParams } } diff --git a/packages/experimental/client-ui-forge/src/client/changes-service.ts b/packages/experimental/client-ui-forge/src/client/changes-service.ts new file mode 100644 index 0000000000..fa3f1f6735 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/changes-service.ts @@ -0,0 +1,173 @@ +/** + * The changes view's face for other Client plugins, which the forge panel provides as `ctx.forgeChanges`: the + * changes tab's addresses and kinds, opening a view, the titles of Host lenses, and line annotation sources. + */ + +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ForgeExtensionState, ForgeLensId } from '../types.ts' +import { changesAddress, parseChangesAddress, type ChangesParams, type ChangesTarget } from './changes-address.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** The changes view's face for other Client plugins. */ + forgeChanges: ForgeChangesService + } +} + +/** The title of a filter lens a Host plugin registers, which a Client plugin describes. */ +export interface ForgeLensDescription { + /** Identity of the Host lens. */ + readonly id: ForgeLensId + /** Title in the current language, read whenever the view draws. */ + readonly title: () => string + /** Position among the lenses, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number +} + +/** Where one line annotation sits in a file of a changes view. */ +export interface ForgeLineAnnotation { + /** Identity within its source, stable across updates; it keys the drawn entry. */ + readonly key: string + /** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */ + readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file' + /** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */ + readonly digest?: string + /** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */ + readonly version: string | number +} + +/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */ +export interface ForgeAnnotationSource { + /** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */ + readonly id: string + /** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number + /** + * Observe the annotations of one view, by path. The changes view calls it once per view and source registration; + * the source republishes through the same observable whenever the annotations change. + * @param target - the view's Session and source. + * @returns annotations by repository-relative path. + */ + observe(target: ChangesTarget): HostObservable> +} + +/** What the service needs from the right sidebar. */ +export interface ForgeChangesSidebar { + /** Session whose sidebar shows, or undefined without one. */ + readonly mounted: () => SessionId | undefined + /** Open a resource address in the shown Session's sidebar. */ + readonly openResource: (address: string, params: ChangesParams | undefined) => void +} + +/** The position of an ordered entry, 0 without an `order`. */ +function positionOf(entry: { readonly order?: number }): number { + return entry.order ?? 0 +} + +/** Entries kept by identity in registration order, published sorted by `order`. */ +class OrderedEntries implements HostObservable { + private entries: readonly T[] = [] + private readonly listeners = new Set<() => void>() + + constructor(private readonly what: string) {} + + readonly getSnapshot = (): readonly T[] => this.entries + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + return () => { this.listeners.delete(listener) } + } + + add(entry: T): () => void { + if (this.entries.some(item => item.id === entry.id)) throw new Error(`forge-panel: a ${this.what} "${entry.id}" is already registered`) + // A stable sort keeps registration order among equal positions. + this.publish([...this.entries, entry].sort((a, b) => positionOf(a) - positionOf(b))) + return () => { this.publish(this.entries.filter(item => item !== entry)) } + } + + private publish(next: readonly T[]): void { + if (next.length === this.entries.length && next.every((item, index) => item === this.entries[index])) return + this.entries = next + for (const listener of [...this.listeners]) listener() + } +} + +/** + * The changes view's face for other Client plugins. Registrations return their disposer, which the registering plugin + * holds in its own `ctx.effect` so a registration lives exactly as long as that plugin. + */ +export class ForgeChangesService { + /** Titles of Host lenses in display order. */ + readonly lenses: HostObservable + /** Annotation sources in stacking order. */ + readonly annotationSources: HostObservable + private readonly lensEntries = new OrderedEntries('lens description') + private readonly sourceEntries = new OrderedEntries('annotation source') + + /** + * @param sidebar - the right sidebar's open path. + * @param extensions - the Host's registered lenses and annotation limit, or null before the Host reports them. + * @param kinds - tab kinds of the changes view and the change request panel. + */ + constructor( + private readonly sidebar: ForgeChangesSidebar, + readonly extensions: HostObservable, + readonly kinds: { readonly changes: string; readonly panel: string }, + ) { + this.lenses = this.lensEntries + this.annotationSources = this.sourceEntries + } + + /** + * Mint the address of a changes view. + * @param target - Session and source. + * @returns the `dsh-resource://forge-changes/…` address. + */ + address(target: ChangesTarget): string { + return changesAddress(target) + } + + /** + * Read the Session and source back out of a changes address. + * @param address - a resource address. + * @returns the target, or undefined for an address the forge panel did not mint. + */ + parse(address: string): ChangesTarget | undefined { + return parseChangesAddress(address) + } + + /** + * Open or reveal a changes view in the shown Session's right sidebar, scrolled to `params.path` with the lens + * `params.lens` chosen. + * @param target - Session and source; the Session must be the one the sidebar shows. + * @param params - file to scroll to and lens to choose. + * @throws when `target.sessionId` is not the Session the sidebar shows. + */ + open(target: ChangesTarget, params?: ChangesParams): void { + if (this.sidebar.mounted() !== target.sessionId) { + throw new Error(`forge-panel: Session ${target.sessionId} is not the Session the sidebar shows`) + } + this.sidebar.openResource(changesAddress(target), params) + } + + /** + * Describe the title of a Host lens. A lens the Host registers without a description shows its identity. + * @param description - the lens identity, title, and position. + * @returns the disposer that withdraws the description. + * @throws when another description holds the identity. + */ + describeLens(description: ForgeLensDescription): () => void { + return this.lensEntries.add(description) + } + + /** + * Register a line annotation source; its `forge.diff.line.annotation` entry, keyed by `source.id`, draws each one. + * @param source - the source. + * @returns the disposer that withdraws the source and its annotations. + * @throws when another source holds the identity. + */ + registerAnnotations(source: ForgeAnnotationSource): () => void { + return this.sourceEntries.add(source) + } +} diff --git a/packages/experimental/client-ui-forge/src/client/changes-store.ts b/packages/experimental/client-ui-forge/src/client/changes-store.ts index ff05303e7d..d7aff92d0b 100644 --- a/packages/experimental/client-ui-forge/src/client/changes-store.ts +++ b/packages/experimental/client-ui-forge/src/client/changes-store.ts @@ -22,6 +22,8 @@ export interface ChangesTabState { commits: ForgeCommitRange | null /** Review layer whose files show. */ lens: ChangesLens + /** Identity of the Host filter lens that keeps some of the shown files, or null for none. */ + filterLens: string | null /** Whether files of the `test` layer hide from the file tree and the diff. */ hideTests: boolean /** Whether deletions and additions show in two columns. */ @@ -50,6 +52,7 @@ type ChangesActions = { based: (draft: ChangesState, tabId: string, base: ForgeBaseBranch | null) => void committed: (draft: ChangesState, tabId: string, commits: ForgeCommitRange | null) => void lensed: (draft: ChangesState, tabId: string, lens: ChangesLens) => void + filtered: (draft: ChangesState, tabId: string, lens: string | null) => void toggledTests: (draft: ChangesState, tabId: string) => void toggledSplit: (draft: ChangesState, tabId: string) => void toggledWrap: (draft: ChangesState, tabId: string) => void @@ -67,7 +70,7 @@ export function createChangesStore(): EngineStoreHandle { const tab = d.byTab[tabId] if (tab === undefined) { - d.byTab[tabId] = { scope: 'branch', base: null, commits: null, lens: 'all', hideTests: false, split: true, wrap: true, navigated: revision } + d.byTab[tabId] = { + scope: 'branch', base: null, commits: null, lens: 'all', filterLens: null, hideTests: false, split: true, wrap: true, navigated: revision, + } } else tab.navigated = revision }, /** @@ -114,6 +119,13 @@ export function createChangesStore(): EngineStoreHandle { bucket(d, tabId).lens = lens }, + /** + * Choose the Host filter lens that keeps some of the shown files, or none. + * @param d - draft state. + * @param tabId - the tab being drawn. + * @param lens - the lens identity, or null for none. + */ + filtered: (d, tabId: string, lens: string | null) => { bucket(d, tabId).filterLens = lens }, /** * Hide or show the files of the `test` layer; hiding them leaves the `test` lens for every file. * @param d - draft state. diff --git a/packages/experimental/client-ui-forge/src/client/diff-rows.ts b/packages/experimental/client-ui-forge/src/client/diff-rows.ts index 3269793b54..f06984e058 100644 --- a/packages/experimental/client-ui-forge/src/client/diff-rows.ts +++ b/packages/experimental/client-ui-forge/src/client/diff-rows.ts @@ -33,6 +33,10 @@ export type DiffSegment = * `count` is null while the length of the file is unknown. */ | { readonly kind: 'gap'; readonly index: number; readonly count: number | null } + /** Consecutive hunks a filter lens folds, drawn as one row that shows them, with the unchanged lines between them. */ + | { readonly kind: 'folded'; readonly hunks: readonly number[] } + +const NO_FOLDS: ReadonlySet = new Set() /** A line as drawn: without the carriage return of a CRLF line ending. */ function drawn(text: string): string { @@ -142,13 +146,17 @@ function endsNewSide(hunk: ForgeDiffHunk): boolean { * Unchanged lines before a hunk, between hunks, and after the last hunk * collapse into one gap each; an open gap draws its lines from `lines` once * they are known. The lines after the last hunk are unknown until `lines` - * arrives, unless the file is new, deleted, or its last hunk reaches its end. + * arrives, unless the file is new, deleted, or its last hunk reaches its end. Consecutive folded hunks draw as one + * folded segment that takes the unchanged lines between them too. * @param file - one file of a diff. * @param lines - the file's new side, which {@link matchesHunks} accepted, or undefined while it has not been read. * @param open - indexes of the gaps the user expanded. + * @param folded - indexes of the hunks a filter lens folds. * @returns the segments in file order. */ -export function segmentsOf(file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet): DiffSegment[] { +export function segmentsOf( + file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet, folded: ReadonlySet = NO_FOLDS, +): DiffSegment[] { const segments: DiffSegment[] = [] let rows: DiffRow[] = [] const flush = (): void => { @@ -168,9 +176,18 @@ export function segmentsOf(file: ForgeDiffFile, lines: readonly string[] | undef } let newEnd = 0 let oldEnd = 0 + let run: number[] | null = null for (const [index, hunk] of file.hunks.entries()) { - if (hunk.newStart - 1 > newEnd) gap(index, newEnd + 1, hunk.newStart - 1, hunk.oldStart - hunk.newStart) - rows.push(...hunkRows(hunk)) + if (run !== null && folded.has(index)) run.push(index) + else { + run = null + if (hunk.newStart - 1 > newEnd) gap(index, newEnd + 1, hunk.newStart - 1, hunk.oldStart - hunk.newStart) + if (folded.has(index)) { + flush() + run = [index] + segments.push({ kind: 'folded', hunks: run }) + } else rows.push(...hunkRows(hunk)) + } newEnd = hunk.newStart + hunk.newLines - 1 oldEnd = hunk.oldStart + hunk.oldLines - 1 } diff --git a/packages/experimental/client-ui-forge/src/client/index.ts b/packages/experimental/client-ui-forge/src/client/index.ts index 4e8c0e6fad..04a211fafd 100644 --- a/packages/experimental/client-ui-forge/src/client/index.ts +++ b/packages/experimental/client-ui-forge/src/client/index.ts @@ -11,6 +11,18 @@ export { inject } from './mount.ts' export type { ForgePanelKey } from './locales.ts' export type { ChangeRequestActions, ChangeRequestCardProps } from './ChangeRequestCard.tsx' export type { ChangesParams, ChangesSource, ChangesTarget } from './changes-address.ts' +export type { + ForgeAnnotationSource, ForgeChangesService, ForgeChangesSidebar, ForgeLensDescription, ForgeLineAnnotation, +} from './changes-service.ts' +export type { + ForgeChangeRequestCardActionsProps, ForgeChangesFileMenuProps, ForgeChangesToolbarProps, ForgeCommentActionsProps, + ForgeLineAnnotationProps, +} from './slots.ts' +// The Host face's lens and extension types that the slot owner props and the changes view surface name. +export type { + ForgeExtensionState, ForgeLensFile, ForgeLensFrame, ForgeLensId, ForgeLensKeep, ForgeLensRequest, ForgeLineRange, + ForgeRegisteredLens, +} from '../types.ts' export type { ChangesTabInjected, ChangesTabProps } from './ChangesTab.tsx' export type { ChangesTabTitleProps } from './ChangesTabTitle.tsx' export type { DiffFileAction, DiffFileProps, DiffFileText } from './DiffFile.tsx' diff --git a/packages/experimental/client-ui-forge/src/client/lens-filter.ts b/packages/experimental/client-ui-forge/src/client/lens-filter.ts new file mode 100644 index 0000000000..bdb5d51019 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/lens-filter.ts @@ -0,0 +1,136 @@ +/** A changes view's filter lens: the request to the Host, its progress and result, and which hunks it folds. */ + +import { useEffect, useState } from 'react' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeDiffHunk, ForgeLensFrame, ForgeLensKeep, ForgeLensRequest, ForgeLineRange, ForgeRegisteredLens } from '../types.ts' +import type { HostStream } from './source.ts' + +/** Where a lens request stands for the shown files. */ +export type LensRun = + /** No lens is chosen, or the files have not loaded. */ + | { readonly kind: 'idle' } + /** The lens runs; `done` and `total` are null before it reports progress. */ + | { readonly kind: 'running'; readonly done: number | null; readonly total: number | null } + /** The files the lens keeps, by path. */ + | { readonly kind: 'ready'; readonly files: Readonly> } + /** + * The request failed with a Remote error code and message, or with `forgePanel/lens-interrupted` and no message when the + * stream ended without a result, as after a lost connection. + */ + | { readonly kind: 'failed'; readonly code: string; readonly message: string } + +/** What a view knows when it asks for a lens. */ +export interface LensRunInput { + /** Whether the view is visible; a hidden view starts no request. */ + readonly visible: boolean + /** The chosen registered lens, or null for none. */ + readonly lens: ForgeRegisteredLens | null + /** The source of the shown files, or null before they load. */ + readonly source: ForgeLensRequest['source'] | null + /** `lensVersion` of the shown files, or null before they load. */ + readonly version: string | null + /** Changes on each retry. */ + readonly attempt: number + /** Open the Host's lens stream. */ + readonly open: (request: ForgeLensRequest, signal: AbortSignal) => HostStream +} + +/** The run of the chosen lens and the results already known for the shown files. */ +export interface LensRunState { + readonly run: LensRun + /** + * Read what a registered lens keeps of the shown files. + * @returns the kept files once that lens, at that version, answered for the shown source and files. + */ + readonly resultOf: (lens: ForgeRegisteredLens) => Readonly> | undefined +} + +const IDLE: LensRun = { kind: 'idle' } + +/** The files each lens keeps, by lens identity and version. */ +type LensResults = ReadonlyMap>> + +const NO_RESULTS: LensResults = new Map() + +/** Names one lens at one registered version, so a lens registered again at another version is asked again. */ +function lensKeyOf(lens: ForgeRegisteredLens): string { + return `${lens.id}\u0000${lens.version}` +} + +/** + * Ask the Host for the chosen lens whenever the shown source or files, the lens or its version, or the attempt change, + * keeping the results of every lens asked for the same source and files. A view that becomes hidden stops its request; + * a result already known is not asked for again. + * @param input - the view's lens, files, and stream opener. + * @returns the run and the known results. + */ +export function useLensRun(input: LensRunInput): LensRunState { + const { visible, lens, source, version, attempt, open } = input + // Results hold for one source at one version of its files: equal files of another scope have other old sides. + const scope = source === null || version === null ? null : `${JSON.stringify(source)}\u0000${version}` + const [kept, setKept] = useState<{ readonly scope: string | null; readonly files: LensResults }>({ scope: null, files: new Map() }) + const results = kept.scope === scope ? kept.files : NO_RESULTS + const [run, setRun] = useState<{ readonly key: string; readonly run: LensRun } | null>(null) + const lensId = lens?.id ?? null + const lensKey = lens === null ? null : lensKeyOf(lens) + const key = lensKey === null || scope === null ? null : `${scope}\u0000${lensKey}\u0000${attempt}` + const known = lensKey === null ? undefined : results.get(lensKey) + useEffect(() => { + if (!visible || key === null || lensId === null || lensKey === null || source === null || version === null) return + if (known !== undefined) return + const controller = new AbortController() + const stream = open({ source, version, lens: lensId }, controller.signal) + setRun({ key, run: { kind: 'running', done: null, total: null } }) + void (async () => { + try { + for await (const frame of stream) { + if (controller.signal.aborted) return + if (frame.kind === 'progress') { + setRun({ key, run: { kind: 'running', done: frame.done, total: frame.total } }) + continue + } + setKept(previous => ({ + scope, files: new Map(previous.scope === scope ? previous.files : []).set(lensKey, frame.files), + })) + return + } + if (!controller.signal.aborted) setRun({ key, run: { kind: 'failed', code: 'forgePanel/lens-interrupted', message: '' } }) + } catch (error) { + if (controller.signal.aborted) return + const failure = remoteErrorOf(error) + setRun({ key, run: { + kind: 'failed', code: failure?.code ?? 'forgePanel/lens-failed', + message: failure?.message ?? (error instanceof Error ? error.message : String(error)), + } }) + } + })() + return () => { + controller.abort() + stream.dispose() + } + }, [visible, key, lensId, lensKey, scope, source, version, known, open]) + const shown: LensRun = key === null ? IDLE : known !== undefined ? { kind: 'ready', files: known } : run?.key === key ? run.run : IDLE + return { run: shown, resultOf: entry => results.get(lensKeyOf(entry)) } +} + +/** Whether a hunk's lines on one side meet any of the ranges. */ +function meets(start: number, count: number, ranges: readonly ForgeLineRange[]): boolean { + const end = start + count - 1 + return count > 0 && ranges.some(range => range.start <= end && range.end >= start) +} + +/** + * The hunks of a kept file that touch none of the lens's lines on either side. + * @param hunks - the file's hunks. + * @param keep - what the lens keeps of the file. + * @returns the indexes of the hunks to fold, empty when the lens names no lines. + */ +export function foldedHunks(hunks: readonly ForgeDiffHunk[], keep: ForgeLensKeep): ReadonlySet { + const ranges = keep.ranges + if (ranges === undefined) return new Set() + const folded = new Set() + for (const [index, hunk] of hunks.entries()) { + if (!meets(hunk.oldStart, hunk.oldLines, ranges.old) && !meets(hunk.newStart, hunk.newLines, ranges.new)) folded.add(index) + } + return folded +} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index bb31556a50..837f6568a1 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -233,6 +233,21 @@ export const zh = { 'lens.testHidden': '测试文件已隐藏', 'lens.menuAria': '分层透镜:{lens}', 'lens.empty': '没有要显示的文件', + 'filterLens.label': '透镜', + 'filterLens.aria': '筛选透镜', + 'filterLens.chosenAria': '筛选透镜:{lens}', + 'filterLens.heading': '筛选透镜', + 'filterLens.none': '不使用透镜', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': '清除透镜', + 'filterLens.failed': '透镜「{lens}」没有完成:{message}', + 'filterLens.stale': '变更已重新读取,刷新后再按「{lens}」筛选', + 'filterLens.removed': '透镜「{lens}」已移除', + 'filterLens.interrupted': '透镜「{lens}」的请求中断了', + 'filterLens.folded': '另有 {count} 处与「{lens}」无关的改动已折叠', + 'filterLens.unfold': '展开', + 'annotation.outdated': '写在较早改动上的注解 · {count}', + 'annotation.hidden': '此文件另有 {count} 条注解未显示', 'tests.hide': '隐藏测试文件', 'tests.hideHint': '不显示测试、快照、本地化文件、锁文件和生成的文件', 'viewed.label': '已审阅', @@ -665,6 +680,21 @@ export const en: Record = { 'lens.testHidden': 'Test files are hidden', 'lens.menuAria': 'Review layer: {lens}', 'lens.empty': 'No files to show', + 'filterLens.label': 'Lens', + 'filterLens.aria': 'Filter lens', + 'filterLens.chosenAria': 'Filter lens: {lens}', + 'filterLens.heading': 'Filter lenses', + 'filterLens.none': 'No lens', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Clear lens', + 'filterLens.failed': 'The lens “{lens}” did not finish: {message}', + 'filterLens.stale': 'The changes were read again; refresh to filter them by “{lens}”', + 'filterLens.removed': 'The lens “{lens}” was removed', + 'filterLens.interrupted': 'The lens “{lens}” stopped before it finished', + 'filterLens.folded': '{count} changes unrelated to “{lens}” folded', + 'filterLens.unfold': 'Show', + 'annotation.outdated': 'Annotations on an earlier change · {count}', + 'annotation.hidden': '{count} more annotations in this file are not shown', 'tests.hide': 'Hide test files', 'tests.hideHint': 'Hides tests, snapshots, locale files, lockfiles, and generated files', 'viewed.label': 'Viewed', @@ -1101,6 +1131,21 @@ export const ja: Record = { 'lens.testHidden': 'テストファイルは非表示です', 'lens.menuAria': 'レビューレイヤー:{lens}', 'lens.empty': '表示するファイルはありません', + 'filterLens.label': 'レンズ', + 'filterLens.aria': 'フィルターレンズ', + 'filterLens.chosenAria': 'フィルターレンズ: {lens}', + 'filterLens.heading': 'フィルターレンズ', + 'filterLens.none': 'レンズなし', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'レンズを解除', + 'filterLens.failed': 'レンズ「{lens}」が完了しませんでした: {message}', + 'filterLens.stale': '変更が再読み込みされました。更新してから「{lens}」で絞り込んでください', + 'filterLens.removed': 'レンズ「{lens}」は削除されました', + 'filterLens.interrupted': 'レンズ「{lens}」の要求が中断されました', + 'filterLens.folded': '「{lens}」に関係しない {count} 件の変更を折りたたみました', + 'filterLens.unfold': '表示', + 'annotation.outdated': '以前の変更への注釈 · {count}', + 'annotation.hidden': 'このファイルには表示されていない注釈がさらに {count} 件あります', 'tests.hide': 'テストファイルを非表示', 'tests.hideHint': 'テスト、スナップショット、ロケールファイル、ロックファイル、生成ファイルを表示しません', 'viewed.label': '確認済み', @@ -1530,6 +1575,21 @@ export const es: Record = { 'lens.testHidden': 'Los archivos de prueba están ocultos', 'lens.menuAria': 'Capa de revisión: {lens}', 'lens.empty': 'No hay archivos que mostrar', + 'filterLens.label': 'Lente', + 'filterLens.aria': 'Lente de filtro', + 'filterLens.chosenAria': 'Lente de filtro: {lens}', + 'filterLens.heading': 'Lentes de filtro', + 'filterLens.none': 'Sin lente', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Quitar lente', + 'filterLens.failed': 'La lente «{lens}» no terminó: {message}', + 'filterLens.stale': 'Los cambios se volvieron a leer; actualiza para filtrarlos por «{lens}»', + 'filterLens.removed': 'Se quitó la lente «{lens}»', + 'filterLens.interrupted': 'La lente «{lens}» se interrumpió antes de terminar', + 'filterLens.folded': '{count} cambios no relacionados con «{lens}» plegados', + 'filterLens.unfold': 'Mostrar', + 'annotation.outdated': 'Anotaciones sobre un cambio anterior · {count}', + 'annotation.hidden': 'Este archivo tiene {count} anotaciones más que no se muestran', 'tests.hide': 'Ocultar archivos de prueba', 'tests.hideHint': 'Oculta pruebas, instantáneas, archivos de idioma, archivos de bloqueo y archivos generados', 'viewed.label': 'Revisado', @@ -1959,6 +2019,21 @@ export const fr: Record = { 'lens.testHidden': 'Les fichiers de test sont masqués', 'lens.menuAria': 'Couche de revue : {lens}', 'lens.empty': 'Aucun fichier à afficher', + 'filterLens.label': 'Lentille', + 'filterLens.aria': 'Lentille de filtre', + 'filterLens.chosenAria': 'Lentille de filtre : {lens}', + 'filterLens.heading': 'Lentilles de filtre', + 'filterLens.none': 'Aucune lentille', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Retirer la lentille', + 'filterLens.failed': 'La lentille « {lens} » n’a pas abouti : {message}', + 'filterLens.stale': 'Les modifications ont été relues ; actualisez pour les filtrer par « {lens} »', + 'filterLens.removed': 'La lentille « {lens} » a été retirée', + 'filterLens.interrupted': 'La lentille « {lens} » s’est interrompue avant de finir', + 'filterLens.folded': '{count} modifications sans rapport avec « {lens} » repliées', + 'filterLens.unfold': 'Afficher', + 'annotation.outdated': 'Annotations sur une modification antérieure · {count}', + 'annotation.hidden': '{count} autres annotations de ce fichier ne sont pas affichées', 'tests.hide': 'Masquer les fichiers de test', 'tests.hideHint': 'Masque les tests, instantanés, fichiers de langue, fichiers de verrouillage et fichiers générés', 'viewed.label': 'Vu', @@ -2388,6 +2463,21 @@ export const de: Record = { 'lens.testHidden': 'Testdateien sind ausgeblendet', 'lens.menuAria': 'Prüfebene: {lens}', 'lens.empty': 'Keine Dateien anzuzeigen', + 'filterLens.label': 'Linse', + 'filterLens.aria': 'Filterlinse', + 'filterLens.chosenAria': 'Filterlinse: {lens}', + 'filterLens.heading': 'Filterlinsen', + 'filterLens.none': 'Keine Linse', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Linse entfernen', + 'filterLens.failed': 'Die Linse „{lens}“ wurde nicht fertig: {message}', + 'filterLens.stale': 'Die Änderungen wurden neu gelesen; aktualisieren, um nach „{lens}“ zu filtern', + 'filterLens.removed': 'Die Linse „{lens}“ wurde entfernt', + 'filterLens.interrupted': 'Die Linse „{lens}“ wurde vor dem Ende unterbrochen', + 'filterLens.folded': '{count} Änderungen ohne Bezug zu „{lens}“ eingeklappt', + 'filterLens.unfold': 'Anzeigen', + 'annotation.outdated': 'Anmerkungen zu einer früheren Änderung · {count}', + 'annotation.hidden': '{count} weitere Anmerkungen dieser Datei werden nicht angezeigt', 'tests.hide': 'Testdateien ausblenden', 'tests.hideHint': 'Blendet Tests, Snapshots, Sprachdateien, Lockfiles und generierte Dateien aus', 'viewed.label': 'Angesehen', @@ -2817,6 +2907,21 @@ export const ru: Record = { 'lens.testHidden': 'Тестовые файлы скрыты', 'lens.menuAria': 'Слой проверки: {lens}', 'lens.empty': 'Нет файлов для показа', + 'filterLens.label': 'Линза', + 'filterLens.aria': 'Линза-фильтр', + 'filterLens.chosenAria': 'Линза-фильтр: {lens}', + 'filterLens.heading': 'Линзы-фильтры', + 'filterLens.none': 'Без линзы', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Убрать линзу', + 'filterLens.failed': 'Линза «{lens}» не завершилась: {message}', + 'filterLens.stale': 'Изменения прочитаны заново; обновите, чтобы отфильтровать их по «{lens}»', + 'filterLens.removed': 'Линза «{lens}» удалена', + 'filterLens.interrupted': 'Линза «{lens}» прервалась, не завершившись', + 'filterLens.folded': 'Свёрнуто изменений, не связанных с «{lens}»: {count}', + 'filterLens.unfold': 'Показать', + 'annotation.outdated': 'Заметки к более раннему изменению · {count}', + 'annotation.hidden': 'Ещё заметок в этом файле не показано: {count}', 'tests.hide': 'Скрыть тестовые файлы', 'tests.hideHint': 'Скрывает тесты, снимки, файлы локализации, lock-файлы и сгенерированные файлы', 'viewed.label': 'Просмотрено', @@ -3246,6 +3351,21 @@ export const pt: Record = { 'lens.testHidden': 'Os arquivos de teste estão ocultos', 'lens.menuAria': 'Camada de revisão: {lens}', 'lens.empty': 'Nenhum arquivo para mostrar', + 'filterLens.label': 'Lente', + 'filterLens.aria': 'Lente de filtro', + 'filterLens.chosenAria': 'Lente de filtro: {lens}', + 'filterLens.heading': 'Lentes de filtro', + 'filterLens.none': 'Nenhuma lente', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Remover lente', + 'filterLens.failed': 'A lente “{lens}” não terminou: {message}', + 'filterLens.stale': 'As alterações foram lidas de novo; atualize para filtrá-las por “{lens}”', + 'filterLens.removed': 'A lente “{lens}” foi removida', + 'filterLens.interrupted': 'A lente “{lens}” parou antes de terminar', + 'filterLens.folded': '{count} alterações sem relação com “{lens}” recolhidas', + 'filterLens.unfold': 'Mostrar', + 'annotation.outdated': 'Anotações em uma alteração anterior · {count}', + 'annotation.hidden': 'Mais {count} anotações deste arquivo não são mostradas', 'tests.hide': 'Ocultar arquivos de teste', 'tests.hideHint': 'Oculta testes, snapshots, arquivos de idioma, arquivos de bloqueio e arquivos gerados', 'viewed.label': 'Revisado', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index d9304ea46a..84e4cc70ee 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -17,13 +17,18 @@ import type {} from '@deepseek-ai/dsh-experimental-client-ui-forge/remote' import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' -import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgePanelChangeRequest } from '../types.ts' +import type { + ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgePanelChangeRequest, +} from '../types.ts' +import { AnnotationView } from './annotations.ts' +import { ForgeChangesService } from './changes-service.ts' +import type {} from './slots.ts' import { ReviewQueue } from './review-queue.ts' import { ViewedFiles } from './viewed-files.ts' import { formatReviewComment, reviewQuoteSummary, type ReviewSelection } from './review.ts' import { formatThreadQuote, threadQuoteSummary } from './review-threads.ts' import { ActionToast } from './ActionToast.tsx' -import { CHANGES_ID, changesDefinition } from './changes-address.ts' +import { CHANGES_ID, CHANGES_KIND, changesDefinition, parseChangesAddress } from './changes-address.ts' import { createChangesStore } from './changes-store.ts' import { ChangesTab, type ChangesTabInjected } from './ChangesTab.tsx' import { ChangesTabTitle } from './ChangesTabTitle.tsx' @@ -72,6 +77,8 @@ interface SessionStores { readonly visibility: VisibilitySource readonly reviews: WeakMap readonly viewed: ViewedFiles + /** Plugin annotations of each changes view of the Session, by address. */ + readonly annotations: Map readonly release: () => void } @@ -116,13 +123,38 @@ function registerUi(ctx: Context): void { stores.delete(sessionId) }, 'forge-panel: release Session state') store = { - panel, visibility: createVisibilitySource(), reviews: new WeakMap(), viewed: new ViewedFiles(sessionId), + panel, visibility: createVisibilitySource(), reviews: new WeakMap(), viewed: new ViewedFiles(sessionId), annotations: new Map(), release: () => { void dispose() }, } stores.set(sessionId, store) } return store } + // The Host's lenses and annotation limit, streamed while any view reads them. + const extensionSource = createStreamSource({ + open: signal => ctx.remote.forgePanel.extensions(signal), + subscribeReset: listener => ctx.on('connection/reset', listener), + }, null, (_previous, frame) => frame) + ctx.effect(() => () => { extensionSource.close() }, 'forge-panel: extension stream') + const changes = new ForgeChangesService({ + mounted: () => ctx.sidebarRight.mounted.getSnapshot(), + openResource: (address, params) => { ctx.sidebarRight.openResource(address, params === undefined ? undefined : { params }) }, + }, { + getSnapshot: () => extensionSource.observable.getSnapshot().state, + subscribe: listener => extensionSource.observable.subscribe(listener), + }, { changes: CHANGES_KIND, panel: TAB_KIND }) + const withdrawChanges = ctx.reflect.provide('forgeChanges', changes) + ctx.effect(() => () => { void withdrawChanges() }, 'forge-panel: changes view face') + const annotationsOf = (store: SessionStores, address: string): AnnotationView => { + let view = store.annotations.get(address) + if (view === undefined) { + const target = parseChangesAddress(address) + if (target === undefined) throw new Error(`forge-panel: not a changes address "${address}"`) + view = new AnnotationView(changes.annotationSources, target) + store.annotations.set(address, view) + } + return view + } const settled = (result: RemoteResult, failure: ForgePanelKey, codes: Partial> = {}): boolean => { if (result.ok) return true notices.report(codes[result.error.code] ?? failure) @@ -271,7 +303,12 @@ function registerUi(ctx: Context): void { const changesFace = (sessionId: SessionId): ChangesTabInjected => { const store = storesOf(sessionId) return { - keyedHooks: { panel: visibility => visibility === 'visible' ? store.panel.hooks.panel : undefined }, + keyedHooks: { + panel: visibility => visibility === 'visible' ? store.panel.hooks.panel : undefined, + annotations: address => annotationsOf(store, address), + }, + hooks: { lenses: changes.lenses, extensions: extensionSource.observable }, + changesLens: (request, signal) => ctx.remote.forgePanel.changesLens(sessionId, request, signal), reconnect: store.panel.reconnect, localDiff: (scope, signal) => ctx.remote.forgePanel.localDiff(sessionId, scope, signal), diffBases: (query, signal) => ctx.remote.forgePanel.diffBases(sessionId, query, signal), @@ -356,6 +393,7 @@ function registerUi(ctx: Context): void { }), 'forge-panel: sidebar tab') ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID, locale: NS, inject: tabFace, + children: { 'forge.change-request.card.actions': { kind: 'list', scope: 'session' } }, }, ForgeTab)) ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID, locale: NS, @@ -363,6 +401,12 @@ function registerUi(ctx: Context): void { ctx.effect(() => ctx.sidebarRightTabs.register(changesDefinition(t)), 'forge-panel: changes tab') ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: CHANGES_ID, locale: NS, store: createChangesStore(), inject: changesFace, + children: { + 'forge.changes.toolbar': { kind: 'list', scope: 'session' }, + 'forge.changes.file.menu': { kind: 'list', scope: 'session' }, + 'forge.diff.line.annotation': { kind: 'keyed', scope: 'session' }, + 'forge.diff.comment.actions': { kind: 'list', scope: 'session' }, + }, }, ChangesTab)) ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: CHANGES_ID, locale: NS, diff --git a/packages/experimental/client-ui-forge/src/client/slots.ts b/packages/experimental/client-ui-forge/src/client/slots.ts new file mode 100644 index 0000000000..724463b03e --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/slots.ts @@ -0,0 +1,81 @@ +/** The forge panel's extension slots and the props their owners pass. */ + +import type { ChangeRequestRef, ChangeRequestState } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeLensFile } from '../types.ts' +import type { ChangesTarget } from './changes-address.ts' +import type { ForgeLineAnnotation } from './changes-service.ts' + +/** Owner props of `forge.changes.toolbar`. */ +export interface ForgeChangesToolbarProps { + /** The view the toolbar belongs to. */ + readonly target: ChangesTarget + /** `bar`: a 28px tool in the toolbar row; `menu`: `MenuItemButton` rows of the More menu a narrow toolbar folds entries into. */ + readonly form: 'bar' | 'menu' + /** Close the More menu after a row acted; a no-op in the toolbar row. */ + readonly close: () => void +} + +/** Owner props of `forge.changes.file.menu`. */ +export interface ForgeChangesFileMenuProps { + /** The view the file belongs to. */ + readonly target: ChangesTarget + /** The file whose menu opened. */ + readonly file: ForgeLensFile + /** Close the menu after a row acted. */ + readonly dismiss: () => void +} + +/** Owner props of `forge.diff.line.annotation`. */ +export interface ForgeLineAnnotationProps { + /** The view the annotation shows in. */ + readonly target: ChangesTarget + /** Repository-relative path of the annotated file. */ + readonly path: string + /** The annotation its source reported. */ + readonly annotation: ForgeLineAnnotation +} + +/** Owner props of `forge.diff.comment.actions`. */ +export interface ForgeCommentActionsProps { + /** The view the comment form belongs to. */ + readonly target: ChangesTarget + /** The lines the comment is on. */ + readonly selection: { readonly path: string; readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } + /** Whether the comment has no text, so actions stay disabled. */ + readonly empty: boolean + /** Whether a send runs, so actions stay disabled. */ + readonly busy: boolean + /** + * Hand the comment's text to `deliver`. The form shows itself busy until `deliver` settles, closes when it resolves + * to undefined, and keeps the text with the message it resolves to otherwise. + * @param deliver - receives the text. + */ + readonly send: (deliver: (body: string) => Promise) => void +} + +/** Owner props of `forge.change-request.card.actions`. */ +export interface ForgeChangeRequestCardActionsProps { + /** Binding URL of the change request. */ + readonly url: string + /** Parsed reference, or null when no provider serves the URL. */ + readonly ref: ChangeRequestRef | null + /** Head commit of the latest status, or null before one. */ + readonly headSha: string | null + /** Lifecycle state of the latest status, or null before one. */ + readonly state: ChangeRequestState | null +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** Tools a plugin adds to the changes toolbar, after its flexible space and before the thread list toggle. */ + 'forge.changes.toolbar': { kind: 'list'; scope: 'session'; owner: ForgeChangesToolbarProps } + /** Rows a plugin adds to a file's menu, below the built-in rows. */ + 'forge.changes.file.menu': { kind: 'list'; scope: 'session'; owner: ForgeChangesFileMenuProps } + /** The content of one line annotation, keyed by its source; the changes view draws the frame around it. */ + 'forge.diff.line.annotation': { kind: 'keyed'; scope: 'session'; owner: ForgeLineAnnotationProps } + /** Buttons a plugin adds to the line comment form, between Add to input and the code host actions. */ + 'forge.diff.comment.actions': { kind: 'list'; scope: 'session'; owner: ForgeCommentActionsProps } + /** Icon buttons a plugin adds to a change request card's head, before Open in browser. */ + 'forge.change-request.card.actions': { kind: 'list'; scope: 'session'; owner: ForgeChangeRequestCardActionsProps } + } +} diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 3e42c6cfc6..ebc09dcb61 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,7 +6,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - BranchUpdateMethod, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, + BranchUpdateMethod, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, + ForgeFailure, ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' @@ -25,8 +26,12 @@ import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint, - localCommits, localDiff, localText, NoForkPoint, + localCommits, localDiff, localOldText, localText, NoForkPoint, } from './local-diff.ts' +import type { ForkPoint } from './local-diff.ts' +import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from './lenses.ts' +import type { LensSubject } from './lenses.ts' +import { lensVersion } from './lens-version.ts' import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' @@ -35,8 +40,9 @@ import { ReviewCache } from './review-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits, - ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, + ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, + ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -50,8 +56,16 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */ -type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string } +/** Panel limits plus the branch and commit listing limits, the worktree branch prefix, and the lens and annotation limits. */ +type ControllerConfig = PanelConfig & { + readonly maxBranches: number + readonly maxCommits: number + readonly worktreePrefix: string + readonly lensTimeoutMs: number + readonly maxLensReadBytes: number + readonly maxCachedLensBytes: number + readonly maxAnnotationsPerFile: number +} /** * Serves the forge panel. Following a Session inspects the checkout of its @@ -89,6 +103,10 @@ export class ForgePanelController extends TypertRemoteService { interfacePaths: z.array(z.string()).default([]), maxCachedReviewBytes: z.number().default(16_777_216), reviewRefreshMs: z.number().default(60_000), + lensTimeoutMs: z.number().default(60_000), + maxLensReadBytes: z.number().default(33_554_432), + maxCachedLensBytes: z.number().default(4_194_304), + maxAnnotationsPerFile: z.number().default(100), }) private readonly home: Context @@ -99,6 +117,10 @@ export class ForgePanelController extends TypertRemoteService { private readonly patches: PatchCache private readonly layers: FileLayers private readonly reviews: ReviewCache + private readonly lenses = new LensRegistry() + private readonly lensResults: LensCache + /** Review changes `forge/review-changed` announced per change request, which each panel entry reports. */ + private readonly reviewRevisions = new Map() private states: ChangeRequestStates | undefined private readonly stopPanels: () => Promise private readonly stopStates: () => Promise @@ -107,13 +129,16 @@ export class ForgePanelController extends TypertRemoteService { super(ctx, 'forgePanel') const resolved = config as Required if (resolved.gitCommand.trim().length === 0) throw new Error('forge-panel: gitCommand must not be empty') - for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs'] as const) { + for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs', 'lensTimeoutMs'] as const) { const value = resolved[key] if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) { throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } } - for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes'] as const) { + for (const key of [ + 'maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes', 'maxLensReadBytes', + 'maxCachedLensBytes', 'maxAnnotationsPerFile', + ] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') @@ -125,6 +150,8 @@ export class ForgePanelController extends TypertRemoteService { this.config = resolved this.patches = new PatchCache(resolved.maxCachedDiffBytes) this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs) + this.lensResults = new LensCache(resolved.maxCachedLensBytes) + ctx.effect(() => () => { this.lenses.close() }, 'forge-panel: lens streams') this.stopPanels = ctx.effect(() => async () => { const panels = [...this.panels.values()] this.panels.clear() @@ -153,6 +180,7 @@ export class ForgePanelController extends TypertRemoteService { const events = ctx.on('session/event', (session: Session, event: SessionEvent) => { this.panels.get(session)?.observe(event) }) + const reviewChanges = ctx.on('forge/review-changed', (ref: ChangeRequestRef) => { this.reviewChanged(ref) }) const services = ctx.on('internal/service', (name: string) => { if (name !== 'worktrees') return for (const panel of this.panels.values()) panel.updateWorktree() @@ -162,6 +190,7 @@ export class ForgePanelController extends TypertRemoteService { yield stateOwner.dispose yield inbox yield events + yield reviewChanges yield services yield stopPanels yield stopStates @@ -418,16 +447,13 @@ export class ForgePanelController extends TypertRemoteService { if (update === null || !('snapshot' in update)) { throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {}) } - if (commits !== null) return await this.commitsDiff(ref, commits, signal) - const { headSha, headBranch, baseBranch } = update.snapshot - const key = changeRequestKey(ref) - const version = JSON.stringify([headSha, baseBranch]) - let read = this.patches.get(key, version) - if (read === undefined) { - read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal) - this.patches.set(key, version, read) + if (commits !== null) { + const { files } = await this.commitFiles(ref, commits, signal) + const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) + return { headSha: commits.to, files, localAhead: null, fileUrls } } - const files = this.layers.classify(parseDiff(read.patch), read.attributes) + const { headSha, headBranch } = update.snapshot + const files = await this.headFiles(ref, update.snapshot, signal) let localAhead: number | null = null try { localAhead = await aheadOf( @@ -462,6 +488,86 @@ export class ForgePanelController extends TypertRemoteService { return text } + /** + * Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending + * the registration aborts its running classifications and waits for them. + * @param lens - the lens. + * @returns the disposer that unregisters the lens and waits for its classifications to stop. + * @throws when another registration holds `lens.id`. + */ + registerLens(lens: ForgeLens): () => Promise { + const dispose = this.ctx.effect(() => this.lenses.add(lens), 'forge-panel: lens') + return async () => { await dispose() } + } + + /** + * Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts + * after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns the registered lenses and the annotation limit, in publication order. + */ + @Remote({ mode: 'stream' }) + async *extensions(signal: AbortSignal): AsyncIterable { + for await (const lenses of this.lenses.follow(signal)) yield { lenses, maxAnnotationsPerFile: this.config.maxAnnotationsPerFile } + } + + /** + * Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens + * runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until + * `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files + * are those `changeRequestDiff` reads. + * @param session - Session whose checkout or binding the view shows. + * @param request - the view's source, the version of the files it shows, and the lens. + * @param signal - ends the classification. + * @returns progress frames, then one result frame. + * @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends; + * `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and + * when local files changed while the lens ran; + * `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers + * over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files. + */ + @Remote({ mode: 'stream' }) + async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable { + signal.throwIfAborted() + const registration = this.lenses.get(request.lens) + if (registration === undefined) throw new RemoteError('forgePanel/lens-missing', `No lens "${request.lens}" is registered`, {}) + const subject = await this.lensSubject(session, request.source, signal) + // The registration may have ended while the files were read; its lens neither runs nor answers from memory then. + signal.throwIfAborted() + if (registration.lifetime.aborted) throw new RemoteError('forgePanel/lens-missing', `No lens "${request.lens}" is registered`, {}) + if (lensVersion(subject.files) !== request.version) { + throw new RemoteError('forgePanel/lens-stale', 'The changes were read again since the view showed them', {}) + } + const key = JSON.stringify([subject.key, request.version, request.lens, registration.lens.version]) + const kept = this.lensResults.get(key) + if (kept !== undefined) { + yield { kind: 'result', files: kept } + return + } + const limits = { + timeoutMs: this.config.lensTimeoutMs, maxReadBytes: this.config.maxLensReadBytes, maxResultBytes: this.config.maxCachedLensBytes, + } + try { + for await (const frame of lensFrames(progress => runLens(registration, subject, limits, signal, progress))) { + if (frame.kind === 'result') { + // Local files can change while the lens reads them; a result about other contents is neither kept nor sent. + if (request.source.kind === 'local') { + const now = await this.lensSubject(session, request.source, signal) + if (lensVersion(now.files) !== request.version) { + throw new RemoteError('forgePanel/lens-stale', 'The changes moved while the lens read them', {}) + } + } + this.lensResults.set(key, frame.files) + } + yield frame + } + } catch (error) { + if (error instanceof LensWithdrawn) throw new RemoteError('forgePanel/lens-missing', error.message, {}) + if (error instanceof LensFailed) throw new RemoteError('forgePanel/lens-failed', error.message, {}) + throw error + } + } + /** * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the * whole change request. @@ -870,8 +976,23 @@ export class ForgePanelController extends TypertRemoteService { return this.home.workingDirectory.get(session) === directory ? missing : null } - /** The changes of consecutive commits of a change request, from the first one's first parent to the last. */ - private async commitsDiff(ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal): Promise { + /** The files of a change request at the head a status recorded, read once per head and base branch while the cache keeps them. */ + private async headFiles(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise { + const { headSha, baseBranch } = snapshot + const key = changeRequestKey(ref) + const version = JSON.stringify([headSha, baseBranch]) + let read = this.patches.get(key, version) + if (read === undefined) { + read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal) + this.patches.set(key, version, read) + } + return this.layers.classify(parseDiff(read.patch), read.attributes) + } + + /** The files of consecutive commits of a change request, from the first one's first parent, which is returned too, to the last. */ + private async commitFiles( + ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal, + ): Promise<{ readonly files: ForgeDiffFile[]; readonly parent: string }> { const list = await this.home.forge.commits(ref, signal) if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {}) if ('code' in list) throw readError(list) @@ -883,9 +1004,7 @@ export class ForgePanelController extends TypertRemoteService { const { patch, attributes } = await this.patchAt( ref, commits.to, async operation => await this.home.forge.compare(ref, parent, commits.to, operation), signal, ) - const files = this.layers.classify(parseDiff(patch), attributes) - const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) - return { headSha: commits.to, files, localAhead: null, fileUrls } + return { files: this.layers.classify(parseDiff(patch), attributes), parent } } /** @@ -1020,10 +1139,95 @@ export class ForgePanelController extends TypertRemoteService { return this.states } + /** Drop the threads kept for a change request after an accepted review change and let its panel entries report it. */ + private reviewChanged(ref: ChangeRequestRef): void { + const key = changeRequestKey(ref) + this.reviews.drop(key) + this.reviewRevisions.set(key, (this.reviewRevisions.get(key) ?? 0) + 1) + for (const panel of this.panels.values()) panel.reviewChanged() + } + + /** The files a lens request names with their reader and the key results for them are kept under. */ + private async lensSubject( + session: Session, source: ForgeLensRequest['source'], signal: AbortSignal, + ): Promise { + if (source.kind === 'local') { + const inspection = await this.checkoutOf(session, signal) + const root = inspection.checkout.root + const { scope } = source + const fork: ForkPoint | null = scope.kind !== 'branch' ? null : await diffing(scope.base === null + ? forkPoint(gitIn(this.home, this.config, session, root, signal), inspection, this.worktreeState(session).created) + : chosenForkPoint(gitIn(this.home, this.config, session, root, signal), scope.base)) + const { files } = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal)) + return { + key: JSON.stringify(['local', session.id, scope]), + source: { kind: 'local', scope }, + files, + read: async (side, file, inner) => { + if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null + return side === 'new' + ? await diffing(localText(this.home, this.config, session, root, scope, file.path, inner)) + : await diffing(localOldText(this.home, this.config, session, root, scope, fork, file.previousPath ?? file.path, inner)) + }, + } + } + const { ref, update } = this.bound(session, source.url) + if (update === null || !('snapshot' in update)) { + throw new RemoteError('forgePanel/lens-stale', 'The change request status has not been read yet', {}) + } + const { snapshot } = update + const { commits } = source + let files: ForgeDiffFile[] + let newCommit: string + let oldCommit: (inner: AbortSignal) => Promise + if (commits === null) { + files = await this.headFiles(ref, snapshot, signal) + newCommit = snapshot.headSha + // One merge base serves every old side of the run; a failed lookup is tried again by the next read. + let base: Promise | undefined + oldCommit = async (inner) => { + base ??= this.mergeBaseOf(ref, snapshot, inner) + try { + return await base + } catch (error) { + base = undefined + throw error + } + } + } else { + const read = await this.commitFiles(ref, commits, signal) + files = read.files + newCommit = commits.to + oldCommit = () => Promise.resolve(read.parent) + } + return { + key: JSON.stringify(['change', changeRequestKey(ref), newCommit, commits]), + source: { kind: 'change', ref, headSha: snapshot.headSha, commits }, + files, + read: async (side, file, inner) => { + if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null + const commit = side === 'new' ? newCommit : await oldCommit(inner) + const text = await this.home.forge.fileText(ref, commit, side === 'new' ? file.path : file.previousPath ?? file.path, inner) + if (typeof text === 'string') return text + if (text.code === 'not-found') return null + throw new Error(text.message) + }, + } + } + + /** The merge base whose files the old side of a change request's diff at the status's head shows. */ + private async mergeBaseOf(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise { + if (snapshot.baseSha === undefined) throw new Error('The code host provider reports no base commit to read the old side at') + const base = await this.home.forge.mergeBase(ref, snapshot.baseSha, snapshot.headSha, signal) + if (typeof base !== 'string') throw new Error(base.message) + return base + } + private panelOf(session: Session): SessionPanel { let panel = this.panels.get(session) if (panel === undefined) { - const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, () => { + const revision = (ref: ChangeRequestRef): number => this.reviewRevisions.get(changeRequestKey(ref)) ?? 0 + const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, revision, () => { if (this.panels.get(session) !== created) return this.panels.delete(session) void created.dispose() diff --git a/packages/experimental/client-ui-forge/src/lens-version.ts b/packages/experimental/client-ui-forge/src/lens-version.ts new file mode 100644 index 0000000000..cca6dea479 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/lens-version.ts @@ -0,0 +1,27 @@ +/** + * The version of a diff's files that a lens request names. The panel host and the changes view compute it alike, so a + * request refers to exactly the files its view shows. + */ + +/** + * Name the files of one diff: equal versions describe the same paths with the same changes in the same order. + * @param files - the diff's files in display order. + * @returns 14 hexadecimal digits of a 53-bit hash over each path and change digest. + */ +export function lensVersion(files: readonly { readonly path: string; readonly digest: string }[]): string { + // cyrb53: two 32-bit multiply-xorshift lanes folded into 53 bits. + let h1 = 0xdeadbeef + let h2 = 0x41c6ce57 + for (const file of files) { + for (const text of [file.path, '\u0000', file.digest, '\u0001']) { + for (let index = 0; index < text.length; index += 1) { + const code = text.charCodeAt(index) + h1 = Math.imul(h1 ^ code, 2654435761) + h2 = Math.imul(h2 ^ code, 1597334677) + } + } + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909) + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909) + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0') +} diff --git a/packages/experimental/client-ui-forge/src/lenses.ts b/packages/experimental/client-ui-forge/src/lenses.ts new file mode 100644 index 0000000000..0251503d5d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/lenses.ts @@ -0,0 +1,284 @@ +/** Filter lenses registered on the forge panel host, the runs that classify one diff with one of them, and the kept results. */ + +import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import type { + ForgeLens, ForgeLensFile, ForgeLensFrame, ForgeLensInput, ForgeLensKeep, ForgeLensSource, ForgeRegisteredLens, +} from './types.ts' + +/** The files a lens kept, by path. */ +export type LensFiles = Readonly> + +/** Why a lens run produced no result; the message names the cause for the reader. */ +export class LensFailed extends Error { + override name = 'LensFailed' +} + +/** The reason a run stops when its lens's registration ends. */ +export class LensWithdrawn extends Error { + override name = 'LensWithdrawn' +} + +/** One registered lens and the runs that use it. */ +export interface LensRegistration { + /** The lens as its plugin registered it. */ + readonly lens: ForgeLens + /** Aborts with a {@link LensWithdrawn} once the registration ends. */ + readonly lifetime: AbortSignal + /** + * Keep one run among the work the registration's disposer waits for. + * @param run - the run. + * @returns the same run. + */ + track(run: Promise): Promise +} + +/** + * The lenses registered on one panel host. Identities are unique while registered; the follow streams of every reader + * receive the list after each change, and end once the registry closes. + */ +export class LensRegistry { + private readonly entries = new Map() + private readonly listeners = new Set<() => void>() + private readonly closed = new AbortController() + + /** + * Register a lens. + * @param lens - the lens. + * @returns the disposer, which aborts the lens's running classifications and waits for them. + * @throws when another registration holds `lens.id`. + */ + add(lens: ForgeLens): () => Promise { + if (this.entries.has(lens.id)) throw new Error(`forge-panel: a lens "${lens.id}" is already registered`) + const lifetime = new AbortController() + const runs = new Set>() + const registration: LensRegistration = { + lens, + lifetime: lifetime.signal, + track: (run) => { + const settled = run.then(() => undefined, () => undefined) + runs.add(settled) + void settled.then(() => runs.delete(settled)) + return run + }, + } + this.entries.set(lens.id, registration) + this.changed() + return async () => { + this.entries.delete(lens.id) + lifetime.abort(new LensWithdrawn(`the lens "${lens.id}" was unregistered`)) + this.changed() + await Promise.allSettled([...runs]) + } + } + + /** + * Find a registered lens. + * @param id - its identity. + * @returns the registration, or undefined while no lens holds the identity. + */ + get(id: string): LensRegistration | undefined { + return this.entries.get(id) + } + + /** + * Stream the registered lenses: the current list first, then the list after each change; changes that arrive while + * the reader is busy collapse into the next list. + * @param signal - ends the stream. + * @returns identities and versions in registration order. + */ + async *follow(signal: AbortSignal): AsyncIterable { + const stop = AbortSignal.any([signal, this.closed.signal]) + let wake = Promise.withResolvers() + const listener = (): void => { wake.resolve() } + this.listeners.add(listener) + stop.addEventListener('abort', listener) + try { + while (!stop.aborted) { + const current = wake + yield [...this.entries.values()].map(({ lens }) => ({ id: lens.id, version: lens.version })) + await current.promise + wake = Promise.withResolvers() + } + } finally { + this.listeners.delete(listener) + stop.removeEventListener('abort', listener) + } + } + + /** End every follow stream; registrations still end through their own disposers. */ + close(): void { + this.closed.abort() + } + + private changed(): void { + for (const listener of this.listeners) listener() + } +} + +/** One diff a lens classifies, with the reader of its files' sides. */ +export interface LensSubject { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`. + * @returns the text, or null when the side does not exist or holds binary content. + */ + readonly read: (side: 'old' | 'new', file: ForgeLensFile, signal: AbortSignal) => Promise +} + +/** Bounds of one lens run, from the panel's configuration. */ +export interface LensLimits { + /** `lensTimeoutMs`. */ + readonly timeoutMs: number + /** `maxLensReadBytes`. */ + readonly maxReadBytes: number + /** `maxCachedLensBytes`, which bounds one result as JSON. */ + readonly maxResultBytes: number +} + +/** + * Classify one diff with one lens. The lens's signal aborts with the caller's, when the registration ends, and after + * `timeoutMs`; the run settles then even when the lens ignores its signal, while the registration's disposer waits until + * `classify` itself settles. A run whose signal aborted before it started does not call the lens. Paths the lens names + * outside the diff are left out of the result. + * @param registration - the registered lens. + * @param subject - the diff and its reader. + * @param limits - deadline, read budget, and result bound. + * @param signal - the caller's cancellation. + * @param progress - receives the lens's progress while it runs. + * @returns the files the lens kept. + * @throws `signal.reason` once the caller aborts; a {@link LensWithdrawn} once the registration ends; a + * {@link LensFailed} when the lens rejects, runs past the deadline, reads past the budget, or answers over the bound. + */ +export async function runLens( + registration: LensRegistration, + subject: LensSubject, + limits: LensLimits, + signal: AbortSignal, + progress: (done: number, total: number) => void, +): Promise { + using timer = deadline(AbortSignal.any([signal, registration.lifetime]), limits.timeoutMs, 'FORGE_LENS_TIMEOUT') + const operation = timer.signal + const byPath = new Map(subject.files.map(file => [file.path, file])) + let read = 0 + const overBudget = (): LensFailed => new LensFailed(`the lens read more than maxLensReadBytes (${limits.maxReadBytes} bytes) of file text`) + const input: ForgeLensInput = { + source: subject.source, + files: subject.files, + text: async (side, path, inner) => { + const file = byPath.get(path) + if (file === undefined) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a file of this diff`) + if (read > limits.maxReadBytes) throw overBudget() + const text = await subject.read(side, file, AbortSignal.any([inner, operation])) + if (text === null) return null + read += Buffer.byteLength(text) + if (read > limits.maxReadBytes) throw overBudget() + return text + }, + progress: (done, total) => { if (!operation.aborted) progress(done, total) }, + } + let result: Awaited> + try { + // A registration that ended or a caller that left before the run starts never reaches the lens. + operation.throwIfAborted() + const stopped = new Promise((_resolve, reject) => { + operation.addEventListener('abort', () => { reject(new Error('the lens run stopped', { cause: operation.reason })) }, { once: true }) + }) + // The race observes `stopped`; this handler only keeps a later abort from rejecting unobserved. + void stopped.catch(() => undefined) + // The registration's disposer waits for the classification itself; the race only decides when the caller hears back. + const classified = registration.track(Promise.resolve().then(() => registration.lens.classify(input, operation))) + result = await Promise.race([classified, stopped]) + } catch (error) { + if (signal.aborted) throw signal.reason + if (registration.lifetime.aborted) throw registration.lifetime.reason + if (timeoutOf(operation) !== undefined) throw new LensFailed(`the lens ran past lensTimeoutMs (${limits.timeoutMs} ms)`) + if (error instanceof LensFailed) throw error + throw new LensFailed(`the lens failed: ${error instanceof Error ? error.message : String(error)}`) + } + if (read > limits.maxReadBytes) throw overBudget() + const files: Record = {} + for (const [path, keep] of Object.entries(result.files)) { + if (byPath.has(path)) files[path] = keep + } + if (Buffer.byteLength(JSON.stringify(files)) > limits.maxResultBytes) { + throw new LensFailed(`the lens result exceeds maxCachedLensBytes (${limits.maxResultBytes} bytes)`) + } + return files +} + +/** + * Turn one run into frames: the latest progress whenever the lens reported some since the last frame, then the result. + * @param run - starts the run with the progress receiver. + * @returns progress frames, then one result frame. + * @throws the run's failure after its last progress frame. + */ +export async function* lensFrames( + run: (progress: (done: number, total: number) => void) => Promise, +): AsyncIterable { + // A box, so the reads below see what the progress callback writes. + const reports: { latest: { readonly done: number; readonly total: number } | null; finished: boolean } = { latest: null, finished: false } + // A function, so each check reads what the settlement wrote rather than the value the loop condition narrowed. + const finished = (): boolean => reports.finished + let wake = Promise.withResolvers() + const outcome = run((done, total) => { + reports.latest = { done, total } + wake.resolve() + }) + const settled = outcome.then(() => { reports.finished = true }, () => { reports.finished = true }) + while (!finished()) { + const current = wake + await Promise.race([current.promise, settled]) + wake = Promise.withResolvers() + const reported = reports.latest + reports.latest = null + if (reported !== null && !finished()) yield { kind: 'progress', done: reported.done, total: reported.total } + } + yield { kind: 'result', files: await outcome } +} + +/** Lens results kept for later requests, at most `maxBytes` of them as JSON, the least recently used dropped first. */ +export class LensCache { + private readonly entries = new Map() + private bytes = 0 + + /** @param maxBytes - `maxCachedLensBytes`. */ + constructor(private readonly maxBytes: number) {} + + /** + * Read a kept result, which becomes the most recently used. + * @param key - the request's files, lens, and lens version. + * @returns the result, or undefined when none is kept. + */ + get(key: string): LensFiles | undefined { + const entry = this.entries.get(key) + if (entry === undefined) return undefined + this.entries.delete(key) + this.entries.set(key, entry) + return entry.files + } + + /** + * Keep a result no larger than `maxBytes`, replacing one under the same key and dropping the least recently used + * results until the rest fit. + * @param key - the request's files, lens, and lens version. + * @param files - the result. + */ + set(key: string, files: LensFiles): void { + const previous = this.entries.get(key) + if (previous !== undefined) { + this.entries.delete(key) + this.bytes -= previous.bytes + } + const bytes = Buffer.byteLength(JSON.stringify(files)) + this.entries.set(key, { files, bytes }) + this.bytes += bytes + for (const [oldest, entry] of this.entries) { + if (this.bytes <= this.maxBytes) break + this.entries.delete(oldest) + this.bytes -= entry.bytes + } + } +} diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 88496f040c..17c753643a 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -273,6 +273,51 @@ export async function localText( return text } +/** + * Read the old side of one changed file in a scope: the fork point for the `branch` scope, the first parent of the + * first chosen commit for chosen commits, the index for `unstaged`, else HEAD. + * @param ctx - context that provides `subprocess`, `sandbox`, and `sandboxPolicy`. + * @param config - Git and size limits. + * @param session - Session whose sandbox policy and execution world apply. + * @param root - top-level directory of the checkout. + * @param scope - the scope whose old side to read. + * @param fork - the `branch` scope's fork point, or null for other scopes. + * @param path - path relative to `root` on the old side, as the diff names it. + * @param signal - cancellation. + * @returns the text, or null when the old side has no such file or holds binary content. + * @throws NoForkPoint for the `branch` scope without `fork`; CommitsMissing for a chosen commit that is not a full + * object name; DiffTooLarge over `maxDiffBytes`; an Error for a path outside the checkout or a failed read. + */ +export async function localOldText( + ctx: Context, + config: DiffConfig, + session: Session, + root: string, + scope: ForgeLocalScope, + fork: ForkPoint | null, + path: string, + signal: AbortSignal, +): Promise { + if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`) + let revision: string + switch (scope.kind) { + case 'branch': + if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with') + if (scope.commits !== null && !COMMIT.test(scope.commits.from)) throw new CommitsMissing('The chosen commit is not a full object name') + revision = scope.commits === null ? fork.commit : `${scope.commits.from}^` + break + case 'unstaged': revision = ''; break + case 'uncommitted': case 'staged': revision = 'HEAD'; break + /* v8 ignore next -- closed ForgeLocalScope union exhaustiveness guard */ + default: return assertNever(scope, 'ForgeLocalScope.kind') + } + const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) + // Git exits with 128 for a path or revision that does not exist, such as the parent of a root commit. + const shown = await bounded(git('show', ['show', `${revision}:${path}`], [0, 128])) + if (shown.exitCode !== 0 || shown.stdout.slice(0, BINARY_PROBE).includes('\0')) return null + return shown.stdout +} + /** * Measure the `branch` scope for the panel's card. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index ead8fecc97..15e6b3408d 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -2,7 +2,7 @@ import { isDeepStrictEqual } from 'node:util' import type { Context } from '@deepseek-ai/cordis' -import type { ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge' +import type { ChangeRequestRef, ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type {} from '@deepseek-ai/dsh-experimental-worktree' import type {} from '@deepseek-ai/dsh-sandbox-policy' @@ -75,6 +75,7 @@ export class SessionPanel { * @param worktreeStates - reads the `forgeWorktree` projection of the Session. * @param creations - reads the running creation and restoration, the last failed creation, and what a message of the * Session waits for. + * @param reviewRevision - reads how many review changes were announced for a change request. * @param onIdle - called when the last follower leaves. */ constructor( @@ -83,6 +84,7 @@ export class SessionPanel { readonly session: Session, private readonly worktreeStates: ProjectionHandle, private readonly creations: Pick, + private readonly reviewRevision: (ref: ChangeRequestRef) => number, private readonly onIdle: () => void, ) { this.current = { @@ -198,6 +200,11 @@ export class SessionPanel { await Promise.all([inspection, probe]) } + /** Publish the review revisions of the bound change requests after a review change was announced. */ + reviewChanged(): void { + this.publish({ ...this.current, changeRequests: this.entries(this.ctx.forgeSession.changeRequests(this.session)) }) + } + /** * Stop inspections, probes, and the change request watch, end every follower, and wait for pending work. * @returns settles once pending inspections and probes have ended. @@ -211,7 +218,8 @@ export class SessionPanel { private entries(changeRequests: readonly SessionChangeRequest[]): ForgePanelChangeRequest[] { return changeRequests.map((entry) => { if (entry.update !== null && 'snapshot' in entry.update) this.snapshots.set(entry.url, entry.update.snapshot) - return { ...entry, snapshot: this.snapshots.get(entry.url) ?? null } + const reviewRevision = entry.ref === null ? 0 : this.reviewRevision(entry.ref) + return { ...entry, snapshot: this.snapshots.get(entry.url) ?? null, reviewRevision } }) } diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 22c641e0d3..2be78af676 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -1,7 +1,8 @@ /** Browser-safe panel state, the worktree request record, Remote error codes, and Host configuration of the forge panel. */ import type {} from '@deepseek-ai/dsh-typert-protocol' -import type { ChangeRequestSnapshot, ForgeCommit, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { ChangeRequestRef, ChangeRequestSnapshot, ForgeCommit, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types' /** Git facts for the checkout that contains the Session's current directory. */ @@ -185,6 +186,11 @@ export type ForgeChangeRequestStatesFrame = export interface ForgePanelChangeRequest extends SessionChangeRequest { /** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */ readonly snapshot: ChangeRequestSnapshot | null + /** + * Number of review changes `forge/review-changed` announced for the change request since the panel host started; it + * grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it. + */ + readonly reviewRevision: number } /** Everything the panel shows for one Session. */ @@ -347,6 +353,102 @@ export interface ForgeChangeRequestDiff { readonly fileUrls: Readonly> } +/** Opaque identity of a filter lens, chosen by the plugin that registers it, such as `example/public-interface`. */ +export type ForgeLensId = Branded<'ForgeLensId'> + +/** One changed file a lens classifies: the diff's description of it, without the lines. */ +export type ForgeLensFile = Pick + +/** Lines `start` through `end` of one side of a file, both inclusive and 1-based. */ +export interface ForgeLineRange { + readonly start: number + readonly end: number +} + +/** What a lens keeps of one file. */ +export interface ForgeLensKeep { + /** + * Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand. + * Omitted: every hunk of the file shows. + */ + readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] } +} + +/** The files a lens keeps, by path; a file the result does not name is filtered out. */ +export interface ForgeLensResult { + readonly files: Readonly> +} + +/** What a changes view shows, as a lens sees it. */ +export type ForgeLensSource = + /** Local changes of a Session's checkout in one scope. */ + | { readonly kind: 'local'; readonly scope: ForgeLocalScope } + /** A change request at one head commit, whole or as consecutive commits. */ + | { readonly kind: 'change'; readonly ref: ChangeRequestRef; readonly headSha: string; readonly commits: ForgeCommitRange | null } + +/** What one `classify` call receives. */ +export interface ForgeLensInput { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order, with the layer the panel gave it. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to + * null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not + * in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot + * locate, and when the read fails. + */ + text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise + /** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */ + progress(done: number, total: number): void +} + +/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */ +export interface ForgeLens { + /** Identity the plugin chooses; one registration holds an id at a time. */ + readonly id: ForgeLensId + /** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */ + readonly version: string + /** + * Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the + * registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result. + */ + classify(input: ForgeLensInput, signal: AbortSignal): Promise +} + +/** What a changes view asks a lens to classify: its source, the version of the files it shows, and the lens. */ +export interface ForgeLensRequest { + /** The view's source: local changes in a scope, or a binding URL with its chosen commits. */ + readonly source: + | { readonly kind: 'local'; readonly scope: ForgeLocalScope } + | { readonly kind: 'change'; readonly url: string; readonly commits: ForgeCommitRange | null } + /** `lensVersion` of the files the view shows; files read since with another version refuse the request. */ + readonly version: string + /** Identity of the registered lens. */ + readonly lens: string +} + +/** One frame of a lens request: how far the lens is, then what it keeps. */ +export type ForgeLensFrame = + | { readonly kind: 'progress'; readonly done: number; readonly total: number } + | { readonly kind: 'result'; readonly files: Readonly> } + +/** A registered lens as changes views see it. */ +export interface ForgeRegisteredLens { + /** Identity of the lens. */ + readonly id: string + /** The lens's `version`; a view does not reuse results of another version. */ + readonly version: string +} + +/** Facts about the panel's extensions that every changes view reads. */ +export interface ForgeExtensionState { + /** The registered lenses, in registration order. */ + readonly lenses: readonly ForgeRegisteredLens[] + /** Most line annotations a changes view shows in one file, across every annotation source. */ + readonly maxAnnotationsPerFile: number +} + /** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */ export interface ForgeLocalCommits { /** HEAD commit the list was read at. */ @@ -421,6 +523,14 @@ export interface Config { * request's update time does not change when a thread is resolved. */ reviewRefreshMs?: number + /** Deadline in milliseconds for one lens `classify` call. */ + lensTimeoutMs?: number + /** Most UTF-8 bytes of file text one lens `classify` call may read. */ + maxLensReadBytes?: number + /** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */ + maxCachedLensBytes?: number + /** Most line annotations a changes view shows in one file, across every annotation source. */ + maxAnnotationsPerFile?: number } declare module '@deepseek-ai/dsh-typert-protocol' { @@ -486,6 +596,15 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/review-unsupported': Record /** The code host did not provide the change request's review threads, or its status has not been read yet; the message says why. */ 'forgePanel/review-failed': Record + /** No lens with the requested identity is registered, as after its plugin unloaded. */ + 'forgePanel/lens-missing': Record + /** The files the view shows are no longer the files the panel reads, so the view reads them again before asking. */ + 'forgePanel/lens-stale': Record + /** + * The lens failed, ran past `lensTimeoutMs`, read more than `maxLensReadBytes`, or answered over `maxCachedLensBytes`; + * the message says which. + */ + 'forgePanel/lens-failed': Record } } diff --git a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts index 5fda643a3f..ca192f0054 100644 --- a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts @@ -60,7 +60,7 @@ describe('createChangesStore', () => { const store = createChangesStore().create() store.actions.navigated('tab-1', 1) expect(store.getSnapshot().byTab['tab-1']).toEqual({ - scope: 'branch', base: null, commits: null, lens: 'all', hideTests: false, split: true, wrap: true, navigated: 1, + scope: 'branch', base: null, commits: null, lens: 'all', filterLens: null, hideTests: false, split: true, wrap: true, navigated: 1, }) store.actions.scoped('tab-1', 'staged') store.actions.based('tab-1', { ref: 'refs/heads/topic', name: 'topic' }) @@ -68,10 +68,11 @@ describe('createChangesStore', () => { store.actions.toggledWrap('tab-1') store.actions.lensed('tab-1', 'interface') store.actions.toggledTests('tab-1') + store.actions.filtered('tab-1', 'fixture/exports') store.actions.navigated('tab-1', 2) expect(store.getSnapshot().byTab['tab-1']).toEqual({ - scope: 'staged', base: { ref: 'refs/heads/topic', name: 'topic' }, commits: null, lens: 'interface', hideTests: true, - split: false, wrap: false, navigated: 2, + scope: 'staged', base: { ref: 'refs/heads/topic', name: 'topic' }, commits: null, lens: 'interface', filterLens: 'fixture/exports', + hideTests: true, split: false, wrap: false, navigated: 2, }) store.actions.navigated('tab-2', 1) store.actions.forget('tab-1') diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 495ca88e83..ac864ffbd5 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -18,11 +18,16 @@ import { ViewedFiles } from '../src/client/viewed-files.ts' import { createChangesStore } from '../src/client/changes-store.ts' import { ChangesTab, type ChangesTabInjected, type ChangesTabProps } from '../src/client/ChangesTab.tsx' import { en, zh } from '../src/client/locales.ts' -import type { PanelSnapshot } from '../src/client/source.ts' +import type { HostStream, PanelSnapshot, StreamSnapshot } from '../src/client/source.ts' +import type { ForgeLensDescription } from '../src/client/changes-service.ts' +import type { ViewAnnotations } from '../src/client/annotations.ts' +import type { ForgeChangesToolbarProps } from '../src/client/slots.ts' +import { lensVersion } from '../src/lens-version.ts' import css from '../src/client/ChangesTab.module.css' import baseCss from '../src/client/BaseMenu.module.css' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelChangeRequest, ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeExtensionState, ForgeLensId, ForgeLocalDiff, + ForgePanelChangeRequest, ForgePanelState, } from '../src/types.ts' import type { ChangeRequestKey, ForgeCommitList, ForgeReviewData, ForgeReviewId, ForgeReviewThread, ForgeReviewWriteResult, ForgeThreadId, @@ -186,12 +191,23 @@ function hookOf(instance: { subscribe: (listener: () => void) => () => void; } } +/** A Host stream that yields `frames`, then fails with `failure` when one is given. */ +function hostStream(frames: readonly F[], failure?: unknown): HostStream { + return { + dispose: vi.fn(), + async *[Symbol.asyncIterator]() { + for (const frame of frames) yield frame + if (failure !== undefined) throw failure + }, + } +} + /** Let the Remote reads the view awaits settle. */ async function settle(): Promise { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) } -type Faces = { -readonly [K in Exclude]: ReturnType> } +type Faces = { -readonly [K in Exclude]: ReturnType> } interface MountOptions { readonly translate?: typeof t @@ -204,6 +220,19 @@ interface MountOptions { readonly setup?: (faces: Faces) => void /** Viewed marks; each mount otherwise reads the Session's marks from browser storage. */ readonly viewedFiles?: ViewedFiles + /** The Host's lenses and annotation limit; null stands for facts not reported yet. */ + readonly extensions?: ForgeExtensionState | null + /** Lens titles Client plugins describe. */ + readonly lenses?: readonly ForgeLensDescription[] + /** Plugin annotations of the view by path, or null while the renderer has no source for the view. */ + readonly annotations?: ViewAnnotations | null +} + +/** One plugin slot the view drew: its name, the owner props, and the dispatch options. */ +interface SlotCall { + readonly key: string + readonly owner: unknown + readonly options: unknown } function mount(options: MountOptions = {}) { @@ -270,8 +299,27 @@ function mount(options: MountOptions = {}) { changeRequestReviewWrite: vi.fn(async () => ok({ ok: true })), createChangeRequest: vi.fn(), report: vi.fn(), + changesLens: vi.fn(() => hostStream([])), } options.setup?.(faces) + const extensions = createSnapshotStore>({ + state: options.extensions === undefined ? { lenses: [], maxAnnotationsPerFile: 100 } : options.extensions, disconnected: false, + }) + const lenses = createSnapshotStore(options.lenses ?? []) + const annotations = createSnapshotStore( + options.annotations === null ? undefined : options.annotations ?? new Map()) + const useAnnotationsOf = bindSnapshotSelector(annotations) + function useAnnotations(key: string): ViewAnnotations | undefined + function useAnnotations(key: string, select: (value: ViewAnnotations | undefined) => S): S + function useAnnotations(_key: string, select?: (value: ViewAnnotations | undefined) => S): S | ViewAnnotations | undefined { + return select === undefined ? useAnnotationsOf(value => value) : useAnnotationsOf(select) + } + const slotCalls: SlotCall[] = [] + // Records each plugin slot the view draws and draws nothing for it. + const renderSlot = ((key: string, owner: unknown, slotOptions?: unknown) => { + slotCalls.push({ key, owner, options: slotOptions }) + return null + }) as ChangesTabProps['renderSlot'] const viewedFiles = options.viewedFiles ?? new ViewedFiles(SESSION) const props: ChangesTabProps = { useTabInfo: () => ({ @@ -286,6 +334,10 @@ function mount(options: MountOptions = {}) { useStore: hookOf(store), actions: store.actions, usePanel, + useExtensions: bindSnapshotSelector(extensions), + useLenses: bindSnapshotSelector(lenses), + useAnnotations, + renderSlot, ...faces, viewedFiles, t: options.translate ?? t, @@ -298,7 +350,10 @@ function mount(options: MountOptions = {}) { return element } const paths = (): (string | null)[] => [...view.container.querySelectorAll('[data-forge-diff-file]')].map(element => element.getAttribute('data-forge-diff-file')) - return { view, panel, visibility, stops, navigation, store, aborter, tabActions, unbind, faces, viewedFiles, section, paths } + return { + view, panel, visibility, stops, navigation, store, aborter, tabActions, unbind, faces, viewedFiles, section, paths, extensions, lenses, + annotations, slotCalls, + } } /** Visible texts of the rows a section draws, in order. */ @@ -2374,6 +2429,37 @@ describe('ChangesTab review threads', () => { expect(scrolled.mock.contexts).toContain(card(m, 'notes')) }) + it('reads the threads and the viewed marks again when the host announces a review change', async () => { + const m = mount({ source, setup: reviewed() }) + await settle() + const reviews = m.faces.changeRequestReview.mock.calls.length + const marks = m.faces.changeRequestViewed.mock.calls.length + const current = m.panel.getSnapshot() + const state = current?.state + if (current === undefined || state === undefined || state === null) throw new Error('the panel has no state') + const announced = state.changeRequests.map(item => ({ ...item, reviewRevision: 1 })) + act(() => { m.panel.set({ ...current, state: { ...state, changeRequests: announced } }) }) + await settle() + expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(reviews + 1) + expect(m.faces.changeRequestViewed).toHaveBeenCalledTimes(marks + 1) + }) + + it('clears a filter lens that hides the file of a thread the reader opens from the thread list', async () => { + const lens = 'fixture/exports' + const m = mount({ source, extensions: { lenses: [{ id: lens, version: '1' }], maxAnnotationsPerFile: 5 }, params: { lens }, setup: (faces) => { + reviewed()(faces) + faces.changesLens.mockImplementation(() => hostStream([{ kind: 'result', files: { 'docs/notes.txt': {} } }])) + } }) + await settle() + expect(m.view.container.querySelector('[data-forge-diff-file="src/app.ts"]')).toBeNull() + fireEvent.click(m.view.getByRole('button', { name: /^Review threads, / })) + scrolled.mockClear() + fireEvent.click(m.view.getByRole('complementary').querySelector('[data-forge-thread-item="on-row"]')!) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBeNull() + await settle() + expect(scrolled.mock.contexts).toContain(card(m, 'on-row')) + }) + it('draws a file a thread jump targets before its section comes within reach, and keeps it drawn', async () => { // A double that never reports a section as reached, as for files far below the scrollport. vi.stubGlobal('IntersectionObserver', class { @@ -2477,3 +2563,143 @@ describe('ChangesTab review threads', () => { expect(card(m, 'on-row')).toBeNull() }) }) + +describe('ChangesTab extensions', () => { + const EXPORTS = 'fixture/exports' + const KEPT = { 'src/app.ts': { ranges: { old: [], new: [{ start: 3, end: 3 }] } }, 'src/new.ts': {}, 'docs/gone.txt': { ranges: { old: [], new: [] } } } + const describedLenses: readonly ForgeLensDescription[] = [{ id: EXPORTS as ForgeLensId, title: () => 'Exports' }] + const UNUSED = { id: 'lint/unused', version: '1' } + const hosted: ForgeExtensionState = { lenses: [UNUSED, { id: EXPORTS, version: '1' }], maxAnnotationsPerFile: 5 } + + it('offers the Host lenses by their descriptions and filters the files to those a chosen lens keeps, folding the hunks it is not about', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, setup: (faces) => { + faces.changesLens.mockReturnValueOnce(hostStream([{ kind: 'progress', done: 1, total: 6 }, { kind: 'result', files: KEPT }])) + } }) + await settle() + const trigger = m.view.getByRole('button', { name: 'Filter lens' }) + act(() => { trigger.click() }) + expect(within(document.body).getAllByRole('menuitem').map(row => row.textContent)).toEqual(['No lens', 'Exports—', 'lint/unused—']) + act(() => { within(document.body).getByRole('menuitem', { name: 'Exports—' }).click() }) + await settle() + expect(m.faces.changesLens.mock.calls[0]?.[0]).toEqual({ + source: { kind: 'local', scope: { kind: 'branch', base: null, commits: null } }, version: lensVersion(LOCAL.files), lens: EXPORTS, + }) + expect(m.paths()).toEqual(['docs/gone.txt', 'src/app.ts', 'src/new.ts']) + const chosen = m.view.getByRole('button', { name: 'Filter lens: Exports' }) + expect(chosen.textContent).toBe('Exports3') + expect(chosen.closest(`.${css.lensSlot}`)).not.toBeNull() + expect(m.view.getByRole('radiogroup', { name: 'Review layer' }).textContent).toBe('All3Interface0Implementation3Tests0') + const fold = m.section('src/app.ts').querySelector('[data-forge-lens-fold]') + expect(fold?.textContent).toBe('1 changes unrelated to “Exports” foldedShow') + act(() => { fold?.click() }) + expect(m.section('src/app.ts').querySelector('[data-forge-lens-fold]')).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-old-line="11"]')).not.toBeNull() + act(() => { m.section('docs/gone.txt').querySelector('[data-forge-lens-fold]')?.click() }) + expect(m.section('docs/gone.txt').querySelector('[data-old-line="1"]')).not.toBeNull() + + act(() => { chosen.click() }) + act(() => { within(document.body).getByRole('menuitem', { name: 'No lens' }).click() }) + expect(m.paths()).toHaveLength(6) + expect(m.faces.changesLens).toHaveBeenCalledTimes(1) + }) + + it('chooses the lens a navigation names, and stops filtering with a notice once the Host withdraws it', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, params: { lens: EXPORTS }, setup: (faces) => { + faces.changesLens.mockReturnValue(hostStream([{ kind: 'result', files: KEPT }])) + } }) + await settle() + expect(m.paths()).toEqual(['docs/gone.txt', 'src/app.ts', 'src/new.ts']) + act(() => { m.extensions.set({ state: { ...hosted, lenses: [UNUSED] }, disconnected: false }) }) + expect(m.paths()).toHaveLength(6) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBeNull() + expect(m.faces.report).toHaveBeenCalledWith('filterLens.removed', { lens: 'Exports' }) + }) + + it('asks again for a lens registered at another version and for equal files of another scope', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, params: { lens: EXPORTS }, setup: (faces) => { + faces.changesLens.mockImplementation(() => hostStream([{ kind: 'result', files: KEPT }])) + } }) + await settle() + expect(m.faces.changesLens).toHaveBeenCalledTimes(1) + // The same registrations published again reuse the result. + act(() => { m.extensions.set({ state: { ...hosted, lenses: [{ ...UNUSED }, { id: EXPORTS, version: '1' }] }, disconnected: false }) }) + await settle() + expect(m.faces.changesLens).toHaveBeenCalledTimes(1) + act(() => { m.extensions.set({ state: { ...hosted, lenses: [UNUSED, { id: EXPORTS, version: '2' }] }, disconnected: false }) }) + await settle() + expect(m.faces.changesLens).toHaveBeenCalledTimes(2) + fireEvent.click(m.view.getByRole('button', { name: 'Branch' })) + fireEvent.click(m.view.getByRole('menuitem', { name: 'Unstaged' })) + await settle() + expect(m.faces.changesLens).toHaveBeenCalledTimes(3) + expect(m.faces.changesLens.mock.calls[2]?.[0]) + .toEqual({ source: { kind: 'local', scope: { kind: 'unstaged' } }, version: lensVersion(LOCAL.files), lens: EXPORTS }) + }) + + it('reports a failed lens with a retry and a clear, and a lens refused for files read again with a refresh', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, params: { lens: EXPORTS }, setup: (faces) => { + faces.changesLens + .mockReturnValueOnce(hostStream([], new RemoteError('forgePanel/lens-failed', 'the lens failed: parser crashed', {}))) + .mockReturnValueOnce(hostStream([], new RemoteError('forgePanel/lens-stale', 'read again', {}))) + .mockReturnValueOnce(hostStream([])) + } }) + await settle() + expect(m.view.getByText('The lens “Exports” did not finish: the lens failed: parser crashed')).toBeTruthy() + act(() => { m.view.getByRole('button', { name: 'Retry' }).click() }) + await settle() + expect(m.view.getByText('The changes were read again; refresh to filter them by “Exports”')).toBeTruthy() + const reads = m.faces.localDiff.mock.calls.length + act(() => { m.view.getAllByRole('button', { name: 'Refresh changes' }).at(-1)?.click() }) + await settle() + expect(m.faces.localDiff.mock.calls.length).toBeGreaterThan(reads) + expect(m.view.getByText('The lens “Exports” stopped before it finished')).toBeTruthy() + act(() => { m.view.getByRole('button', { name: 'Clear lens' }).click() }) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBeNull() + expect(m.view.queryByRole('button', { name: 'Clear lens' })).toBeNull() + }) + + it('draws the plugin slots of the toolbar, the More menu, the line annotations, the file menu, and the comment form', async () => { + const annotation = { key: 'n1', place: { side: 'R' as const, startLine: 4, endLine: 4 }, version: 1 } + const m = mount({ extensions: hosted, lenses: describedLenses, annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]) }) + await settle() + const target = { sessionId: SESSION, source: { kind: 'local' } } + const calls = (name: string): readonly SlotCall[] => m.slotCalls.filter(call => call.key === name) + const bar = calls('forge.changes.toolbar')[0]?.owner as ForgeChangesToolbarProps | undefined + expect(bar).toMatchObject({ target, form: 'bar' }) + // The row has no menu to close. + expect(() => { bar?.close() }).not.toThrow() + expect(calls('forge.diff.line.annotation')[0]).toEqual({ key: 'forge.diff.line.annotation', owner: { target, path: 'src/app.ts', annotation }, options: { entryKey: 'notes' } }) + expect(m.section('src/app.ts').querySelector('[data-forge-annotation="notes/n1"]')).not.toBeNull() + + act(() => { m.view.getByRole('button', { name: 'More view options' }).click() }) + expect(within(document.body).getAllByRole('menuitem').map(row => row.textContent)).toContain('Exports—') + expect(calls('forge.changes.toolbar').at(-1)?.owner).toMatchObject({ target, form: 'menu' }) + act(() => { within(document.body).getByRole('menuitem', { name: 'Exports—' }).click() }) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBe(EXPORTS) + + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'More actions for app.ts' }).click() }) + expect(calls('forge.changes.file.menu')).toHaveLength(1) + expect(calls('forge.changes.file.menu')[0]?.owner).toMatchObject({ target, file: { path: 'src/app.ts' } }) + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'Select line R4' }).click() }) + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'Add comment' }).click() }) + expect(calls('forge.diff.comment.actions')[0]?.owner).toMatchObject({ target, selection: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4 } }) + }) +}) + +describe('ChangesTab extensions before the Host reports them', () => { + it('offers no lens and draws no annotations until the Host names its lenses and annotation limit', async () => { + const annotation = { key: 'n1', place: { side: 'R' as const, startLine: 4, endLine: 4 }, version: 1 } + const m = mount({ extensions: null, annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]) }) + await settle() + expect(m.view.queryByRole('button', { name: 'Filter lens' })).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-forge-annotation]')).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-forge-hidden-annotations]')).toBeNull() + }) + + it('draws no annotations while the renderer has no source for the view', async () => { + const m = mount({ annotations: null }) + await settle() + expect(m.paths()).toHaveLength(6) + expect(m.view.container.querySelector('[data-forge-annotation]')).toBeNull() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index 28c7ad748c..828cd18fb0 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -88,6 +88,8 @@ export interface EntryOptions { readonly origin?: BindingOrigin /** Snapshot an earlier poll returned, kept by a binding whose latest poll failed. */ readonly kept?: ChangeRequestSnapshot + /** Review changes announced for the change request; defaults to none. */ + readonly reviewRevision?: number } /** Binding of pull request `number` whose latest poll returned `status`, or that has not been polled yet. */ @@ -97,7 +99,7 @@ export function entry( options: EntryOptions = {}, ): ForgePanelChangeRequest { const key = `github:github.com/octo/demo#${number}` as ChangeRequestKey - const binding = { url: `https://github.com/octo/demo/pull/${number}`, origin: options.origin ?? 'created', ref: ref(number) } + const binding = { url: `https://github.com/octo/demo/pull/${number}`, origin: options.origin ?? 'created', ref: ref(number), reviewRevision: options.reviewRevision ?? 0 } if (status === null) return { ...binding, update: null, snapshot: null } if ('code' in status) return { ...binding, update: { key, fetchedAt: 1, failure: status }, snapshot: options.kept ?? null } return { ...binding, update: { key, fetchedAt: 1, snapshot: status }, snapshot: status } @@ -105,7 +107,7 @@ export function entry( /** Binding of a URL that no provider serves. */ export function unserved(url: string): ForgePanelChangeRequest { - return { url, origin: 'created', ref: null, update: null, snapshot: null } + return { url, origin: 'created', ref: null, update: null, snapshot: null, reviewRevision: 0 } } /** Checkout of `/work/repo` on `main`. */ diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 064d66d112..8a7c391f56 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -1822,7 +1822,7 @@ describe('forgePanel actions', () => { // The refresh found the same state, which the panel already published. const refreshed = follower.states.at(-1) expect(refreshed?.checkout.state).toBe('none') - expect(refreshed?.changeRequests).toEqual([{ url: 'https://unserved.test/a/b/pull/3', origin: 'created', ref: null, update: null, snapshot: null }]) + expect(refreshed?.changeRequests).toEqual([{ url: 'https://unserved.test/a/b/pull/3', origin: 'created', ref: null, update: null, snapshot: null, reviewRevision: 0 }]) expect(opened.sandbox.calls.length).toBeGreaterThan(inspections) expect(opened.provider.fetches).toEqual([]) expect(opened.provider.probes).toEqual([]) @@ -2060,6 +2060,10 @@ describe('forgePanel configuration', () => { [{ maxBranches: 2.5 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxCachedDiffBytes: 0 }, 'forge-panel: maxCachedDiffBytes must be a positive integer'], [{ maxCommits: 0 }, 'forge-panel: maxCommits must be a positive integer'], + [{ lensTimeoutMs: 0 }, 'forge-panel: lensTimeoutMs must be a positive integer no greater than 2147483647'], + [{ maxLensReadBytes: 0 }, 'forge-panel: maxLensReadBytes must be a positive integer'], + [{ maxCachedLensBytes: -1 }, 'forge-panel: maxCachedLensBytes must be a positive integer'], + [{ maxAnnotationsPerFile: 1.5 }, 'forge-panel: maxAnnotationsPerFile must be a positive integer'], [{ testPaths: ['**/*.spec.*', ' '] }, 'forge-panel: testPaths entries must not be empty'], [{ interfacePaths: [''] }, 'forge-panel: interfacePaths entries must not be empty'], [{ worktreePrefix: '-dsh/' }, prefix], diff --git a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx index efb64ee40b..d125b14179 100644 --- a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx @@ -9,7 +9,12 @@ import { ReviewQueue } from '../src/client/review-queue.ts' import { SectionReach } from '../src/client/section-reach.ts' import { selectReviewLines } from '../src/client/review.ts' import type { ReviewActions } from '../src/client/ReviewComposer.tsx' +import type { ForgeCommentActionsProps } from '../src/client/slots.ts' import type { ForgeDiffFile } from '../src/types.ts' +import type { ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { SourcedAnnotation } from '../src/client/annotations.ts' +import type { FileThreads, ThreadActions } from '../src/client/ReviewThreads.tsx' +import { reviewThread } from './thread-fixtures.client.ts' const file: ForgeDiffFile = { path: 'a.txt', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, layer: 'implementation', digest: 'digest', additions: 3, deletions: 2, hunks: [{ oldStart: 2, oldLines: 3, newStart: 2, newLines: 4, lines: [' same', '-old first', '-old last', '+new first', '+new last', '+'] }] } @@ -23,7 +28,7 @@ function mount(overrides: Partial = {}) { const review: ReviewActions = { source, addToInput, records, onQuoted: (item) => { records.recordAgent(item) } } const handlers = { toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), nextThread: vi.fn(), - reach: new SectionReach(), + reach: new SectionReach(), annotation: vi.fn(() => null), fileMenu: vi.fn(() => null), unfold: vi.fn(), } const props: DiffFileProps = { file, visible: true, expanded: true, large: false, revealed: false, text: undefined, open: new Set(), split: true, wrap: true, badge: '', tooltip: 'a.txt', @@ -342,3 +347,146 @@ it('labels the plus on the unified row that ends a right-side range', () => { expect(m.container.querySelector('[data-review-add="R4"]')).toBeNull() expect(m.container.querySelector('[data-review-add="R3"]')).not.toBeNull() }) + +/** A plugin annotation on a range of one side, the whole file, or a change it was written on. */ +function annotation(key: string, place: SourcedAnnotation['annotation']['place'], digest?: string): SourcedAnnotation { + return { source: 'notes', annotation: { key, place, version: 1, ...digest === undefined ? {} : { digest } } } +} + +/** File threads whose cards share inert actions. */ +function lineThreads(lines: FileThreads['lines']): FileThreads { + const actions: ThreadActions = { + author: null, addToInput: () => true, openLink: vi.fn(), readText: vi.fn(), inputFailed: vi.fn(), focused: null, writes: null, + } + return { lines, file: [], outdated: [], unresolved: lines.length, actions } +} + +/** The annotation frames a section draws, in order. */ +function frames(container: HTMLElement): (string | null)[] { + return [...container.querySelectorAll('[data-forge-annotation]')].map(element => element.getAttribute('data-forge-annotation')) +} + +it('draws plugin annotations after the comments of their last line, in the column of their side, through the handler', () => { + const m = mount({ annotationLimit: 10, annotations: [annotation('r4', { side: 'R', startLine: 3, endLine: 4 }), annotation('l3', { side: 'L', startLine: 3, endLine: 3 })] }) + const rendered = vi.mocked(m.props.handlers.annotation) + expect(rendered.mock.calls.map(([path, item]) => `${path}:${item.annotation.key}`)).toEqual(['a.txt:l3', 'a.txt:r4']) + const notes = m.container.querySelector('[data-forge-annotation="notes/l3"]')!.closest('[data-forge-notes]')! + expect([...notes.children].findIndex(cell => cell.querySelector('[data-forge-annotation]') !== null)).toBe(0) + const right = m.container.querySelector('[data-forge-annotation="notes/r4"]')!.closest('[data-forge-notes]')! + expect([...right.children].findIndex(cell => cell.querySelector('[data-forge-annotation]') !== null)).toBe(1) + + m.rerender() + expect(frames(m.container)).toEqual(['notes/l3', 'notes/r4']) +}) + +it('places annotations on the whole file first, on an earlier change in their own section, and counts those past the limit', () => { + const m = mount({ + annotationLimit: 3, + annotations: [ + annotation('file', 'file'), annotation('old', { side: 'R', startLine: 3, endLine: 3 }, 'other'), annotation('line', { side: 'R', startLine: 3, endLine: 3 }, 'digest'), + annotation('extra', { side: 'R', startLine: 4, endLine: 4 }), + ], + }) + expect(frames(m.container)).toEqual(['notes/file', 'notes/line', 'notes/old']) + expect(m.container.querySelector('[data-forge-outdated-annotations]')!.textContent).toContain('Annotations on an earlier change · 1') + expect(m.container.querySelector('[data-forge-hidden-annotations]')!.textContent).toBe('1 more annotations in this file are not shown') + m.rerender() + expect(frames(m.container)).toEqual([]) +}) + +it('places annotations in the collapsed lines that hold them and after the lines when no row shows them', () => { + const m = mount({ annotationLimit: 10, annotations: [annotation('gap', { side: 'R', startLine: 1, endLine: 1 }), annotation('later', { side: 'R', startLine: 40, endLine: 40 })] }) + const code = m.container.querySelector('[data-review]')! + const rows = [...code.children] + const gap = rows.findIndex(row => row.hasAttribute('data-forge-diff-gap')) + expect(rows[gap + 1]?.getAttribute('data-forge-annotation')).toBe('notes/gap') + expect(rows.at(-1)?.getAttribute('data-forge-annotation')).toBe('notes/later') + + // A new file has no lines after its hunk, so an annotation past them follows the lines. + const added: ForgeDiffFile = { ...file, status: 'added', deletions: 0, additions: 2, hunks: [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 2, lines: ['+a', '+b'] }] } + m.rerender() + expect([...m.container.querySelector('[data-review]')!.children].at(-1)?.getAttribute('data-forge-annotation')).toBe('notes/past') +}) + +it('folds the hunks a lens folds into one row that shows them, holding the threads and annotations on their lines', () => { + const two: ForgeDiffFile = { ...file, additions: 4, deletions: 3, hunks: [file.hunks[0]!, { oldStart: 10, oldLines: 1, newStart: 11, newLines: 2, lines: ['-o', '+n', '+m'] }] } + const thread = reviewThread({ path: 'a.txt' }) + const m = mount({ + file: two, folded: { hunks: new Set([1]), lens: 'Exports' }, annotationLimit: 10, + annotations: [ + annotation('left', { side: 'L', startLine: 10, endLine: 10 }), annotation('right', { side: 'R', startLine: 12, endLine: 12 }), + annotation('kept', { side: 'R', startLine: 3, endLine: 3 }), annotation('end', { side: 'R', startLine: 40, endLine: 40 }), + ], + threads: lineThreads([ + { thread, place: { kind: 'line', side: 'R', startLine: 11, endLine: 11 } }, + { thread: reviewThread({ path: 'a.txt', id: 'thread-end' as ForgeThreadId }), place: { kind: 'line', side: 'R', startLine: 40, endLine: 40 } }, + ]), + }) + const fold = m.container.querySelector('[data-forge-lens-fold]')! + expect(fold.getAttribute('data-forge-lens-fold')).toBe('1') + expect(fold.textContent).toBe('1 changes unrelated to “Exports” foldedShow') + const rows = [...m.container.querySelector('[data-review]')!.children] + const at = rows.indexOf(fold) + expect(rows[at + 1]?.hasAttribute('data-forge-thread')).toBe(true) + expect(rows.slice(at + 2, at + 4).map(row => row.getAttribute('data-forge-annotation'))).toEqual(['notes/left', 'notes/right']) + expect(m.container.querySelector('[data-old-line="10"]')).toBeNull() + fireEvent.click(fold) + expect(m.props.handlers.unfold).toHaveBeenCalledWith('a.txt') +}) + +it('keeps a hunk with an open comment form or a comment saved in the browser drawn when a lens would fold it', () => { + const two: ForgeDiffFile = { ...file, additions: 4, deletions: 3, hunks: [file.hunks[0]!, { oldStart: 10, oldLines: 1, newStart: 11, newLines: 2, lines: ['-o', '+n', '+m'] }] } + const folded = { hunks: new Set([1]), lens: 'Exports' } + const m = mount({ file: two }) + fireEvent.click(m.line('R12')) + fireEvent.click(m.getByRole('button', { name: 'Add comment' })) + fireEvent.change(m.getByRole('textbox'), { target: { value: 'half written' } }) + m.rerender() + expect(m.container.querySelector('[data-forge-lens-fold]')).toBeNull() + expect((m.getByRole('textbox') as HTMLTextAreaElement).value).toBe('half written') + + // Once the form became a saved comment, its hunk still stays drawn, with the comment on its line. + fireEvent.click(m.getByRole('button', { name: 'Add to input' })) + m.rerender() + expect(m.container.querySelector('[data-forge-lens-fold]')).toBeNull() + expect(m.code('R', 12)).toBeTruthy() + expect(m.container.querySelector('[data-forge-review-thread="agent"]')).not.toBeNull() + + // Without either, the hunk folds. + localStorage.clear() + const fresh = mount({ file: two, folded }) + expect(fresh.container.querySelector('[data-forge-lens-fold]')).not.toBeNull() +}) + +it('draws line annotations after a note that replaces the lines and lists the plugin rows of the file menu', () => { + const m = mount({ file: { ...file, binary: true, hunks: [] }, annotationLimit: 10, annotations: [annotation('bin', { side: 'R', startLine: 1, endLine: 1 })] }) + expect(frames(m.container)).toEqual(['notes/bin']) + vi.mocked(m.props.handlers.fileMenu).mockImplementation((_file, dismiss) => ) + fireEvent.click(m.getByRole('button', { name: 'More actions for a.txt' })) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Pin a note' })) + expect(vi.mocked(m.props.handlers.fileMenu).mock.calls[0]?.[0]).toBe(m.props.file) + expect(within(document.body).queryByRole('menuitem', { name: 'Pin a note' })).toBeNull() +}) + +it('hands the comment text to a plugin action, keeping the form with the message it returns and closing it otherwise', async () => { + const owners: ForgeCommentActionsProps[] = [] + const deliver = vi.fn<(body: string) => Promise>().mockResolvedValueOnce('Not pinned').mockResolvedValueOnce(undefined) + const m = mount() + const review: ReviewActions = { + ...m.props.review!, + renderActions: (owner) => { + owners.push({ target: { sessionId: 's' as never, source: { kind: 'local' } }, ...owner }) + return + }, + } + m.rerender() + fireEvent.click(m.line('R4')) + fireEvent.click(m.getByRole('button', { name: 'Add comment' })) + expect(owners.at(-1)).toMatchObject({ selection: { path: 'a.txt', side: 'R', startLine: 4, endLine: 4 }, empty: true, busy: false }) + fireEvent.change(m.getByRole('textbox', { name: 'Leave a comment…' }), { target: { value: 'Pin me' } }) + await act(async () => { fireEvent.click(m.getByRole('button', { name: 'Pin' })) }) + expect(deliver).toHaveBeenCalledWith('Pin me') + expect(m.getByRole('alert').textContent).toBe('Not pinned') + await act(async () => { fireEvent.click(m.getByRole('button', { name: 'Pin' })) }) + expect(m.queryByRole('region', { name: 'Comment on R4' })).toBeNull() +}) diff --git a/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts b/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts index 2cea3656f7..78a1847959 100644 --- a/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts @@ -82,7 +82,7 @@ describe('matchesHunks', () => { describe('segmentsOf', () => { it('collapses the lines before, between, and after the hunks, the last of unknown length', () => { - expect(segmentsOf(file(), undefined, new Set([0, 1])).map(segment => segment.kind === 'gap' ? segment : segment.rows.length)).toEqual([ + expect(segmentsOf(file(), undefined, new Set([0, 1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ { kind: 'gap', index: 0, count: 2 }, 5, { kind: 'gap', index: 1, count: 4 }, @@ -105,7 +105,7 @@ describe('segmentsOf', () => { }) it('keeps unexpanded gaps collapsed once the new side is known, and counts the lines after the last hunk', () => { - expect(segmentsOf(file(), NEW_SIDE, new Set([1])).map(segment => segment.kind === 'gap' ? segment : segment.rows.length)).toEqual([ + expect(segmentsOf(file(), NEW_SIDE, new Set([1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ { kind: 'gap', index: 0, count: 2 }, 11, { kind: 'gap', index: 2, count: 2 }, @@ -133,6 +133,26 @@ describe('segmentsOf', () => { expect(segmentsOf(oldEnding, undefined, new Set()).map(segment => segment.kind)).toEqual(['gap', 'rows', 'gap']) }) + it('draws consecutive folded hunks as one row that takes the lines between them, and the gap before a folded run', () => { + const three = file({ hunks: [...HUNKS, { oldStart: 13, oldLines: 1, newStart: 13, newLines: 1, lines: ['-u', '+t13'] }] }) + expect(segmentsOf(three, undefined, new Set(), new Set([1, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ + { kind: 'gap', index: 0, count: 2 }, + 5, + { kind: 'gap', index: 1, count: 4 }, + { kind: 'folded', hunks: [1, 2] }, + { kind: 'gap', index: 3, count: null }, + ]) + expect(segmentsOf(three, undefined, new Set(), new Set([0, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ + { kind: 'gap', index: 0, count: 2 }, + { kind: 'folded', hunks: [0] }, + { kind: 'gap', index: 1, count: 4 }, + 2, + { kind: 'gap', index: 2, count: 1 }, + { kind: 'folded', hunks: [2] }, + { kind: 'gap', index: 3, count: null }, + ]) + }) + it('draws nothing for a file without hunks', () => { expect(segmentsOf(file({ status: 'renamed', previousPath: 'old.ts', hunks: [] }), undefined, new Set())).toEqual([]) }) diff --git a/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx b/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx new file mode 100644 index 0000000000..fe70a47fc1 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx @@ -0,0 +1,306 @@ +// @vitest-environment jsdom +/** The changes view's face for other Client plugins, the merged annotations of a view, and a view's lens run. */ +import { act, cleanup, fireEvent, render, renderHook, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { AnnotationView } from '../src/client/annotations.ts' +import { changesAddress, type ChangesTarget } from '../src/client/changes-address.ts' +import { + ForgeChangesService, type ForgeAnnotationSource, type ForgeLensDescription, type ForgeLineAnnotation, +} from '../src/client/changes-service.ts' +import { foldedHunks, useLensRun, type LensRunInput } from '../src/client/lens-filter.ts' +import { LensFilterMenu, lensOfRow, lensRowId, NO_LENS, type LensChoice } from '../src/client/LensFilter.tsx' +import { en } from '../src/client/locales.ts' +import type { HostStream } from '../src/client/source.ts' +import type { ForgeDiffHunk, ForgeExtensionState, ForgeLensFrame, ForgeLensId } from '../src/types.ts' + +afterEach(() => { cleanup(); vi.restoreAllMocks() }) + +const t = makeTranslate(en) +const SESSION = SessionId('s1') +const target: ChangesTarget = { sessionId: SESSION, source: { kind: 'change', url: 'https://github.com/octo/demo/pull/7' } } + +function service(mounted: SessionId | undefined = SESSION) { + const openResource = vi.fn() + const extensions = createSnapshotStore(null) + const forge = new ForgeChangesService({ mounted: () => mounted, openResource }, extensions, { changes: 'forge-changes', panel: 'forge-panel' }) + return { forge, openResource, extensions } +} + +function lens(id: string, order?: number): ForgeLensDescription { + return { id: id as ForgeLensId, title: () => id.toUpperCase(), ...order === undefined ? {} : { order } } +} + +/** A source whose annotations of every view a test sets. */ +function source(id: string, order?: number) { + const values = createSnapshotStore>(new Map()) + const observe = vi.fn((_target: ChangesTarget): HostObservable> => values) + const entry: ForgeAnnotationSource = { id, observe, ...order === undefined ? {} : { order } } + return { entry, values, observe } +} + +function note(key: string, line: number, version: string | number = 1): ForgeLineAnnotation { + return { key, place: { side: 'R', startLine: line, endLine: line }, version } +} + +describe('ForgeChangesService', () => { + it('mints and reads changes addresses and opens a view of the Session the sidebar shows', () => { + const { forge, openResource } = service() + const address = forge.address(target) + expect(address).toBe(changesAddress(target)) + expect(forge.parse(address)).toEqual(target) + expect(forge.parse('dsh-resource://other/x')).toBeUndefined() + expect(forge.kinds).toEqual({ changes: 'forge-changes', panel: 'forge-panel' }) + forge.open(target, { lens: 'fixture/exports' }) + forge.open(target) + expect(openResource.mock.calls).toEqual([[address, { lens: 'fixture/exports' }], [address, undefined]]) + expect(() => { service(SessionId('other')).forge.open(target) }).toThrow('forge-panel: Session s1 is not the Session the sidebar shows') + }) + + it('publishes lens descriptions by position, refuses a taken identity, and withdraws one when its plugin unloads', async () => { + const { forge } = service() + const changes = vi.fn() + forge.lenses.subscribe(changes) + const root = new Context() + const fiber = root.plugin({ apply(ctx: Context) { ctx.effect(() => forge.describeLens(lens('b', 1))) } }) + await fiber + const releaseA = forge.describeLens(lens('a', 1)) + forge.describeLens(lens('c')) + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c', 'b', 'a']) + expect(() => forge.describeLens(lens('a'))).toThrow('forge-panel: a lens description "a" is already registered') + await fiber.dispose() + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c', 'a']) + releaseA() + releaseA() + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c']) + expect(changes).toHaveBeenCalledTimes(5) + }) + + it('registers annotation sources by position and withdraws one when its plugin unloads', async () => { + const { forge } = service() + const root = new Context() + const fiber = root.plugin({ apply(ctx: Context) { ctx.effect(() => forge.registerAnnotations(source('notes', 2).entry)) } }) + await fiber + forge.registerAnnotations(source('lint').entry) + expect(forge.annotationSources.getSnapshot().map(item => item.id)).toEqual(['lint', 'notes']) + expect(() => forge.registerAnnotations(source('lint').entry)).toThrow('forge-panel: a annotation source "lint" is already registered') + await fiber.dispose() + expect(forge.annotationSources.getSnapshot().map(item => item.id)).toEqual(['lint']) + }) +}) + +describe('AnnotationView', () => { + it('merges the sources by path in source order, observing them only while read', () => { + const { forge } = service() + const notes = source('notes', 1) + const lint = source('lint') + forge.registerAnnotations(notes.entry) + forge.registerAnnotations(lint.entry) + const view = new AnnotationView(forge.annotationSources, target) + expect(view.getSnapshot().size).toBe(0) + expect(notes.observe).not.toHaveBeenCalled() + + const listener = vi.fn() + const stop = view.subscribe(listener) + expect(notes.observe).toHaveBeenCalledWith(target) + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]]])) }) + act(() => { lint.values.set(new Map([['a.ts', [note('l1', 1)]], ['b.ts', [note('l2', 2)]], ['c.ts', []]])) }) + const merged = view.getSnapshot() + expect([...merged].map(([path, list]) => [path, list.map(item => `${item.source}:${item.annotation.key}`)])) + .toEqual([['a.ts', ['lint:l1', 'notes:n1']], ['b.ts', ['lint:l2']]]) + + // A file whose annotations did not change keeps its list. + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]], ['d.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().get('b.ts')).toBe(merged.get('b.ts')) + expect(view.getSnapshot().get('a.ts')).toBe(merged.get('a.ts')) + const calls = listener.mock.calls.length + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]], ['d.ts', [note('n2', 1)]]])) }) + expect(listener).toHaveBeenCalledTimes(calls) + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3, 2)]], ['d.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().get('a.ts')).not.toBe(merged.get('a.ts')) + + stop() + act(() => { notes.values.set(new Map()) }) + expect(view.getSnapshot().get('d.ts')).toHaveLength(1) + }) + + it('follows sources that register and withdraw while read', () => { + const { forge } = service() + const notes = source('notes') + notes.values.set(new Map([['a.ts', [note('n1', 3)]]])) + const view = new AnnotationView(forge.annotationSources, target) + const stopA = view.subscribe(() => {}) + const stopB = view.subscribe(() => {}) + const release = forge.registerAnnotations(notes.entry) + expect(view.getSnapshot().get('a.ts')).toHaveLength(1) + const lint = source('lint', 1) + lint.values.set(new Map([['a.ts', [note('l1', 2)]]])) + forge.registerAnnotations(lint.entry) + expect(view.getSnapshot().get('a.ts')?.map(item => item.source)).toEqual(['notes', 'lint']) + expect(notes.observe).toHaveBeenCalledTimes(1) + release() + expect(view.getSnapshot().get('a.ts')?.map(item => item.source)).toEqual(['lint']) + act(() => { notes.values.set(new Map([['b.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().has('b.ts')).toBe(false) + stopA() + stopB() + }) +}) + +describe('foldedHunks', () => { + const hunk = (oldStart: number, oldLines: number, newStart: number, newLines: number): ForgeDiffHunk => + ({ oldStart, oldLines, newStart, newLines, lines: [] }) + const hunks = [hunk(1, 3, 1, 3), hunk(10, 0, 10, 2), hunk(20, 2, 22, 0)] + + it('folds the hunks that meet none of the lens lines on either side', () => { + expect([...foldedHunks(hunks, { ranges: { old: [], new: [{ start: 11, end: 11 }] } })]).toEqual([0, 2]) + expect([...foldedHunks(hunks, { ranges: { old: [{ start: 21, end: 30 }], new: [{ start: 3, end: 3 }] } })]).toEqual([1]) + expect([...foldedHunks(hunks, { ranges: { old: [{ start: 10, end: 10 }], new: [{ start: 22, end: 22 }] } })]).toEqual([0, 1, 2]) + expect(foldedHunks(hunks, {}).size).toBe(0) + }) +}) + +describe('useLensRun', () => { + function stream(frames: readonly ForgeLensFrame[], failure?: unknown, gate?: Promise): HostStream { + return { + dispose: vi.fn(), + async *[Symbol.asyncIterator]() { + for (const frame of frames) { + await gate + yield frame + } + await gate + if (failure !== undefined) throw failure + }, + } + } + const EXPORTS = { id: 'fixture/exports', version: '1' } + const OTHER = { id: 'other', version: '1' } + const base: LensRunInput = { + visible: true, lens: EXPORTS, source: { kind: 'local', scope: { kind: 'unstaged' } }, version: 'v1', attempt: 0, + open: () => stream([]), + } + + it('reports progress, then keeps the result, which choosing the lens again reuses without asking', async () => { + const gate = Promise.withResolvers() + const open = vi.fn() + .mockReturnValueOnce(stream([{ kind: 'progress', done: 1, total: 2 }, { kind: 'result', files: { 'a.ts': {} } }], undefined, gate.promise)) + .mockReturnValueOnce(stream([{ kind: 'result', files: {} }])) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + expect(hook.result.current.run).toEqual({ kind: 'running', done: null, total: null }) + expect(open.mock.calls[0]?.[0]).toEqual({ source: base.source, version: 'v1', lens: 'fixture/exports' }) + await act(async () => { gate.resolve(undefined); await gate.promise }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'ready', files: { 'a.ts': {} } }) }) + + hook.rerender({ ...base, open, lens: OTHER }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'ready', files: {} }) }) + hook.rerender({ ...base, open, lens: { ...EXPORTS } }) + expect(hook.result.current.run).toEqual({ kind: 'ready', files: { 'a.ts': {} } }) + expect([hook.result.current.resultOf(EXPORTS), hook.result.current.resultOf(OTHER)]).toEqual([{ 'a.ts': {} }, {}]) + expect(open).toHaveBeenCalledTimes(2) + // A result holds for the lens version that answered it. + expect(hook.result.current.resultOf({ ...EXPORTS, version: '2' })).toBeUndefined() + + // Other files, or equal files of another source, drop the kept results. + hook.rerender({ ...base, open: () => stream([]), version: 'v2' }) + expect(hook.result.current.resultOf(EXPORTS)).toBeUndefined() + hook.rerender({ ...base, open: () => stream([]), source: { kind: 'local', scope: { kind: 'staged' } } }) + expect(hook.result.current.resultOf(EXPORTS)).toBeUndefined() + }) + + it('reports a Remote failure by its code, another failure as a lens failure, and asks nothing while hidden or without files', async () => { + const open = vi.fn() + .mockReturnValueOnce(stream([], new RemoteError('forgePanel/lens-stale', 'read again', {}))) + .mockReturnValueOnce(stream([], new Error('socket closed'))) + .mockReturnValueOnce(stream([], 'stream ended')) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-stale', message: 'read again' }) }) + hook.rerender({ ...base, open, attempt: 1 }) + await vi.waitFor(() => { + expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-failed', message: 'socket closed' }) + }) + hook.rerender({ ...base, open, attempt: 2 }) + await vi.waitFor(() => { + expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-failed', message: 'stream ended' }) + }) + hook.rerender({ ...base, open, attempt: 3, visible: false }) + hook.rerender({ ...base, open, attempt: 3, source: null }) + hook.rerender({ ...base, open, lens: null }) + expect(hook.result.current.run).toEqual({ kind: 'idle' }) + expect(open).toHaveBeenCalledTimes(3) + }) + + it('stops a request whose view hides or unmounts and ignores what it delivers afterwards', async () => { + const gate = Promise.withResolvers() + const opened = stream([{ kind: 'result', files: { 'a.ts': {} } }], new Error('late'), gate.promise) + const failing = stream([], new Error('late'), gate.promise) + const ending = stream([], undefined, gate.promise) + const open = vi.fn().mockReturnValueOnce(opened).mockReturnValueOnce(failing).mockReturnValueOnce(ending) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + hook.rerender({ ...base, open, visible: false }) + expect(opened.dispose).toHaveBeenCalled() + hook.rerender({ ...base, open, attempt: 1 }) + hook.rerender({ ...base, open, attempt: 2 }) + hook.unmount() + await act(async () => { gate.resolve(undefined); await new Promise(resolve => setTimeout(resolve, 0)) }) + expect(failing.dispose).toHaveBeenCalled() + expect(ending.dispose).toHaveBeenCalled() + expect(hook.result.current.run).toEqual({ kind: 'running', done: null, total: null }) + }) +}) + +describe('LensFilterMenu', () => { + const lenses: readonly LensChoice[] = [{ id: 'fixture/exports', title: 'Exports', count: 3 }, { id: 'lint', title: 'Lint', count: null }] + + it('names the lens rows and reads them back', () => { + expect(lensRowId('lint')).toBe('lens:lint') + expect(lensOfRow(lensRowId('lint'))).toBe('lint') + expect(lensOfRow(NO_LENS)).toBeNull() + expect(lensOfRow('split')).toBeUndefined() + }) + + it('offers no lens and each lens with its count, and chooses one', () => { + const choose = vi.fn() + const view = render() + const trigger = view.getByRole('button', { name: 'Filter lens' }) + expect(trigger.textContent).toBe('Lens') + expect(trigger.hasAttribute('data-active')).toBe(false) + act(() => { trigger.click() }) + const menu = within(document.body) + expect(menu.getAllByRole('menuitem').map(row => row.textContent)).toEqual(['No lens', 'Exports3', 'Lint—']) + act(() => { menu.getByRole('menuitem', { name: 'Lint—' }).click() }) + expect(choose).toHaveBeenCalledWith('lint') + act(() => { trigger.click() }) + act(() => { menu.getByRole('menuitem', { name: 'No lens' }).click() }) + expect(choose).toHaveBeenLastCalledWith(null) + act(() => { trigger.click() }) + act(() => { fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }) }) + expect(document.body.querySelectorAll('[role="menuitem"]')).toHaveLength(0) + }) + + it('shows the chosen lens tinted with the files it keeps, its progress while it runs, and stays closed in a hidden tab', () => { + const view = render() + const trigger = view.getByRole('button', { name: 'Filter lens: Exports' }) + expect(trigger.hasAttribute('data-active')).toBe(true) + expect(trigger.textContent).toBe('Exports2/5') + view.rerender() + expect(trigger.textContent).toBe('Exports') + view.rerender() + expect(trigger.textContent).toBe('Exports3') + view.rerender() + expect(view.getByRole('button', { name: 'Filter lens: Lint' }).textContent).toBe('Lint') + act(() => { view.getByRole('button', { name: 'Filter lens: Lint' }).click() }) + expect(document.body.querySelectorAll('[role="menuitem"]')).toHaveLength(0) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx index 433f644b1b..ba6965ec5b 100644 --- a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx @@ -66,6 +66,8 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v const reportVisible = vi.fn<(visible: boolean) => void>() const createChangeRequest = vi.fn<() => void>() const openResource = vi.fn() + // Draws nothing for the card's plugin slot. + const renderSlot = (() => null) as ForgeTabProps['renderSlot'] const props: ForgeTabProps = { useTabInfo: () => tabInfo(useVisibility(current => current), openResource), sessionId: SESSION, @@ -73,7 +75,7 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v useHost: bindSnapshotSelector(host), useLocale: bindSnapshotSelector(createSnapshotStore('en')), reconnect, refresh, remove, markReady, merge, readChecks, rerunChecks, requestReviews, reviewerCandidates, updateBranch, restore, - openLink, copyText, copyPath, reportVisible, createChangeRequest, t, + openLink, copyText, copyPath, reportVisible, createChangeRequest, renderSlot, t, } const view = render() return { diff --git a/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts new file mode 100644 index 0000000000..e382d9382f --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts @@ -0,0 +1,427 @@ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge' +import type { Session } from '@deepseek-ai/dsh-session' +import type { + ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLensRequest, ForgeLensResult, +} from '../src/index.ts' +import { lensVersion } from '../src/lens-version.ts' +import { bench, follow, git, hold, pullUrl, repository, scratch, shellTurn } from './harness.ts' +import type { Bench } from './harness.ts' + +const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +const signal = new AbortController().signal +const HEAD = 'a'.repeat(40) +const BASE = 'b'.repeat(40) +const MERGE_BASE = 'c'.repeat(40) + +async function project(): Promise { + const { path, remove } = await scratch('dsh-forge-lens-') + cleanups.push(remove) + const repo = await repository(path) + await git(repo, 'remote', 'add', 'origin', 'https://fake.test/octo/demo.git') + await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + return repo +} + +async function open(repo: string, config: Parameters[1] = {}): Promise { + const opened = await bench(repo, config) + cleanups.push(() => opened.ctx.fiber.dispose()) + return opened +} + +/** Register `lens` from its own plugin fiber, as a third-party plugin does. */ +async function provideLens(ctx: Context, lens: ForgeLens): Promise> { + const fiber = ctx.plugin({ inject: ['forgePanel'], apply(child: Context) { child.forgePanel.registerLens(lens) } }) + await fiber + return fiber +} + +/** A lens that keeps the files whose new side contains `export`, about those lines, recording every side it read. */ +function exportsLens(reads: string[] = [], id = 'fixture/exports'): ForgeLens & { readonly classify: ReturnType } { + return { + id: id as ForgeLensId, + version: '1', + classify: vi.fn(async (input: ForgeLensInput): Promise => { + const files: Record = {} + for (const [index, file] of input.files.entries()) { + const old = await input.text('old', file.path, signal) + const next = await input.text('new', file.path, signal) + reads.push(`${file.path} old=${JSON.stringify(old)} new=${JSON.stringify(next)}`) + input.progress(index + 1, input.files.length) + const lines = (next ?? '').split('\n') + const exported = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : []) + if (exported.length > 0) files[file.path] = { ranges: { old: [], new: exported } } + } + return { files } + }), + } +} + +/** Settle once `lensSignal` aborts, as a lens that stops its work when asked does. */ +async function untilAborted(lensSignal: AbortSignal): Promise { + return await new Promise((_resolve, reject) => { + lensSignal.addEventListener('abort', () => { reject(new Error('stopped')) }, { once: true }) + }) +} + +async function frames(ctx: Context, session: Session, request: ForgeLensRequest): Promise { + const list: ForgeLensFrame[] = [] + for await (const frame of ctx.forgePanel.changesLens(session, request, signal)) list.push(frame) + return list +} + +async function rejection(ctx: Context, session: Session, request: ForgeLensRequest): Promise { + try { + await frames(ctx, session, request) + } catch (error) { + return error + } + throw new Error('the lens request succeeded') +} + +describe('forgePanel lens registrations', () => { + it('lists each registered lens while its plugin is loaded and withdraws it when the plugin unloads', async () => { + const opened = await open(await project(), { maxAnnotationsPerFile: 7 }) + const controller = new AbortController() + const states = opened.ctx.forgePanel.extensions(controller.signal)[Symbol.asyncIterator]() + cleanups.push(async () => { + controller.abort() + await states.return?.() + }) + const empty: ForgeExtensionState = { lenses: [], maxAnnotationsPerFile: 7 } + await expect(states.next()).resolves.toEqual({ done: false, value: empty }) + + const fiber = await provideLens(opened.ctx, exportsLens()) + await expect(states.next()).resolves.toEqual({ done: false, value: { lenses: [{ id: 'fixture/exports', version: '1' }], maxAnnotationsPerFile: 7 } }) + await expect(provideLens(opened.ctx, exportsLens())).rejects.toThrow('forge-panel: a lens "fixture/exports" is already registered') + await fiber.dispose() + await expect(states.next()).resolves.toEqual({ done: false, value: { lenses: [], maxAnnotationsPerFile: 7 } }) + }) + + it('ends the extension stream when the panel stops', async () => { + const opened = await open(await project()) + const states = opened.ctx.forgePanel.extensions(signal)[Symbol.asyncIterator]() + await states.next() + const waiting = states.next() + await opened.panel.dispose() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + }) + + it('returns a disposer that withdraws the lens', async () => { + const opened = await open(await project()) + const dispose = opened.ctx.forgePanel.registerLens(exportsLens()) + await dispose() + const error = await rejection(opened.ctx, opened.session, { source: { kind: 'local', scope: { kind: 'unstaged' } }, version: '', lens: 'fixture/exports' }) + expect(error).toMatchObject({ code: 'forgePanel/lens-missing', message: 'No lens "fixture/exports" is registered' }) + }) +}) + +describe('forgePanel lenses over local changes', () => { + it('classifies the shown files with both sides read in the Session\'s checkout, then reuses the result', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'export const value = 1\n') + await writeFile(join(repo, 'notes.md'), 'hello\n') + await writeFile(join(repo, 'image.bin'), Buffer.from([0, 1, 2])) + const opened = await open(repo) + const reads: string[] = [] + const lens = exportsLens(reads) + await provideLens(opened.ctx, lens) + const scope = { kind: 'branch', base: null, commits: null } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const request: ForgeLensRequest = { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' } + + const first = await frames(opened.ctx, opened.session, request) + expect(first.at(-1)).toEqual({ kind: 'result', files: { 'tracked.txt': { ranges: { old: [], new: [{ start: 1, end: 1 }] } } } }) + expect(first.slice(0, -1).every(frame => frame.kind === 'progress' && frame.total === 3)).toBe(true) + expect(first.length).toBeGreaterThan(1) + expect(reads).toEqual([ + 'tracked.txt old="initial\\n" new="export const value = 1\\n"', + 'image.bin old=null new=null', + 'notes.md old=null new="hello\\n"', + ]) + expect(lens.classify.mock.calls[0]?.[0]).toMatchObject({ source: { kind: 'local', scope } }) + await expect(frames(opened.ctx, opened.session, request)).resolves.toEqual([ + { kind: 'result', files: { 'tracked.txt': { ranges: { old: [], new: [{ start: 1, end: 1 }] } } } }, + ]) + expect(lens.classify).toHaveBeenCalledTimes(1) + }) + + it('reads the old side at HEAD, at the index, and before the first chosen commit', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'staged\n') + await git(repo, 'add', 'tracked.txt') + await writeFile(join(repo, 'tracked.txt'), 'working\n') + const opened = await open(repo) + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const ask = async (scope: Extract['scope']): Promise => { + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + await frames(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' }) + } + await ask({ kind: 'branch', base: 'refs/remotes/origin/main', commits: null }) + await ask({ kind: 'uncommitted' }) + await ask({ kind: 'staged' }) + await ask({ kind: 'unstaged' }) + await git(repo, 'commit', '--quiet', '-m', 'staged') + const commit = await git(repo, 'rev-parse', 'HEAD') + await ask({ kind: 'branch', base: null, commits: { from: commit, to: commit } }) + expect(reads).toEqual([ + 'tracked.txt old="initial\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="staged\\n"', + 'tracked.txt old="staged\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="staged\\n"', + ]) + }) + + it('reads a renamed file\'s old side at its previous path and a deleted file\'s new side as missing', async () => { + const repo = await project() + await writeFile(join(repo, 'gone.txt'), 'gone\n') + await git(repo, 'add', 'gone.txt') + await git(repo, 'commit', '--quiet', '-m', 'add gone') + await git(repo, 'mv', 'tracked.txt', 'moved.txt') + await git(repo, 'rm', '--quiet', 'gone.txt') + const opened = await open(repo) + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const scope = { kind: 'staged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + await frames(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(reads.sort()).toEqual(['gone.txt old="gone\\n" new=null', 'moved.txt old="initial\\n" new="initial\\n"']) + }) + + it('refuses a request for other files, maps a failed lens, and reports a lens withdrawn while it runs as missing', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'changed\n') + const opened = await open(repo) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const version = lensVersion(files) + await provideLens(opened.ctx, { id: 'fixture/broken' as ForgeLensId, version: '1', classify: async () => { throw new Error('parser crashed') } }) + const started = Promise.withResolvers() + const slow = await provideLens(opened.ctx, { + id: 'fixture/slow' as ForgeLensId, + version: '1', + classify: async (_input, lensSignal) => { + started.resolve(undefined) + return await untilAborted(lensSignal) + }, + }) + + await expect(rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: 'other', lens: 'fixture/broken' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-stale' }) + await expect(rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version, lens: 'fixture/broken' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-failed', message: 'the lens failed: parser crashed' }) + const pending = rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version, lens: 'fixture/slow' }) + await started.promise + await slow.dispose() + await expect(pending).resolves.toMatchObject({ code: 'forgePanel/lens-missing', message: 'the lens "fixture/slow" was unregistered' }) + }) + + it('neither runs nor answers from memory for a lens withdrawn while the files are read', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'export const changed = 1\n') + const opened = await open(repo) + const lens = exportsLens() + const plugin = await provideLens(opened.ctx, lens) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const request: ForgeLensRequest = { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' } + await frames(opened.ctx, opened.session, request) + expect(lens.classify).toHaveBeenCalledTimes(1) + + const held = hold(opened.sandbox, 'diff') + const pending = rejection(opened.ctx, opened.session, request) + await held.reached + await plugin.dispose() + held.release() + await expect(pending).resolves.toMatchObject({ code: 'forgePanel/lens-missing', message: 'No lens "fixture/exports" is registered' }) + expect(lens.classify).toHaveBeenCalledTimes(1) + }) + + it('neither sends nor keeps a result after the local files changed while the lens read them', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'export const value = 1\n') + const opened = await open(repo) + let edits = 0 + const classify = vi.fn(async (input: ForgeLensInput): Promise => { + await input.text('new', 'tracked.txt', signal) + if (edits === 0) { + edits += 1 + await writeFile(join(repo, 'tracked.txt'), 'export const value = 2\n') + } + return { files: { 'tracked.txt': {} } } + }) + await provideLens(opened.ctx, { id: 'fixture/editing' as ForgeLensId, version: '1', classify }) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const request: ForgeLensRequest = { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/editing' } + await expect(rejection(opened.ctx, opened.session, request)) + .resolves.toMatchObject({ code: 'forgePanel/lens-stale', message: 'The changes moved while the lens read them' }) + await writeFile(join(repo, 'tracked.txt'), 'export const value = 1\n') + await expect(frames(opened.ctx, opened.session, request)).resolves.toEqual([{ kind: 'result', files: { 'tracked.txt': {} } }]) + expect(classify).toHaveBeenCalledTimes(2) + }) + + it('passes a cancellation of the reader on unchanged', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'changed\n') + const opened = await open(repo) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const started = Promise.withResolvers() + await provideLens(opened.ctx, { + id: 'fixture/slow' as ForgeLensId, + version: '1', + classify: async (_input, lensSignal) => { + started.resolve(undefined) + return await untilAborted(lensSignal) + }, + }) + const controller = new AbortController() + const iterator = opened.ctx.forgePanel.changesLens(opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/slow' }, + controller.signal)[Symbol.asyncIterator]() + const next = iterator.next() + await started.promise + controller.abort(new Error('view closed')) + await expect(next).rejects.toThrow('view closed') + }) +}) + +describe('forgePanel lenses over change requests', () => { + const PATCH = [ + 'diff --git a/src/a.ts b/src/a.ts', '--- a/src/a.ts', '+++ b/src/a.ts', '@@ -1 +1 @@', '-const a = 1', '+export const a = 1', + 'diff --git a/src/old.ts b/src/new.ts', 'similarity index 90%', 'rename from src/old.ts', 'rename to src/new.ts', + '--- a/src/old.ts', '+++ b/src/new.ts', '@@ -1 +1 @@', '-old', '+export new', + 'diff --git a/src/added.ts b/src/added.ts', 'new file mode 100644', '--- /dev/null', '+++ b/src/added.ts', '@@ -0,0 +1 @@', '+added', + '', + ].join('\n') + + async function bound(base: string | null = BASE): Promise { + const opened = await open(await project()) + opened.provider.overrides.set(7, { headSha: HEAD, ...base === null ? {} : { baseSha: base } }) + opened.provider.patches.set(7, PATCH) + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + const follower = follow(opened.ctx, opened.session) + cleanups.push(follower.stop) + await follower.until(state => state.changeRequests.some(entry => entry.snapshot !== null)) + return opened + } + + it('reads the new side at the head and the old side at the merge base the provider names', async () => { + const opened = await bound() + const mergeBase = vi.fn(async () => MERGE_BASE) + Object.assign(opened.provider, { mergeBase }) + opened.provider.texts.set(`${HEAD}:src/a.ts`, 'export const a = 1\n') + opened.provider.texts.set(`${MERGE_BASE}:src/a.ts`, 'const a = 1\n') + opened.provider.texts.set(`${HEAD}:src/new.ts`, 'export new\n') + opened.provider.texts.set(`${MERGE_BASE}:src/old.ts`, 'old\n') + const reads: string[] = [] + const lens = exportsLens(reads) + await provideLens(opened.ctx, lens) + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + + const result = await frames(opened.ctx, opened.session, + { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(result.at(-1)).toEqual({ kind: 'result', files: { + 'src/a.ts': { ranges: { old: [], new: [{ start: 1, end: 1 }] } }, + 'src/new.ts': { ranges: { old: [], new: [{ start: 1, end: 1 }] } }, + } }) + expect(reads).toEqual([ + 'src/a.ts old="const a = 1\\n" new="export const a = 1\\n"', + 'src/new.ts old="old\\n" new="export new\\n"', + 'src/added.ts old=null new=null', + ]) + expect(mergeBase).toHaveBeenCalledTimes(1) + expect(mergeBase).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), BASE, HEAD, expect.any(AbortSignal)) + expect(lens.classify.mock.calls[0]?.[0]).toMatchObject({ source: { kind: 'change', headSha: HEAD, commits: null, ref: { number: 7 } } }) + }) + + it('reads the old side of chosen commits at the first one\'s parent', async () => { + const opened = await bound() + const first = 'd'.repeat(40) + const parent = 'e'.repeat(40) + const list: ForgeCommitList = { headSha: HEAD, truncated: false, commits: [ + { sha: first, parent, title: 'first', author: null, authoredAt: '2026-11-01T00:00:00Z' }, + { sha: HEAD, parent: first, title: 'head', author: null, authoredAt: '2026-11-02T00:00:00Z' }, + ] } + opened.provider.commitLists.set(7, list) + opened.provider.comparisons.set(`${parent}..${first}`, PATCH) + opened.provider.texts.set(`${parent}:src/a.ts`, 'parent\n') + opened.provider.texts.set(`${first}:src/a.ts`, 'first\n') + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const commits = { from: first, to: first } + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), commits, signal) + + await frames(opened.ctx, opened.session, { source: { kind: 'change', url: pullUrl(7), commits }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(reads[0]).toBe('src/a.ts old="parent\\n" new="first\\n"') + // A missing file reads as an absent side. + expect(reads[1]).toBe('src/new.ts old=null new=null') + }) + + it('fails reads of an old side the provider cannot locate and retries a failed merge base lookup', async () => { + const withoutBase = await bound(null) + await provideLens(withoutBase.ctx, exportsLens()) + const { files } = await withoutBase.ctx.forgePanel.changeRequestDiff(withoutBase.session, pullUrl(7), null, signal) + const request: ForgeLensRequest = { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/exports' } + await expect(rejection(withoutBase.ctx, withoutBase.session, request)).resolves.toMatchObject({ + code: 'forgePanel/lens-failed', message: 'the lens failed: The code host provider reports no base commit to read the old side at', + }) + + const flaky = await bound() + const mergeBase = vi.fn() + .mockResolvedValueOnce({ code: 'unavailable', message: 'compare failed' }) + .mockResolvedValue(MERGE_BASE) + Object.assign(flaky.provider, { mergeBase }) + flaky.provider.texts.set(`${HEAD}:src/a.ts`, 'export const a = 1\n') + flaky.provider.texts.set(`${MERGE_BASE}:src/a.ts`, 'const a = 1\n') + await provideLens(flaky.ctx, { + id: 'fixture/retry' as ForgeLensId, + version: '1', + classify: async (input) => { + await expect(input.text('old', 'src/a.ts', signal)).rejects.toThrow('compare failed') + expect(await input.text('old', 'src/a.ts', signal)).toBe('const a = 1\n') + return { files: {} } + }, + }) + await expect(frames(flaky.ctx, flaky.session, { ...request, lens: 'fixture/retry' })).resolves.toEqual([{ kind: 'result', files: {} }]) + expect(mergeBase).toHaveBeenCalledTimes(2) + }) + + it('fails a file read the host refuses and refuses a change request whose status is not read', async () => { + const opened = await bound() + opened.provider.texts.set(`${HEAD}:src/a.ts`, { code: 'too-large', message: 'file over the contents limit' }) + await provideLens(opened.ctx, { + id: 'fixture/new-only' as ForgeLensId, + version: '1', + classify: async (input) => { + await input.text('new', 'src/a.ts', signal) + return { files: {} } + }, + }) + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + const request: ForgeLensRequest = { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/new-only' } + await expect(rejection(opened.ctx, opened.session, request)) + .resolves.toMatchObject({ code: 'forgePanel/lens-failed', message: 'the lens failed: file over the contents limit' }) + + const unread = await open(await project()) + unread.provider.failures.set(9, { code: 'unavailable', message: 'down' }) + shellTurn(unread.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(9)}\n` }]) + const follower = follow(unread.ctx, unread.session) + cleanups.push(follower.stop) + await follower.until(state => state.changeRequests.some(entry => entry.update !== null)) + await provideLens(unread.ctx, exportsLens()) + await expect(rejection(unread.ctx, unread.session, { source: { kind: 'change', url: pullUrl(9), commits: null }, version: '', lens: 'fixture/exports' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-stale', message: 'The change request status has not been read yet' }) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts b/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts new file mode 100644 index 0000000000..6ca323454f --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts @@ -0,0 +1,263 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ForgeLens, ForgeLensFile, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLensResult } from '../src/types.ts' +import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from '../src/lenses.ts' +import type { LensRegistration, LensSubject } from '../src/lenses.ts' +import { lensVersion } from '../src/lens-version.ts' + +afterEach(() => { + vi.useRealTimers() +}) + +const limits = { timeoutMs: 1_000, maxReadBytes: 64, maxResultBytes: 1_024 } + +function file(path: string, overrides: Partial = {}): ForgeLensFile { + return { path, previousPath: null, status: 'modified', binary: false, layer: 'implementation', hunks: [], digest: `d-${path}`, ...overrides } +} + +function lens(classify: (input: ForgeLensInput, signal: AbortSignal) => Promise, id = 'test/lens'): ForgeLens { + return { id: id as ForgeLensId, version: '1', classify } +} + +function subject(files: readonly ForgeLensFile[], read: LensSubject['read'] = async (side, target) => `${side}:${target.path}`): LensSubject { + return { source: { kind: 'local', scope: { kind: 'unstaged' } }, files, read } +} + +/** Register `target` and return its registration and disposer. */ +function registered(target: ForgeLens): { registry: LensRegistry; registration: LensRegistration; dispose: () => Promise } { + const registry = new LensRegistry() + const dispose = registry.add(target) + const registration = registry.get(target.id) + if (registration === undefined) throw new Error('not registered') + return { registry, registration, dispose } +} + +async function collect(frames: AsyncIterable): Promise { + const list: ForgeLensFrame[] = [] + for await (const frame of frames) list.push(frame) + return list +} + +describe('LensRegistry', () => { + it('refuses a second registration of one identity and frees it once the first ends', async () => { + const registry = new LensRegistry() + const first = lens(async () => ({ files: {} })) + const dispose = registry.add(first) + expect(() => registry.add(lens(async () => ({ files: {} })))).toThrow('forge-panel: a lens "test/lens" is already registered') + expect(registry.get('test/lens')?.lens).toBe(first) + await dispose() + expect(registry.get('test/lens')).toBeUndefined() + await registry.add(first)() + }) + + it('streams the identities after each change, collapsing changes a busy reader missed, until the registry closes', async () => { + const registry = new LensRegistry() + const controller = new AbortController() + const iterator = registry.follow(controller.signal)[Symbol.asyncIterator]() + await expect(iterator.next()).resolves.toEqual({ done: false, value: [] }) + const a = registry.add(lens(async () => ({ files: {} }), 'a')) + registry.add({ ...lens(async () => ({ files: {} }), 'b'), version: '2' }) + await expect(iterator.next()).resolves.toEqual({ done: false, value: [{ id: 'a', version: '1' }, { id: 'b', version: '2' }] }) + await a() + await expect(iterator.next()).resolves.toEqual({ done: false, value: [{ id: 'b', version: '2' }] }) + const waiting = iterator.next() + registry.close() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + + const stopped = registry.follow(controller.signal)[Symbol.asyncIterator]() + await expect(stopped.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('ends a follow stream when its own signal aborts', async () => { + const registry = new LensRegistry() + const controller = new AbortController() + const iterator = registry.follow(controller.signal)[Symbol.asyncIterator]() + await iterator.next() + const waiting = iterator.next() + controller.abort() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + }) + + it('aborts a running classification when its registration ends and waits until the lens itself settles', async () => { + const started = Promise.withResolvers() + const cleanup = Promise.withResolvers() + const steps: string[] = [] + const { registration, dispose } = registered(lens(async (_input, signal) => { + started.resolve(signal) + await new Promise((resolve) => { signal.addEventListener('abort', resolve, { once: true }) }) + await cleanup.promise + steps.push('lens settled') + throw new Error('stopped') + })) + const run = runLens(registration, subject([]), limits, new AbortController().signal, () => {}) + const signal = await started.promise + const disposed = dispose().then(() => { steps.push('disposed') }) + // The caller hears of the withdrawal at once; the disposer waits for the lens's own cleanup. + await expect(run).rejects.toBeInstanceOf(LensWithdrawn) + expect(signal.aborted).toBe(true) + expect(steps).toEqual([]) + cleanup.resolve(undefined) + await disposed + expect(steps).toEqual(['lens settled', 'disposed']) + }) +}) + +describe('runLens', () => { + it('passes the source, files, and reader, and keeps only paths of the diff', async () => { + const files = [file('a.ts'), file('b.ts', { status: 'added' })] + const { registration } = registered(lens(async (input) => { + expect(input.source).toEqual({ kind: 'local', scope: { kind: 'unstaged' } }) + expect(input.files).toBe(files) + expect(await input.text('new', 'a.ts', new AbortController().signal)).toBe('new:a.ts') + return { files: { 'a.ts': { ranges: { old: [], new: [{ start: 1, end: 2 }] } }, 'gone.ts': {} } } + })) + await expect(runLens(registration, subject(files), limits, new AbortController().signal, () => {})) + .resolves.toEqual({ 'a.ts': { ranges: { old: [], new: [{ start: 1, end: 2 }] } } }) + }) + + it('refuses a path outside the diff and counts no text for a missing side', async () => { + const { registration } = registered(lens(async (input) => { + await expect(input.text('old', 'other.ts', new AbortController().signal)).rejects.toThrow('"other.ts" is not a file of this diff') + for (let index = 0; index < 100; index += 1) expect(await input.text('old', 'a.ts', new AbortController().signal)).toBeNull() + return { files: { 'a.ts': {} } } + })) + await expect(runLens(registration, subject([file('a.ts')], async () => null), limits, new AbortController().signal, () => {})) + .resolves.toEqual({ 'a.ts': {} }) + }) + + it('fails once the reads exceed the budget, even when the lens swallows the refusal', async () => { + const text = 'x'.repeat(40) + const reads: string[] = [] + const greedy = registered(lens(async (input) => { + reads.push(String(await input.text('new', 'a.ts', new AbortController().signal))) + await input.text('new', 'a.ts', new AbortController().signal) + return { files: {} } + })) + await expect(runLens(greedy.registration, subject([file('a.ts')], async () => text), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens read more than maxLensReadBytes (64 bytes) of file text')) + expect(reads).toEqual([text]) + + const swallowing = registered(lens(async (input) => { + await input.text('new', 'a.ts', new AbortController().signal) + await input.text('new', 'a.ts', new AbortController().signal).catch(() => null) + await expect(input.text('new', 'a.ts', new AbortController().signal)).rejects.toBeInstanceOf(LensFailed) + return { files: {} } + })) + await expect(runLens(swallowing.registration, subject([file('a.ts')], async () => text), limits, new AbortController().signal, () => {})) + .rejects.toBeInstanceOf(LensFailed) + }) + + it('fails a lens that runs past the deadline even when it ignores its signal', async () => { + vi.useFakeTimers() + const { registration } = registered(lens(async () => await new Promise(() => {}))) + const run = runLens(registration, subject([]), limits, new AbortController().signal, () => {}) + const outcome = expect(run).rejects.toThrow(new LensFailed('the lens ran past lensTimeoutMs (1000 ms)')) + await vi.advanceTimersByTimeAsync(1_000) + await outcome + }) + + it('names the cause of a rejected lens, including a thrown value that is not an error and a synchronous throw', async () => { + const failing = registered(lens(async () => { throw new Error('parser crashed') })) + await expect(runLens(failing.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: parser crashed')) + const odd = registered(lens(async () => { throw 'nope' })) + await expect(runLens(odd.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: nope')) + const sync = registered({ id: 'sync' as ForgeLensId, version: '1', classify: () => { throw new Error('at once') } }) + await expect(runLens(sync.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: at once')) + }) + + it('fails a result over the bound', async () => { + const { registration } = registered(lens(async () => ({ files: { 'a.ts': { ranges: { old: [], new: Array.from({ length: 100 }, (_v, start) => ({ start, end: start })) } } } }))) + await expect(runLens(registration, subject([file('a.ts')]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens result exceeds maxCachedLensBytes (1024 bytes)')) + }) + + it('does not start a lens whose registration ended or whose caller left before the run', async () => { + const classify = vi.fn(async () => ({ files: {} })) + const withdrawn = registered(lens(classify)) + await withdrawn.dispose() + await expect(runLens(withdrawn.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toBeInstanceOf(LensWithdrawn) + const live = registered(lens(classify)) + await expect(runLens(live.registration, subject([]), limits, AbortSignal.abort(new Error('reader left')), () => {})) + .rejects.toThrow('reader left') + expect(classify).not.toHaveBeenCalled() + }) + + it('rethrows the caller\'s reason and stops reporting progress once the caller aborts', async () => { + const controller = new AbortController() + const progress = vi.fn() + const reported = Promise.withResolvers() + const { registration } = registered(lens(async (input) => { + input.progress(1, 2) + reported.resolve(input) + return await new Promise(() => {}) + })) + const run = runLens(registration, subject([]), limits, controller.signal, progress) + const input = await reported.promise + controller.abort(new Error('reader left')) + await expect(run).rejects.toThrow('reader left') + input.progress(2, 2) + expect(progress.mock.calls).toEqual([[1, 2]]) + }) +}) + +describe('lensFrames', () => { + it('yields the latest progress since the previous frame, then the result', async () => { + const step = Promise.withResolvers() + const finish = Promise.withResolvers() + const frames = lensFrames(async (progress) => { + progress(1, 3) + progress(2, 3) + await step.promise + progress(3, 3) + await finish.promise + return { 'a.ts': {} } + })[Symbol.asyncIterator]() + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'progress', done: 2, total: 3 } }) + step.resolve(undefined) + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'progress', done: 3, total: 3 } }) + finish.resolve(undefined) + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'result', files: { 'a.ts': {} } } }) + await expect(frames.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('drops progress reported as the run finishes and passes a failure on', async () => { + await expect(collect(lensFrames(async (progress) => { + progress(1, 1) + return {} + }))).resolves.toEqual([{ kind: 'result', files: {} }]) + await expect(collect(lensFrames(async () => { throw new LensFailed('broken') }))).rejects.toThrow('broken') + }) +}) + +describe('LensCache', () => { + it('keeps results up to its bound, dropping the least recently used and replacing equal keys', () => { + const one = { 'a.ts': {} } + const size = Buffer.byteLength(JSON.stringify(one)) + const cache = new LensCache(size * 2) + cache.set('a', one) + cache.set('b', { 'b.ts': {} }) + expect(cache.get('a')).toBe(one) + cache.set('c', { 'c.ts': {} }) + expect(cache.get('b')).toBeUndefined() + expect(cache.get('a')).toBe(one) + const replaced = { 'c.ts': {} } + cache.set('c', replaced) + expect(cache.get('c')).toBe(replaced) + expect(cache.get('a')).toBe(one) + }) +}) + +describe('lensVersion', () => { + it('changes with any path, digest, or order and is stable otherwise', () => { + const files = [{ path: 'a.ts', digest: '1' }, { path: 'b.ts', digest: '2' }] + expect(lensVersion(files)).toBe(lensVersion([...files])) + expect(lensVersion(files)).toMatch(/^[0-9a-f]{14}$/) + expect(new Set([ + lensVersion(files), lensVersion([...files].reverse()), lensVersion([{ path: 'a.ts', digest: '3' }, files[1]!]), + lensVersion([{ path: 'a.t', digest: 's1' }, files[1]!]), lensVersion([]), + ]).size).toBe(5) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index 79e7653bfc..cd4a2caa08 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -8,7 +8,7 @@ import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, forkPoint, localChanges, - localCommits, localDiff, localText, NoForkPoint, + localCommits, localDiff, localOldText, localText, NoForkPoint, } from '../src/local-diff.ts' import type { DiffConfig, ForkPoint } from '../src/local-diff.ts' import { FileLayers } from '../src/layers.ts' @@ -469,6 +469,51 @@ describe('commits of the branch scope', () => { }) }) +describe('localOldText', () => { + it('reads the old side at the fork point, HEAD, the index, or before the first chosen commit', async () => { + const { repo, fork } = await forked(await directory()) + await writeFile(join(repo, 'staged.txt'), 'edited after staging\n') + const ctx = await context(repo) + const point: ForkPoint = { commit: fork, label: 'origin/main', worktree: false } + const committed = await git(repo, 'rev-parse', 'HEAD') + const read = (scope: ForgeLocalScope, path: string, at: ForkPoint | null = null): Promise => + localOldText(ctx, CONFIG, plainSession(repo), repo, scope, at, path, signal) + + await expect(read({ kind: 'branch', base: null, commits: null }, 'tracked.txt', point)).resolves.toBe('initial\n') + await expect(read({ kind: 'branch', base: null, commits: null }, 'committed.txt', point)).resolves.toBeNull() + await expect(read({ kind: 'uncommitted' }, 'committed.txt')).resolves.toBe('one\n') + await expect(read({ kind: 'staged' }, 'staged.txt')).resolves.toBeNull() + await expect(read({ kind: 'unstaged' }, 'staged.txt')).resolves.toBe('staged\n') + await expect(read({ kind: 'branch', base: null, commits: { from: committed, to: committed } }, 'tracked.txt', point)).resolves.toBe('initial\n') + }) + + it('reads binary content and the parent of a root commit as missing', async () => { + const { repo } = await forked(await directory()) + await writeFile(join(repo, 'blob.bin'), Uint8Array.from([0x61, 0, 0x62])) + await git(repo, 'add', 'blob.bin') + await git(repo, 'commit', '--quiet', '-m', 'blob') + const ctx = await context(repo) + const root = await git(repo, 'rev-list', '--max-parents=0', 'HEAD') + + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'unstaged' }, null, 'blob.bin', signal)).resolves.toBeNull() + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: { from: root, to: root } }, + { commit: root, label: 'root', worktree: false }, 'tracked.txt', signal)).resolves.toBeNull() + }) + + it('refuses a path outside the checkout, a branch without a fork point, and a chosen commit that is not an object name', async () => { + const { repo, fork } = await forked(await directory()) + const ctx = await context(repo) + const point: ForkPoint = { commit: fork, label: 'origin/main', worktree: false } + + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'unstaged' }, null, '../outside.txt', signal)) + .rejects.toThrow('is not a path inside the checkout') + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: null }, null, 'tracked.txt', signal)) + .rejects.toBeInstanceOf(NoForkPoint) + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: { from: 'HEAD', to: 'HEAD' } }, point, + 'tracked.txt', signal)).rejects.toBeInstanceOf(CommitsMissing) + }) +}) + describe('localText', () => { const branch: ForgeLocalScope = { kind: 'branch', base: null, commits: null } diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 5124c90ea3..074ccc311b 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -39,7 +39,8 @@ import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFiel import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import type { - ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, + ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, + ForgeLensRequest, ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, } from '../src/types.ts' import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts' @@ -145,6 +146,7 @@ async function base() { const remote = new Remote() const streams: ReturnType[] = [] const stateStreams: ReturnType>[] = [] + const extensionStreams: ReturnType>[] = [] const forgePanel = { follow: vi.fn((_sessionId: SessionId, signal: AbortSignal) => { const handle = stream(signal) @@ -156,6 +158,12 @@ async function base() { stateStreams.push(handle) return handle }), + extensions: vi.fn((signal: AbortSignal) => { + const handle = stream(signal) + extensionStreams.push(handle) + return handle + }), + changesLens: vi.fn((_sessionId: SessionId, _request: ForgeLensRequest, signal: AbortSignal) => stream(signal)), worktreeCleanup: vi.fn(async (_sessionId: SessionId, _revision: number | null): Promise> => ({ ok: true, value: null })), track: vi.fn(async (_sessionId: SessionId, _url: string): Promise> => OK), @@ -210,7 +218,8 @@ async function base() { const unregisterTab = vi.fn() const sidebarRightTabs = { register: vi.fn((_type: SidebarRightTabDefinition) => unregisterTab) } ctx.provide('sidebarRightTabs', sidebarRightTabs) - const sidebarRight = { openTab: vi.fn(), toggleExpanded: vi.fn(), hide: vi.fn(), + const sidebarRight = { openTab: vi.fn(), toggleExpanded: vi.fn(), hide: vi.fn(), openResource: vi.fn(), + mounted: { getSnapshot: vi.fn((): SessionId | undefined => S1), subscribe: () => () => {} }, tabsIn: vi.fn(() => [{ id: 'forge-tab' as TabId, kind: TAB_KIND }]) } const scopes = new Map>() const sessions = { scope: vi.fn<(id: SessionId) => Context | undefined>((id) => { @@ -240,7 +249,8 @@ async function base() { }, } as never, () => null) return { - ctx, remote, unmount, streams, stateStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight, sessions, scopes, worktreeForm, + ctx, remote, unmount, streams, stateStreams, extensionStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight, sessions, + scopes, worktreeForm, } } @@ -386,6 +396,59 @@ describe('mountForgePanel registration', () => { }) }) +describe('mountForgePanel extension API', () => { + it('provides the changes view face, which opens a view in the shown Session and is withdrawn on unload', async () => { + const f = await fixture() + const forgeChanges = f.ctx.get('forgeChanges') + assert(forgeChanges !== undefined) + expect(forgeChanges.kinds).toEqual({ changes: CHANGES_KIND, panel: TAB_KIND }) + const target = { sessionId: S1, source: { kind: 'local' } } as const + forgeChanges.open(target, { path: 'src/a.ts' }) + expect(f.sidebarRight.openResource).toHaveBeenCalledWith(forgeChanges.address(target), { params: { path: 'src/a.ts' } }) + forgeChanges.open(target) + expect(f.sidebarRight.openResource).toHaveBeenLastCalledWith(forgeChanges.address(target), undefined) + await f.dispose() + await settle() + expect(f.ctx.get('forgeChanges')).toBeUndefined() + }) + + it('streams the Host lenses to the changes view while it reads them, opens lens requests, and keeps one annotation view per address', async () => { + const f = await fixture() + const face = f.changes(S1) + const seen = vi.fn() + const stop = face.hooks.extensions.subscribe(seen) + expect(face.hooks.extensions.getSnapshot().state).toBeNull() + f.extensionStreams[0]?.push({ lenses: [{ id: 'fixture/exports', version: '1' }], maxAnnotationsPerFile: 4 }) + await settle() + expect(face.hooks.extensions.getSnapshot().state).toEqual({ lenses: [{ id: 'fixture/exports', version: '1' }], maxAnnotationsPerFile: 4 }) + const forgeChanges = f.ctx.get('forgeChanges') + assert(forgeChanges !== undefined) + const relay = vi.fn() + const unrelay = forgeChanges.extensions.subscribe(relay) + f.extensionStreams[0]?.push({ lenses: [], maxAnnotationsPerFile: 4 }) + await settle() + expect(forgeChanges.extensions.getSnapshot()).toEqual({ lenses: [], maxAnnotationsPerFile: 4 }) + expect(relay).toHaveBeenCalled() + unrelay() + stop() + expect(face.hooks.lenses).toBe(forgeChanges.lenses) + + const request: ForgeLensRequest = { source: { kind: 'local', scope: { kind: 'unstaged' } }, version: 'v', lens: 'fixture/exports' } + face.changesLens(request, new AbortController().signal) + expect(f.forgePanel.changesLens).toHaveBeenCalledWith(S1, request, expect.any(AbortSignal)) + + const address = forgeChanges.address({ sessionId: S1, source: { kind: 'local' } }) + const view = face.keyedHooks.annotations(address) + expect(face.keyedHooks.annotations(address)).toBe(view) + expect(face.keyedHooks.annotations(forgeChanges.address({ sessionId: S1, source: { kind: 'change', url: 'https://github.com/octo/demo/pull/7' } }))) + .not.toBe(view) + expect(() => face.keyedHooks.annotations('dsh-resource://forge-changes/s1/remote')).toThrow('forge-panel: not a changes address') + + await f.dispose() + expect(f.extensionStreams[0]?.disposed).toHaveBeenCalled() + }) +}) + describe('mountForgePanel Session list', () => { it('shares one change request state stream among every Session row and hover card while any of them reads it', async () => { const f = await fixture() diff --git a/packages/experimental/client-ui-forge/tests/review.host.spec.ts b/packages/experimental/client-ui-forge/tests/review.host.spec.ts index dd9c41145a..c0b85fc02a 100644 --- a/packages/experimental/client-ui-forge/tests/review.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review.host.spec.ts @@ -47,6 +47,25 @@ function polledAt(state: ForgePanelState, url: string, headSha = HEAD, updatedAt } describe('forgePanel change request reviews', () => { + it('reports each accepted review change of any plugin on the bound entry and reads the threads again after it', async () => { + const { opened: panel, follower } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + Object.assign(panel.provider, { readReview, writeReview: async () => ({ ok: true }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + const polled = await follower.until(state => polledAt(state, pullUrl(7))) + expect(polled.changeRequests[0]?.reviewRevision).toBe(0) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal) + const ref = polled.changeRequests[0]?.ref + if (ref === null || ref === undefined) throw new Error('unbound') + + // Another plugin writes through `ctx.forge`, not through this panel. + await panel.ctx.forge.writeReview(ref, { kind: 'resolve', headSha: HEAD, thread: 'thread-1' as ForgeThreadId, resolved: true }, signal) + await follower.until(state => state.changeRequests[0]?.reviewRevision === 1) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + it('reads threads at the displayed head and reuses them for every Session until the update time changes', async () => { const { opened: panel, follower, repo } = await opened() const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) diff --git a/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx b/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx index 2267d73380..3e26ebfc59 100644 --- a/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx @@ -15,7 +15,7 @@ afterEach(() => { function mount(overrides: Partial = {}, visible = true, fold?: string) { const options: ViewOptions = { anyExpanded: false, hasFiles: true, toggleExpansion: vi.fn(), split: true, toggleSplit: vi.fn(), wrap: false, toggleWrap: vi.fn(), - hideTests: true, toggleTests: vi.fn(), refresh: vi.fn(), ...overrides, + hideTests: true, toggleTests: vi.fn(), refresh: vi.fn(), lenses: [], chooseLens: vi.fn(), plugins: vi.fn(() => null), ...overrides, } const view = render(
) const trigger = within(view.container).getByRole('button', { name: en['diff.moreOptions'] }) @@ -73,3 +73,16 @@ it('toggles test files from the menu', () => { fireEvent.click(m.view.getByRole('menuitem', { name: en['tests.hide'] })) expect(m.options.toggleTests).toHaveBeenCalledTimes(1) }) + +it('lists the lenses with the test switch at level 2, chooses one, and draws the plugin rows that close the menu', () => { + const chooseLens = vi.fn() + const plugins = vi.fn((close: () => void) => ) + const m = mount({ lenses: [{ id: 'fixture/exports', title: 'Exports', count: 1 }], chooseLens, plugins }, true, '2') + fireEvent.click(m.trigger) + expect(m.rows()).toEqual(['Expand all files', 'Side by side', 'Wrap lines', 'Hide test files', 'No lens', 'Exports1', 'Notes 2']) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Exports1' })) + expect(chooseLens).toHaveBeenCalledWith('fixture/exports') + fireEvent.click(m.trigger) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Notes 2' })) + expect(m.rows()).toEqual([]) +}) diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index 6bc548094f..779c176d28 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -9,6 +9,7 @@ "src/client", "src/commit-range.ts", "src/css-modules.d.ts", + "src/lens-version.ts", "src/types.ts" ], "references": [ @@ -66,6 +67,9 @@ { "path": "../../typert/protocol" }, + { + "path": "../../util/brand" + }, { "path": "../../util/values" }, diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index 051f252042..d92dfcba55 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -12,6 +12,8 @@ "src/git.ts", "src/local-diff.ts", "src/layers.ts", + "src/lens-version.ts", + "src/lenses.ts", "src/panel.ts", "src/parse.ts", "src/patch-cache.ts", @@ -67,6 +69,9 @@ { "path": "../../typert/protocol" }, + { + "path": "../../util/brand" + }, { "path": "../../util/timeout" }, diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 0cee1a4f70..ce7a374932 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: d19ccf4e026491ad - zh: b70fa4b2affa8340 + en: 7e0ba1b3e7bdc1d6 + zh: 4e6f269af19b444d /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 9b639e511e850042 zh: 25a1a3bde330e7da diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 829cf388aa..c91f2b3278 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -46,7 +46,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. Each status snapshot carries `baseRefOid` as `baseSha`, and leaves it out when GitHub reports no full commit there; given it, `diff` starts this comparison while the GraphQL query confirms the head, and a stale head or another base commit cancels the early comparison and waits for it to end before `diff` returns. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. Each status snapshot carries `baseRefOid` as `baseSha`, and leaves it out when GitHub reports no full commit there; given it, `diff` starts this comparison while the GraphQL query confirms the head, and a stale head or another base commit cancels the early comparison and waits for it to end before `diff` returns. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. `mergeBase` reads `merge_base_commit.sha` from `repos///compare/...?page=2&per_page=1`, a page of the comparison that lists no files, and returns `unavailable` when the answer is not a full commit. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 997808e78c..3f0023c172 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。`mergeBase` 从 `repos///compare/...?page=2&per_page=1` 读取 `merge_base_commit.sha`;这一页比较结果不列文件。返回值不是完整提交时为 `unavailable`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index 84d58344ca..2f2b1d1d1d 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -257,6 +257,25 @@ export class GitHubProvider implements ForgeProvider { return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal) } + /** + * Find the merge base through the compare API. The request names the second page of one commit per page, which + * carries the merge base but not the changed files GitHub lists only on the first page. + */ + async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + const { host, owner, name } = checkedRepository(ref) + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + for (const commit of [base, head]) { + if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + } + const output = await this.read([ + 'api', '--hostname', host, '--jq', '.merge_base_commit.sha', `repos/${owner}/${name}/compare/${base}...${head}?page=2&per_page=1`, + ], signal) + if (typeof output !== 'string') return output + const commit = output.trim() + return isCommit(commit) ? commit.toLowerCase() : { code: 'unavailable', message: 'unexpected GitHub response to the merge base read' } + } + /** Read the viewer's viewed marks through GraphQL, at most `maxViewedFiles`, every page at `headSha`. */ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const failure = this.hostFailure(checkedRepository(ref).host) diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index 7bea15a154..eeabeabe70 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -699,6 +699,7 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.commits(target, signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.compare(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.mergeBase(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) // A repository that cannot name a request is refused before its host, as every read refuses it. const unsafe = pull(7, { ...demo, host: 'unconfigured.example', owner: 'oc/to' }) const invalid = 'forge-github: invalid repository "oc/to/demo"' @@ -706,9 +707,38 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.fileText(unsafe, 'a'.repeat(40), 'file.txt', signal)).rejects.toThrow(invalid) await expect(subject.commits(unsafe, signal)).rejects.toThrow(invalid) await expect(subject.compare(unsafe, 'a'.repeat(40), 'b'.repeat(40), signal)).rejects.toThrow(invalid) + await expect(subject.mergeBase(unsafe, 'a'.repeat(40), 'b'.repeat(40), signal)).rejects.toThrow(invalid) expect(gh.calls).toEqual([]) }) +describe('GitHub provider merge bases', () => { + const base = 'b'.repeat(40) + const head = 'c'.repeat(40) + + it('reads the merge base from the compare page that lists no files', async () => { + const gh = fakeGh(() => output(`${'A'.repeat(40)}\n`)) + + await expect(provider(gh.run).mergeBase(pull(7, enterprise), base, head, signal)).resolves.toBe('a'.repeat(40)) + expect(gh.calls).toEqual([ + ['api', '--hostname', 'ghe.corp.example', '--jq', '.merge_base_commit.sha', `repos/team/svc/compare/${base}...${head}?page=2&per_page=1`], + ]) + }) + + it('reports a refused read as a failure and an answer that names no commit as unavailable', async () => { + await expect(provider(fakeGh(() => output('', 1, 'gh: No common ancestor (HTTP 404)')).run).mergeBase(pull(7), base, head, signal)) + .resolves.toMatchObject({ code: 'not-found' }) + await expect(provider(fakeGh(() => output('null\n')).run).mergeBase(pull(7), base, head, signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response to the merge base read' }) + }) + + it('refuses commits that cannot be inlined without starting gh', async () => { + const gh = fakeGh(() => output('')) + await expect(provider(gh.run).mergeBase(pull(7), 'main', head, signal)).rejects.toThrow('forge-github: invalid commit "main"') + await expect(provider(gh.run).mergeBase(pull(7), base, 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"') + expect(gh.calls).toEqual([]) + }) +}) + describe('GitHub provider overview and viewed marks', () => { const HEAD = 'f'.repeat(40) const unconfigured = pull(1, { ...demo, host: 'gitlab.com' }) diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index 9e385827da..63ab6e5a68 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 8f8960a20cb74708 - zh: 1fc71e5dc46e3c48 + en: cb87b11162a52273 + zh: c16a36d01c4fb53a /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 13cd1124d1..b5553e74be 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -42,6 +42,8 @@ Providers may implement `commits` and `compare` together. `commits(ref, signal)` Providers may implement `viewedFiles` and `setViewed` together. `viewedFiles(ref, headSha, signal)` reads the signed-in user's viewed marks on the files of a change request at head commit `headSha`, each `viewed`, `unviewed`, or `dismissed` when the file changed after it was marked, with a `truncated` flag; `setViewed(ref, { path, viewed, headSha }, signal)` sets or clears one file's mark only while the head is still `headSha`. Both report a moved head as `stale`, which polls a watched change request as a stale `diff` does. When the provider lacks either method, `viewedFiles` returns undefined and `setViewed` a `failed` failure, so a consumer keeps viewed marks itself. +Providers may implement `mergeBase(ref, base, head, signal)`, which names the commit whose files the old side of a change request's diff shows; `ctx.forge.mergeBase` returns `unsupported` without it. After a review write, a submitted review, or a viewed mark the host accepted, the registry announces `forge/review-changed` with the change request and the change, whichever plugin made it; an outcome that is unknown, refused, stale, or unsupported is not announced. The [extension API](../../../docs/subsystems/forge.md#extension-api) lists what other plugins may rely on. + Snapshots carry the overview of a change request. `reviewers` lists requested reviewers first, then the latest reviewer of each account with their verdict and the commit it was given at; `closingIssues` lists the issues the host closes when the change request merges; `reviewersTruncated` and `closingIssuesTruncated` mark lists the provider read only in part. `branchUpdates` names the methods that would bring a head behind its base up to date for the signed-in user, empty when the head is current, conflicts, or may not be updated, so a consumer cannot tell a user without that right that the head is behind. `canRequestReviews` and `canRerunChecks` state the signed-in user's rights, and each check's `rerun` names the host run that reruns it, or null; checks that name one run rerun together once none of them is pending. Providers may implement `rerunChecks(ref, { headSha }, signal)`, which reruns the failed checks of head commit `headSha` whose run has no pending check; `requestReviews(ref, { reviewers }, signal)` together with `reviewerCandidates(ref, query, signal)`, which lists accounts a review can be requested from with the host's suggestions first; and `updateBranch(ref, { method, headSha }, signal)`, which merges or rebases the base into the head only while the head is still `headSha`. Each action resolves to undefined once the host accepted it or to a `ForgeActionFailure`, and polls a watched change request once it settles. The registry fails an action the provider lacks with `failed`, without polling, and returns `unsupported` from `reviewerCandidates` unless the provider implements both review request methods. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index fee6351cdc..6ca034ca50 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -42,6 +42,8 @@ kind: "package-reference" 提供方可以同时实现 `viewedFiles` 与 `setViewed`。`viewedFiles(ref, headSha, signal)` 在 head 提交 `headSha` 上读取当前登录用户对变更请求各文件的已审阅标记,每个文件为 `viewed`、`unviewed`,或在标记后又有改动时为 `dismissed`,并带 `truncated` 标志;`setViewed(ref, { path, viewed, headSha }, signal)` 仅在 head 仍是 `headSha` 时设置或清除一个文件的标记。两者都把已移动的 head 报告为 `stale`,并像过期的 `diff` 一样立即轮询被监听的变更请求。提供方缺少其中任一方法时,`viewedFiles` 返回 undefined,`setViewed` 返回 `failed` 失败,因此使用方自行保存已审阅标记。 +提供方可以实现 `mergeBase(ref, base, head, signal)`,给出变更请求 diff 旧侧所显示文件所在的提交;缺少它时 `ctx.forge.mergeBase` 返回 `unsupported`。托管平台接受一次评审写入、一次评审提交或一个已审阅标记后,注册表以该变更请求和这次变化发出 `forge/review-changed`,无论是哪个插件做的;结果未知、被拒绝、已过时或不支持时不发出。[扩展 API](../../../docs/subsystems/forge.zh.md#extension-api) 列出其他插件可以依赖的内容。 + 快照携带变更请求的概览。`reviewers` 先列出被请求的评审者,再列出每个账号最近一次评审的结论及其所针对的提交;`closingIssues` 列出变更请求合并时代码托管平台会关闭的 issue;`reviewersTruncated` 与 `closingIssuesTruncated` 标记提供方只读取了部分的列表。`branchUpdates` 列出能让落后于基线的 head 为当前登录用户更新的方式;head 已是最新、存在冲突或不允许更新时为空,因此使用方无法告诉没有更新权限的用户 head 已落后。`canRequestReviews` 与 `canRerunChecks` 说明当前登录用户的权限,每个检查的 `rerun` 指出能重跑它的托管平台运行,否则为 null;指向同一运行的检查一起重跑,且要等其中没有检查仍在进行。 提供方可以实现 `rerunChecks(ref, { headSha }, signal)`,重跑 head 提交 `headSha` 中所在运行没有进行中检查的失败检查;可以同时实现 `requestReviews(ref, { reviewers }, signal)` 与 `reviewerCandidates(ref, query, signal)`,后者列出可以请求评审的账号,托管平台的建议排在最前;还可以实现 `updateBranch(ref, { method, headSha }, signal)`,仅在 head 仍是 `headSha` 时把基线合并或变基进 head。每个操作在托管平台接受后返回 undefined,否则返回 `ForgeActionFailure`,结束后会立即轮询被监听的变更请求。提供方缺少某个操作时,注册表以 `failed` 失败返回且不轮询;除非提供方同时实现两个评审请求方法,`reviewerCandidates` 返回 `unsupported`。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index aca2a49f12..ffb792a498 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -8,7 +8,8 @@ import { nextPollDelay } from './schedule.ts' import type { BranchUpdateRequest, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, - ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, + ForgeReviewChange, ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, + ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest, } from './types.ts' @@ -27,6 +28,15 @@ declare module '@deepseek-ai/cordis' { * @mode parallel */ 'forge/providers-changed'(forge: string): void | Promise + /** + * Announces a review change the host accepted through this service: a thread or pending-review write, a submitted + * review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. + * Listener failures are logged without preventing other listeners from running. + * @param ref - change request the change went to. + * @param change - what changed and the head commit it was made against. + * @mode parallel + */ + 'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise } } @@ -343,7 +353,7 @@ export class ForgeService extends Service { /** * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then * poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls - * it as a stale read does. + * it as a stale read does; a write the host took is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param write - the write and the head commit the user saw. * @param signal - cancellation of the write. @@ -357,6 +367,7 @@ export class ForgeService extends Service { ?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' } as const)) if (!result.ok && result.code === 'stale') this.staleRead(ref, write.headSha, result.code) else if (result.ok || result.code !== 'unsupported') this.refresh(ref) + if (result.ok) this.reviewChanged(ref, { kind: 'write', write: write.kind, headSha: write.headSha }) return result } @@ -380,7 +391,8 @@ export class ForgeService extends Service { /** * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still - * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved + * mark is announced with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - the file, its mark, and the head commit the user saw. * @param signal - cancellation of the request. @@ -393,6 +405,7 @@ export class ForgeService extends Service { ? Promise.resolve({ code: 'failed', message: 'This provider keeps no viewed marks' } as const) : provider.setViewed(ref, request, operation)) if (failure?.code === 'stale') this.staleRead(ref, request.headSha, failure.code) + if (failure === undefined) this.reviewChanged(ref, { kind: 'viewed', path: request.path, viewed: request.viewed, headSha: request.headSha }) return failure } @@ -427,7 +440,25 @@ export class ForgeService extends Service { } /** - * Publish one comment or a completed review, then refresh the watched status. + * Find the merge base of two commits of a change request's repository: the commit whose files the old side of the + * change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`. + * @param ref - change request served by a registered provider. + * @param base - full object name of the base commit. + * @param head - full object name of the head commit. + * @param signal - cancellation of the read. + * @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider + * cannot name merge bases. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.mergeBase?.(ref, base, head, operation) + ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not name merge bases' } as const)) + } + + /** + * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced + * with `forge/review-changed`. * @param ref - change request served by a registered provider. * @param request - explicitly selected commit, comments, and review decision. * @param signal - request cancellation. @@ -438,6 +469,7 @@ export class ForgeService extends Service { (provider, operation) => provider.submitReview?.(ref, request, operation) ?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review submission' } as const)) this.refresh(ref) + if (result.ok) this.reviewChanged(ref, { kind: 'submit', headSha: request.headSha }) return result } @@ -560,9 +592,21 @@ export class ForgeService extends Service { } private providersChanged(forge: string): void { + this.announce('provider change', () => this.ctx.parallel('forge/providers-changed', forge)) + } + + private reviewChanged(ref: ChangeRequestRef, change: ForgeReviewChange): void { + this.announce('review change', () => this.ctx.parallel('forge/review-changed', ref, change)) + } + + /** + * Start one parallel dispatch unless the service stopped, keeping it among the work disposal waits for and logging + * listener failures. + */ + private announce(what: string, dispatch: () => Promise): void { if (this.lifetime.signal.aborted) return - const task = this.ctx.parallel('forge/providers-changed', forge).catch((error: unknown) => { - this.ctx.logger.warn(`forge: provider change listener failed: ${String(error)}`) + const task = dispatch().catch((error: unknown) => { + this.ctx.logger.warn(`forge: ${what} listener failed: ${String(error)}`) }) this.pending.add(task) void task.then(() => this.pending.delete(task)) diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 46da83a266..013d3bcbc2 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -405,6 +405,15 @@ export type ForgeReviewWriteResult = | { readonly ok: true } | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } +/** + * One review change the host accepted, which `forge/review-changed` announces: a write to the threads or the pending + * review, a submitted review, or a viewed mark. Each names the head commit the change was made against. + */ +export type ForgeReviewChange = + | { readonly kind: 'write'; readonly write: ForgeReviewWrite['kind']; readonly headSha: string } + | { readonly kind: 'submit'; readonly headSha: string } + | { readonly kind: 'viewed'; readonly path: string; readonly viewed: boolean; readonly headSha: string } + /** Result of a review submission; unknown outcomes must be checked on the host before another submission. */ export type ForgeReviewResult = | { readonly ok: true; readonly url: string } @@ -544,6 +553,12 @@ export interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Find the merge base of commits `base` and `head` in the change request's repository, as a full object name: the + * commit whose files the old side of a change request's diff shows. Omission declares that the provider cannot name + * it, so readers of the old side get `unsupported`. + */ + mergeBase?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise /** * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a diff --git a/packages/experimental/forge/tests/review-changed.spec.ts b/packages/experimental/forge/tests/review-changed.spec.ts new file mode 100644 index 0000000000..f03a6baadb --- /dev/null +++ b/packages/experimental/forge/tests/review-changed.spec.ts @@ -0,0 +1,114 @@ +import type { Context } from '@deepseek-ai/cordis' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { + ChangeRequestRef, ForgeReviewChange, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, +} from '../src/types.ts' +import { FakeProvider, forgeContext, provide, ref } from './fake-provider.ts' + +let ctx: Context | undefined + +afterEach(async () => { + await ctx?.fiber.dispose() + ctx = undefined +}) + +const head = 'a'.repeat(40) +const resolve: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread: 'thread-1' as ForgeThreadId, resolved: true } + +/** Record every announced change in order. */ +function record(target: Context): [ChangeRequestRef, ForgeReviewChange][] { + const changes: [ChangeRequestRef, ForgeReviewChange][] = [] + target.on('forge/review-changed', (changed, change) => { changes.push([changed, change]) }) + return changes +} + +describe('forge/review-changed', () => { + it('announces each review write, submission, and viewed mark the host accepted', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + Object.assign(provider, { + writeReview: async () => ({ ok: true }), + submitReview: async () => ({ ok: true, url: 'https://fake.test/Octo/Demo/change/3#review' }), + viewedFiles: async () => ({ headSha: head, files: {}, truncated: false }), + setViewed: async () => undefined, + }) + await provide(ctx, provider) + const changes = record(ctx) + const signal = new AbortController().signal + + await ctx.forge.writeReview(ref(3), resolve, signal) + await ctx.forge.submitReview(ref(3), { kind: 'review', headSha: head, event: 'approve', body: '', comments: [] }, signal) + await ctx.forge.setViewed(ref(3), { path: 'src/a.ts', viewed: false, headSha: head }, signal) + + await vi.waitFor(() => { expect(changes).toHaveLength(3) }) + expect(changes).toEqual([ + [ref(3), { kind: 'write', write: 'resolve', headSha: head }], + [ref(3), { kind: 'submit', headSha: head }], + [ref(3), { kind: 'viewed', path: 'src/a.ts', viewed: false, headSha: head }], + ]) + }) + + it.each(['unsupported', 'stale', 'failed', 'unknown'] as const)('announces nothing for a %s write', async (code) => { + ctx = await forgeContext() + const provider = new FakeProvider() + const result: ForgeReviewWriteResult = { ok: false, code, message: code } + if (code !== 'unsupported') Object.assign(provider, { writeReview: async () => result }) + await provide(ctx, provider) + const changes = record(ctx) + + await ctx.forge.writeReview(ref(3), resolve, new AbortController().signal) + await ctx.forge.submitReview(ref(3), { kind: 'comment', headSha: head, comment: { path: 'a', side: 'R', startLine: 1, endLine: 1, body: 'x' } }, + new AbortController().signal) + await ctx.forge.setViewed(ref(3), { path: 'src/a.ts', viewed: true, headSha: head }, new AbortController().signal) + await new Promise(settled => setTimeout(settled, 0)) + + expect(changes).toEqual([]) + }) + + it('contains a failed listener without changing the write result', async () => { + ctx = await forgeContext() + const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const provider = new FakeProvider() + Object.assign(provider, { writeReview: async () => ({ ok: true }) }) + await provide(ctx, provider) + ctx.on('forge/review-changed', () => { throw new Error('listener failed') }) + const changes = record(ctx) + + await expect(ctx.forge.writeReview(ref(3), resolve, new AbortController().signal)).resolves.toEqual({ ok: true }) + await vi.waitFor(() => { expect(warning).toHaveBeenCalledWith(expect.stringContaining('review change listener failed')) }) + expect(changes).toHaveLength(1) + }) + + it('stops calling a listener once its plugin fiber is disposed', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + Object.assign(provider, { writeReview: async () => ({ ok: true }) }) + await provide(ctx, provider) + const listener = vi.fn() + const fiber = ctx.plugin({ inject: ['forge'], apply(child: Context) { child.on('forge/review-changed', listener) } }) + await fiber + await ctx.forge.writeReview(ref(3), resolve, new AbortController().signal) + await vi.waitFor(() => { expect(listener).toHaveBeenCalledTimes(1) }) + + await fiber.dispose() + await ctx.forge.writeReview(ref(3), resolve, new AbortController().signal) + await new Promise(settled => setTimeout(settled, 0)) + expect(listener).toHaveBeenCalledTimes(1) + }) +}) + +describe('mergeBase', () => { + it('reports a provider without merge bases as unsupported and forwards to one with them', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + + await expect(ctx.forge.mergeBase(ref(3), 'b'.repeat(40), head, signal)) + .resolves.toEqual({ code: 'unsupported', message: 'This provider does not name merge bases' }) + const mergeBase = vi.fn(async () => 'c'.repeat(40)) + Object.assign(provider, { mergeBase }) + await expect(ctx.forge.mergeBase(ref(3), 'b'.repeat(40), head, signal)).resolves.toBe('c'.repeat(40)) + expect(mergeBase).toHaveBeenCalledWith(ref(3), 'b'.repeat(40), head, expect.any(AbortSignal)) + }) +}) diff --git a/packages/experimental/liveshare/package.json b/packages/experimental/liveshare/package.json index 6f911b774e..0d91fc3a73 100644 --- a/packages/experimental/liveshare/package.json +++ b/packages/experimental/liveshare/package.json @@ -113,6 +113,7 @@ "@deepseek-ai/dsh-client-ui-reference": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", diff --git a/packages/experimental/liveshare/tests/viewer-page-roster.client.ts b/packages/experimental/liveshare/tests/viewer-page-roster.client.ts index e43e067812..cfffa8f488 100644 --- a/packages/experimental/liveshare/tests/viewer-page-roster.client.ts +++ b/packages/experimental/liveshare/tests/viewer-page-roster.client.ts @@ -3,8 +3,8 @@ * * A served viewer page is the owner's own Web shell with the owner's client plugins; this roster is the * subset the viewer page specs need: the wire plugin, the Gateway, remote access, the Session/Workspace controllers, - * the menu service, presentation plugins, and the Liveshare `./client` face, which mounts the viewer surfaces when the - * carrier names a share. Every row is the package's own `/client` face registered as a module-table + * Session status, the menu service, presentation plugins, and the Liveshare `./client` face, which mounts the viewer + * surfaces when the carrier names a share. Every row is the package's own `/client` face registered as a module-table * factory. It must be imported only after {@link prepareViewerRemoteFaces} answered the generated * `/remote` faces these plugins import. * @@ -31,6 +31,7 @@ import * as uiFileDrag from '@deepseek-ai/dsh-client-ui-file-drag/client' import * as uiLayout from '@deepseek-ai/dsh-client-ui-layout/client' import * as uiRenderer from '@deepseek-ai/dsh-client-ui-renderer/client' import * as uiSession from '@deepseek-ai/dsh-client-ui-session/client' +import * as uiSessionStatus from '@deepseek-ai/dsh-client-ui-session-status/client' import * as uiSettings from '@deepseek-ai/dsh-client-ui-settings/client' import * as uiSidebar from '@deepseek-ai/dsh-client-ui-sidebar/client' import * as uiSidebarRight from '@deepseek-ai/dsh-client-ui-sidebar-right/client' @@ -70,6 +71,7 @@ export const VIEWER_PAGE_ROSTER: readonly ViewerPageRosterRow[] = [ { id: '@deepseek-ai/dsh-client-ui-settings', exports: uiSettings }, { id: '@deepseek-ai/dsh-client-ui-layout', exports: uiLayout }, { id: '@deepseek-ai/dsh-client-ui-session', exports: uiSession }, + { id: '@deepseek-ai/dsh-client-ui-session-status', exports: uiSessionStatus }, { id: '@deepseek-ai/dsh-client-ui-sidebar', exports: uiSidebar }, { id: '@deepseek-ai/dsh-client-ui-conversation', exports: uiConversation }, { id: '@deepseek-ai/dsh-client-ui-chat', exports: uiChat }, diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 36cbd48ee7..010b01d154 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -109,8 +109,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -151,8 +151,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -190,8 +190,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -254,8 +254,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -308,8 +308,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -355,8 +355,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -419,8 +419,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -468,8 +468,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -522,8 +522,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -583,8 +583,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -636,8 +636,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -700,8 +700,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -753,8 +753,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -800,8 +800,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -854,8 +854,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -903,8 +903,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -961,8 +961,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1003,8 +1003,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1044,8 +1044,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1076,8 +1076,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1117,8 +1117,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1168,8 +1168,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1219,8 +1219,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1264,8 +1264,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1298,8 +1298,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1335,8 +1335,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1382,8 +1382,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1445,8 +1445,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1509,8 +1509,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1550,8 +1550,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1597,8 +1597,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1655,8 +1655,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1715,8 +1715,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1760,8 +1760,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1804,8 +1804,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1864,8 +1864,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1924,8 +1924,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -1965,8 +1965,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2006,8 +2006,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2068,8 +2068,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2131,8 +2131,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2174,8 +2174,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2219,8 +2219,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2281,8 +2281,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2347,8 +2347,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2385,8 +2385,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2435,8 +2435,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2506,8 +2506,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2573,8 +2573,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2637,8 +2637,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2663,6 +2663,307 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'deliverables.review.file.actions\', () => ctx.slots.register(\n { name: \'deliverables.review.file.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-deliverables/src/client/file-actions.ts:21', }, + { + key: 'forge.change-request.card.actions', + kind: 'list', + scope: 'session', + summary: 'Icon buttons a plugin adds to a change request card\'s head, before Open in browser.', + doc: 'Icon buttons a plugin adds to a change request card\'s head, before Open in browser.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Owner props of `forge.change-request.card.actions`. */\nexport interface ForgeChangeRequestCardActionsProps {\n /** Binding URL of the change request. */\n readonly url: string\n /** Parsed reference, or null when no provider serves the URL. */\n readonly ref: ChangeRequestRef | null\n /** Head commit of the latest status, or null before one. */\n readonly headSha: string | null\n /** Lifecycle state of the latest status, or null before one. */\n readonly state: ChangeRequestState | null\n}', + ], + ownerPropsReferences: [ + 'ChangeRequestRef', + 'ChangeRequestState', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (experimental-client-ui-forge), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'forge.change-request.card.actions\', () => ctx.slots.register(\n { name: \'forge.change-request.card.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/experimental/client-ui-forge/src/client/slots.ts:79', + }, + { + key: 'forge.changes.file.menu', + kind: 'list', + scope: 'session', + summary: 'Rows a plugin adds to a file\'s menu, below the built-in rows.', + doc: 'Rows a plugin adds to a file\'s menu, below the built-in rows.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Owner props of `forge.changes.file.menu`. */\nexport interface ForgeChangesFileMenuProps {\n /** The view the file belongs to. */\n readonly target: ChangesTarget\n /** The file whose menu opened. */\n readonly file: ForgeLensFile\n /** Close the menu after a row acted. */\n readonly dismiss: () => void\n}', + ], + ownerPropsReferences: [ + 'ChangesTarget', + 'ForgeLensFile', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (experimental-client-ui-forge), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'forge.changes.file.menu\', () => ctx.slots.register(\n { name: \'forge.changes.file.menu\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/experimental/client-ui-forge/src/client/slots.ts:73', + }, + { + key: 'forge.changes.toolbar', + kind: 'list', + scope: 'session', + summary: 'Tools a plugin adds to the changes toolbar, after its flexible space and before the thread list toggle.', + doc: 'Tools a plugin adds to the changes toolbar, after its flexible space and before the thread list toggle.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Owner props of `forge.changes.toolbar`. */\nexport interface ForgeChangesToolbarProps {\n /** The view the toolbar belongs to. */\n readonly target: ChangesTarget\n /** `bar`: a 28px tool in the toolbar row; `menu`: `MenuItemButton` rows of the More menu a narrow toolbar folds entries into. */\n readonly form: \'bar\' | \'menu\'\n /** Close the More menu after a row acted; a no-op in the toolbar row. */\n readonly close: () => void\n}', + ], + ownerPropsReferences: [ + 'ChangesTarget', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (experimental-client-ui-forge), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'forge.changes.toolbar\', () => ctx.slots.register(\n { name: \'forge.changes.toolbar\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/experimental/client-ui-forge/src/client/slots.ts:71', + }, + { + key: 'forge.diff.comment.actions', + kind: 'list', + scope: 'session', + summary: 'Buttons a plugin adds to the line comment form, between Add to input and the code host actions.', + doc: 'Buttons a plugin adds to the line comment form, between Add to input and the code host actions.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Owner props of `forge.diff.comment.actions`. */\nexport interface ForgeCommentActionsProps {\n /** The view the comment form belongs to. */\n readonly target: ChangesTarget\n /** The lines the comment is on. */\n readonly selection: { readonly path: string; readonly side: \'L\' | \'R\'; readonly startLine: number; readonly endLine: number }\n /** Whether the comment has no text, so actions stay disabled. */\n readonly empty: boolean\n /** Whether a send runs, so actions stay disabled. */\n readonly busy: boolean\n /**\n * Hand the comment\'s text to `deliver`. The form shows itself busy until `deliver` settles, closes when it resolves\n * to undefined, and keeps the text with the message it resolves to otherwise.\n * @param deliver - receives the text.\n */\n readonly send: (deliver: (body: string) => Promise) => void\n}', + ], + ownerPropsReferences: [ + 'ChangesTarget', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (experimental-client-ui-forge), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'forge.diff.comment.actions\', () => ctx.slots.register(\n { name: \'forge.diff.comment.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/experimental/client-ui-forge/src/client/slots.ts:77', + }, + { + key: 'forge.diff.line.annotation', + kind: 'keyed', + scope: 'session', + summary: 'The content of one line annotation, keyed by its source; the changes view draws the frame around it.', + doc: 'The content of one line annotation, keyed by its source; the changes view draws the frame around it.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [ + '/** Owner props of `forge.diff.line.annotation`. */\nexport interface ForgeLineAnnotationProps {\n /** The view the annotation shows in. */\n readonly target: ChangesTarget\n /** Repository-relative path of the annotated file. */\n readonly path: string\n /** The annotation its source reported. */\n readonly annotation: ForgeLineAnnotation\n}', + ], + ownerPropsReferences: [ + 'ChangesTarget', + 'ForgeLineAnnotation', + ], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useAccess: (action: RemoteEndpoint) => boolean', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'open: any string the owner dispatches (no compile-time key set), none are taken yet', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (experimental-client-ui-forge), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'forge.diff.line.annotation\', () => ctx.slots.register(\n { name: \'forge.diff.line.annotation\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/experimental/client-ui-forge/src/client/slots.ts:75', + }, { key: 'main', kind: 'keyed', @@ -2685,8 +2986,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2719,8 +3020,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2779,8 +3080,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2820,8 +3121,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2864,8 +3165,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2921,8 +3222,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -2974,8 +3275,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3027,8 +3328,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3080,8 +3381,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3126,8 +3427,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3183,8 +3484,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3217,8 +3518,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3254,8 +3555,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3297,8 +3598,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3350,8 +3651,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3384,8 +3685,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3437,8 +3738,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3483,8 +3784,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3517,8 +3818,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3551,8 +3852,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3604,8 +3905,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3645,8 +3946,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3675,8 +3976,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3728,8 +4029,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3782,8 +4083,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3835,8 +4136,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3892,8 +4193,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3924,8 +4225,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3956,8 +4257,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -3988,8 +4289,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4039,8 +4340,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4101,8 +4402,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4135,8 +4436,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4169,8 +4470,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4204,8 +4505,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4237,8 +4538,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4299,8 +4600,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4352,8 +4653,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4408,8 +4709,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4447,8 +4748,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4507,8 +4808,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4567,8 +4868,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4626,8 +4927,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4686,8 +4987,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4738,8 +5039,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4798,8 +5099,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4858,8 +5159,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4906,8 +5207,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -4968,8 +5269,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5009,8 +5310,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5073,8 +5374,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5135,8 +5436,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5191,8 +5492,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5247,8 +5548,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5281,8 +5582,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5313,8 +5614,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5347,8 +5648,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5381,8 +5682,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5437,8 +5738,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5490,8 +5791,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5528,8 +5829,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5587,8 +5888,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5702,8 +6003,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', @@ -5752,8 +6053,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useContextMenu: UseContextMenu', 'useWorkspaces: SnapshotSelectorHook', 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', 'useSessionRetainInfo: UseSessionRetainInfo', 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 46b1adec53..6c526c8301 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1313,7 +1313,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise', - description: 'Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls it as a stale read does.', + description: 'Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls it as a stale read does; a write the host took is announced with `forge/review-changed`.', parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'write', description: 'the write and the head commit the user saw.' }, { name: 'signal', description: 'cancellation of the write.' }], returns: 'whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the outcome must be checked on the host before the write is tried again.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], @@ -1327,7 +1327,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise', - description: 'Set or clear the signed-in user\'s viewed mark on one file of a change request while its head is still `request.headSha`. A `stale` failure polls a watched change request again as ForgeService.diff does.', + description: 'Set or clear the signed-in user\'s viewed mark on one file of a change request while its head is still `request.headSha`. A `stale` failure polls a watched change request again as ForgeService.diff does; a saved mark is announced with `forge/review-changed`.', parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'the file, its mark, and the head commit the user saw.' }, { name: 'signal', description: 'cancellation of the request.' }], returns: 'undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], @@ -1346,9 +1346,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that does not read commits returns `unavailable`.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], }, + { + signature: 'async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise', + description: 'Find the merge base of two commits of a change request\'s repository: the commit whose files the old side of the change request\'s diff shows when `base` is the snapshot\'s `baseSha` and `head` its `headSha`.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'base', description: 'full object name of the base commit.' }, { name: 'head', description: 'full object name of the head commit.' }, { name: 'signal', description: 'cancellation of the read.' }], + returns: 'the merge base\'s full object name, or why the host did not provide it; `unsupported` when the provider cannot name merge bases.', + throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], + }, { signature: 'async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise', - description: 'Publish one comment or a completed review, then refresh the watched status.', + description: 'Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced with `forge/review-changed`.', parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'explicitly selected commit, comments, and review decision.' }, { name: 'signal', description: 'request cancellation.' }], returns: 'a publication URL or a failure, including an unknown write outcome.', }, @@ -1489,6 +1496,26 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the text.', throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/diff-too-large` when the host or its provider refuses the file over a size limit; `forgePanel/diff-failed` when the host does not provide the file otherwise.'], }, + { + signature: 'registerLens(lens: ForgeLens): () => Promise', + description: 'Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending the registration aborts its running classifications and waits for them.', + parameters: [{ name: 'lens', description: 'the lens.' }], + returns: 'the disposer that unregisters the lens and waits for its classifications to stop.', + throws: ['when another registration holds `lens.id`.'], + }, + { + signature: '@Remote({ mode: \'stream\' }) async *extensions(signal: AbortSignal): AsyncIterable', + description: 'Stream the facts every changes view reads about the panel\'s extensions: the current facts first, then the facts after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops.', + parameters: [{ name: 'signal', description: 'ends the stream.' }], + returns: 'the registered lenses and the annotation limit, in publication order.', + }, + { + signature: '@Remote({ mode: \'stream\' }) async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable', + description: 'Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until `maxCachedLensBytes` evicts them. Local changes are read with the Session\'s permissions; a change request\'s files are those `changeRequestDiff` reads.', + parameters: [{ name: 'session', description: 'Session whose checkout or binding the view shows.' }, { name: 'request', description: 'the view\'s source, the version of the files it shows, and the lens.' }, { name: 'signal', description: 'ends the classification.' }], + returns: 'progress frames, then one result frame.', + throws: ['`forgePanel/lens-missing` while no lens holds the identity or once its registration ends; `forgePanel/lens-stale` before a change request\'s status was read, when the files differ from `request.version`, and when local files changed while the lens ran; `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files.'], + }, { signature: '@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise', description: 'Read the signed-in user\'s viewed marks on the files of a change request of a Session, which the host keeps for the whole change request.', @@ -5273,6 +5300,14 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.', parameters: [{ name: 'forge', description: 'family whose provider changed.' }], }, + { + name: 'forge/review-changed', + mode: 'parallel', + signature: '\'forge/review-changed\'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise', + summary: 'Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark.', + description: 'Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. Listener failures are logged without preventing other listeners from running.', + parameters: [{ name: 'ref', description: 'change request the change went to.' }, { name: 'change', description: 'what changed and the head commit it was made against.' }], + }, { name: 'fs/delete-intent', mode: 'waterfall', @@ -6833,6 +6868,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeDiffStatus', declaration: 'export type ForgeDiffStatus = \'added\' | \'deleted\' | \'modified\' | \'renamed\';', }, + { + name: 'ForgeExtensionState', + declaration: 'export interface ForgeExtensionState {\n readonly lenses: readonly ForgeRegisteredLens[];\n readonly maxAnnotationsPerFile: number;\n}', + }, { name: 'ForgeFailure', declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unsupported\' | \'unavailable\';\n readonly message: string;\n}', @@ -6841,10 +6880,50 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeFileLayer', declaration: 'export type ForgeFileLayer = \'interface\' | \'implementation\' | \'test\';', }, + { + name: 'ForgeLens', + declaration: 'export interface ForgeLens {\n readonly id: ForgeLensId;\n readonly version: string;\n classify(input: ForgeLensInput, signal: AbortSignal): Promise;\n}', + }, + { + name: 'ForgeLensFile', + declaration: 'export type ForgeLensFile = Pick;', + }, + { + name: 'ForgeLensFrame', + declaration: 'export type ForgeLensFrame = {\n readonly kind: \'progress\';\n readonly done: number;\n readonly total: number;\n} | {\n readonly kind: \'result\';\n readonly files: Readonly>;\n};', + }, + { + name: 'ForgeLensId', + declaration: 'export type ForgeLensId = Branded<\'ForgeLensId\'>;', + }, + { + name: 'ForgeLensInput', + declaration: 'export interface ForgeLensInput {\n readonly source: ForgeLensSource;\n readonly files: readonly ForgeLensFile[];\n text(side: \'old\' | \'new\', path: string, signal: AbortSignal): Promise;\n progress(done: number, total: number): void;\n}', + }, + { + name: 'ForgeLensKeep', + declaration: 'export interface ForgeLensKeep {\n readonly ranges?: {\n readonly old: readonly ForgeLineRange[];\n readonly new: readonly ForgeLineRange[];\n };\n}', + }, + { + name: 'ForgeLensRequest', + declaration: 'export interface ForgeLensRequest {\n readonly source: {\n readonly kind: \'local\';\n readonly scope: ForgeLocalScope;\n } | {\n readonly kind: \'change\';\n readonly url: string;\n readonly commits: ForgeCommitRange | null;\n };\n readonly version: string;\n readonly lens: string;\n}', + }, + { + name: 'ForgeLensResult', + declaration: 'export interface ForgeLensResult {\n readonly files: Readonly>;\n}', + }, + { + name: 'ForgeLensSource', + declaration: 'export type ForgeLensSource = {\n readonly kind: \'local\';\n readonly scope: ForgeLocalScope;\n} | {\n readonly kind: \'change\';\n readonly ref: ChangeRequestRef;\n readonly headSha: string;\n readonly commits: ForgeCommitRange | null;\n};', + }, { name: 'ForgeLineComment', declaration: 'export interface ForgeLineComment {\n readonly path: string;\n readonly side: \'L\' | \'R\';\n readonly startLine: number;\n readonly endLine: number;\n readonly body: string;\n}', }, + { + name: 'ForgeLineRange', + declaration: 'export interface ForgeLineRange {\n readonly start: number;\n readonly end: number;\n}', + }, { name: 'ForgeLocalChanges', declaration: 'export interface ForgeLocalChanges {\n readonly base: string;\n readonly files: readonly ForgeChangedFile[];\n}', @@ -6867,7 +6946,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgePanelChangeRequest', - declaration: 'export interface ForgePanelChangeRequest extends SessionChangeRequest {\n readonly snapshot: ChangeRequestSnapshot | null;\n}', + declaration: 'export interface ForgePanelChangeRequest extends SessionChangeRequest {\n readonly snapshot: ChangeRequestSnapshot | null;\n readonly reviewRevision: number;\n}', }, { name: 'ForgePanelState', @@ -6889,6 +6968,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeReadiness', declaration: 'export interface ForgeReadiness {\n readonly state: \'ready\' | \'unauthenticated\' | \'unavailable\';\n readonly message: string | null;\n}', }, + { + name: 'ForgeRegisteredLens', + declaration: 'export interface ForgeRegisteredLens {\n readonly id: string;\n readonly version: string;\n}', + }, { name: 'ForgeRepository', declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', @@ -6897,6 +6980,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRerunRequest', declaration: 'export interface ForgeRerunRequest {\n readonly headSha: string;\n}', }, + { + name: 'ForgeReviewChange', + declaration: 'export type ForgeReviewChange = {\n readonly kind: \'write\';\n readonly write: ForgeReviewWrite[\'kind\'];\n readonly headSha: string;\n} | {\n readonly kind: \'submit\';\n readonly headSha: string;\n} | {\n readonly kind: \'viewed\';\n readonly path: string;\n readonly viewed: boolean;\n readonly headSha: string;\n};', + }, { name: 'ForgeReviewComment', declaration: 'export interface ForgeReviewComment {\n readonly id: ForgeCommentId;\n readonly author: ForgeCommentAuthor | null;\n readonly body: string;\n readonly createdAt: string;\n readonly pending: boolean;\n readonly url: string | null;\n readonly viewerCanEdit: boolean;\n readonly viewerCanDelete: boolean;\n}', diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index f50ebd3356..f393d17741 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -98,6 +98,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-schedule` | no | Host task management page and Session reminder catalog | | `@deepseek-ai/dsh-client-ui-secret-mask` | no | Web display masking for recognized credentials in sent user text | | `@deepseek-ai/dsh-client-ui-session` | no | Session Controller adapter for React and session-scoped slots | +| `@deepseek-ai/dsh-client-ui-session-status` | no | Client Session status table: running state, the effective pending interaction, and completion reminders | | `@deepseek-ai/dsh-client-ui-settings` | no | Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract | | `@deepseek-ai/dsh-client-ui-settings-account` | yes | Manage DeepSeek login and open Platform billing pages | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | no | Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace | diff --git a/packages/test-support/client-runtime/package.json b/packages/test-support/client-runtime/package.json index 29f310d16c..d2fb71a67b 100644 --- a/packages/test-support/client-runtime/package.json +++ b/packages/test-support/client-runtime/package.json @@ -44,6 +44,7 @@ "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-web": "workspace:*", @@ -76,6 +77,7 @@ "@deepseek-ai/dsh-client-ui-layout": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", diff --git a/packages/test-support/client-runtime/src/index.ts b/packages/test-support/client-runtime/src/index.ts index b6d8f94afc..7f6aafb2d2 100644 --- a/packages/test-support/client-runtime/src/index.ts +++ b/packages/test-support/client-runtime/src/index.ts @@ -1,6 +1,7 @@ /** * jsdom slot test runtime: a real small runtime — Cordis `Context`, the - * renderer-owned `SlotRegistry`, the `ui-session` adapter, and the UI renderer — assembled around + * renderer-owned `SlotRegistry`, the `ui-session` adapter, the + * `ui-session-status` table, and the UI renderer — assembled around * test-owned session/workspace doubles and a fail-loud file-upload stub, so feature specs exercise * declaration, registration, scope, store, inject, rendering, updates, and * disposal without hand-building the machinery per suite. @@ -28,6 +29,9 @@ import { createSlotRenderer as createRenderer } from '@deepseek-ai/dsh-client-ui import { apply as applyUiSession, inject as uiSessionInject, } from '@deepseek-ai/dsh-client-ui-session/client' +import { + apply as applySessionStatus, inject as sessionStatusInject, +} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -293,6 +297,7 @@ export class SlotTestRuntime { const runtime = new SlotTestRuntime(ctx, ctx.get('slots') as SlotRegistry) await ctx.plugin(allowAllAccessPlugin).await() await ctx.plugin({ inject: [...uiSessionInject], apply: applyUiSession }).await() + await ctx.plugin({ inject: [...sessionStatusInject], apply: applySessionStatus }).await() return runtime } diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index bb327af364..496fc29e7c 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -17,7 +17,7 @@ import { createScope, type SessionReference } from '@deepseek-ai/dsh-api-session import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { - PropsRenderSlots, SessionStandardProps, SlotRendererHost, + GlobalStandardProps, PropsRenderSlots, SessionStandardProps, SlotRendererHost, } from '@deepseek-ai/dsh-client-ui-slots' import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -790,6 +790,25 @@ describe('fixture session face', () => { await runtime.dispose() }) + it('publishes running status through the real ui-session-status root hook', async () => { + const reference = createSnapshotStore(undefined) + const runtime = await runtimeWithFrame(reference) + runtime.slots.register({ name: 'trt.chat' }, (props: SessionStandardProps & GlobalStandardProps) => ( + running:{props.useSessionStatus(status => String(status.get(props.sessionId)?.running))} + )) + const view = runtime.renderRoot() + await runtime.sessions.add({ id: 's1' }) + using bound = runtime.sessions.retain('s1' as SessionId) + await bound.ready + act(() => { reference.set(bound) }) + expect(view.container.textContent).toContain('running:false') + + act(() => { runtime.remote.emit('api-session/status', ['s1', true]) }) + expect(view.container.textContent).toContain('running:true') + expect(runtime.ctx.uiSession.sessionStatus.getSnapshot().get('s1' as SessionId)?.running).toBe(true) + await runtime.dispose() + }) + it('copies projections into a later Session generation', async () => { const runtime = await runtimeWithFrame() const id = await runtime.sessions.add({ id: 'seeded-projection' }) diff --git a/packages/test-support/client-runtime/tsconfig.json b/packages/test-support/client-runtime/tsconfig.json index a4f9971fe0..47e0ae67cc 100644 --- a/packages/test-support/client-runtime/tsconfig.json +++ b/packages/test-support/client-runtime/tsconfig.json @@ -27,6 +27,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../../client/ui-session-status" + }, { "path": "../../api/workspace-controller/tsconfig.client.json" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c6fdd161be..d4e254a713 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3079,6 +3079,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../../client/ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../../client/ui-session-status '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../../client/ui-settings @@ -4075,6 +4078,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../ui-settings @@ -4307,6 +4313,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../ui-settings @@ -5665,9 +5674,6 @@ importers: '@deepseek-ai/dsh-api-remote-access': specifier: workspace:* version: link:../../api/remote-access - '@deepseek-ai/dsh-api-remotes': - specifier: workspace:* - version: link:../../api/remotes '@deepseek-ai/dsh-api-session-controller': specifier: workspace:* version: link:../../api/session-controller @@ -5683,9 +5689,6 @@ importers: '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:* version: link:../ui-slots - '@deepseek-ai/dsh-remote-mock': - specifier: workspace:* - version: link:../../test-support/remote-mock '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session @@ -5696,6 +5699,39 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-session-status: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-api-session-controller': + specifier: workspace:* + version: link:../../api/session-controller + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-session': + specifier: workspace:* + version: link:../ui-session + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-remote-mock': + specifier: workspace:* + version: link:../../test-support/remote-mock + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + packages/client/ui-settings: dependencies: '@deepseek-ai/schemastery': @@ -6780,6 +6816,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-sidebar-right': specifier: workspace:* version: link:../ui-sidebar-right @@ -7025,6 +7064,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:* version: link:../ui-slots @@ -7169,6 +7211,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:* version: link:../ui-slots @@ -7247,6 +7292,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../ui-session-status '@deepseek-ai/dsh-client-ui-sidebar': specifier: workspace:* version: link:../ui-sidebar @@ -9307,6 +9355,9 @@ importers: '@deepseek-ai/dsh-api-session-controller': specifier: workspace:* version: link:../../api/session-controller + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../../client/locale @@ -10798,6 +10849,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../../client/ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../../client/ui-session-status '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../../client/ui-settings @@ -17584,6 +17638,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../../client/ui-session + '@deepseek-ai/dsh-client-ui-session-status': + specifier: workspace:* + version: link:../../client/ui-session-status '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:* version: link:../../client/ui-settings diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 88fc939459..12950471bb 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -222,6 +222,7 @@ export const SERVICE_WALK_EXEMPTIONS: Record = { resources: 'client-side resource model (protocol providers, pins, live sources) — packages/client/resources/README.md owns the API', sidebarRight: 'client-side right-Sidebar navigation face — packages/client/ui-sidebar-right/README.md owns the API', sidebarRightTabs: 'client-side right-Sidebar tab-type registry — packages/client/ui-sidebar-right/README.md owns the API', + forgeChanges: 'client-side changes view face for other plugins — docs/subsystems/forge.md#extension-api owns the API', documentPreviews: 'client-side document renderer registry — docs/subsystems/sidebar-right.md owns the API', } @@ -439,6 +440,11 @@ export const LINK_MAP: Readonly> = { ForgeReviewersRequest: 'forge.md', ForgeViewedFiles: 'forge.md', ForgeViewedRequest: 'forge.md', + ForgeReviewChange: 'forge.md', + ForgeLens: 'forge.md', + ForgeLensRequest: 'forge.md', + ForgeLensFrame: 'forge.md', + ForgeExtensionState: 'forge.md', ForgeCommitRange: 'forge.md', ForgeFileLayer: 'forge.md', ForgeChangeRequestStatesFrame: 'forge.md', diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 5285d3a2e6..aaacccf9ff 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -99,7 +99,7 @@ const PEER_REQUIRED_HOST_EXPORTS = { '@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'], '@deepseek-ai/dsh-session-persistence': ['SessionPersistenceNotFoundError'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. - '@deepseek-ai/dsh-timeout': ['deadline'], + '@deepseek-ai/dsh-timeout': ['deadline', 'timeoutOf'], } as const satisfies HostDependencyExports /** Exact import specifier to reviewed runtime exports. */ diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 43725880bf..2803769eeb 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2957,6 +2957,41 @@ "doc": "docs/subsystems/forge.md", "symbol": "ForgeViewedRequest", "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewChange", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeLens", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeLensInput", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeLensResult", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeLensKeep", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeLineAnnotation", + "source": "packages/experimental/client-ui-forge/src/client/changes-service.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeAnnotationSource", + "source": "packages/experimental/client-ui-forge/src/client/changes-service.ts" } ] } diff --git a/scripts/verify-package-dependencies.spec.ts b/scripts/verify-package-dependencies.spec.ts index 4bb04e21bb..a82f5c90b2 100644 --- a/scripts/verify-package-dependencies.spec.ts +++ b/scripts/verify-package-dependencies.spec.ts @@ -254,7 +254,7 @@ describe('package dependency scope', () => { expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-fs']).toEqual(['FsError']) expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-session']) .toEqual(['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf']) - expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-timeout']).toEqual(['deadline']) + expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-timeout']).toEqual(['deadline', 'timeoutOf']) }) it('discovers the Client directory, dsh.client declarations, and configured Host packages', () => { diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 6424868d38..e4805fdca1 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -136,6 +136,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/store': { kind: 'none', reason: 'Browser-side state primitives; register nothing model-facing.' }, 'packages/client/ui-renderer': { kind: 'none', reason: 'Browser-side render assembly; registers nothing model-facing.' }, 'packages/client/ui-session': { kind: 'none', reason: 'Browser-side Session adapter; registers nothing model-facing.' }, + 'packages/client/ui-session-status': { kind: 'none', reason: 'Browser-side Session status table; registers nothing model-facing.' }, 'packages/client/connection': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/file-upload': { kind: 'none', reason: 'Browser-side request-body transport; registers nothing model-facing.' }, 'packages/api/remotes': { kind: 'none', reason: 'The Remote BFF selects business methods and forwarded events; selected services own any model-visible effect.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 1ccb5adc32..09d8c65a71 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -292,6 +292,8 @@ "@deepseek-ai/dsh-client-ui-renderer/client": ["./packages/client/ui-renderer/src/client"], "@deepseek-ai/dsh-client-ui-session": ["./packages/client/ui-session/src"], "@deepseek-ai/dsh-client-ui-session/client": ["./packages/client/ui-session/src/client"], + "@deepseek-ai/dsh-client-ui-session-status": ["./packages/client/ui-session-status/src"], + "@deepseek-ai/dsh-client-ui-session-status/client": ["./packages/client/ui-session-status/src/client"], "@deepseek-ai/dsh-client-connection": ["./packages/client/connection/src"], "@deepseek-ai/dsh-client-file-upload": ["./packages/client/file-upload/src"], "@deepseek-ai/dsh-client-file-upload/client": ["./packages/client/file-upload/src/client/index.ts"], diff --git a/tsconfig.client.json b/tsconfig.client.json index f15b78502b..93710b9a2c 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -167,6 +167,7 @@ { "path": "./packages/client/locale/tsconfig.client.json" }, { "path": "./packages/client/ui-renderer" }, { "path": "./packages/client/ui-session" }, + { "path": "./packages/client/ui-session-status" }, { "path": "./packages/client/resources" }, { "path": "./packages/api/workspace-files/tsconfig.client.json" }, { "path": "./packages/client/web" },