feat(tasks): 第二轮真机反馈——聚合条动作行、模式 chip、弹窗用量/耗时、原生侧栏转录、动效

用户在自己跑的 3080 实例上测完报回六条,逐条修:

1. 「已完成的聚合卡下方空荡荡」= 上一轮把计数收进徽标后那条只剩一个
   chevron(我的取舍造成)。小条改为动作行:组图标 + 「展开」(新词条
   tasksFoldExpandShort × 20 词典)+ 出错尾注 + 展开箭头。
2. 「展开后的子代理点不回去」= 真缺陷:expandedGroups 压过了 foldedIds,
   展开组内卡片的 chevron 失效。改成手动折叠优先(手动 → 页级规则 →
   组展开),补模型 + 组件两层判别性用例。
3. 「一次性一直显示」→ 模式词搬进徽标行成 chip(用户口径)。智能体卡不再
   有 mono 元信息行,卡片高度预算拆成 GRAPH_AGENT_NODE_H / GRAPH_NODE_H
   (只有 workflow run 卡保留元信息行),rowStrideFor(nodes) 按模型里有没有
   run 选行距。
4. 动效:接入 @formkit/auto-animate(用户选定,~3KB、无依赖无安装脚本)+
   useAutoAnimateRef 包装(WAAPI 守卫 → jsdom 空转、尊重 reduced-motion),
   挂到画布卡片层 / 树视图 / 任务抽屉;详情卡另加 140ms 入场关键帧。核心
   bundle +56KB(未压缩 CJS)。
5. 弹窗多两项:Token 用量(宿主 tokenUsage 四桶求和,悬停给明细)+ 耗时
   (宿主 subagentTiming,按 3s 轮询刷新)。SidebarProjectionSnapshot 镜像
   补两个键、模型新增 metrics 入参;**按存在性渲染**,没有测量就不显示这一
   行(0 是投影初始态,与「没工作过」不可区分)。
6. 「查看转录」改为在原生右侧栏打开:宿主 ui-subagent 的 subagentchat tab
   类型(宿主自己的子代理列表就是点行=主窗、点 chevron=侧栏)。插件照抄其
   地址公式并调 openResource(..., { kind, preferNewPane: true }),三级降级回
   主窗;页脚变「主按钮 + caret 菜单(在主窗口中打开)」。

测试 2238 passed / 17 skipped(191 文件)、tsc 0 错误、eslint 0 错误、构建
通过;新构建已装进 sidebar-test profile,:3080 上挂载正常、0 pageerror。
动效观感与真实数据的两行数值未在真机逐帧核验(右栏在无头上下文里被
transform 移出视口,合成点击不稳)——已如实记进设计文档的第二轮偏差段。
This commit is contained in:
Menghuan1918 committed 2026-10-11 23:15:40 +08:00
1 parent ba9dc57f56
commit 9ccc147e00
44 files changed
+1160 -181

No files matched your search

+11
View File
@@ -4,6 +4,17 @@
### Unreleased
- 🃏 **任务卡小条只说原生状态**(首轮):运行中不再是「● 运行中 正在读取文件」这样把状态念两遍,而是**活动行取代状态词**——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build` 等措辞来自宿主 `chat` 命名空间,与主对话逐字一致;已结算小条同理(只留 `已读取文件、执行了命令`)。**`空闲` 与 `出错` 保留状态词**(不被任何活动措辞蕴含),完全没有活动数据时回退状态词,小条永不空着。状态点、执行扫光与折叠 chevron、22px 高度都不变。
- 🧩 **主代理卡片接上自己的实时数据**:`subagents.live` 路由一直把拓扑根的 fold 结果放在 `live[rootSessionId]`,而模型从未把它挂到根节点上——于是主代理卡片的状态文本**恒为 thinking 兜底**,与主会话在做什么无关。现在根卡显示真实状态,树模式根行的实时行也从恒定的「思考中…」变成真实活动。
- 🔎 **节点详情浮窗的活动行移到标题下方**:原来在键值格里(`最近活动 | 值`),右对齐的值列在 280px 被省略、标签又占掉三分之一宽;现在是标题下的一行 10px 小字(宿主措辞)+ 夹两行的实时文本尾行,**没有活动数据就不渲染**(此前每个浮窗都会显示「最近活动:正在分析请求」,已结算节点也一样)。词条 `tasksNodeActivity` 随这一行从 20 份词典删除。
- 🗂 **聚合卡改为「按组展开」**:点一个聚合卡只展开**该组**(`fold:<parentId>` / `fold:<parentId>:idle`),兄弟组、页级折叠与手工折叠都不受影响;控制条按钮仍是页级展开/折叠,且**收起时清掉按组展开**。树里的聚合行同一语义。**展开后卡片自己的 chevron 仍然有效**(手动折叠是该节点的最新意图,优先级高于组展开),聚合卡随之重新出现并能再次展开——否则「展开后点不回去了」。
- 🔢 **聚合卡计数只说一次、小条变动作行**:待命组徽标此前印的是**字面量字母 N**(`tasksFoldIdleGroup` 在 20 份词典里都没有 `{count}` 插值),现在插值出真实计数;小条不再是重复计数的空条,而是「组图标 + 展开 + 出错尾注 + 展开箭头」,完整 tally 仍是卡片的 `aria-label` 与 tooltip。
- 🏷 **模式词搬进徽标行**:子代理卡片此前每个都有一行 mono 元信息写着「一次性」——同一句话在每张卡上重复一次、还占一行高。现在模式(一次性 / 可持续)是**徽标旁的 chip**,智能体卡因此不再有元信息行、卡片高度预算同步收窄(只有工作流 run 卡还保留那行状态 / 成员元信息,行距按模型里有没有 run 取)。
- 📊 **节点详情多两项事实**:新增 **Token 用量**(宿主 `tokenUsage` projection 的四个互斥桶求和,悬停给出未缓存输入 / 缓存读取 / 缓存写入 / 输出明细)与 **耗时**(宿主 `subagentTiming`:已结算回合 + 正在跑的那一轮,按页面轮询刷新)。两项都按宿主投影的**存在性**渲染——没有测量就不显示这一行,绝不打印一个说不清的 0;`SidebarProjectionSnapshot.values` 的镜像类型同步补上这两个键。
- 🪟 **「查看转录」改为在原生右侧栏打开**(这是宿主自带能力):`dsh-resource://subagentchat/session/<childId>?parent=&mode=` + `ctx.sidebarRight.openResource(..., { kind: 'subagentchat', preferNewPane: true })`——与宿主自己的子代理列表(点行 = 主窗、点 chevron = 侧栏)同一套 tab 类型,主列保持不动;右侧新增小下拉按钮,菜单里可**在主窗中打开**(走原有的 `uiWorkspace.openSession` + 页签重挂)。宿主没有该 tab 类型 / 没有右栏 / 没有挂载会话时逐项降级回主窗并保持单按钮。
- ✨ **动效**:接入 `@formkit/auto-animate`(`useAutoAnimateRef`,包一层 WAAPI 守卫,jsdom 与非 WAAPI 环境自动空转、并尊重 `prefers-reduced-motion`)——画布卡片、树模式行、后台任务行在折叠 / 新增 / 结算时滑入滑出而不是硬闪;详情卡另加入场关键帧(140ms,reduced-motion 下关闭)。
- 🧪 测试:新增 `tests/session-metrics.spec.ts`(5 条:四桶求和、空投影、运行中耗时按渲染时钟、0 不算工作、时钟回拨不显示负数)与 `tests/activity-icons.spec.ts`(3 条:13 个类别全覆盖、读 / 命令 / 搜索 / 网页互不同型、`undefined` 走思考图标);`tests/tasks-page.spec.tsx` 补 6 条(原生状态取代状态词、无数据回退、根卡真实状态、浮窗活动块位置、一次只开一组 + 判据极性的判别性用例、展开后成员仍可手工折回、Token / 耗时两行、侧栏打开地址 + 下拉在主窗打开 + 无宿主能力时单按钮、模式 chip 在徽标行);`tests/tasks-graph-layout.spec.ts` 的高度 / 行距断言跟随新的卡片预算。[设计文档](docs/plans/2026-10-11-tasks-status-and-group-fold.md)。
- 🃏 **任务卡小条只说原生状态**:运行中小条不再是「● 运行中 正在读取文件」这样把状态念两遍,而是**活动行取代状态词**——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build` 等措辞全部来自宿主 `chat` 命名空间,与主对话逐字一致;已结算小条同理(只留 `已读取文件、执行了命令`,不重复「已完成」)。**`空闲` 与 `出错` 保留状态词**(「待命」「失败」不被任何活动措辞蕴含),**完全没有活动数据时回退状态词**,小条永不空着。状态点、执行扫光与折叠 chevron 不变,小条仍是 22px——画布几何与卡片高度预算零改动。
- 🧩 **主代理卡片接上自己的实时数据**:`subagents.live` 路由一直把拓扑根的 fold 结果放在 `live[rootSessionId]`,而模型从未把它挂到根节点上——于是**主代理卡片的状态文本恒为 thinking 兜底**(「正在分析请求」),与主会话在做什么无关。现在根卡显示真实状态,树模式根行的实时行也从恒定的「思考中…」变成真实活动。
- 🔎 **节点详情浮窗的活动行移到标题下方**:那行原来在键值格里(`最近活动 | 值`),右对齐的值列在 280px 里被省略,标签又占掉三分之一宽;现在它是标题下的一行 10px 小字(宿主措辞),实时文本尾行紧接其下并夹到两行。**没有活动数据就不渲染这一块**——此前每个节点浮窗都会显示「最近活动:正在分析请求」,已结算节点也不例外。词条 `tasksNodeActivity` 随这一行从 20 份词典删除。
+2 -2
View File
@@ -224,9 +224,9 @@ dsh registry enable dsh-external/dsh-better-sidebar
> 📦 **正式版**(npm `latest`):支持线**不变**——仍仅支持 **DSH 0.1.7-rc.1+**(peer 下限 `^0.1.7-rc.1`,CI 钉 `@deepseek-ai/dsh@0.1.7-rc.1`),0.21.1 的用户直接升级即可。**DSH 0.1.6-alpha.2 及更早请继续固定 v0.19.1**。
- 🧩 **任务管理页重做成工作流图**(主显示模式):会话树渲染为分层节点 + 贝塞尔连线——拖拽平移、滚轮缩放到光标、内容包围盒居中适配、右下角控制条(图/树切换 + 折叠开关 + 缩放 + 适配);**经典缩进树保留**(键盘可导航),两种模式共享同一个视图模型,折叠状态与团队富化不会视觉漂移。
- 🃏 **双段式节点卡**:上段是类型徽章(主代理 / 子代理 / 成员 / 工作流 / 已完成聚合)+ 相位徽标 + 名称 + 元信息;下段小条是状态点 + **原生状态文本**(**主 Agent 同款合并活动行**:并发工具按类别归并 + 计数 + 在跑那条的细节,措辞取宿主 `chat` 词条——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build`),运行中与已结算都由它**取代状态词**(不再念两遍「运行中 / 已完成」),`空闲` 与 `出错` 保留状态词、没有活动数据时回退状态词;已完成节点在小条上有折叠按钮;运行中小条从左到右**完整扫过**(`prefers-reduced-motion` 下关闭)。8px 圆角、层级只用上段极淡底色表达、当前会话加粗 accent 描边。
- 🃏 **双段式节点卡**:上段是类型徽章(主代理 / 子代理 / 成员 / 工作流 / 已完成聚合)+ 相位徽标 + **模式 chip**(一次性 / 可持续,与徽标同一行)+ 名称(只有工作流 run 另带一行状态 / 成员元信息);下段小条是状态点 + **原生状态文本**(**主 Agent 同款合并活动行**:并发工具按类别归并 + 计数 + 在跑那条的细节,措辞取宿主 `chat` 词条——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build`),运行中与已结算都由它**取代状态词**(不再念两遍「运行中 / 已完成」),`空闲` 与 `出错` 保留状态词、没有活动数据时回退状态词;已完成节点在小条上有折叠按钮;运行中小条从左到右**完整扫过**(`prefers-reduced-motion` 下关闭)。8px 圆角、层级只用上段极淡底色表达、当前会话加粗 accent 描边。
- 🔀 **工作流 run 入图**:从 `tool-workflow/*` 事件折叠出 run(与官方面板同一批),run 挂在发起代理下、成员 agent 重挂到 run 下并按相位分框、同色相位徽标;catalog 里没有的成员用 run 数据合成占位节点,跑完的 run 仍能看到成员。
- 🗂 **折叠分两组、各自说清是什么**:`✓ N 已完成`(含出错,失败单独报 `出错 N`)与 `N 个待命`(跑完一轮、随时可被叫起来的 teammate)是**两行**;手动折叠按钮永远有效,自动聚合只在待命成员 ≥3 时收空闲成员;聚合卡名字行写「前两个名字 + `+N`」、徽标写**真实计数**(`✓ N 已完成` / `N 个待命`),小条只留出错尾注与展开箭头;**点聚合只展开该组**(兄弟组与页级折叠都不动),页级展开/折叠仍在右下控制条,且那里收起时会把按组展开一并清掉。
- 🗂 **折叠分两组、各自说清是什么**:`✓ N 已完成`(含出错,失败单独报 `出错 N`)与 `N 个待命`(跑完一轮、随时可被叫起来的 teammate)是**两行**;手动折叠按钮永远有效,自动聚合只在待命成员 ≥3 时收空闲成员;聚合卡名字行写「前两个名字 + `+N`」、徽标写**真实计数**(`✓ N 已完成` / `N 个待命`),小条是动作行(图标 + 「展开」+ 出错尾注 + 展开箭头);**点聚合只展开该组**(兄弟组与页级折叠都不动),页级展开/折叠仍在右下控制条,且那里收起时会把按组展开一并清掉。
- 🪟 **两个常驻浮动窗**(抽出可复用的 `FloatingWindow`):后台任务输出与共享任务详情/编辑——可拖拽、可四边拉伸、内容区自滚动,只靠关闭按钮或 Escape 结束(外部点击 / 失焦 / 锚点离屏都不关);任务窗把余量交给描述区,拉大是给内容更多空间而不是留白,动作行固定在底部。
- 👥 **Agent Teams 任务板(实验层)**:成员富化到对应节点、常驻任务条列出成员与共享任务;状态机跟随宿主(待办 → 认领 → 进行中 → 完成 → 重开)+ 改派 / 编辑 / 两击删除,CAS 过期修订单独提示;成员活动由 `subagents.live` 的 running 叠加。
- 🔄 **后台任务改读宿主客户端 `ctx.jobs`**(推送 roster + 非消费输出流 + kill):删掉自建的 `jobs.list` / `jobs.output` / `jobs.kill` 三条路由与事件回放镜像,彻底不碰模型 `job_output` 游标;输出在常驻浮动窗里流式显示并尾随,代理数 ≥8 时抽屉自动折叠。
+2 -2
View File
@@ -233,9 +233,9 @@ WeChat / QQ group QR codes will live here. After uploading the QR images (drag t
> 📦 **Stable release** (npm `latest`): the support line is **unchanged** — DSH **0.1.7-rc.1+** only (peer floor `^0.1.7-rc.1`, CI pins `@deepseek-ai/dsh@0.1.7-rc.1`), so v0.21.1 users can upgrade straight away. **Hosts on DSH 0.1.6-alpha.2 or earlier keep pinning v0.19.1.**
- 🧩 **The Tasks page is now a workflow graph** (the primary view): the session tree renders as layered nodes joined by bezier edges — drag to pan, wheel-zoom to the cursor, fit to the content box, a control cluster bottom-right (graph/tree toggle + fold switch + zoom + fit); the **classic indented tree is kept** (keyboard-navigable) and both modes share one view model, so fold state and team enrichment never drift apart.
- 🃏 **Two-segment node cards**: the top segment is the kind badge (main agent / subagent / teammate / workflow / completed aggregate) + phase badge + name + meta; the bottom bar is the state dot + the **native status text** (**the same merged activity line the main agent shows**: concurrent tools grouped and counted, with the running call's detail — wording from the host's `chat` namespace, i.e. analyzing the request / reading a file · main.ts / preparing to read a file / running a command · npm run build). That line **takes the state word's place** for running and settled nodes (the state is no longer printed twice), while `idle` and `error` keep their word and a node with no activity data falls back to it; finished nodes carry a fold button on the bar; a running bar is swept across its **whole** width (disabled under `prefers-reduced-motion`). 8px-rounded, hierarchy carried by a faint top-segment tint only, the session you are on wearing a heavier accent border.
- 🃏 **Two-segment node cards**: the top segment is the kind badge (main agent / subagent / teammate / workflow / completed aggregate) + phase badge + a **mode chip** (one-shot / continuable, sharing the badge's row) + name — only a workflow run keeps a mono meta line (status / member tally); the bottom bar is the state dot + the **native status text** (**the same merged activity line the main agent shows**: concurrent tools grouped and counted, with the running call's detail — wording from the host's `chat` namespace, i.e. analyzing the request / reading a file · main.ts / preparing to read a file / running a command · npm run build). That line **takes the state word's place** for running and settled nodes (the state is no longer printed twice), while `idle` and `error` keep their word and a node with no activity data falls back to it; finished nodes carry a fold button on the bar; a running bar is swept across its **whole** width (disabled under `prefers-reduced-motion`). 8px-rounded, hierarchy carried by a faint top-segment tint only, the session you are on wearing a heavier accent border.
- 🔀 **Workflow runs enter the graph**: runs folded from `tool-workflow/*` events (the same events the official panel folds) hang under their origin agent, with member agents re-parented below and boxed per phase with matching badges; members with no catalog row are synthesized from the run's own data, so a finished run still shows who took part.
- 🗂 **Folding split into two groups that say what they hold**: `✓ N completed` (including failures, called out as `N failed`) and `N idle` (teammates that finished a turn and can be called back at any moment) are **two separate rows**; the manual fold button always works, the automatic rule only sweeps idle members once there are 3 or more, and an aggregate's name line reads "first two names + `+N`" while its badge carries the **real count** (`✓ N completed` / `N idle`) and the bar keeps only the failure tail plus the expand chevron. **Clicking an aggregate reveals THAT group only** — sibling groups and the page-level rule stay put; the page-level expand/collapse lives in the bottom-right cluster, and collapsing there drops the per-group openings too.
- 🗂 **Folding split into two groups that say what they hold**: `✓ N completed` (including failures, called out as `N failed`) and `N idle` (teammates that finished a turn and can be called back at any moment) are **two separate rows**; the manual fold button always works, the automatic rule only sweeps idle members once there are 3 or more, and an aggregate's name line reads "first two names + `+N`" while its badge carries the **real count** (`✓ N completed` / `N idle`) and its bar is the action row (group glyph + `Expand` + the failure tail + the expand chevron). **Clicking an aggregate reveals THAT group only** — sibling groups and the page-level rule stay put; the page-level expand/collapse lives in the bottom-right cluster, and collapsing there drops the per-group openings too.
- 🪟 **Two persistent floating windows** (extracted into a reusable `FloatingWindow`): background-job output and the shared task's detail/edit surface — draggable, resizable from every edge, a self-scrolling body, dismissed only by the close button or Escape (no outside click / blur / anchor observer); the task window hands its spare height to the description, so enlarging it gives the content room, and the action row is pinned to the bottom.
- 👥 **Agent Teams board (experimental layer)**: members enrich their nodes and an always-visible strip lists the roster and shared tasks; the state machine follows the host (pending → claim → in progress → complete → reopen) with reassign / edit / two-step delete, and stale CAS revisions get their own notice; member activity is overlaid from `subagents.live`'s `running` flag.
- 🔄 **Background jobs now read the host's client `ctx.jobs`** (a pushed roster plus a non-consuming output stream and `kill`): the plugin deleted its own `jobs.list` / `jobs.output` / `jobs.kill` routes and the event-replay mirror, never touching the model's `job_output` cursor; output streams in a persistent floating window with tail-follow, and the drawer auto-collapses at 8+ agents.
@@ -112,14 +112,36 @@ state === 'running' → liveActivityLabel(summary) // 宿主 mess
已补 `tests/tasks-page.spec.tsx` 的「drops the per-group openings when the CLUSTER collapses the page」
用例;把判据翻回去即红(实测),这条用例是判别性的。
## 第二轮(用户真机测试反馈,同日)
用户在 3080 实例上实际测试后报回六条,逐条处置:
| # | 反馈 | 处置 |
|---|---|---|
| 1 | 已完成的【聚合】卡下方空荡荡 | **是我上一轮的取舍造成的**:把计数收进徽标后,没有出错时那条只剩右侧一个 chevron。现在小条是**动作行**:组图标 + 「展开」+ 出错尾注 + 展开箭头(`tasksFoldExpandShort` 新词条,20 份词典) |
| 2 | 展开后的子代理点不回去 | **真缺陷**:`expandedGroups` 压过了 `foldedIds`,导致展开组内卡片的 chevron 失效。改为**手动折叠优先**(手动 → 页级规则 → 组展开),并补两层判别性用例(模型 + 组件) |
| 3 | 一次性子代理一直显示「一次性」 | 模式词**搬进徽标行**成 chip(用户口径:「和可续接等状态放到和子代理那个徽标一行上」)。智能体卡因此不再有 mono 元信息行,卡片高度预算拆成 `GRAPH_AGENT_NODE_H` / `GRAPH_NODE_H`(只有 workflow run 卡保留元信息行),`rowStrideFor(nodes)` 按模型里有没有 run 选行距 |
| 4 | 动效,允许引入新库 | 用户选定 `@formkit/auto-animate`(~3KB,无依赖无安装脚本)。加 `useAutoAnimateRef` 包装(WAAPI 守卫 → jsdom 空转;尊重 `prefers-reduced-motion`),挂到画布卡片层 / 树视图 / 任务抽屉;详情卡另加 140ms 入场关键帧。核心 bundle 因此增大约 56KB(未压缩 CJS,含库源码 27KB) |
| 5 | 弹窗多显示 token 与耗时 | 新增 **Token 用量** + **耗时** 两行。数据来自宿主投影(`tokenUsage` 四桶求和;`subagentTiming` 已结算 + 本次运行,按页面 3s 轮询刷新),`SidebarProjectionSnapshot.values` 镜像补两个键、模型新增 `metrics` 入参。**按存在性渲染**:没有测量就不显示这一行(0 是投影的初始态,与「没工作过」不可区分) |
| 6 | 「查看转录」改为在侧边栏打开(原生能力),右侧加下拉按钮可在主窗打开 | 确认宿主确有该能力:`@deepseek-ai/dsh-client-ui-subagent` 注册 `subagentchat` tab 类型,宿主自己的子代理列表就是「点行 = 主窗、点 chevron = 侧栏」。插件照抄其地址公式(宿主不导出 builder/parser)并调 `openResource(addr, {kind:'subagentchat', preferNewPane:true})`,三级降级回主窗;页脚变为「主按钮 + caret 菜单(在主窗口中打开)」 |
### 第二轮的实施偏差与未验证项
1. **画布上的 FLIP 位移会被缩放比例影响**:auto-animate 用 `getBoundingClientRect` 量测、以未缩放的 `transform` 播放,而卡片层带着 fit 的 `scale(k)`——插入 / 移除的淡入淡出不受影响,**位置移动**的行程在 k≠1 时按 k 缩放(落点仍然正确)。选择接受并在 `use-auto-animate.ts` 里写明;若真机观感不够好,画布那一处可退化回 CSS 入场关键帧(库只保留树 / 抽屉)。
2. **真机只跑通到「插件挂载 + 零 pageerror」**:新构建已装进 `sidebar-test` profile 并在 http://127.0.0.1:3080 提供服务(`[data-dsh-better-sidebar]` 挂载、`/sidebar/api/*` 200、无 pageerror / console error)。但**动效与观感的逐帧复核没做成**:宿主右栏在无头上下文里以 `transform` 平移到视口外,我的合成点击无法稳定地把任务页调出来(多次尝试后放弃)。这一条由维护者自己在实例上看。
3. **实机数据的两个新行未在真机核验**:Token / 耗时两行通过夹具断言(25.5K / 2 分 42 秒)与 `session-metrics` 单测覆盖,但没有在真实子代理会话上截图确认数值口径(真实会话的 `tokenUsage` 是整段日志累计,包含 fork 继承前缀这一点已写进 `context-types.ts` 的注释)。
4. **`uses` 依赖新增**:`@formkit/auto-animate@^0.10.0` 进 `dependencies`(无 `cordis`、无安装脚本,市场约束满足)。本 worktree 的 `node_modules` 因此从符号链接物化为独立副本(源仓库未被触碰,见仓库规则)。
## 验证证据
| 项 | 结果 |
|---|---|
| `tsc --noEmit`(等价 `pnpm typecheck`) | ✅ 0 错误 |
| `eslint .` | ✅ 0 错误 |
| `vitest run`(全套) | ✅ **2227 passed / 17 skipped / 0 failed**(190 文件) |
| `tsc -p tsconfig.build.json` + `tsdown` | ✅ 构建通过(核心 bundle 与三个 chunk 正常产出) |
| `vitest run`(全套) | ✅ **2238 passed / 17 skipped / 0 failed**(191 文件,含第二轮新增的 3 个 spec 文件) |
| `tsc -p tsconfig.build.json` + `tsdown` | ✅ 构建通过(核心 bundle 1,333,699 字节,较首轮 +56KB = auto-animate 及其包装) |
| 真机挂载(`sidebar-test` profile,DSH 0.2.0-rc.2,:3080) | ✅ 装进独立 profile 后 `[data-dsh-better-sidebar]` 挂载、`/sidebar/api/*`(settings.get / session.phase / session.cwd)200、**0 pageerror / 0 console error**;动效观感未逐帧核验(见偏差 2) |
本轮新增/改写的守护:
+1
View File
@@ -145,6 +145,7 @@
"@codemirror/state": "^6.7.1",
"@codemirror/view": "^6.43.8",
"@deepseek-ai/schemastery": "^3.18.4",
"@formkit/auto-animate": "^0.10.0",
"@lezer/highlight": "^1.2.3",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+91 -69
View File
@@ -74,9 +74,12 @@ importers:
'@deepseek-ai/schemastery':
specifier: ^3.18.4
version: 3.18.4
'@formkit/auto-animate':
specifier: ^0.10.0
version: 0.10.0
'@lezer/highlight':
specifier: ^1.2.3
version: 1.2.3
version: 1.2.5
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
@@ -227,7 +230,7 @@ importers:
version: 18.3.1
'@types/ws':
specifier: ^8.5.10
version: 8.18.1
version: 8.18.2
anser:
specifier: ^2.3.5
version: 2.3.5
@@ -269,7 +272,7 @@ importers:
version: 3.0.0
micromark-core-commonmark:
specifier: ^2.0.3
version: 2.0.3
version: 2.0.4
micromark-extension-gfm:
specifier: ^3.0.0
version: 3.0.0
@@ -278,7 +281,7 @@ importers:
version: 3.1.0
micromark-factory-space:
specifier: ^2.0.1
version: 2.0.1
version: 2.1.0
micromark-util-character:
specifier: ^2.1.1
version: 2.1.1
@@ -293,7 +296,7 @@ importers:
version: 2.0.1
micromark-util-types:
specifier: ^2.0.2
version: 2.0.2
version: 2.0.3
react:
specifier: ^18.2.0
version: 18.2.0
@@ -950,6 +953,9 @@ packages:
'@noble/hashes':
optional: true
'@formkit/auto-animate@0.10.0':
resolution: {integrity: sha512-KGomRttjUfORuPUaR/ZGQw+6xfMrTM+sxnILv7JAd9AmabU9rg9i6gF/iC0Ih+QpKCubJpCA/1DX9UHKE8cX+A==}
'@huanlin/dsh-plugin-better-locale@0.1.0':
resolution: {integrity: sha512-fGXDgVq1R3gVTi2M9TMn2x5ROqiaYkhEsFJqYF5xiVUFfs9KjwIpOF0ZbhUyK6vFBOeYP4uetc/ZVknQb38WrQ==}
engines: {node: '>=22.0.0'}
@@ -1050,8 +1056,8 @@ packages:
'@lezer/go@1.0.1':
resolution: {integrity: sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==}
'@lezer/highlight@1.2.3':
resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}
'@lezer/highlight@1.2.5':
resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==}
'@lezer/html@1.3.13':
resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
@@ -1495,8 +1501,8 @@ packages:
'@types/unist@3.0.3':
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
'@types/ws@8.18.1':
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
'@types/ws@8.18.2':
resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}
'@typescript-eslint/eslint-plugin@8.69.0':
resolution: {integrity: sha512-t5jQTKPIgVW1PE6dR6H6Qz5gm8zjMlX5/2gRaOGd9eO6V7J+tQc6iWKukEe7dY8u9HyYasQ0yfF0/FSSTEO2gA==}
@@ -2594,8 +2600,8 @@ packages:
mermaid@11.17.0:
resolution: {integrity: sha512-Jo9N377Wb4MSnHFPTbLi2SxFpsQl4eVHoxnW5U1Md9EazvgMp3s+4ohDxr81YNTgbn5Kj7HJ3yslrSJ52kwpbA==}
micromark-core-commonmark@2.0.3:
resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
micromark-core-commonmark@2.0.4:
resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==}
micromark-extension-gfm-autolink-literal@2.1.0:
resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
@@ -2627,8 +2633,8 @@ packages:
micromark-factory-label@2.0.1:
resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}
micromark-factory-space@2.0.1:
resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}
micromark-factory-space@2.1.0:
resolution: {integrity: sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==}
micromark-factory-title@2.0.1:
resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}
@@ -2654,6 +2660,9 @@ packages:
micromark-util-decode-string@2.0.1:
resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}
micromark-util-edit-map@1.0.0:
resolution: {integrity: sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==}
micromark-util-encode@2.0.1:
resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}
@@ -2675,8 +2684,8 @@ packages:
micromark-util-symbol@2.0.1:
resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}
micromark-util-types@2.0.2:
resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}
micromark-util-types@2.0.3:
resolution: {integrity: sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==}
micromark@4.0.2:
resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}
@@ -3002,6 +3011,10 @@ packages:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
source-map-js@1.2.2:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
space-separated-tokens@2.0.2:
resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}
@@ -3639,7 +3652,7 @@ snapshots:
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.1
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@codemirror/lang-vue@0.1.3':
@@ -3648,7 +3661,7 @@ snapshots:
'@codemirror/lang-javascript': 6.2.5
'@codemirror/language': 6.12.4
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@codemirror/lang-xml@6.1.0':
@@ -3666,7 +3679,7 @@ snapshots:
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.1
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/yaml': 1.0.4
@@ -3675,7 +3688,7 @@ snapshots:
'@codemirror/state': 6.7.1
'@codemirror/view': 6.43.9
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
style-mod: 4.1.3
@@ -4128,6 +4141,8 @@ snapshots:
'@exodus/bytes@1.15.1': {}
'@formkit/auto-animate@0.10.0': {}
'@huanlin/dsh-plugin-better-locale@0.1.0(@deepseek-ai/cordis@4.0.4)(@deepseek-ai/dsh-client-locale@0.2.0-rc.2(@deepseek-ai/cordis@4.0.4))(@deepseek-ai/dsh-client-ui-primitives@0.2.0-rc.2(@deepseek-ai/cordis@4.0.4))(@deepseek-ai/dsh-client-ui-settings@0.2.0-rc.2(@deepseek-ai/cordis@4.0.4))(@deepseek-ai/dsh-client-ui-slots@0.2.0-rc.2(@deepseek-ai/cordis@4.0.4))(@deepseek-ai/dsh-invariants@0.2.0-rc.2(@deepseek-ai/cordis@4.0.4))(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@deepseek-ai/cordis': 4.0.4(@deepseek-ai/cordis-plugin-include@1.0.9)(@deepseek-ai/cordis-plugin-loader@1.0.5)
@@ -4207,47 +4222,47 @@ snapshots:
'@lezer/cpp@1.1.6':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/css@1.3.6':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/go@1.0.1':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/highlight@1.2.3':
'@lezer/highlight@1.2.5':
dependencies:
'@lezer/common': 1.5.2
'@lezer/html@1.3.13':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/java@1.1.3':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/javascript@1.5.4':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/json@1.0.3':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/lr@1.4.10':
@@ -4257,36 +4272,36 @@ snapshots:
'@lezer/markdown@1.7.2':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/php@1.0.5':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/python@1.1.19':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/rust@1.0.2':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/xml@1.0.6':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@lezer/yaml@1.0.4':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.10
'@marijn/find-cluster-break@1.0.3': {}
@@ -4630,7 +4645,7 @@ snapshots:
'@types/unist@3.0.3': {}
'@types/ws@8.18.1':
'@types/ws@8.18.2':
dependencies:
'@types/node': 24.13.3
@@ -5634,7 +5649,7 @@ snapshots:
micromark-util-decode-string: 2.0.1
micromark-util-normalize-identifier: 2.0.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
unist-util-stringify-position: 4.0.0
transitivePeerDependencies:
- supports-color
@@ -5768,42 +5783,43 @@ snapshots:
ts-dedent: 2.3.0
uuid: 14.0.2
micromark-core-commonmark@2.0.3:
micromark-core-commonmark@2.0.4:
dependencies:
decode-named-character-reference: 1.3.0
devlop: 1.1.0
micromark-factory-destination: 2.0.1
micromark-factory-label: 2.0.1
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-factory-title: 2.0.1
micromark-factory-whitespace: 2.0.1
micromark-util-character: 2.1.1
micromark-util-chunked: 2.0.1
micromark-util-classify-character: 2.0.1
micromark-util-edit-map: 1.0.0
micromark-util-html-tag-name: 2.0.1
micromark-util-normalize-identifier: 2.0.1
micromark-util-resolve-all: 2.0.1
micromark-util-subtokenize: 2.1.0
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-autolink-literal@2.1.0:
dependencies:
micromark-util-character: 2.1.1
micromark-util-sanitize-uri: 2.0.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-footnote@2.1.0:
dependencies:
devlop: 1.1.0
micromark-core-commonmark: 2.0.3
micromark-factory-space: 2.0.1
micromark-core-commonmark: 2.0.4
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-normalize-identifier: 2.0.1
micromark-util-sanitize-uri: 2.0.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-strikethrough@2.1.0:
dependencies:
@@ -5812,27 +5828,27 @@ snapshots:
micromark-util-classify-character: 2.0.1
micromark-util-resolve-all: 2.0.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-table@2.1.1:
dependencies:
devlop: 1.1.0
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-tagfilter@2.0.0:
dependencies:
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm-task-list-item@2.1.0:
dependencies:
devlop: 1.1.0
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-gfm@3.0.0:
dependencies:
@@ -5843,54 +5859,54 @@ snapshots:
micromark-extension-gfm-tagfilter: 2.0.0
micromark-extension-gfm-task-list-item: 2.1.0
micromark-util-combine-extensions: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-extension-math@3.1.0:
dependencies:
'@types/katex': 0.16.8
devlop: 1.1.0
katex: 0.16.47
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-factory-destination@2.0.1:
dependencies:
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-factory-label@2.0.1:
dependencies:
devlop: 1.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-factory-space@2.0.1:
micromark-factory-space@2.1.0:
dependencies:
micromark-util-character: 2.1.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-factory-title@2.0.1:
dependencies:
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-factory-whitespace@2.0.1:
dependencies:
micromark-factory-space: 2.0.1
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-character@2.1.1:
dependencies:
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-chunked@2.0.1:
dependencies:
@@ -5900,12 +5916,12 @@ snapshots:
dependencies:
micromark-util-character: 2.1.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-combine-extensions@2.0.1:
dependencies:
micromark-util-chunked: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-decode-numeric-character-reference@2.0.2:
dependencies:
@@ -5918,6 +5934,10 @@ snapshots:
micromark-util-decode-numeric-character-reference: 2.0.2
micromark-util-symbol: 2.0.1
micromark-util-edit-map@1.0.0:
dependencies:
micromark-util-types: 2.0.3
micromark-util-encode@2.0.1: {}
micromark-util-html-tag-name@2.0.1: {}
@@ -5928,7 +5948,7 @@ snapshots:
micromark-util-resolve-all@2.0.1:
dependencies:
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-sanitize-uri@2.0.1:
dependencies:
@@ -5941,11 +5961,11 @@ snapshots:
devlop: 1.1.0
micromark-util-chunked: 2.0.1
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
micromark-util-symbol@2.0.1: {}
micromark-util-types@2.0.2: {}
micromark-util-types@2.0.3: {}
micromark@4.0.2:
dependencies:
@@ -5953,8 +5973,8 @@ snapshots:
debug: 4.4.3
decode-named-character-reference: 1.3.0
devlop: 1.1.0
micromark-core-commonmark: 2.0.3
micromark-factory-space: 2.0.1
micromark-core-commonmark: 2.0.4
micromark-factory-space: 2.1.0
micromark-util-character: 2.1.1
micromark-util-chunked: 2.0.1
micromark-util-combine-extensions: 2.0.1
@@ -5965,7 +5985,7 @@ snapshots:
micromark-util-sanitize-uri: 2.0.1
micromark-util-subtokenize: 2.1.0
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
micromark-util-types: 2.0.3
transitivePeerDependencies:
- supports-color
@@ -6121,7 +6141,7 @@ snapshots:
dependencies:
nanoid: 3.3.18
picocolors: 1.1.1
source-map-js: 1.2.1
source-map-js: 1.2.2
prelude-ls@1.2.1: {}
@@ -6277,6 +6297,8 @@ snapshots:
source-map-js@1.2.1: {}
source-map-js@1.2.2: {}
space-separated-tokens@2.0.2: {}
stackback@0.0.2: {}
+5 -1
View File
@@ -33,6 +33,7 @@ import {
type TreeJob,
} from './subagent-jobs.ts'
import { FloatingWindow } from './FloatingWindow.tsx'
import { useAutoAnimateRef } from './use-auto-animate.ts'
import { t } from './locales.ts'
import css from './tasks-graph.module.css'
@@ -69,6 +70,9 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode {
/** Manual override; undefined = follow the auto rule. */
const [manualOpen, setManualOpen] = useState<boolean | undefined>(undefined)
const open = manualOpen ?? autoOpen
/** The rows: a job arriving or settling slides in instead of blinking. */
const rowsRef = useRef<HTMLDivElement>(null)
useAutoAnimateRef(rowsRef)
const [armedId, setArmedId] = useState<string | undefined>(undefined)
const [killingId, setKillingId] = useState<string | undefined>(undefined)
const [killErrorId, setKillErrorId] = useState<string | undefined>(undefined)
@@ -134,7 +138,7 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode {
</button>
{!autoOpen && <div className={css.jobsAutoNote}>{t('jobsAutoCollapsed')}</div>}
{open && (
<div className={css.jobsDrawerBody}>
<div className={css.jobsDrawerBody} ref={rowsRef}>
{rows.map((row) => {
const { job } = row
const live = isJobLive(job)
+28 -5
View File
@@ -48,6 +48,8 @@ import {
rootAncestor,
} from './subagent-detect.ts'
import { subagentCatalogs } from './subagent-catalog.ts'
import { sessionMetrics } from './session-metrics.ts'
import { hasTranscriptAside, openTranscriptAside } from './subagent-chat.ts'
import { teamMembersOf, teamProjectionOf } from './team-projection.ts'
import { treeSessionIds } from './subagent-lineage.ts'
import { orderJobs, type TreeJob } from './subagent-jobs.ts'
@@ -205,6 +207,9 @@ export function SubagentView(props: {
// The projected per-parent catalogs, already folded into the view shape the
// topology consumes (see subagent-catalog.ts).
const catalogs = useMemo(() => subagentCatalogs(list.projectionsBySession), [list.projectionsBySession])
// Token usage and turn timing ride the same snapshot: the popover's two
// extra facts are read here, not fetched (see ./session-metrics.ts).
const metrics = useMemo(() => sessionMetrics(list.projectionsBySession), [list.projectionsBySession])
// The topology root: the main agent of the current session's tree.
const rootId = useMemo(() => rootAncestor(byId, sessionId), [byId, sessionId])
@@ -266,6 +271,7 @@ export function SubagentView(props: {
rootId,
currentSessionId: sessionId,
live,
metrics,
runs,
teamMembers,
teamTasks: team?.tasks ?? [],
@@ -273,7 +279,7 @@ export function SubagentView(props: {
foldedIds,
expandedGroups,
})),
[byId, catalogs, rootId, sessionId, live, runs, teamMembers, team, folded, foldedIds, expandedGroups],
[byId, catalogs, rootId, sessionId, live, metrics, runs, teamMembers, team, folded, foldedIds, expandedGroups],
)
/**
@@ -293,7 +299,16 @@ export function SubagentView(props: {
else sessions.openSubagent?.(target)
}, [ctx, sessions])
const openChild = useCallback((address: SidebarSubagentAddress): void => {
/**
* Show one child session. `'side'` (the default) hands the transcript to the
* host's OWN right-sidebar tab and leaves the main column alone — that is the
* native affordance the host's subagent list uses, and it is skipped when the
* deployment cannot host it (no `subagentchat` type, no right column, or no
* mounted seat). `'main'` is the old behavior: the shell re-roots the Tasks
* page on the child and the main view follows.
*/
const openChild = useCallback((address: SidebarSubagentAddress, place: 'side' | 'main' = 'side'): void => {
if (place === 'side' && openTranscriptAside(ctx, address)) return
// Notify the shell first: the jump switches the sidebar to the child
// session's own layout, and the shell re-opens the Tasks page on top
// of it (the topology stays rooted at the main agent with the child
@@ -304,7 +319,7 @@ export function SubagentView(props: {
} catch (error) {
console.error('[dsh-better-sidebar] open subagent failed:', error)
}
}, [openConversation, onOpenChild])
}, [ctx, openConversation, onOpenChild])
/** Jump back to the main agent (the topology root) from its node. */
const openMain = useCallback((): void => {
@@ -325,9 +340,9 @@ export function SubagentView(props: {
}, [sessions])
/** Jump from the detail window into the node's transcript. */
const jumpToNode = useCallback((node: TasksAgentNode): void => {
const jumpToNode = useCallback((node: TasksAgentNode, place: 'side' | 'main' = 'side'): void => {
if (node.childAddress !== undefined) {
openChild(node.childAddress)
openChild(node.childAddress, place)
setPopover(null)
return
}
@@ -337,6 +352,13 @@ export function SubagentView(props: {
}
}, [openChild, openMain])
/**
* Whether this deployment can host a child transcript in its right column.
* Read once per ctx (the services arrive with the profile, not later), and it
* drives whether the detail window offers the choice at all.
*/
const asideAvailable = useMemo(() => hasTranscriptAside(ctx), [ctx])
/** Fold one settled node into its parent's aggregate (its card's chevron). */
const foldNode = useCallback((node: TasksAgentNode): void => {
setFoldedIds(current => {
@@ -503,6 +525,7 @@ export function SubagentView(props: {
return (
<AgentNodePopover
node={node}
asideAvailable={asideAvailable}
onJump={jumpToNode}
onOpenTask={openTaskById}
/>
+24 -8
View File
@@ -41,10 +41,11 @@ import {
type GraphBox,
} from './tasks-graph-layout.ts'
import {
activityLine, agentIdentity, agentMeta, foldErrorTally, foldPreviews, foldTally,
activityLine, agentChip, agentMeta, foldErrorTally, foldPreviews, FoldGlyph, foldTally,
TaskLine, WorkflowGlyph, workflowMeta,
} from './tasks-shared.tsx'
import { CardBar, CardTop, phaseClass, type CardKind } from './tasks-card.tsx'
import { useAutoAnimateRef } from './use-auto-animate.ts'
import { t } from './locales.ts'
import css from './tasks-graph.module.css'
import canvasCss from './tasks-canvas.module.css'
@@ -185,6 +186,14 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
onFoldNode, mode, onModeChange, loading,
} = props
const containerRef = useRef<HTMLDivElement>(null)
/**
* The cards' own layer: FLIP-animated, so folding a group makes the cards
* leave (and the canvas re-slot) instead of blinking. The layer is the
* canvas's scaled child, so a move animation is scaled with the zoom — see
* use-auto-animate.ts.
*/
const cardsRef = useRef<HTMLDivElement>(null)
useAutoAnimateRef(cardsRef)
const [tf, setTf] = useState({ x: 0, y: 0, k: 1 })
const [dragging, setDragging] = useState(false)
/** Pointer travel of the in-flight gesture (click suppression). */
@@ -441,6 +450,7 @@ export function TasksGraph(props: TasksGraphProps): ReactNode {
</div>
)}
<div
ref={cardsRef}
className={css.canvasInner}
style={{
width: layout.width,
@@ -562,6 +572,8 @@ function renderAgentNode(
const foldable = (settled || node.state === 'idle') && node.parentId !== undefined
/** The merged process line the bar shows in place of the state word. */
const activity = activityLine(node)
/** The identity word beside the kind badge (one badge row, no meta line). */
const chip = agentChip(node)
return (
<div
key={node.id}
@@ -588,8 +600,8 @@ function renderAgentNode(
kind={agentCardKind(node)}
depth={node.depth}
{...(node.phase === undefined ? {} : { phase: node.phase })}
{...(chip === undefined ? {} : { chip })}
name={node.label}
meta={agentIdentity(node)}
>
<TaskLine tasks={node.tasks} onOpenTask={onOpenTask} />
</CardTop>
@@ -646,12 +658,14 @@ function renderWorkflowNode(
/**
* One fold aggregate node: the finished or the waiting members of one parent,
* collapsed. Its bar is the action row (expand THIS group), so the whole card
* stays one click target.
* collapsed. Its bar is the action row — the group's own glyph, the word that
* names what a click does, and the expand chevron — so the whole card stays one
* click target.
*
* The count is printed ONCE: the badge names it, so the bar only carries what
* the badge cannot say — a stray failure ("出错 N" would otherwise hide inside
* the ✓) — beside the expand chevron. The full tally stays the card's
* The count is printed ONCE: the badge above names it, so the bar carries the
* ACTION instead (a bare chevron in an otherwise empty strip read as a broken
* card), plus the one fact the badge cannot say — a stray failure ("出错 N"
* would otherwise hide inside the ✓). The full tally stays the card's
* accessible name and tooltip, which a screen reader reads instead of the
* badge's inner text.
*/
@@ -686,8 +700,10 @@ function renderFoldNode(
extraClass={css.cardNamePlain}
/>
<CardBar state={node.foldKind === 'idle' ? 'idle' : 'done'} stateWord={false}>
<span className={css.barFoldGlyph} aria-hidden="true"><FoldGlyph size={10} /></span>
<span className={css.barAction} title={foldTally(node)}>{t('tasksFoldExpandShort')}</span>
{errors !== undefined && (
<span className={css.barActivity} title={foldTally(node)}>{errors}</span>
<span className={css.barError}>{errors}</span>
)}
<span className={css.barFold} aria-hidden="true">
<IconChevronDownOutlineRegular size={12} />
+138 -13
View File
@@ -24,18 +24,42 @@
* The team board is NOT here: it is always visible as a strip above the
* canvas (TeamBoard.tsx).
*/
import type { ReactNode } from 'react'
import { useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
import { Button, IconRightUpOutlineRegular, StateDot, Tag } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarSubagentAddress } from '../context-types.ts'
import {
Button, IconChevronDownOutlineRegular, IconRightUpOutlineRegular, MenuSurface, StateDot, Tag,
useDismissOnOutsidePointer,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarSubagentAddress, SidebarTokenUsage } from '../context-types.ts'
import type { TasksAgentNode, TasksWorkflowNode } from './tasks-model.ts'
import {
activityLine, AgentGlyph, WorkflowGlyph, flatten, modeLabel, nodeDotState, taskDotState,
taskStatusLabel, taskTone, workflowStatusKey,
} from './tasks-shared.tsx'
import { t, type CopyKey } from './locales.ts'
import { elapsedMs, totalTokens } from './session-metrics.ts'
import { formatJobDuration } from './subagent-jobs.ts'
import { formatTokens } from './sidechat-transcript.ts'
import { chatT, t, type CopyKey } from './locales.ts'
import css from './tasks-graph.module.css'
/**
* The usage row's tooltip: the four buckets the host bills separately, in the
* host's own words (the `chat` namespace's usage dialog). Undefined when that
* wording is unavailable — an empty `title` would still swallow the hover.
*/
function usageTitle(usage: SidebarTokenUsage): string | undefined {
const buckets: [string | undefined, number][] = [
[chatT('message.turnUsage.input'), usage.uncachedInputTokens],
[chatT('message.turnUsage.cacheRead'), usage.cacheReadTokens],
[chatT('message.turnUsage.cacheWrite'), usage.cacheWriteTokens],
[chatT('message.turnUsage.output'), usage.outputTokens],
]
const parts = buckets
.filter(([label]) => label !== undefined)
.map(([label, count]) => `${label ?? ''} ${formatTokens(count)}`)
return parts.length === 0 ? undefined : parts.join(' · ')
}
/** The display-state label key. */
function stateKey(state: TasksAgentNode['state']): CopyKey {
switch (state) {
@@ -71,6 +95,78 @@ function PopTitleRow(props: { glyph: ReactNode; title: string }): ReactNode {
)
}
/**
* The transcript jump, offered the way the host's own subagent list offers it:
* the primary action opens the child's transcript in the NATIVE right sidebar
* (the `subagentchat` tab type — the page never re-implements a transcript
* pane), and the caret beside it opens the main window instead.
*
* The ROOT node has no child to embed — it IS the main session — and a host
* without the `subagentchat` type has no sidebar to open into, so both keep the
* single button.
*/
function JumpActions(props: {
node: TasksAgentNode
asideAvailable: boolean
onJump(node: TasksAgentNode, place: 'side' | 'main'): void
}): ReactNode {
const { node, asideAvailable, onJump } = props
const [open, setOpen] = useState(false)
const rootRef = useRef<HTMLSpanElement>(null)
useDismissOnOutsidePointer(rootRef, open, setOpen)
const split = asideAvailable && node.childAddress !== undefined
const primaryPlace = split ? 'side' : 'main'
return (
<>
<Button
variant="primary"
size="sm"
icon={<IconRightUpOutlineRegular size={12} />}
onClick={() => { onJump(node, primaryPlace) }}
>
{t('tasksNodeJump')}
</Button>
{split && (
<span className={css.jumpMore} ref={rootRef}>
<Button
variant="primary"
size="sm"
className={css.jumpMoreButton}
aria-label={t('tasksNodeOpenMain')}
aria-haspopup="menu"
aria-expanded={open}
title={t('tasksNodeOpenMain')}
onClick={() => { setOpen(current => !current) }}
>
{/*
The split's caret, the same split the host's own jump control
shows: the glyph names the MENU it opens, never the primary
action beside it.
*/}
<IconChevronDownOutlineRegular size={12} />
</Button>
{open && (
<MenuSurface compact className={css.jumpMenu} role="menu">
<Button
variant="ghost"
size="sm"
role="menuitem"
className={css.jumpMenuItem}
onClick={() => {
setOpen(false)
onJump(node, 'main')
}}
>
{t('tasksNodeOpenMain')}
</Button>
</MenuSurface>
)}
</span>
)}
</>
)
}
/**
* The agent node detail popover.
*
@@ -83,7 +179,13 @@ function PopTitleRow(props: { glyph: ReactNode; title: string }): ReactNode {
*/
export function AgentNodePopover(props: {
node: TasksAgentNode
onJump(node: TasksAgentNode): void
/**
* Whether the host can host a child transcript in its right column. Without
* it (no `subagentchat` tab type, no right column) the footer is a single
* main-view button — the choice simply does not exist.
*/
asideAvailable: boolean
onJump(node: TasksAgentNode, place: 'side' | 'main'): void
/** Open the shared task window for one of the node's tasks. */
onOpenTask(taskId: string, anchor: HTMLElement): void
}): ReactNode {
@@ -91,6 +193,15 @@ export function AgentNodePopover(props: {
/** The row's mode word; `unknown` claims no mode and this row is omitted. */
const nodeMode = modeLabel(node.mode)
const liveText = node.live?.text !== undefined ? flatten(node.live.text) : undefined
/** Tokens the node's own session was billed for (host projection). */
const usage = node.metrics?.usage
/**
* How long it worked. Read per render on purpose: the page re-reads its live
* snapshot every 3s, which is also the cadence at which a running node's open
* turn grows (the projection's `through` only moves when an event commits).
*/
const elapsed = elapsedMs(node.metrics?.timing, Date.now())
const usageTip = usage === undefined ? undefined : usageTitle(usage)
// The merged activity the main conversation would show for this node's
// newest range — the host's own wording, in its running or settled form
// (see activityLine).
@@ -123,6 +234,23 @@ export function AgentNodePopover(props: {
{node.team.role === 'lead' ? 'lead' : node.team.name}
</PopRow>
)}
{/*
What the node SPENT and how long it worked: both come from the host's
session projections, and either row is omitted when the host published
nothing — a "0 tok / 0s" line would claim measurements we do not have.
*/}
{usage !== undefined && (
<PopRow label={t('tasksNodeTokens')}>
<span {...(usageTip === undefined ? {} : { title: usageTip })}>
{formatTokens(totalTokens(usage))}
</span>
</PopRow>
)}
{elapsed !== undefined && (
<PopRow label={t('tasksNodeDuration')}>
{formatJobDuration(elapsed, t)}
</PopRow>
)}
</PopRows>
{(node.tasks?.length ?? 0) > 0 && (
<div className={css.popSection}>
@@ -148,14 +276,11 @@ export function AgentNodePopover(props: {
)}
{(node.childAddress !== undefined || node.parentId === undefined) && (
<div className={css.popFoot}>
<Button
variant="primary"
size="sm"
icon={<IconRightUpOutlineRegular size={12} />}
onClick={() => { onJump(node) }}
>
{t('tasksNodeJump')}
</Button>
<JumpActions
node={node}
asideAvailable={props.asideAvailable}
onJump={onJump}
/>
</div>
)}
</div>
+6
View File
@@ -24,6 +24,7 @@ import {
TaskLine, WorkflowGlyph, workflowMeta,
} from './tasks-shared.tsx'
import { FoldToggleButton, ViewModeToggle } from './TasksGraph.tsx'
import { useAutoAnimateRef } from './use-auto-animate.ts'
import { t } from './locales.ts'
import css from './tasks-graph.module.css'
@@ -50,6 +51,11 @@ export function TasksTree(props: TasksTreeProps): ReactNode {
mode, onModeChange, loading,
} = props
const bodyRef = useRef<HTMLDivElement>(null)
// Rows fold and unfold here too: the same FLIP host the graph's cards use,
// scoped to the top level (a nested row is animated by its own parent level
// in the graph; the tree keeps one host, so its rows arrive in place rather
// than blinking).
useAutoAnimateRef(bodyRef)
/** children by parent id (model order preserved). */
const childrenOf = useMemo(() => {
+4
View File
@@ -460,6 +460,10 @@ export const ar: Record<string, string> = {
tasksNodeDetail: 'تفاصيل العقدة',
workflowRun: 'سير العمل',
tasksNodeState: 'الحالة',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'الوضع',
tasksNodeModel: 'الطراز',
tasksNodeTeamRole: 'دور الفريق',
+4
View File
@@ -445,6 +445,10 @@ export const de: Record<string, string> = {
tasksNodeDetail: 'Knotendetails',
workflowRun: 'Workflow',
tasksNodeState: 'Status',
tasksFoldExpandShort: "Aufklappen",
tasksNodeTokens: "Token-Nutzung",
tasksNodeDuration: "Dauer",
tasksNodeOpenMain: "Im Hauptfenster öffnen",
tasksNodeMode: 'Modus',
tasksNodeModel: 'Modell',
tasksNodeTeamRole: 'Teamrolle',
+4
View File
@@ -452,6 +452,10 @@ export const fr: Record<string, string> = {
tasksNodeDetail: 'Détails du nœud',
workflowRun: 'Workflow',
tasksNodeState: 'État',
tasksFoldExpandShort: "Développer",
tasksNodeTokens: "Jetons",
tasksNodeDuration: "Durée",
tasksNodeOpenMain: "Ouvrir dans la fenêtre principale",
tasksNodeMode: 'Mode',
tasksNodeModel: 'Modèle',
tasksNodeTeamRole: 'Rôle dans l’équipe',
+4
View File
@@ -459,6 +459,10 @@ export const hi: Record<string, string> = {
tasksNodeDetail: 'नोड विवरण',
workflowRun: 'वर्कफ़्लो',
tasksNodeState: 'स्थिति',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'मोड',
tasksNodeModel: 'मॉडल',
tasksNodeTeamRole: 'टीम भूमिका',
+4
View File
@@ -457,6 +457,10 @@ export const id: Record<string, string> = {
tasksNodeDetail: 'Detail node',
workflowRun: 'Alur kerja',
tasksNodeState: 'Status',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Mode',
tasksNodeModel: 'Model',
tasksNodeTeamRole: 'Peran tim',
+4
View File
@@ -450,6 +450,10 @@ export const it: Record<string, string> = {
tasksNodeDetail: 'Dettagli del nodo',
workflowRun: 'Workflow',
tasksNodeState: 'Stato',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Modalità',
tasksNodeModel: 'Modello',
tasksNodeTeamRole: 'Ruolo nel team',
+4
View File
@@ -459,6 +459,10 @@ export const ja: Record<string, string> = {
tasksNodeDetail: 'ノード詳細',
workflowRun: 'ワークフロー',
tasksNodeState: '状態',
tasksFoldExpandShort: "展開",
tasksNodeTokens: "Token 使用量",
tasksNodeDuration: "所要時間",
tasksNodeOpenMain: "メインウィンドウで開く",
tasksNodeMode: 'モード',
tasksNodeModel: 'モデル',
tasksNodeTeamRole: 'チーム役割',
+4
View File
@@ -451,6 +451,10 @@ export const ko: Record<string, string> = {
tasksNodeDetail: '노드 상세',
workflowRun: '워크플로',
tasksNodeState: '상태',
tasksFoldExpandShort: "펼치기",
tasksNodeTokens: "토큰 사용량",
tasksNodeDuration: "소요 시간",
tasksNodeOpenMain: "메인 창에서 열기",
tasksNodeMode: '모드',
tasksNodeModel: '모델',
tasksNodeTeamRole: '팀 역할',
+4
View File
@@ -457,6 +457,10 @@ export const nl: Record<string, string> = {
tasksNodeDetail: 'Knooppuntdetails',
workflowRun: 'Workflow',
tasksNodeState: 'Status',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Modus',
tasksNodeModel: 'Model',
tasksNodeTeamRole: 'Teamrol',
+4
View File
@@ -461,6 +461,10 @@ export const pl: Record<string, string> = {
tasksNodeDetail: 'Szczegóły węzła',
workflowRun: 'Przepływ pracy',
tasksNodeState: 'Stan',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Tryb',
tasksNodeModel: 'Model',
tasksNodeTeamRole: 'Rola w zespole',
+4
View File
@@ -442,6 +442,10 @@ export const pt: Record<string, string> = {
tasksNodeDetail: 'Detalhes do nó',
workflowRun: 'Workflow',
tasksNodeState: 'Estado',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Modo',
tasksNodeModel: 'Modelo',
tasksNodeTeamRole: 'Função na equipe',
+4
View File
@@ -457,6 +457,10 @@ export const ru: Record<string, string> = {
tasksNodeDetail: 'Сведения об узле',
workflowRun: 'Рабочий процесс',
tasksNodeState: 'Состояние',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Режим',
tasksNodeModel: 'Модель',
tasksNodeTeamRole: 'Роль в команде',
+4
View File
@@ -442,6 +442,10 @@ export const sv: Record<string, string> = {
tasksNodeDetail: 'Noddetaljer',
workflowRun: 'Arbetsflöde',
tasksNodeState: 'Status',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Läge',
tasksNodeModel: 'Modell',
tasksNodeTeamRole: 'Teamroll',
+4
View File
@@ -459,6 +459,10 @@ export const th: Record<string, string> = {
tasksNodeDetail: 'รายละเอียดโหนด',
workflowRun: 'เวิร์กโฟลว์',
tasksNodeState: 'สถานะ',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'โหมด',
tasksNodeModel: 'โมเดล',
tasksNodeTeamRole: 'บทบาทในทีม',
+4
View File
@@ -459,6 +459,10 @@ export const tr: Record<string, string> = {
tasksNodeDetail: 'Düğüm ayrıntıları',
workflowRun: 'İş akışı',
tasksNodeState: 'Durum',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Mod',
tasksNodeModel: 'Model',
tasksNodeTeamRole: 'Takım rolü',
+4
View File
@@ -459,6 +459,10 @@ export const vi: Record<string, string> = {
tasksNodeDetail: 'Chi tiết nút',
workflowRun: 'Quy trình',
tasksNodeState: 'Trạng thái',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Chế độ',
tasksNodeModel: 'Mô hình',
tasksNodeTeamRole: 'Vai trò trong nhóm',
+4
View File
@@ -474,6 +474,10 @@ export const zhHK: Record<string, string> = {
tasksNodeDetail: '節點詳情',
workflowRun: '工作流',
tasksNodeState: '狀態',
tasksFoldExpandShort: "展開",
tasksNodeTokens: "Token 用量",
tasksNodeDuration: "耗時",
tasksNodeOpenMain: "在主視窗中打開",
tasksNodeMode: '模式',
tasksNodeModel: '模型',
tasksNodeTeamRole: '團隊角色',
+4
View File
@@ -474,6 +474,10 @@ export const zhMO: Record<string, string> = {
tasksNodeDetail: '節點詳情',
workflowRun: '工作流',
tasksNodeState: '狀態',
tasksFoldExpandShort: "展開",
tasksNodeTokens: "Token 用量",
tasksNodeDuration: "耗時",
tasksNodeOpenMain: "在主視窗中打開",
tasksNodeMode: '模式',
tasksNodeModel: '模型',
tasksNodeTeamRole: '團隊角色',
+4
View File
@@ -474,6 +474,10 @@ export const zhTW: Record<string, string> = {
tasksNodeDetail: '節點詳情',
workflowRun: '工作流',
tasksNodeState: '狀態',
tasksFoldExpandShort: "展開",
tasksNodeTokens: "Token 用量",
tasksNodeDuration: "耗時",
tasksNodeOpenMain: "在主視窗中打開",
tasksNodeMode: '模式',
tasksNodeModel: '模型',
tasksNodeTeamRole: '團隊角色',
+8
View File
@@ -471,6 +471,10 @@ export const zh = {
tasksNodeDetail: '节点详情',
workflowRun: '工作流',
tasksNodeState: '状态',
tasksFoldExpandShort: "展开",
tasksNodeTokens: "Token 用量",
tasksNodeDuration: "耗时",
tasksNodeOpenMain: "在主窗口中打开",
tasksNodeMode: '模式',
tasksNodeModel: '模型',
tasksNodeTeamRole: '团队角色',
@@ -1041,6 +1045,10 @@ export const en: Record<keyof typeof zh, string> = {
tasksNodeDetail: 'Node detail',
workflowRun: 'Workflow',
tasksNodeState: 'State',
tasksFoldExpandShort: "Expand",
tasksNodeTokens: "Tokens",
tasksNodeDuration: "Duration",
tasksNodeOpenMain: "Open in the main window",
tasksNodeMode: 'Mode',
tasksNodeModel: 'Model',
tasksNodeTeamRole: 'Team role',
+85
View File
@@ -0,0 +1,85 @@
/**
* The Tasks page's per-session METRICS: how much a node consumed (tokens) and
* how long it actually worked (its own turn timing) — the two facts the node
* detail popover adds beside the state.
*
* Both come from the host's session projections, which the client publishes in
* `SessionListState.projectionsBySession` (see the mirror in
* ../context-types.ts). This module is the pure adapter between that snapshot
* and the shape the view model carries, plus the two display rules, so the
* popover never re-derives them:
*
* - **Tokens** are a session TOTAL in four disjoint buckets. The reader wants
* one number plus a breakdown, so {@link totalTokens} sums them (input
* buckets + output) and {@link inputTokens} keeps the billed-input half.
* - **Duration** is `settledMs` (closed turns) plus the live part of an open
* turn. `active.through` only advances when an event commits, so a running
* node's elapsed time is measured to `Date.now()` and refreshed by the page's
* own poll — never by a timer of this module's own.
*
* Everything degrades silently: a session with no events, a host without the
* projection, or a key the fold omitted simply reports nothing, and the caller
* hides the row rather than printing a zero it cannot justify.
*/
import type {
SidebarProjectionSnapshot,
SidebarSubagentTiming,
SidebarTokenUsage,
} from '../context-types.ts'
/** One session's metrics, as the view model carries them on its node. */
export interface SessionMetrics {
usage?: SidebarTokenUsage
timing?: SidebarSubagentTiming
}
/** The billed input tokens: every bucket that is not output. */
export function inputTokens(usage: SidebarTokenUsage): number {
return usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens
}
/** The session's total tokens (input buckets + output). */
export function totalTokens(usage: SidebarTokenUsage): number {
return inputTokens(usage) + usage.outputTokens
}
/**
* The node's elapsed working time in ms, or undefined when the host published
* no timing for it.
*
* @param timing - the session's `subagentTiming`.
* @param now - the clock the caller's render is pinned to.
*/
export function elapsedMs(timing: SidebarSubagentTiming | undefined, now: number): number | undefined {
if (timing === undefined) return undefined
const active = timing.active === undefined ? 0 : Math.max(0, now - timing.active.since)
const total = timing.settledMs + active
// 0 means "no closed turn and no open one" — the projection's init state,
// which is indistinguishable from "this session never worked". Show nothing.
return total > 0 ? total : undefined
}
/**
* Fold the projection snapshot into one metrics row per session.
*
* Sessions the snapshot does not carry are simply absent (the page's own poll
* fills them in), and a session carrying neither key is omitted so the caller's
* map stays small.
*
* @param projections - `SessionListState.projectionsBySession`.
*/
export function sessionMetrics(
projections: Readonly<Record<string, SidebarProjectionSnapshot>> | undefined,
): Readonly<Record<string, SessionMetrics>> {
const out: Record<string, SessionMetrics> = {}
for (const [sessionId, snapshot] of Object.entries(projections ?? {})) {
const usage = snapshot.values.tokenUsage
const timing = snapshot.values.subagentTiming
if (usage === undefined && timing === undefined) continue
out[sessionId] = {
...(usage === undefined ? {} : { usage }),
...(timing === undefined ? {} : { timing }),
}
}
return out
}
+85
View File
@@ -0,0 +1,85 @@
/**
* The host's OWN "subagent transcript in the right sidebar" affordance.
*
* DSH ships a native right-sidebar tab type for child transcripts
* (`@deepseek-ai/dsh-client-ui-subagent`, kind `subagentchat`, registered at the
* `builtin` band) and its subagent list already uses it: clicking a row opens
* the transcript in the MAIN view, and the small chevron beside it opens the
* same transcript in the sidebar. The Tasks page therefore hands the child over
* instead of re-implementing a transcript pane — one click opens the native tab,
* and the main column keeps whatever the reader was looking at.
*
* The address is `dsh-resource://subagentchat/session/<childId>?parent=&mode=`.
* The host exports neither its builder nor its parser to third parties, so the
* two lines below are a deliberate copy of the host's own formula; the parser
* (`parseSubagentChatAddress`) is the contract that keeps them honest.
*
* Every failure path answers `false` so the caller can fall back to the
* main-view jump it used before: a deployment without `ui-subagent` has no such
* tab type at all, and the public write face THROWS when no session seat is
* mounted (a global panel, a column that was never mounted).
*/
import type { Context, SidebarSubagentAddress } from '../context-types.ts'
/** The host's tab kind for an embedded child conversation. */
export const SUBAGENT_CHAT_KIND = 'subagentchat'
/** The host's `dsh-resource://` prefix for that tab type. */
export const SUBAGENT_CHAT_ADDRESS = 'dsh-resource://subagentchat/session/'
/** The tab registry, probed structurally (the service can arrive late). */
interface TabRegistryFace {
get?(kind: string): unknown
}
/** The write face of the native right column, structurally probed. */
interface SidebarRightFace {
openResource?(address: string, options?: { kind?: string; preferNewPane?: boolean }): void
}
/**
* The host's own subagent-chat resource address for one child session.
* @param address - the child's lineage (parent, child, mode).
*/
export function subagentChatAddress(address: SidebarSubagentAddress): string {
const query = new URLSearchParams({ parent: address.parentSessionId, mode: address.mode })
return `${SUBAGENT_CHAT_ADDRESS}${encodeURIComponent(address.childSessionId)}?${query}`
}
/** Whether the host can host a child transcript in its right column. */
export function hasTranscriptAside(ctx: Context): boolean {
try {
const tabs = ctx.get('sidebarRightTabs') as unknown as TabRegistryFace | undefined
if (tabs?.get?.(SUBAGENT_CHAT_KIND) === undefined) return false
return typeof (ctx.get('sidebarRight') as unknown as SidebarRightFace | undefined)?.openResource === 'function'
} catch {
return false
}
}
/**
* Open one child's transcript in the native right sidebar.
*
* @param ctx - the client context.
* @param address - the child to open.
* @returns whether the sidebar took it; `false` means the caller must fall back
* to the main-view jump (no such tab type, no right column, or the host threw
* because no session seat is mounted).
*/
export function openTranscriptAside(ctx: Context, address: SidebarSubagentAddress): boolean {
if (!hasTranscriptAside(ctx)) return false
try {
const right = ctx.get('sidebarRight') as unknown as SidebarRightFace
// `preferNewPane` mirrors the host's own subagent list: the transcript sits
// beside whatever the reader already has open, and degrades to the target
// pane when splitting is not allowed.
right.openResource?.(subagentChatAddress(address), {
kind: SUBAGENT_CHAT_KIND,
preferNewPane: true,
})
return true
} catch (error) {
console.error('[dsh-better-sidebar] open the child transcript in the sidebar failed:', error)
return false
}
}
+9 -1
View File
@@ -96,6 +96,13 @@ export function CardTop(props: {
depth: number
/** Workflow phase (a member's badge). */
phase?: { index: number; title?: string }
/**
* The identity CHIP beside the kind badge — the node's own mode word
* (一次性 / 可持续) or the one team state the badge cannot express. It shares
* the badge row on purpose: as a mono line of its own it repeated the same
* word on every card and spent a 16px row saying it.
*/
chip?: string
/** The node's name (already resolved by the model). */
name: string
/** The mono meta line under the name. */
@@ -105,7 +112,7 @@ export function CardTop(props: {
/** Extra rows the caller appends (the team task line). */
children?: ReactNode
}): ReactNode {
const { kind, count, foldKind, depth, phase } = props
const { kind, count, foldKind, depth, phase, chip } = props
return (
<span className={clsx(css.cardTop, depthClass(depth))}>
<span className={css.cardBadges}>
@@ -120,6 +127,7 @@ export function CardTop(props: {
{phase.title ?? t('workflowPhaseUnnamed')}
</span>
)}
{chip !== undefined && chip !== '' && <span className={css.kindChip}>{chip}</span>}
</span>
<span className={clsx(css.cardName, props.extraClass)} title={props.name}>{props.name}</span>
{props.meta !== undefined && props.meta !== '' && (
+34 -11
View File
@@ -60,12 +60,22 @@ const NODE_BAR_H = 22
* `+N` chip's own 1px outline (the tallest shape the row can take). */
const NODE_TASK_H = 15 + 3
/** Badges + TWO title lines + the mono meta line + the state bar: long agent
* names are clamped to two lines instead of ellipsizing to a couple of
* characters (see `.cardName` in tasks-graph.module.css), so the reserve
* covers that second line. */
export const GRAPH_NODE_H = NODE_CHROME_H + NODE_PAD_TOP + NODE_BADGE_H
+ NODE_TITLE_LINES * NODE_TITLE_LINE_H + NODE_META_H + NODE_PAD_BOTTOM + NODE_BAR_H
/**
* An AGENT card: badges + TWO title lines + the state bar. Long agent names are
* clamped to two lines instead of ellipsizing to a couple of characters (see
* `.cardName` in tasks-graph.module.css), so the reserve covers that second
* line. The mode word moved into the badge row, so an agent card carries no
* mono meta line — reserving one left a visible 16px hole above the bar.
*/
export const GRAPH_AGENT_NODE_H = NODE_CHROME_H + NODE_PAD_TOP + NODE_BADGE_H
+ NODE_TITLE_LINES * NODE_TITLE_LINE_H + NODE_PAD_BOTTOM + NODE_BAR_H
/**
* The tallest card on the canvas: a workflow RUN keeps its mono meta line
* (status · member tally), which no badge can express. {@link rowStrideFor}
* narrows the row pitch back to {@link GRAPH_AGENT_NODE_H} for a model without
* runs, so agent-only trees do not grow 16px of empty gutter per row.
*/
export const GRAPH_NODE_H = GRAPH_AGENT_NODE_H + NODE_META_H
/** Extra height of an agent node carrying a shared-task line (team members). */
export const GRAPH_TASK_H = NODE_TASK_H
@@ -78,10 +88,21 @@ export const GRAPH_FIT_MIN_SCALE = 0.78
export const GRAPH_GAP_X = 28
export const GRAPH_GAP_Y = 53
export const GRAPH_PAD = 16
/** The row stride (one row of cards plus the vertical gutter). Every card
* shape must fit inside it — see {@link nodeHeight} for the tallest one. */
/** The tallest row stride (the run card plus the vertical gutter). */
export const GRAPH_ROW_STRIDE = GRAPH_NODE_H + GRAPH_GAP_Y
/**
* The row pitch one model actually needs: the tallest card it draws plus the
* gutter. A workflow run is the only node that keeps a meta line, so a tree
* without runs never reserves that line.
*
* @param nodes - the model's node list.
*/
export function rowStrideFor(nodes: readonly TasksNode[]): number {
const tallest = nodes.some(node => node.kind === 'workflow') ? GRAPH_NODE_H : GRAPH_AGENT_NODE_H
return tallest + GRAPH_GAP_Y
}
/** One laid-out node. */
export interface GraphBox {
id: string
@@ -111,7 +132,8 @@ export interface LayoutOptions {
*/
function nodeHeight(node: TasksNode): number {
if (node.kind !== 'agent') return GRAPH_NODE_H
return (node.tasks?.length ?? 0) > 0 ? GRAPH_NODE_H + GRAPH_TASK_H : GRAPH_NODE_H
const base = GRAPH_AGENT_NODE_H
return (node.tasks?.length ?? 0) > 0 ? base + GRAPH_TASK_H : base
}
/**
@@ -136,6 +158,7 @@ function bands(children: readonly TasksNode[], cols: number): TasksNode[][] {
*/
export function layoutTasksGraph(nodes: readonly TasksNode[], options: LayoutOptions = {}): GraphLayout {
const cols = Math.max(1, options.maxBandCols ?? 4)
const stride = rowStrideFor(nodes)
const ids = new Set(nodes.map(node => node.id))
const roots = nodes.filter(node => node.parentId === undefined || !ids.has(node.parentId))
const childrenOf = new Map<string, TasksNode[]>()
@@ -171,7 +194,7 @@ export function layoutTasksGraph(nodes: readonly TasksNode[], options: LayoutOpt
boxes.set(node.id, {
id: node.id,
x: Math.round(centerX - GRAPH_NODE_W / 2),
y: GRAPH_PAD + row * GRAPH_ROW_STRIDE,
y: GRAPH_PAD + row * stride,
w: GRAPH_NODE_W,
h: nodeHeight(node),
})
@@ -206,7 +229,7 @@ export function layoutTasksGraph(nodes: readonly TasksNode[], options: LayoutOpt
const allBoxes = [...boxes.values()]
const width = Math.max(GRAPH_PAD * 2 + GRAPH_NODE_W, ...allBoxes.map(box => box.x + box.w + GRAPH_PAD))
const height = Math.max(GRAPH_PAD * 2 + GRAPH_NODE_H, ...allBoxes.map(box => box.y + box.h + GRAPH_PAD))
const height = Math.max(GRAPH_PAD * 2 + GRAPH_AGENT_NODE_H, ...allBoxes.map(box => box.y + box.h + GRAPH_PAD))
return { boxes, width, height }
}
+83
View File
@@ -239,6 +239,19 @@
color: var(--dsw-alias-label-secondary);
}
/* The identity chip (the node's mode word) rides the badge row: it is the same
word on every card of its kind, so a line of its own only repeated itself.
Plain ink, no border — the kind badge beside it owns the box. */
.kindChip {
flex: none;
max-width: 46%;
font: var(--dsw-font-xxxs-11);
color: var(--dsw-alias-label-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* The workflow phase badge: the SECOND grouping axis. It takes the ink family
(the level edge owns the accent family) so the two never read as one. */
.phaseBadge {
@@ -390,6 +403,32 @@
text-overflow: ellipsis;
}
/* The aggregate's bar is the ACTION row: the group's glyph, the word naming
what a click does, and the chevron. The count lives on the badge above, so
the bar carries the action instead — a lone chevron in an empty strip read
as a broken card. The failure tail keeps the error ink, because it is the
one fact the ✓ badge cannot say. */
.barFoldGlyph {
flex: none;
display: inline-flex;
align-items: center;
color: var(--dsw-alias-label-tertiary);
}
.barAction {
flex: 1;
min-width: 0;
color: var(--dsw-alias-state-business-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.barError {
flex: none;
color: var(--dsw-alias-state-error-primary);
}
.barFold {
flex: none;
display: inline-flex;
@@ -758,6 +797,7 @@
values and the body (secondary), the keys, group headers and hints
(tertiary). A card never paints a fourth rung. */
.popCard {
animation: dsh-pop-in 140ms cubic-bezier(0.2, 0.8, 0.3, 1);
display: flex;
flex-direction: column;
gap: 4px;
@@ -772,6 +812,18 @@
box-sizing: border-box;
}
@keyframes dsh-pop-in {
from { opacity: 0; transform: translateY(4px) scale(0.985); }
to { opacity: 1; transform: none; }
}
/* Motion is decoration: the card is fully usable without it. */
@media (prefers-reduced-motion: reduce) {
.popCard {
animation: none;
}
}
/* The head band. It is exactly one control tall (28px, the host's `sm`), so a
card with a head action and a card without one put their title on the SAME
line of the grid; the micro caps inside ride the middle of that band and
@@ -1034,6 +1086,37 @@
text-overflow: ellipsis;
}
/* The jump split of the detail card: the primary action keeps the row and the
caret beside it opens the main-window alternative — the same split the host's
own subagent jump control wears. The menu is positioned from the caret (the
card is the portal's content root, so nothing clips it) and dismisses on an
outside pointerdown via the host's own hook. */
.popFoot > .jumpMore {
position: relative;
flex: none;
display: inline-flex;
width: 28px;
}
.jumpMoreButton {
width: 100%;
padding: 0;
}
.jumpMenu {
position: absolute;
right: 0;
bottom: calc(100% + 6px);
z-index: 4;
min-width: 152px;
padding: 4px;
}
.jumpMenuItem {
width: 100%;
justify-content: flex-start;
}
/* The streamed text tail under it keeps the card's smallest voice, clamped to
two lines: the tail is capped at 400 characters upstream, which would
otherwise push the state rows out of the card. */
+43 -24
View File
@@ -33,6 +33,7 @@ import type { SidebarChildLiveView } from '../context-types.ts'
import type { WorkflowRunView } from '../workflow-runs.ts'
import { isSideThreadSummary } from './subagent-detect.ts'
import { childLive, isKnownLeaf, type SubagentCatalogView } from './subagent-catalog.ts'
import type { SessionMetrics } from './session-metrics.ts'
import type { TeamMemberRow } from './team-projection.ts'
/** Display state of one agent node (drives the dot + fold candidacy). */
@@ -65,6 +66,8 @@ export interface TasksAgentNode {
current: boolean
/** Live tail of a running child (the merged activity + newest text). */
live?: SidebarChildLiveView
/** Token usage + turn timing of the node's own session (see ./session-metrics.ts). */
metrics?: SessionMetrics
/** Team enrichment (roster row matched by session id). */
team?: {
role: 'lead' | 'teammate'
@@ -142,6 +145,13 @@ export interface TasksModelInput {
rootId: string
currentSessionId: string
live: Readonly<Record<string, SidebarChildLiveView | undefined>>
/**
* Per-session token usage and turn timing, keyed by session id (the same
* shape as {@link TasksModelInput.live}). Both are host projections, so a
* session the snapshot does not carry simply has no metrics and the popover
* hides the row.
*/
metrics?: Readonly<Record<string, SessionMetrics | undefined>>
runs: readonly WorkflowRunView[]
teamMembers: readonly TeamMemberRow[]
/** The team's shared tasks; each lands on its OWNER's node. */
@@ -161,8 +171,10 @@ export interface TasksModelInput {
* The fold GROUPS the reader expanded by clicking their aggregate card
* ({@link foldGroupId}). A group listed here shows its members while every
* other group stays folded — expanding one aggregate must never unfold the
* page. It is consulted only where a member would otherwise be folded, so
* the global rule and the manual per-node folds are untouched underneath.
* page. It is consulted only where a member would otherwise be folded, and it
* yields to {@link foldedIds}: folding one node back by hand is the reader's
* newest explicit intent, and a group that ignored it would leave that card's
* own chevron dead.
*/
expandedGroups?: ReadonlySet<string>
}
@@ -323,6 +335,7 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
byId, catalogs, rootId, currentSessionId, live, runs, teamMembers, folded, foldedIds,
} = input
const expandedGroups = input.expandedGroups
const metrics = input.metrics
const teamTasks = input.teamTasks ?? []
const teamById = new Map(teamMembers.map(member => [member.id, member]))
/** Owner display name → node id (the board assigns by member name). */
@@ -417,6 +430,7 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
activity,
current: entry.id === currentSessionId,
...(view !== undefined ? { live: view } : {}),
...(metrics?.[entry.id] !== undefined ? { metrics: metrics[entry.id] } : {}),
...(team !== undefined ? { team } : {}),
...(tasksByNode.get(entry.id) !== undefined ? { tasks: tasksByNode.get(entry.id) } : {}),
hasChildren: !isKnownLeaf(catalogs, entry.id),
@@ -466,6 +480,8 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
activity: member.outcome === undefined ? 'running' : 'inactive',
current: member.childId !== '' && member.childId === currentSessionId,
synthesized: true,
...(childKnown && metrics?.[member.childId] !== undefined
? { metrics: metrics[member.childId] } : {}),
...(childKnown && tasksByNode.get(member.childId) !== undefined
? { tasks: tasksByNode.get(member.childId) } : {}),
...(childKnown
@@ -482,12 +498,11 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
// Fold: this parent's non-executing children collapse into one aggregate
// PER GROUP — finished/failed work in one row, waiting members in another,
// so the badge can say what it holds and a reader can sweep one without
// the other. Three triggers, three guard sets: the page-level `folded` rule
// also spares branching nodes and (below the idle head count) teammates; a
// manual `foldedIds` fold is the reader asking for THAT node, so it only
// spares running/current work; and `expandedGroups` is the reader having
// opened ONE aggregate, which keeps that group's members out of the fold
// while every other group stays exactly as it was.
// the other. Three triggers, one precedence per member: a manual
// `foldedIds` fold always wins (the reader pointed at THAT node), the
// page-level `folded` rule decides next (sparing branching nodes and, below
// the idle head count, teammates), and `expandedGroups` only relaxes that
// rule for the one group the reader opened.
const idleMembers = visibleAgentChildren
.filter(child => child.state === 'idle' && child.team !== undefined).length
const foldIdleMembers = idleMembers >= FOLD_IDLE_MIN
@@ -502,12 +517,11 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
// therefore which expansion could have revealed it.
const group: TasksFoldKind = child.state === 'idle' ? 'idle' : 'done'
const expanded = expandedGroups?.has(foldGroupId(group, parentId)) === true
if ((!auto && !manual) || expanded) {
kept.push(child)
} else if (group === 'idle') {
idleFold.push(child)
if (manual || (auto && !expanded)) {
if (group === 'idle') idleFold.push(child)
else doneFold.push(child)
} else {
doneFold.push(child)
kept.push(child)
}
}
@@ -523,14 +537,15 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
out.push(runNode)
const members = memberNodes[index] ?? []
// The run's own members fold under the same triggers, the same two groups
// and the same per-group expansion. The AUTOMATIC trigger applies the same
// STRUCTURAL guards as the parent's children — a member is often a
// RE-PARENTED catalog node (a real directory with `hasChildren`, team
// enrichment and its own run), not the synthetic leaf this loop used to
// assume, and folding one hid its whole branch (issue #784). The roster
// guard does not apply here: the member is not a roster row of this
// parent, and the idle head count is a roster-scanning rule — run members
// keep their own container's rule.
// and the same precedence (manual fold, then the page-level rule, then
// the group expansion). The AUTOMATIC trigger applies the same STRUCTURAL
// guards as the parent's children — a member is often a RE-PARENTED
// catalog node (a real directory with `hasChildren`, team enrichment and
// its own run), not the synthetic leaf this loop used to assume, and
// folding one hid its whole branch (issue #784). The roster guard does
// not apply here: the member is not a roster row of this parent, and the
// idle head count is a roster-scanning rule — run members keep their own
// container's rule.
const keptMembers: TasksAgentNode[] = []
const runDone: TasksAgentNode[] = []
const runIdle: TasksAgentNode[] = []
@@ -540,9 +555,12 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
const manual = foldedIds?.has(member.id) === true && foldable
const group: TasksFoldKind = member.state === 'idle' ? 'idle' : 'done'
const expanded = expandedGroups?.has(foldGroupId(group, runNode.id)) === true
if ((!auto && !manual) || expanded) keptMembers.push(member)
else if (group === 'idle') runIdle.push(member)
else runDone.push(member)
if (manual || (auto && !expanded)) {
if (group === 'idle') runIdle.push(member)
else runDone.push(member)
} else {
keptMembers.push(member)
}
}
out.push(...keptMembers)
if (runDone.length > 0) out.push(foldNode('done', runNode.id, runNode.depth + 1, runDone))
@@ -570,6 +588,7 @@ export function buildTasksModel(input: TasksModelInput): TasksNode[] {
activity: rootSummary?.running === true ? 'running' : 'inactive',
current: rootId === currentSessionId,
...(rootLive !== undefined ? { live: rootLive } : {}),
...(metrics?.[rootId] !== undefined ? { metrics: metrics[rootId] } : {}),
...(rootTeam !== undefined ? { team: rootTeam } : {}),
...(tasksByNode.get(rootId) !== undefined ? { tasks: tasksByNode.get(rootId) } : {}),
})
+19 -10
View File
@@ -188,20 +188,29 @@ export function agentMeta(node: TasksAgentNode): string {
}
/**
* The CARD's mono meta line: WHO the node is, never its state.
* The identity CHIP of an agent card: the word that rides BESIDE the kind badge
* (一次性 / 可持续), or the one team state the badge cannot express (准备中 /
* 出错).
*
* The state belongs to the card's bottom bar (the state dot there, and the
* state word whenever no activity line takes its place), so repeating it here
* would print "已完成" twice inside one 190px card — the densest complaint the
* readability pass had to fix. The accessible name keeps {@link agentMeta}
* (state included), because a screen reader never sees the bar's dot.
* It is a chip and not a line of its own because the mode is the same word on
* every card of its kind: as a mono meta line it cost a 16px row to repeat
* itself, and the reader's report was exactly "模型一次性的子代理一直显示一次性".
* A plain teammate answers undefined — the badge already reads 成员 — and the
* root answers undefined too (its badge reads 主代理).
*
* The state stays out of it: the card's bottom bar carries it (its dot, and its
* word whenever no activity line takes that place), and the accessible name
* keeps {@link agentMeta} with the state included, because a screen reader
* never sees the bar's dot.
*/
export function agentIdentity(node: TasksAgentNode): string {
// The root's badge already reads 主代理: an identity line would repeat it.
if (node.parentId === undefined) return ''
export function agentChip(node: TasksAgentNode): string | undefined {
if (node.parentId === undefined) return undefined
const mode = modeLabel(node.mode)
if (mode !== undefined) return mode
return node.team === undefined ? '' : teamRoleLabel(node.team) ?? ''
if (node.team === undefined) return undefined
if (node.team.phase === 'provisioning') return t('tasksStateProvisioning')
if (node.team.phase === 'failed') return t('tasksStateError')
return undefined
}
/** The roster row's own identity word (the fallback for a modelless teammate). */
+42
View File
@@ -0,0 +1,42 @@
/**
* The Tasks page's motion host: `@formkit/auto-animate` (FLIP) attached through
* ONE guarded hook, so every animated container in the page behaves the same and
* the test / non-WAAPI environments stay inert.
*
* What it buys: cards animate in and out when a group folds or expands, siblings
* slide to their new slots, and a tree row / job row never pops. The library
* needs `Element.prototype.animate` (Web Animations API — the plugin already
* requires modern Chromium for the native sidebar) and a real layout pass, so
* the hook attaches to nothing when either is missing: jsdom renders the same
* DOM without motion, and no test has to stub an animation engine.
*
* The library respects `prefers-reduced-motion` on its own (its
* `disrespectUserMotionPreference` option defaults to false), which is the same
* contract the bar's sweep keeps in CSS.
*/
import autoAnimate from '@formkit/auto-animate'
import { useEffect, type RefObject } from 'react'
/** Whether this environment can run FLIP animations at all. */
function canAnimate(): boolean {
return typeof Element !== 'undefined'
&& typeof Element.prototype.animate === 'function'
&& typeof document !== 'undefined'
}
/**
* Animate one container's children.
*
* @param ref - the container whose DIRECT children are animated. Layout changes
* below the direct children (a card's own rows) are not animated — that is the
* library's own scope rule, and the page keeps one host per list it wants
* animated.
*/
export function useAutoAnimateRef<T extends HTMLElement>(ref: RefObject<T | null>): void {
useEffect(() => {
const element = ref.current
if (element === null || !canAnimate()) return
const controller = autoAnimate(element)
return () => { controller.destroy?.() }
}, [ref])
}
+32
View File
@@ -525,11 +525,43 @@ export interface SidebarProjectionSnapshot {
subagentCatalog?: readonly SidebarSubagentCatalogEntry[]
/** The Lead Session's team board (only the team's Lead carries one). */
agentTeam?: SidebarTeamProjection
/** Provider-reported token usage, accumulated over the session's log. */
tokenUsage?: SidebarTokenUsage
/** Turn timing of a descriptor-backed CHILD session (see ./session-metrics.ts). */
subagentTiming?: SidebarSubagentTiming
}
state: 'idle' | 'loading' | 'ready' | 'error'
error: { code?: string; message?: string } | null
}
/**
* The host's `tokenUsage` projection: provider-reported usage accumulated over
* the session's whole durable log, in four DISJOINT buckets (`uncachedInputTokens`
* is what the provider billed at full price; reasoning tokens are already inside
* `outputTokens`). It is a SESSION total, not a per-turn figure.
*/
export interface SidebarTokenUsage {
uncachedInputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
}
/**
* The host's `subagentTiming` projection: how long a descriptor-backed child
* session actually worked.
*
* Neither half is a session AGE. `settledMs` sums CLOSED turn durations and is
* 0 until the child's first `turn/end`; `active` exists only while an open turn
* is running, and a session with no `subagent/descriptor` — the topology ROOT,
* any ordinary session — never gets one at all.
*/
export interface SidebarSubagentTiming {
settledMs: number
/** The open turn: `since` = its `turn/start` time, `through` = the newest folded event. */
active?: { since: number; through: number }
}
/** One direct-child row of the host's `subagentCatalog` projection. */
export interface SidebarSubagentCatalogEntry {
/** Child session id (`childId` in the durable event). */
+67
View File
@@ -0,0 +1,67 @@
/**
* Unit tests for the Tasks page's per-session metrics (token usage + turn
* timing): the fold from the host's projection snapshot, the two totals the
* popover prints, and the rule that a session with no measurements reports
* nothing rather than a zero it cannot justify.
*/
import { describe, expect, it } from 'vitest'
import {
elapsedMs, inputTokens, sessionMetrics, totalTokens,
} from '../src/client/session-metrics.ts'
import type { SidebarProjectionSnapshot } from '../src/context-types.ts'
/** One projection row carrying the metric keys under test. */
function snapshot(values: SidebarProjectionSnapshot['values'], state: 'idle' | 'ready' = 'ready'): SidebarProjectionSnapshot {
return { values, state, error: null }
}
/** A usage row with the four disjoint buckets. */
const USAGE = {
uncachedInputTokens: 1_000,
outputTokens: 4_000,
cacheReadTokens: 20_000,
cacheWriteTokens: 500,
}
describe('sessionMetrics', () => {
it('folds the two metric keys per session and skips sessions without any', () => {
const metrics = sessionMetrics({
a: snapshot({ tokenUsage: USAGE }),
b: snapshot({ subagentTiming: { settledMs: 1_500 } }),
c: snapshot({ subagentCatalog: [] }),
d: snapshot({ tokenUsage: USAGE, subagentTiming: { settledMs: 0 } }),
})
expect(Object.keys(metrics).sort()).toEqual(['a', 'b', 'd'])
expect(metrics.a?.usage?.outputTokens).toBe(4_000)
expect(metrics.a?.timing).toBeUndefined()
expect(metrics.b?.usage).toBeUndefined()
expect(metrics.d?.timing?.settledMs).toBe(0)
})
it('answers an empty map for a host without the projection store', () => {
expect(sessionMetrics(undefined)).toEqual({})
})
it('sums the four DISJOINT buckets as the session total', () => {
expect(inputTokens(USAGE)).toBe(21_500)
expect(totalTokens(USAGE)).toBe(25_500)
})
})
describe('elapsedMs', () => {
it('counts closed turns plus the open one, measured to the caller’s clock', () => {
// `active.through` only advances when an event commits, so a running node's
// elapsed time is measured against the render clock, not `through`.
expect(elapsedMs({ settledMs: 1_000, active: { since: 10_000, through: 11_000 } }, 13_500))
.toBe(4_500)
expect(elapsedMs({ settledMs: 2_500 }, 99_999)).toBe(2_500)
})
it('reports nothing when the host published no timing, or none of it is work', () => {
// 0 is the projection's init state, indistinguishable from "never worked".
expect(elapsedMs(undefined, 1_000)).toBeUndefined()
expect(elapsedMs({ settledMs: 0 }, 1_000)).toBeUndefined()
// A clock that moved backwards must not print a negative duration.
expect(elapsedMs({ settledMs: 5, active: { since: 10_000, through: 10_000 } }, 9_000)).toBe(5)
})
})
+49 -18
View File
@@ -2,12 +2,14 @@
* Unit tests for the layered graph layout: parent centering, depth rows, the
* sibling-band WRAP that keeps a narrow sidebar readable (and the row
* reservation that stops a wrapped band from landing on a sibling's
* children), the PER-SHAPE card height (the live rows and the shared-task row
* a card renders are reserved, so a card never renders outside its box), and
* the width-aware solver.
* children), the PER-SHAPE card height (the mode chip's badge row and the
* shared-task row a card renders are reserved, so a card never renders outside
* its box), and the width-aware solver.
*/
import { describe, expect, it } from 'vitest'
import {
GRAPH_AGENT_NODE_H,
GRAPH_GAP_Y,
GRAPH_NODE_H,
GRAPH_NODE_W,
GRAPH_PAD,
@@ -16,6 +18,7 @@ import {
bandColsFor,
layoutTasksGraph,
layoutTasksGraphForWidth,
rowStrideFor,
} from '../src/client/tasks-graph-layout.ts'
import type { TasksAgentNode, TasksNode, TasksNodeTask } from '../src/client/tasks-model.ts'
@@ -47,11 +50,19 @@ const ACTIVITY = {
summary: { counts: [{ kind: 'read' as const, count: 1 }], running: 'read' as const, runningDetail: 'x' },
}
/** The row index of one laid-out node. */
function layoutRow(layout: ReturnType<typeof layoutTasksGraph>, id: string): number {
/**
* The row index of one laid-out node. The pitch is per MODEL now (a run card
* keeps its meta line, an agent card does not), so the helper asks the layout's
* own rule rather than the tallest constant.
*/
function layoutRow(
layout: ReturnType<typeof layoutTasksGraph>,
id: string,
nodes: readonly TasksNode[],
): number {
const box = layout.boxes.get(id)
if (box === undefined) throw new Error(`no box for ${id}`)
return (box.y - GRAPH_PAD) / GRAPH_ROW_STRIDE
return (box.y - GRAPH_PAD) / rowStrideFor(nodes)
}
describe('layout: card heights', () => {
@@ -63,16 +74,19 @@ describe('layout: card heights', () => {
]
const layout = layoutTasksGraph(nodes)
// The merged activity lives in the bar, which every card renders: a
// running node and a settled one reserve exactly the same base height.
expect(layout.boxes.get('root')?.h).toBe(GRAPH_NODE_H)
expect(layout.boxes.get('busy')?.h).toBe(GRAPH_NODE_H)
expect(layout.boxes.get('owner')?.h).toBe(GRAPH_NODE_H + GRAPH_TASK_H)
// running node and a settled one reserve exactly the same base height. The
// base is the AGENT card (badges + two title lines + the bar): the mode
// word moved into the badge row, so no card reserves a mono meta line —
// only a workflow RUN does (see the stride case below).
expect(layout.boxes.get('root')?.h).toBe(GRAPH_AGENT_NODE_H)
expect(layout.boxes.get('busy')?.h).toBe(GRAPH_AGENT_NODE_H)
expect(layout.boxes.get('owner')?.h).toBe(GRAPH_AGENT_NODE_H + GRAPH_TASK_H)
})
it('keeps every card shape inside one row stride', () => {
// The stride is the row pitch: a card taller than it would overlap the
// next row (and its phase frame).
const tallest = GRAPH_NODE_H + GRAPH_TASK_H
const tallest = GRAPH_AGENT_NODE_H + GRAPH_TASK_H
expect(GRAPH_ROW_STRIDE).toBeGreaterThanOrEqual(tallest)
const nodes: TasksNode[] = [
agent('root'),
@@ -80,6 +94,23 @@ describe('layout: card heights', () => {
]
const layout = layoutTasksGraph(nodes)
expect(layout.boxes.get('busiest')?.h).toBe(tallest)
// An agent-only model pitches its rows at the agent card; a model with a
// workflow run (the only card that keeps a meta line) pitches at the
// taller run card, so no card ever pokes into the row below.
const withRun: TasksNode[] = [
...nodes,
{
kind: 'workflow', id: 'run:r', parentId: 'root', depth: 1,
run: {
runId: 'r', name: 'audit', originSessionId: 'root', status: 'running',
phases: [], startedSeq: 1, startedAt: 0,
},
},
]
expect(rowStrideFor(nodes)).toBe(GRAPH_AGENT_NODE_H + GRAPH_GAP_Y)
expect(rowStrideFor(withRun)).toBe(GRAPH_NODE_H + GRAPH_GAP_Y)
// …and the run card itself is the card that needs the meta line.
expect(layoutTasksGraph(withRun).boxes.get('run:r')?.h).toBe(GRAPH_NODE_H)
})
it('gives every node a box even with a defensive orphan', () => {
@@ -94,9 +125,9 @@ describe('layout: card heights', () => {
for (let index = 0; index < 5; index += 1) nodes.push(agent(`c${index}`, 'root'))
const layout = layoutTasksGraph(nodes, { maxBandCols: 2 })
// Three wrapped rows of 2/2/1, never five on one line.
expect([layoutRow(layout, 'c0'), layoutRow(layout, 'c1')]).toEqual([1, 1])
expect([layoutRow(layout, 'c2'), layoutRow(layout, 'c3')]).toEqual([2, 2])
expect(layoutRow(layout, 'c4')).toBe(3)
expect([layoutRow(layout, 'c0', nodes), layoutRow(layout, 'c1', nodes)]).toEqual([1, 1])
expect([layoutRow(layout, 'c2', nodes), layoutRow(layout, 'c3', nodes)]).toEqual([2, 2])
expect(layoutRow(layout, 'c4', nodes)).toBe(3)
// The canvas stays as narrow as one wrapped band.
expect(layout.width).toBeLessThanOrEqual(2 * GRAPH_NODE_W + 28 + 2 * GRAPH_PAD)
})
@@ -109,8 +140,8 @@ describe('layout: card heights', () => {
agent('c', 'root'), agent('d', 'root'), agent('a1', 'a'),
]
const layout = layoutTasksGraph(nodes, { maxBandCols: 2 })
expect(layoutRow(layout, 'c')).toBeGreaterThan(layoutRow(layout, 'a1'))
expect(layoutRow(layout, 'd')).toBe(layoutRow(layout, 'c'))
expect(layoutRow(layout, 'c', nodes)).toBeGreaterThan(layoutRow(layout, 'a1', nodes))
expect(layoutRow(layout, 'd', nodes)).toBe(layoutRow(layout, 'c', nodes))
})
})
@@ -132,7 +163,7 @@ describe('bandColsFor / layoutTasksGraphForWidth', () => {
const wide = layoutTasksGraphForWidth(nodes, 720)
// Four 176px cards fit one band inside the floor budget at 720px, so the
// whole sibling set stays on one row.
expect(['c0', 'c1', 'c2', 'c3'].map(id => layoutRow(wide, id))).toEqual([1, 1, 1, 1])
expect(['c0', 'c1', 'c2', 'c3'].map(id => layoutRow(wide, id, nodes))).toEqual([1, 1, 1, 1])
expect(wide.width).toBeLessThanOrEqual(720 / 0.78)
})
@@ -145,6 +176,6 @@ describe('bandColsFor / layoutTasksGraphForWidth', () => {
// Never wider than the tolerant budget (a small pan is allowed, a 3x
// overflow is not), and never a one-child-per-row ladder.
expect(narrow.width).toBeLessThanOrEqual(((360 - 24) / 0.78) * 1.2)
expect(layoutRow(narrow, 'c1')).toBe(layoutRow(narrow, 'c0'))
expect(layoutRow(narrow, 'c1', nodes)).toBe(layoutRow(narrow, 'c0', nodes))
})
})
+14 -11
View File
@@ -390,18 +390,21 @@ describe('buildTasksModel', () => {
.toEqual(['fold:root', 'fold:root:idle'])
})
it('keeps a member released while its group is open, even with a stale manual fold', () => {
// `foldedIds` is a per-node request; the aggregate's click means "show me
// these now", so an open group wins over a hand-folded member the page has
// not finished dropping.
const model = buildTasksModel(input({
catalogs: { root: catalog([child('done-1')]) },
byId: { root: summary('root'), 'done-1': summary('done-1') },
folded: true,
foldedIds: new Set(['done-1']),
it('lets a hand-folded member fold back INSIDE an open group', () => {
// The card's own chevron is the newest explicit intent: with the group open
// it must still fold that one node back (the reader's "cannot collapse it
// again" report), and the aggregate then reappears holding it.
const base = input({
catalogs: { root: catalog([child('done-1'), child('done-2')]) },
byId: { root: summary('root'), 'done-1': summary('done-1'), 'done-2': summary('done-2') },
expandedGroups: new Set(['fold:root']),
}))
expect(model.map(node => node.id)).toEqual(['root', 'done-1'])
})
expect(buildTasksModel(base).map(node => node.id)).toEqual(['root', 'done-1', 'done-2'])
expect(buildTasksModel({ ...base, foldedIds: new Set(['done-1']) }).map(node => node.id))
.toEqual(['root', 'done-2', 'fold:root'])
expect(buildTasksModel({ ...base, foldedIds: new Set(['done-1']) })
.find(node => node.kind === 'fold'))
.toMatchObject({ id: 'fold:root', memberIds: ['done-1'] })
})
it('expands a RUN member group by its own aggregate id', () => {
+182 -4
View File
@@ -85,8 +85,19 @@ function makeJobsService() {
/** The jobs service the page reads (rebuilt per test in beforeEach). */
let jobsFake: ReturnType<typeof makeJobsService>
/**
* The host's native right column, as the page writes to it: the tab registry
* probe (`sidebarRightTabs.get`) plus the `openResource` write face. `undefined`
* models a deployment without `ui-subagent` — the transcript then has nowhere
* to open but the main window.
*/
interface AsideSpy {
opened: string[]
options: Array<{ kind?: string; preferNewPane?: boolean } | undefined>
}
/** The client context face SubagentView touches. */
function makeCtx(store: Store, navigation?: NavigationSpy): Context {
function makeCtx(store: Store, navigation?: NavigationSpy, aside?: AsideSpy): Context {
return {
sessions: {
list: store,
@@ -97,6 +108,19 @@ function makeCtx(store: Store, navigation?: NavigationSpy): Context {
if (name === 'uiWorkspace' && navigation !== undefined) {
return { openSession: (target: SidebarSubagentAddress | string) => { navigation.opened.push(target) } }
}
if (name === 'sidebarRightTabs' && aside !== undefined) {
// The page probes for the host's own `subagentchat` tab type before it
// writes; a host without it must not be called.
return { get: (kind: string) => (kind === 'subagentchat' ? { kind } : undefined) }
}
if (name === 'sidebarRight' && aside !== undefined) {
return {
openResource: (address: string, options?: { kind?: string; preferNewPane?: boolean }) => {
aside.opened.push(address)
aside.options.push(options)
},
}
}
return undefined
},
} as unknown as Context
@@ -960,9 +984,9 @@ describe('Tasks page: the shared task window', () => {
const aggregate = container.querySelector('[data-graph-node="fold:root:idle"]') as HTMLElement
expect(aggregate).not.toBeNull()
// The badge carries the REAL count (it used to print the literal copy "N"),
// and the bar does not print it a second time.
// and the bar carries the ACTION instead of repeating it.
expect(aggregate.querySelector('[data-card-kind="fold"]')?.textContent).toBe('3 个待命')
expect(aggregate.querySelector('[data-card-bar]')?.textContent).toBe('')
expect(aggregate.querySelector('[data-card-bar]')?.textContent).toBe('展开')
expect(aggregate.textContent).not.toContain('已完成')
// The finished group is a DIFFERENT row (empty here: nothing is done).
expect(container.querySelector('[data-graph-node="fold:root"]')).toBeNull()
@@ -1010,7 +1034,9 @@ describe('Tasks page: the shared task window', () => {
// same expand glyph the aggregate card's bar does.
const expandGlyph = glyph('button[aria-label="展开已完成的节点"]')
expect(expandGlyph).not.toBe('')
expect(glyph('[data-graph-node^="fold:"] [data-card-bar]')).toBe(expandGlyph)
// The aggregate's bar now opens with the GROUP glyph and closes with the
// expand chevron: the chevron is the cell that must match the cluster.
expect(glyph('[data-graph-node^="fold:"] [data-card-bar] > span:last-child')).toBe(expandGlyph)
// Unfold: the cards' own control COLLAPSES one node, and it must not share
// the expand glyph (the reader's report was that both looked identical).
@@ -1339,4 +1365,156 @@ describe('Tasks page: the node status line and per-group expansion', () => {
expect(aggregate.textContent).toContain('✓ 3 已完成')
unmount()
})
it('folds one member back from inside an open group (the card chevron stays live)', async () => {
// The reader's report: after opening an aggregate, clicking a card's own
// chevron did nothing. The manual fold is the newest intent and must beat
// the group's expansion, so the node returns to a NEW aggregate holding it
// while its siblings stay visible.
const store = makeStore(snapshotWithChildren(3))
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
)
await flushJobs()
await act(async () => {
(container.querySelector('[data-graph-node="fold:root"]') as HTMLElement).click()
})
expect(container.querySelector('[data-graph-node="child-0"]')).not.toBeNull()
expect(container.querySelector('[data-graph-node="fold:root"]')).toBeNull()
await act(async () => {
(container.querySelector(
'[data-graph-node="child-0"] button[aria-label="收进已完成聚合"]',
) as HTMLButtonElement).click()
})
expect(container.querySelector('[data-graph-node="child-0"]')).toBeNull()
expect(container.querySelector('[data-graph-node="child-1"]')).not.toBeNull()
const aggregate = container.querySelector('[data-graph-node="fold:root"]') as HTMLElement
expect(aggregate).not.toBeNull()
expect(aggregate.textContent).toContain('✓ 1 已完成')
unmount()
})
})
/**
* The detail window's two extra facts (token usage + turn timing) and the
* transcript jump: the child opens in the host's OWN right-sidebar tab by
* default, and the caret beside it offers the main window.
*/
describe('Tasks page: node metrics and the sidebar transcript jump', () => {
/** A snapshot whose child carries the host's metric projections. */
function snapshotWithMetrics(): SidebarSessionList {
const list = snapshotWithChildren(1)
Object.assign(list.projectionsBySession ?? {}, {
'child-0': {
values: {
subagentCatalog: [],
tokenUsage: {
uncachedInputTokens: 1_000, outputTokens: 4_000, cacheReadTokens: 20_000, cacheWriteTokens: 500,
},
subagentTiming: { settledMs: 162_000 },
},
state: 'ready',
error: null,
},
})
return list
}
/** Render, unfold the page and open the first child's detail window. */
async function openDetail(ctx: Context): Promise<{ unmount(): void, dialog: HTMLElement }> {
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx }),
)
await flushJobs()
await act(async () => {
(container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement).click()
})
await act(async () => {
(container.querySelector('[data-graph-node="child-0"]') as HTMLElement).click()
})
return { unmount, dialog: document.querySelector('[role="dialog"]') as HTMLElement }
}
it('shows what the node spent and how long it worked', async () => {
const { unmount, dialog } = await openDetail(makeCtx(makeStore(snapshotWithMetrics())))
// 25.5K total, formatted the page's own way (517 / 12.2K / 1.2M).
expect(dialog.textContent).toContain('Token 用量')
expect(dialog.textContent).toContain('25.5K')
// 162s = 2 分 42 秒, in the same shape (and copy) the job rows use.
expect(dialog.textContent).toContain('耗时')
expect(dialog.textContent).toContain('2 分 42 秒')
unmount()
})
it('hides both rows when the host published no measurements', async () => {
const { unmount, dialog } = await openDetail(makeCtx(makeStore(snapshotWithChildren(1))))
expect(dialog.textContent).not.toContain('Token 用量')
expect(dialog.textContent).not.toContain('耗时')
unmount()
})
it('opens the child transcript in the native sidebar, and the main window from the caret', async () => {
const navigation: NavigationSpy = { opened: [] }
const aside: AsideSpy = { opened: [], options: [] }
const { unmount, dialog } = await openDetail(makeCtx(makeStore(snapshotWithChildren(1)), navigation, aside))
// The primary action hands the child to the host's `subagentchat` tab: the
// address carries parent + mode, and the main column is left alone.
await act(async () => {
([...dialog.querySelectorAll('button')].find(button => button.textContent?.includes('查看转录')) as HTMLButtonElement).click()
})
expect(aside.opened).toEqual([
'dsh-resource://subagentchat/session/child-0?parent=root&mode=one-shot',
])
expect(aside.options[0]).toEqual({ kind: 'subagentchat', preferNewPane: true })
expect(navigation.opened).toEqual([])
// The caret opens the alternative: the main view, through the workspace
// face the shell owns (the old behavior).
const { dialog: second } = await openDetail(makeCtx(makeStore(snapshotWithChildren(1)), navigation, aside))
const caret = [...second.querySelectorAll('button')]
.find(button => button.getAttribute('aria-label') === '在主窗口中打开') as HTMLButtonElement
expect(caret).toBeDefined()
await act(async () => { caret.click() })
const item = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('在主窗口中打开')) as HTMLButtonElement
expect(item).toBeDefined()
await act(async () => { item.click() })
expect(navigation.opened).toEqual([
{ parentSessionId: 'root', childSessionId: 'child-0', mode: 'one-shot' },
])
unmount()
})
it('offers no sidebar alternative on a host without the subagent-chat tab', async () => {
const navigation: NavigationSpy = { opened: [] }
const { unmount, dialog } = await openDetail(makeCtx(makeStore(snapshotWithChildren(1)), navigation))
expect(dialog.querySelector('[aria-label="在主窗口中打开"]')).toBeNull()
await act(async () => {
([...dialog.querySelectorAll('button')].find(button => button.textContent?.includes('查看转录')) as HTMLButtonElement).click()
})
expect(navigation.opened).toEqual([
{ parentSessionId: 'root', childSessionId: 'child-0', mode: 'one-shot' },
])
unmount()
})
it('rides the node mode on the badge row instead of a mono meta line', async () => {
const { unmount, container } = (() => {
const rendered = renderRoot(createElement(SubagentView, {
sessionId: 'root', active: true, ctx: makeCtx(makeStore(snapshotWithChildren(1))),
}))
return rendered
})()
await flushJobs()
await act(async () => {
(container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement).click()
})
const card = container.querySelector('[data-graph-node="child-0"]') as HTMLElement
// The chip is a child of the badge row, not a row of its own.
const badges = card.querySelector('[data-card-kind="subagent"]')?.parentElement as HTMLElement
expect(badges.textContent).toBe('子代理一次性')
unmount()
})
})