From 909f536eabdbe48baae9e8ec3f70f0a0b561ab12 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 22 Oct 2026 22:25:07 -0700 Subject: [PATCH] feat(sidechat): render local images and present deliveries Cache markdown label objects by value so MarkdownText's memo survives parent re-renders; pass streaming for unsettled assistant rows. Rewrite local image destinations in Side Chat prose against the session cwd through the existing /sidebar/file media route. Map present tool calls and deliverables/presented events to a compact delivery card with thumbnails and the plugin's file-open path. Add the change spec, exploration notes, and regression tests. --- .../exploration.md | 64 ++++++ .../2026-10-22-sidechat-render-parity/spec.md | 164 ++++++++++++++ src/client/SideChatView.module.css | 86 ++++++++ src/client/SideChatView.tsx | 110 +++++++++- src/client/locales-ar.ts | 2 + src/client/locales-de.ts | 2 + src/client/locales-fr.ts | 2 + src/client/locales-hi.ts | 2 + src/client/locales-id.ts | 2 + src/client/locales-it.ts | 2 + src/client/locales-ja.ts | 2 + src/client/locales-ko.ts | 2 + src/client/locales-nl.ts | 2 + src/client/locales-pl.ts | 2 + src/client/locales-pt.ts | 2 + src/client/locales-ru.ts | 2 + src/client/locales-sv.ts | 2 + src/client/locales-th.ts | 2 + src/client/locales-tr.ts | 2 + src/client/locales-vi.ts | 2 + src/client/locales-zh-HK.ts | 2 + src/client/locales-zh-MO.ts | 2 + src/client/locales-zh-TW.ts | 2 + src/client/locales.ts | 4 + src/client/markdown-images.ts | 142 ++++++++---- src/client/markdown-labels.tsx | 70 ++++-- src/client/sidechat-transcript.ts | 99 +++++++++ tests/helpers/sidechat-view-harness.tsx | 206 ++++++++++++++++++ tests/sidechat-markdown-images.spec.tsx | 127 +++++++++++ tests/sidechat-markdown-labels.spec.tsx | 200 +++++++++++++++++ tests/sidechat-present-card.spec.tsx | 200 +++++++++++++++++ 31 files changed, 1449 insertions(+), 61 deletions(-) create mode 100644 docs/plans/2026-10-22-sidechat-render-parity/exploration.md create mode 100644 docs/plans/2026-10-22-sidechat-render-parity/spec.md create mode 100644 tests/helpers/sidechat-view-harness.tsx create mode 100644 tests/sidechat-markdown-images.spec.tsx create mode 100644 tests/sidechat-markdown-labels.spec.tsx create mode 100644 tests/sidechat-present-card.spec.tsx diff --git a/docs/plans/2026-10-22-sidechat-render-parity/exploration.md b/docs/plans/2026-10-22-sidechat-render-parity/exploration.md new file mode 100644 index 00000000..0b28cef8 --- /dev/null +++ b/docs/plans/2026-10-22-sidechat-render-parity/exploration.md @@ -0,0 +1,64 @@ +# 探索笔记 — Side Chat 渲染对齐与 Markdown 性能 + +快照于 `f418302`(2026-10-22),会过时;执行前按 spec 的代码地图重新核对。 + +## 审计来源 + +- 2026-10-22 的只读能力矩阵与性能基线由维护者留档;本文件只保留与实现直接相关的结论。 + +## 差距摘要 + +| 类别 | 主 Session | Side Chat | 结论 | +| --- | --- | --- | --- | +| 本地 Markdown 图片 | `` via `pathImages`/`fileImages` | alt text | 修(D2) | +| 远程图片 | `` + lightbox | `` 无 lightbox | 保持 | +| present/deliverables | toolview key `present` + turn-tail 卡 | 通用 tool 行 | 修(D3) | +| assistant/tool-result image block | gallery + attachment loader | reducer 丢弃 | 非目标(另案) | +| fileMentions、reasoning Markdown、max-tokens/cancel/retry | 有 | 无/纯文本 | 非目标 | +| GFM、代码卡、表格、KaTeX、footnotes、raw HTML、mermaid | 对齐 | 对齐 | 不动 | +| 性能 | windowed、labels memo | 无 windowing、labels 不稳定、无 streaming | 修(D1);windowing 另案 | + +**设计事实**:Side Chat 只显示 thread 自己的对话;继承父日志在 `session/end-seed` 处切掉。父 Session 的图片附件本来就不在 Side Chat 出现;composer 是纯 textarea,不支持图片输入。 + +## 测试 harness(sidechat-view) + +`tests/sidechat-view.spec.tsx` 已提供完整的真实组件 harness: +- `FakeLocale`(zh)、`EVENTS`(thread 自己的事件:user/turn/tool/assistant/turn-end)、`makeStore`/`makeConnection`、`FakeSocket`(阻止真实 WebSocket)、fetch stub(`sidechat.events`/`info` 等)。 +- 渲染:`renderRoot(createElement(SideChatView, ...))`;可直接在 `EVENTS` 里加 `tool/call` + `deliverables/presented`/local-image markdown 事件,断言 DOM。 +- 现有覆盖:bash TerminalBlock + turnSummary;disconnect banner;archive;queue/echo/model picker。 +- 相关:`tests/sidechat-transcript.spec.ts`(纯 mapping)、`tests/markdown-images.spec.ts`(`rewriteLocalImageUrls`)、`tests/markdown-crlf.spec.ts`(image+link rewrite 的 CRLF byte parity)、`tests/markdown-copy-labels.spec.tsx`(labels chrome)、`tests/test-utils.ts`(`renderRoot`/act)。 +- locale 一致性:`rg -l "locale" tests`(如 `tests/locales*.spec.ts`)钉住 key 覆盖;新增 present 卡片文案必须全量。 + +## 性能基线(jsdom,2026-10-22 审计) + +- 真实 `SideChatView`(100 turns = 200 markdown 组件): + - streaming push **101.7–117.8 ms** → labels 缓存原型 **3.3–3.8 ms**(~27–32×) + - composer keystroke **105.1–117.2 ms** → **3.5–3.9 ms** + - 100 组件 push 62.4 → 2.0 ms + - mount:100 组件 126 ms render/248 ms wall;200 组件 219–244 ms/428–470 ms;labels 缓存不改善 +- 隔离 harness(100% 长 prose 行):100 行 95.4→1.10 ms(~87×);200 行 190.6→1.36 ms(~140×);复现 v0.26 的 96.8 ms。 +- 未传 `streaming` 的增长行:8 KB 时 15.8 ms/update → 0.92 ms(streaming + stable labels,17×);labels 新鲜时 14.8 ms。 +- live payload:236 B/chunk;1000 chunks 236 KB;60 s 回答约 34 MB 累计重发(带宽/GC,非当前卡顿主因)。 +- 宿主主聊天 mounted-window:50/150/1000 行;Side Chat 无窗口化(另案)。 + +## 关键代码位置(快照,执行前复核) + +- `src/client/markdown-labels.tsx`:`markdownTextProps`(labels 对象;所有调用点)。 +- `src/client/SideChatView.tsx`:`renderRow`(MarkdownText)、`toolCardBody`、`rows`(useMemo)、composer、`MarkdownDelegateProvider`、`useMarkdownSurface`。 +- `src/client/sidechat-transcript.ts`:`blockText`、`transcriptRows`、`callCard`/`resultCard`/`SidechatToolCard`、事件 switch。 +- `src/client/markdown-images.ts`:`rewriteLocalImageUrls`、`resolveLocalMediaDest`、`normalizeLocalPath`。 +- `src/client/use-markdown-surface.ts`:`rewrite`(link-only)、`openFile`;`src/client/markdown-navigation.ts`(要求 image 先行)。 +- `src/client/sidebar-file.ts`:`openSidebarFile`(插件自己的文件打开路径)。 +- `/sidebar/file` 媒体路由:`src/index.ts`(约 1611-1669)/`src/sidechat-routes.ts`(会话 scoped)。 +- 主聊天 present:`packages/client/ui-deliverables/src/client/index.ts:83,106-110`(toolview key `present` → `PresentRow`;turn-tail deliverables)、`PresentedFileCard.tsx`、`Deliverables.tsx`;`deliverables/presented` 事件 `{turn, callId, files:[{path, description?}]}`(`packages/deliverables/tool-present`)。 +- 主聊天 image:`ui-chat/src/client/chat/AssistantMarkdown.tsx:132-158`、`MessageItem.tsx:20-40`、`UserContent.tsx:22-45`;loader `ui-chat/src/client/apply.ts:274-277`。 +- 宿主 MarkdownText:`ui-primitives/src/markdown/MarkdownText.tsx:174-196`(memo;labels/pathImages/fileMentions 词汇);`render.tsx:103-108,630-646`(非 http(s) 图片 → alt)。 + +## 实现注意 + +- 图片 rewrite:prose base 用 session cwd;先 mask 代码区域;绝对 `/sidebar/file` URL(`hostRouteUrl`)以保留反向代理前缀;不要改宿主渲染器。 +- present 卡片:数据来自 `deliverables/presented`(优先,绝对 path)或调用 args(相对 cwd);按 callId 去重;seed 事件过滤;图片缩略图走 `/sidebar/file`;点击 `openSidebarFile`;21 个 locale 加 key。 +- labels 缓存:模块级 Map,键为 `copyLabel/copiedLabel/codeLabel/wrapLabel/unwrapLabel` 值拼接;有界(locale 有限);不得用对象身份 WeakMap(调用方新建字面量)。 +- streaming:未 settled assistant 行 true,settled/静态 false;streaming 模式依赖 labels 稳定。 +- 测试:确定性断言(labels 引用、render-count、DOM);计时只作报告证据,不作为 CI gate。全量套件唯一允许的既有失败是本地 git 2.34.1 的 `tests/git.spec.ts` 环境用例(CI 覆盖真实环境)。 +- 浏览器:第二实例需独立 `DSH_HOME` 与 session DB;禁止触碰生产 3080 的进程/profile;plugin-mount lane 可复用。 diff --git a/docs/plans/2026-10-22-sidechat-render-parity/spec.md b/docs/plans/2026-10-22-sidechat-render-parity/spec.md new file mode 100644 index 00000000..0ec74ea3 --- /dev/null +++ b/docs/plans/2026-10-22-sidechat-render-parity/spec.md @@ -0,0 +1,164 @@ +--- +type: ChangeSpec +title: Side Chat 渲染对齐与 Markdown 性能 +description: 修 Side Chat 的本地 Markdown 图片、present/deliverables 卡片,并让 markdown labels 稳定、live 行走 streaming,消除每行全量重解析。 +status: active +--- + +# Side Chat 渲染对齐与 Markdown 性能 + +## 目标 + +Side Chat 是插件自建的 compact transcript,不是宿主 chat 的复用视图。它在三处落后于主 Session:本地 Markdown 图片只回退 alt 文本、image/file content block 在 reducer 被丢弃、`present` 工具没有 deliverables 卡片。同时,`markdownTextProps` 每次新建 labels 对象,打穿宿主 `MarkdownText` 的 `memo`,导致流式 push 与每次按键都重解析整个 transcript。 + +本 spec 的交付:Side Chat 的**本地 Markdown 图片**正常渲染;Side Chat 的**`present` 文件交付**有 compact 卡片;**markdown 渲染热路径**不再全量重解析,live 行走增量 `streaming`。不改变宿主、不改变会话格式、不增加新服务端路由。 + +## 契约层(durable) + +### 行为契约 + +**C1 — 本地 Markdown 图片(Side Chat prose)** +- 任何 Side Chat prose 行(user/assistant 的 Markdown 文本)中的本地图片目的地——相对路径(`./cat.png`、`cat.png`)、绝对本地路径、reference-style 定义——必须解析为可显示的图片,而不是 alt 文本。 +- 解析基准:当前会话的工作目录(session cwd);相对路径按该目录解析,绝对路径按原样。 +- 生成的媒体 URL 必须走插件已有的本地文件媒体路由(形如 `/sidebar/file?sessionId=…&path=…&cwd=…` 的绝对 http(s) URL),从而满足宿主 `MarkdownText` 的 http(s) allowlist;不得引入新的 host API 或新的公开路由。 +- 非本地目的地(http/https/data/mailto/锚点)保持不变;代码块与 inline code 中的图片语法不得被改写(复用现有代码区域 masking)。 +- 图片改写必须先于现有的本地链接改写执行;链接改写不得吞掉图片目的地。 +- 远程 http(s) 图片保持现有行为(渲染、无 lightbox)。 + +**C2 — `present` 交付卡片(Side Chat)** +- Side Chat 的 thread **自身**日志中出现 `present` 工具调用或 `deliverables/presented` 事件时,必须渲染一张 compact deliverables 卡片。 +- 卡片每个文件显示:文件类型图标、文件名(basename)、可选 description;图片文件额外显示缩略图(通过已有本地媒体路由);点击文件使用插件已有的 `openSidebarFile` 路径打开。 +- 文件数据来源优先级:`deliverables/presented` 事件(含绝对的 `files[].path` / `description`,以 `turn`/`callId` 关联)优先;事件尚未到达时使用 `present` 调用的参数(`files`,按 cwd 解析)。 +- 同一个 `present` 调用只出现一张卡片;事件到达时按 `callId` 附着/更新,不重复渲染。 +- 继承 seed 中的 `present`/deliverables 事件不得渲染(Side Chat 只显示 thread 自己的对话)。 +- 卡片文案必须走 locale 字典,不允许硬编码;新增 key 覆盖全部现有 locale,并通过 locale key 一致性测试。 +- 不新增服务端依赖/路由;不引入 `ui-deliverables` 等新的 host peer。 + +**C3 — Markdown 渲染热路径** +- `markdownTextProps(text, labels)` 对**相同 label 值**必须返回**同一个**嵌套 `labels` 对象引用(模块级、有界缓存);不同 label 值必须返回不同对象。 +- Side Chat 的未 settled assistant live 行必须向宿主 `MarkdownText` 传 `streaming={true}`;settled 行传 `false`/省略。 +- 父组件因流式 push 或 composer 按键重渲染时,未变化的行不得重新执行 `MarkdownText` 的解析(memo 必须命中);只有文本变化/新增的行重新解析。 +- 不改变宿主 `MarkdownText` 实现;标签缓存同时惠及插件其它 markdown 调用点(编辑器预览/diff/TaskWindow)。 + +**C4 — 兼容与安全** +- 仅客户端改动;不改变会话事件、`SESSION_FORMAT_VERSION`、sidechat 路由协议或 profile 配置。 +- 保持宿主 peer 基线 `^0.2.1-rc.1`;不新增依赖。 +- 文件读取只经现有会话 scoped 的 `/sidebar/file` 路由和 `openSidebarFile`;卡片/缩略图不得接受任意路径输入、不得绕过会话范围。 +- 现有 Side Chat 行为不回归:远程图片、本地文件链接、tool 行、reasoning/injection/error/turnSummary、pending/echo、push/poll。 + +### 交付物与验收 + +**D1 — Markdown labels 稳定 + streaming** +- 可观察结果:相同 label 值返回同一 labels 引用;未 settled assistant 行走 `streaming`;父组件重渲染时未变化行的 `MarkdownText` 解析次数为 0。 +- 验收: + - `pnpm vitest run tests/markdown-copy-labels.spec.tsx tests/sidechat-view.spec.tsx` 通过;新增的 labels identity / render-count 用例在旧实现上失败(TDD Red 证据)。 + - 真实 `SideChatView` 性能测量(jsdom,50/100/200 markdown 组件)记录 push/keystroke;200 组件目标 < 10ms(基线 101.7–117.8ms),数字写入交付报告。 +- 状态:`- [x]` + +**D2 — Side Chat 本地 Markdown 图片** +- 可观察结果:Side Chat 行中的 `![alt](./cat.png)`/绝对本地路径/reference image 渲染为 ``,src 为 `/sidebar/file?...` 绝对 URL;代码块中的示例不改写;http(s) 图片不变。 +- 验收: + - `pnpm vitest run tests/markdown-images.spec.ts tests/markdown-crlf.spec.ts tests/sidechat-view.spec.tsx` 通过;新增的局部图片 DOM 用例在旧实现上失败(Red)。 + - 浏览器验证:第二实例或 plugin-mount 场景中,Side Chat 行显示本地图片(截图证据)。 +- 状态:`- [x]` + +**D3 — Side Chat `present` 卡片** +- 可观察结果:thread 自身 `present` 调用/`deliverables/presented` 事件渲染 compact 卡片(文件名/描述/图标/图片缩略图/打开动作);seed 中事件不渲染;同一次调用不重复。 +- 验收: + - `pnpm vitest run tests/sidechat-transcript.spec.ts tests/sidechat-view.spec.tsx tests/locales.spec.ts`(或等价 locale 一致性测试)通过;新增 mapping/DOM 用例在旧实现上失败(Red)。 + - 浏览器验证:Side Chat 显示 present 卡片且点击可打开文件(截图证据)。 +- 状态:`- [x]` + +**D4 — 一次性测量与验证** +- 可观察结果:一次完整验证运行覆盖 D1–D3 的单元/jsdom、全量测试、类型、lint、build、浏览器 UI 与性能测量;记录命令与结果。 +- 验收(同一分支、同一轮执行): + - `pnpm run test`(全量;唯一允许的既有失败是本地 git 2.34.1 的 `tests/git.spec.ts` 环境用例,需在报告中标注;CI 覆盖真实环境)。 + - `pnpm run typecheck`、`pnpm run lint`、`pnpm run build` 全部通过。 + - 浏览器:第二实例(隔离 `DSH_HOME` + 独立 session DB)或 plugin-mount lane;打开含本地图片 + present 卡片的 Side Chat,记录截图/DOM 证据。 + - 性能:同一 jsdom 测量脚本在最终分支记录 50/100/200 行 push/keystroke,与审计基线对比。 +- 状态:`- [x]` + +### 明确非目标(Out of scope) + +- image/file **content block**(assistant/tool-result/legacy user)与 attachment loader:需要新的会话内授权 attachment 路由,另案。 +- Side Chat composer 的图片粘贴/上传/附件输入:独立功能。 +- fileMentions、reasoning body Markdown、max-tokens/cancelled/`llm/retry` 行。 +- 长 transcript 窗口化/虚拟化、live payload 游标。 +- 宿主仓库修改、生产部署/重启、上游 PR(需 owner 单独批准)。 + +### 已确认约束 + +- 基线分支 `upstream/dev`(PR #1035 已合入);单 PR(spec 默认),分支名 `fix/sidechat-render-parity`。 +- 仅插件仓库改动;§C4 的兼容/安全约束。 +- 前端变更必须浏览器验证(不能只靠 jsdom/代码审查)。 +- 测试不得用真实计时作为 CI gate;计时数字只作交付证据,确定性 gate 用 labels 引用/render-count。 +- 不硬编码 UI 文案;locale 全量覆盖。 +- 不在上游 PR/issue 发评论;上游 PR 与生产动作需 owner 批准。 + +### 关键决策 + +- **present 卡片插件侧实现**,不复用宿主 `ui-deliverables`:后者不是插件 peer,且 `PresentRow`/`Deliverables` 依赖 host chat 的 slot/chat-node owner 与 image loader,接入成本高于自绘 compact 卡片。 +- **图片采用 source rewrite**(复用 `rewriteLocalImageUrls`)而非 `pathImages` prop:现有 helper 已处理相对/绝对/reference/masking,且产出绝对 `/sidebar/file` URL,无需给共享 `MarkdownText` 传新词汇;prose 以 cwd 为 base。 +- **labels 按值缓存**(不动调用点、惠及所有 markdown 面),而不是把 labels 提升到每个调用方。 +- **streaming 依据行的 settled 状态**:只有未 settled 的 assistant live 行传 true;settled/静态行保持 false。 +- **一次性测量**:确定性测试 + 一次浏览器 e2e + 一次性能测量,都在最终分支同一轮完成,不拆多轮。 + +## 上下文层(volatile snapshot) + +**快照于 `f418302`(upstream/dev,2026-10-22)**,声明会过时;执行前重新核对代码与依赖。 + +### 基线与工作区 + +- 插件仓库:`/data/user/nolanho/code/DSH-better-sidebar`;本 worktree `/.worktrees/sidechat-render`,分支 `fix/sidechat-render-parity`,基于 `f418302`(PR #1035 已合入)。 +- 宿主:`/root/dsh-web/app` 的 DSH 0.2.1-rc.2 线;插件 peer 基线 `^0.2.1-rc.1`。 +- 依赖:worktree 已 `pnpm install --frozen-lockfile`(0.2.1-rc.1 devDeps;注意主 checkout 的 node_modules 是旧的 0.1.7-rc.1)。 +- 审计证据:2026-10-22 的只读能力矩阵与性能基线由维护者留档;本 spec 的验证证据见文末。 + +### 当前实现证据(file:line 快照) + +- 本地图片:`src/client/markdown-labels.tsx:37-52`(无 pathImages);`src/client/SideChatView.tsx:1254`(provider 无 fileImages);宿主 `ui-primitives/src/markdown/render.tsx:103-108,630-646`(非 http(s) → alt);`src/client/markdown-images.ts:102-139`(已有 rewrite,仅编辑器预览用);`src/client/use-markdown-surface.ts:125-128`(rewrite 仅链接);`src/client/markdown-navigation.ts:336-339`(要求 image rewrite 先行)。 +- content block 丢弃:`src/client/sidechat-transcript.ts:110-121`(blockText 只 text)、`:442-468`(user)、`:515-525`(assistant)、`:163-190`(tool result);主聊天 image 路径 `ui-chat/src/client/chat/MessageItem.tsx:20-40`、`UserContent.tsx:22-45`、`AssistantMarkdown.tsx:132-158`、`ui-chat/src/client/apply.ts:274-277`。 +- present:宿主 `packages/client/ui-deliverables/src/client/index.ts:83`(`tool.call.toolview` key `present` → `PresentRow`)、`:106-110`(turn-tail deliverables);插件 `sidechat-transcript.ts:218-302`(callCard/resultCard 仅 bash/edit/write/read)、`SideChatView.tsx:428-467`(toolCardBody)、`sidechat-transcript.ts:402-580`(无 `deliverables/presented` case)。 +- 性能:`src/client/markdown-labels.tsx:37-52`(每次新嵌套 labels);`SideChatView.tsx:636`(composer state 与 rows 同组件)、`:1255`(rows.map 无 memo 边界)、`:890-910`(rows useMemo);宿主 `ui-primitives/src/markdown/MarkdownText.tsx:174-196`(memo + useMemo deps labels);`src/client/sidechat-push.ts:29-31`(250ms/60ms 合并);主聊天 mounted-window `ui-chat/src/client/chat/fork/mounted-window.ts`。 + +### 代码地图(供执行者核对) + +- Side Chat:`src/client/SideChatView.tsx`(renderRow、toolCardBody、composer、rows)、`src/client/sidechat-transcript.ts`(transcriptRows、blockText、cards)、`src/client/markdown-labels.tsx`、`src/client/markdown-images.ts`、`src/client/use-markdown-surface.ts`、`src/client/markdown-navigation.ts`。 +- 媒体/打开:`src/index.ts`/`src/sidechat-routes.ts` 的 `/sidebar/file` 与 `openSidebarFile`(`src/client/sidebar-file.ts`);`src/client/api.ts` 的 hostRouteUrl/mediaUrl。 +- 测试:`tests/sidechat-view.spec.tsx`、`tests/sidechat-transcript.spec.ts`、`tests/markdown-images.spec.ts`、`tests/markdown-crlf.spec.ts`、`tests/markdown-copy-labels.spec.tsx`、`tests/test-utils.ts`、locale 测试(`rg -l "locale" tests`)。 +- 颜色/布局:`SideChatView.module.css`;工具行/卡片沿用现有 `css.sidechatRow*`。 +- 构建/门禁:`package.json` scripts(`test`/`typecheck`/`lint`/`build`/`test:mount`);CI `.github/workflows/ci.yml` 的 plugin-mount lane。 + +### 探索笔记 + +- `exploration.md`(同目录):根因、测试 harness 细节、性能基线数字。 + +### 风险与回归基线 + +- labels 缓存必须按值且**有界**;locale 数量有限,键为五个 label 值拼接。 +- streaming 与 labels 缓存有依赖:streaming 模式依赖 labels 稳定;只加 streaming 不加缓存会回退到全量解析。 +- 图片 rewrite 与链接 rewrite 顺序:image 先行;代码区域 masking 必须保留;CRLF/byte parity 由既有 `markdown-crlf.spec.ts` 覆盖。 +- present 事件可能先于/后于 call 到达;seed 中事件必须过滤(现有 `threadOwnLogEvents` 已切 seed;transcript 再按 `seedEnd` 过滤)。 +- locale 新增 key 必须全量;否则 locale 一致性测试失败。 +- 浏览器 e2e 需要第二实例/隔离 DB;禁止触碰生产 3080 进程/profile。 + +## 验证证据(2026-10-22,worktree 分支 `fix/sidechat-render-parity`) + +- **聚焦**:新增 3 个 spec(10 tests)全绿;既有 6 个相关 spec(94 tests)全绿;`tsc --noEmit`、`eslint .` 干净。 +- **全量**:`vitest run` 221 文件通过 / 1 失败(`tests/git.spec.ts` 的 2.34.1 环境用例,基线同失败,spec 允许)/ 2 跳过;2683 tests 通过。 +- **构建**:`pnpm run build` + `pnpm pack` 成功(tarball 4.6 MB)。 +- **浏览器 e2e(第二实例,宿主 0.2.1-rc.2,独立 DSH_HOME + JSONL session store + 确定性 Messages mock)**: + - `present` 卡片渲染 `Present files` + `README.md`/`Render-check document` + `running-whale@2x.png`/`Render-check image`,图片缩略图 28×28; + - assistant 文本的本地 Markdown 图片渲染为 `/sidebar/file` 的 ``(alt `whale`,`naturalWidth=28`); + - 点击卡片文件在插件编辑器打开 `README.md`; + - 浏览器截图由维护者留档(仓库外);确定性 mock 脚本见验收记录。 +- **性能(jsdom,真实 `SideChatView`,修复后 worktree)**:200 markdown 组件 push 3.60 ms / keystroke 5.37 ms(审计基线 101.7–117.8 / 105.1–117.2 ms,约 20–30×);100 组件 2.24 / 3.40 ms;50 组件 1.93 / 1.38 ms;隔离 100 行 0.71 ms、200 行 1.39 ms;labels 引用相等;未变化行的 `MarkdownText` 执行数为 0;8 KB 增长行 22.0 ms(settled)→ 1.01 ms(streaming)。 +- **plugin-mount lane(本地,非基线宿主 0.2.1-rc.2)**:12 passed / 3 skipped / 1 failed;失败点是 `tests/e2e/mount.e2e.ts` 的 `hostRpc session.list` 参数描述符(0.2.1-rc.2 要求 `request`,仓库 CI 基线 0.2.1-rc.1),不是插件渲染;sidechat tab/view 在 sweep 与 perf e2e 中已加载。CI 基线宿主上该 lane 不受影响。 + +### 交付状态 + +- D1 `- [x]`;D2 `- [x]`;D3 `- [x]`;D4 `- [x]`(PR / 生产为 owner 门)。 + +### 待解决 + +- 无(范围、present 实现方式、图片 rewrite、测量口径均已定;上游 PR/生产为 owner 门,不阻塞实现)。 diff --git a/src/client/SideChatView.module.css b/src/client/SideChatView.module.css index 087bc4a1..8f5e9c27 100644 --- a/src/client/SideChatView.module.css +++ b/src/client/SideChatView.module.css @@ -378,6 +378,92 @@ user-select: none; } +/* ── present deliverables card ──────────────────────────────────────── + * One card per `present` call (or per event-only delivery), one row per + * delivered file: image thumbnail (through the media route) or type glyph, + * basename, optional description, and a click that opens the file. The + * quietest possible surface — a hairline box around ink-weight rows: the + * main pane's delivery card at side-chat scale. */ +.sidechatDeliverables { + align-self: stretch; + display: flex; + flex-direction: column; + gap: 4px; + padding: 6px 8px; + border: 1px solid var(--dsw-alias-hairline); + border-radius: 8px; +} + +.sidechatDeliverablesHead { + font: var(--dsw-font-xxs-12); + color: var(--dsw-alias-label-tertiary); + user-select: none; +} + +.sidechatDeliverablesList { + display: flex; + flex-direction: column; + gap: 2px; + margin: 0; + padding: 0; + list-style: none; +} + +.sidechatDeliverableItem { + min-width: 0; +} + +.sidechatDeliverable { + display: flex; + align-items: center; + gap: 6px; + width: 100%; + min-width: 0; + padding: 3px 4px; + border: none; + border-radius: 6px; + background: transparent; + font: var(--dsw-font-xxs-12); + color: var(--dsw-alias-label-secondary); + text-align: left; + cursor: pointer; + transition: background-color 100ms ease-out, color 100ms ease-out; +} + +.sidechatDeliverable:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +/* An image deliverable leads with its own pixels, so the reader recognizes + * the artifact before reading the name. */ +.sidechatDeliverableThumb { + flex: none; + width: 28px; + height: 28px; + border-radius: 4px; + object-fit: cover; + background: var(--dsw-alias-bg-base); +} + +.sidechatDeliverableName { + flex: none; + max-width: 55%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--dsw-alias-label-primary); +} + +.sidechatDeliverableDesc { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--dsw-alias-label-tertiary); +} + /* Shimmer sweep text: generating (streaming row labels, creating hero). */ .sidechatShimmerText { background-image: linear-gradient( diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 42ff2384..90300b3f 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -37,6 +37,7 @@ import clsx from 'clsx' import { ConnectionIndicator, DiffBlock, + FileTypeIcon, IconApiOutlineRegular, IconArchiveOutlineRegular, IconBrowseOutlineRegular, @@ -56,12 +57,17 @@ import { StateDot, TerminalBlock, Tooltip, + classifyFileType, type DiffBlockLabels, type MenuEntry, type ReadBlockLabels, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import { markdownTextProps } from './markdown-labels.tsx' +import { rewriteProseLocalImageUrls } from './markdown-images.ts' +import { hostTransportBase } from './desktop-env.ts' +import { baseName } from './paths.ts' +import { openSidebarFile } from './sidebar-file.ts' import { useMarkdownSurface } from './use-markdown-surface.ts' import { IconHistoryOutline16, IconSaveOutline16 } from './icons.tsx' import type { Context, SidebarHistoryEntry, SidebarSessionEvent } from '../context-types.ts' @@ -86,7 +92,7 @@ import { type SidechatToolCard, type SidechatTranscriptRow, } from './sidechat-transcript.ts' -import { api } from './api.ts' +import { api, mediaUrl } from './api.ts' import { usePolling } from './use-polling.ts' import { useSidechatPush } from './use-sidechat-push.ts' import { t } from './locales.ts' @@ -469,21 +475,38 @@ function toolLeading(name: string, failed: boolean): React.ReactNode { } } -/** One row renderer (React keys ride the source event seq). `rewrite` is the - * surface's markdown link pass — the rows are model prose, so a relative link - * resolves against the session cwd (see use-markdown-surface). */ -function renderRow(row: SidechatTranscriptRow, labels: RowLabels, rewrite: (text: string) => string): React.ReactNode { +/** The per-view helpers every row renderer needs, collected in one stable + * object so a row body never rebuilds them per render. */ +interface RowSurface { + /** The row's prose pass: local image destinations become session media URLs + * first, then the surface's local-link pass runs (see the view's wiring). */ + rewrite: (text: string) => string + /** Open one delivered file through the plugin's own open path. */ + openFile: (path: string) => void + /** The session-scoped media URL of one image deliverable. */ + media: (path: string) => string +} + +/** One row renderer (React keys ride the source event seq). `surface` is the + * markdown prose pass the rows run before rendering — the rows are model + * prose, so a relative destination resolves against the session cwd (see + * use-markdown-surface) — plus the delivered-file open and media helpers. */ +function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSurface): React.ReactNode { switch (row.kind) { case 'user': return (
- +
) case 'assistant': return (
- + {/* `streaming` keeps the host's incremental parse across chunks + instead of restarting it; only the durable (settled) message is + the final parse. It rides the row's own flag so a superseded + live row never claims to be settled. */} +
) case 'reasoning': @@ -525,6 +548,43 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, rewrite: (text ) } + case 'deliverables': { + if (row.files.length === 0) return null + return ( +
+
{t('sideChatDeliverables')}
+ +
+ ) + } case 'tool': { const body = row.card !== undefined ? toolCardBody(row.card, row.executing === true, labels) @@ -658,11 +718,43 @@ export function SideChatView(props: { /** Heading slugs, anchor jumps and `.md` link claiming for the transcript (a * prose surface: it renders no file of its own, so a relative link target * resolves against the session cwd). */ - const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatText } = useMarkdownSurface({ + const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatLinks } = useMarkdownSurface({ ctx, sessionId: scope.sessionId, cwd: scope.cwd, }) + /** + * The prose pass every row runs before rendering: LOCAL image destinations + * become absolute `/sidebar/file` media URLs FIRST (the host renderer only + * draws absolute http(s) image sources, and a row is not a file, so relative + * destinations resolve against the session cwd), and the surface's local-link + * pass runs second — it must never see a raw image destination (see + * markdown-navigation.ts). Both passes mask code regions, so a fenced + * example stays literal. + */ + const rewriteChatText = useCallback( + (text: string): string => rewriteChatLinks( + rewriteProseLocalImageUrls(text, scope, scope.cwd, hostTransportBase()), + ), + [rewriteChatLinks, scope], + ) + /** Open one delivered file: the plugin's own editor path, session-scoped + * like every other open in this view (a relative path resolves against the + * session cwd). */ + const openDeliveredFile = useCallback((path: string): void => { + try { + openSidebarFile(ctx, scope.sessionId, path) + } catch (error) { + console.error('[dsh-better-sidebar] side chat deliverable open failed', error) + } + }, [ctx, scope.sessionId]) + /** The session-scoped media URL of one image deliverable (the card's + * thumbnail; the same route the markdown image pass produces). */ + const deliverableMediaUrl = useCallback((path: string): string => mediaUrl(scope, path), [scope]) + const rowSurface = useMemo( + () => ({ rewrite: rewriteChatText, openFile: openDeliveredFile, media: deliverableMediaUrl }), + [rewriteChatText, openDeliveredFile, deliverableMediaUrl], + ) const transcriptRef = useCallback((element: HTMLDivElement | null) => { scrollRef.current = element chatSurfaceRef(element) @@ -1252,7 +1344,7 @@ export function SideChatView(props: { clickable at all (see use-markdown-surface), scoped to this transcript so nothing outside it is claimed. */} - {rows.map(row => renderRow(row, rowLabels, rewriteChatText))} + {rows.map(row => renderRow(row, rowLabels, rowSurface))} {/* The unclaimed inbox: accepted messages whose claim has not logged them yet. The same bubble surface (and markdown pass) as a durable user row, plus the state word and the dequeue button. */} diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index 4a8350bf..fae3b4cc 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -440,6 +440,8 @@ export const ar: Record = { sideChatCancelTitle: 'إلغاء الدور الجاري (يُحتفظ بالعمل في قائمة الانتظار)', sideChatError: 'خطأ في المحادثة الجانبية: {message}', sideChatTurnUsage: 'إدخال {input} توكن · إخراج {output} توكن', + sideChatDeliverables: 'الملفات المسلَّمة', + sideChatDeliverableOpen: 'فتح {name}', sideChatBlockCollapse: 'طي', sideChatBlockCollapseAria: 'طي', sideChatBlockExpand: 'توسيع {hidden} أسطر', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index 7ea981f1..4d6862be 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -425,6 +425,8 @@ export const de: Record = { sideChatCancelTitle: 'Laufende Runde abbrechen (wartende Nachrichten bleiben erhalten)', sideChatError: 'Seitenchat-Fehler: {message}', sideChatTurnUsage: 'Eingabe {input} tok · Ausgabe {output} tok', + sideChatDeliverables: 'Gelieferte Dateien', + sideChatDeliverableOpen: '{name} öffnen', sideChatBlockCollapse: 'Einklappen', sideChatBlockCollapseAria: 'Einklappen', sideChatBlockExpand: '{hidden} Zeilen ausklappen', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index ab322e4e..ced68d61 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -432,6 +432,8 @@ export const fr: Record = { sideChatCancelTitle: 'Interrompre le tour en cours (la file d’attente est conservée)', sideChatError: 'Erreur de la discussion latérale : {message}', sideChatTurnUsage: 'Entrée {input} tok · Sortie {output} tok', + sideChatDeliverables: 'Fichiers livrés', + sideChatDeliverableOpen: 'Ouvrir {name}', sideChatBlockCollapse: 'Réduire', sideChatBlockCollapseAria: 'Réduire', sideChatBlockExpand: 'Déplier {hidden} lignes', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index bfd69d66..121a9cf8 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -439,6 +439,8 @@ export const hi: Record = { sideChatCancelTitle: 'चल रहे टर्न को रोकें (कतारबद्ध कार्य रखा जाता है)', sideChatError: 'साइड चैट त्रुटि: {message}', sideChatTurnUsage: 'इनपुट {input} टोकन · आउटपुट {output} टोकन', + sideChatDeliverables: 'सौंपी गई फ़ाइलें', + sideChatDeliverableOpen: '{name} खोलें', sideChatBlockCollapse: 'सिकोड़ें', sideChatBlockCollapseAria: 'सिकोड़ें', sideChatBlockExpand: '{hidden} पंक्तियाँ विस्तृत करें', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 4cdc7046..019a043d 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -437,6 +437,8 @@ export const id: Record = { sideChatCancelTitle: 'Batalkan giliran yang berjalan (pekerjaan antrean dipertahankan)', sideChatError: 'Kesalahan Side Chat: {message}', sideChatTurnUsage: 'Input {input} tok · Output {output} tok', + sideChatDeliverables: 'Berkas yang diserahkan', + sideChatDeliverableOpen: 'Buka {name}', sideChatBlockCollapse: 'Lipat', sideChatBlockCollapseAria: 'Lipat', sideChatBlockExpand: 'Perlihatkan {hidden} baris', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index d48b7020..86dec0ee 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -430,6 +430,8 @@ export const it: Record = { sideChatCancelTitle: 'Interrompe il turno in corso (il lavoro in coda è conservato)', sideChatError: 'Errore della chat laterale: {message}', sideChatTurnUsage: 'Input {input} tok · Output {output} tok', + sideChatDeliverables: 'File consegnati', + sideChatDeliverableOpen: 'Apri {name}', sideChatBlockCollapse: 'Comprimi', sideChatBlockCollapseAria: 'Comprimi', sideChatBlockExpand: 'Espandi {hidden} righe', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 3ab38788..0a52de4a 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -439,6 +439,8 @@ export const ja: Record = { sideChatCancelTitle: '現在のターンを中止(キューは保持)', sideChatError: 'サイド会話エラー:{message}', sideChatTurnUsage: '入力 {input} tok · 出力 {output} tok', + sideChatDeliverables: '納品ファイル', + sideChatDeliverableOpen: '{name} を開く', sideChatBlockCollapse: '折りたたむ', sideChatBlockCollapseAria: '折りたたむ', sideChatBlockExpand: '{hidden} 行を展開', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index 3e783706..ca6a98a4 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -431,6 +431,8 @@ export const ko: Record = { sideChatCancelTitle: '현재 턴 중단(대기열 유지)', sideChatError: '사이드 대화 오류: {message}', sideChatTurnUsage: '입력 {input} tok · 출력 {output} tok', + sideChatDeliverables: '전달된 파일', + sideChatDeliverableOpen: '{name} 열기', sideChatBlockCollapse: '접기', sideChatBlockCollapseAria: '접기', sideChatBlockExpand: '{hidden}줄 펼치기', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 09c3a6c9..826b05cd 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -437,6 +437,8 @@ export const nl: Record = { sideChatCancelTitle: 'De lopende beurt afbreken (wachtrij blijft behouden)', sideChatError: 'Side Chat-fout: {message}', sideChatTurnUsage: 'Invoer {input} tok · Uitvoer {output} tok', + sideChatDeliverables: 'Opgeleverde bestanden', + sideChatDeliverableOpen: '{name} openen', sideChatBlockCollapse: 'Invouwen', sideChatBlockCollapseAria: 'Invouwen', sideChatBlockExpand: '{hidden} regels uitvouwen', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index f81886d2..99ff0f01 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -441,6 +441,8 @@ export const pl: Record = { sideChatCancelTitle: 'Przerwij bieżącą turę (kolejka jest zachowana)', sideChatError: 'Błąd czatu bocznego: {message}', sideChatTurnUsage: 'Wejście {input} tok · Wyjście {output} tok', + sideChatDeliverables: 'Przekazane pliki', + sideChatDeliverableOpen: 'Otwórz {name}', sideChatBlockCollapse: 'Zwiń', sideChatBlockCollapseAria: 'Zwiń', sideChatBlockExpand: 'Rozwiń {hidden} wierszy', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index 1e96a8fd..94d8fe66 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -422,6 +422,8 @@ export const pt: Record = { sideChatCancelTitle: 'Abortar o turno em execução (o trabalho na fila é mantido)', sideChatError: 'Erro no chat lateral: {message}', sideChatTurnUsage: 'Entrada {input} tok · Saída {output} tok', + sideChatDeliverables: 'Arquivos entregues', + sideChatDeliverableOpen: 'Abrir {name}', sideChatBlockCollapse: 'Recolher', sideChatBlockCollapseAria: 'Recolher', sideChatBlockExpand: 'Expandir {hidden} linhas', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 4cbd7baf..dbc67125 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -437,6 +437,8 @@ export const ru: Record = { sideChatCancelTitle: 'Прервать текущий ход (очередь сохраняется)', sideChatError: 'Ошибка бокового чата: {message}', sideChatTurnUsage: 'Вход {input} tok · Выход {output} tok', + sideChatDeliverables: 'Переданные файлы', + sideChatDeliverableOpen: 'Открыть {name}', sideChatBlockCollapse: 'Свернуть', sideChatBlockCollapseAria: 'Свернуть', sideChatBlockExpand: 'Развернуть {hidden} строк', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index bcb98c28..6f60df87 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -422,6 +422,8 @@ export const sv: Record = { sideChatCancelTitle: 'Avbryt den pågående vändan (köat arbete behålls)', sideChatError: 'Sidochattsfel: {message}', sideChatTurnUsage: 'In {input} tok · Ut {output} tok', + sideChatDeliverables: 'Levererade filer', + sideChatDeliverableOpen: 'Öppna {name}', sideChatBlockCollapse: 'Fäll ihop', sideChatBlockCollapseAria: 'Fäll ihop', sideChatBlockExpand: 'Visa {hidden} rader', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index 88dffaaf..c89ad337 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -439,6 +439,8 @@ export const th: Record = { sideChatCancelTitle: 'ยกเลิกการทำงานรอบปัจจุบัน (งานในคิวยังคงอยู่)', sideChatError: 'ข้อผิดพลาดแชทด้านข้าง: {message}', sideChatTurnUsage: 'อินพุต {input} tok · เอาต์พุต {output} tok', + sideChatDeliverables: 'ไฟล์ที่ส่งมอบ', + sideChatDeliverableOpen: 'เปิด {name}', sideChatBlockCollapse: 'ย่อ', sideChatBlockCollapseAria: 'ย่อ', sideChatBlockExpand: 'ขยาย {hidden} บรรทัด', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index 14db2224..9b86953e 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -439,6 +439,8 @@ export const tr: Record = { sideChatCancelTitle: 'Geçerli turu durdur (sıradaki iş korunur)', sideChatError: 'Yan sohbet hatası: {message}', sideChatTurnUsage: 'Giriş {input} tok · Çıkış {output} tok', + sideChatDeliverables: 'Teslim edilen dosyalar', + sideChatDeliverableOpen: '{name} dosyasını aç', sideChatBlockCollapse: 'Daralt', sideChatBlockCollapseAria: 'Daralt', sideChatBlockExpand: '{hidden} satırı genişlet', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 20d74210..22c2e1b7 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -439,6 +439,8 @@ export const vi: Record = { sideChatCancelTitle: 'Hủy vòng hiện tại (giữ hàng đợi)', sideChatError: 'Lỗi chat bên: {message}', sideChatTurnUsage: 'Vào {input} tok · Ra {output} tok', + sideChatDeliverables: 'Tệp đã bàn giao', + sideChatDeliverableOpen: 'Mở {name}', sideChatBlockCollapse: 'Thu gọn', sideChatBlockCollapseAria: 'Thu gọn', sideChatBlockExpand: 'Mở rộng {hidden} dòng', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index b3af2e81..a9ddd14c 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -454,6 +454,8 @@ export const zhHK: Record = { sideChatCancelTitle: '中止目前回合(保留佇列)', sideChatError: '側邊對話出錯:{message}', sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok', + sideChatDeliverables: '交付檔案', + sideChatDeliverableOpen: '開啟 {name}', sideChatBlockCollapse: '收起', sideChatBlockCollapseAria: '收起', sideChatBlockExpand: '展開 {hidden} 行', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index 21252b6e..f3f69f2b 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -454,6 +454,8 @@ export const zhMO: Record = { sideChatCancelTitle: '中止目前回合(保留佇列)', sideChatError: '側邊對話出錯:{message}', sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok', + sideChatDeliverables: '交付檔案', + sideChatDeliverableOpen: '開啟 {name}', sideChatBlockCollapse: '收起', sideChatBlockCollapseAria: '收起', sideChatBlockExpand: '展開 {hidden} 行', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index 4c7795be..10ff62b3 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -454,6 +454,8 @@ export const zhTW: Record = { sideChatCancelTitle: '中止目前回合(保留佇列)', sideChatError: '側邊對話出錯:{message}', sideChatTurnUsage: '輸入 {input} tok · 輸出 {output} tok', + sideChatDeliverables: '交付檔案', + sideChatDeliverableOpen: '開啟 {name}', sideChatBlockCollapse: '收起', sideChatBlockCollapseAria: '收起', sideChatBlockExpand: '展開 {hidden} 行', diff --git a/src/client/locales.ts b/src/client/locales.ts index 1700f663..d2160e3e 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -451,6 +451,8 @@ export const zh = { sideChatCancelTitle: '中止当前回合(保留队列)', sideChatError: '侧边对话出错:{message}', sideChatTurnUsage: '输入 {input} tok · 输出 {output} tok', + sideChatDeliverables: '交付文件', + sideChatDeliverableOpen: '打开 {name}', sideChatBlockCollapse: '收起', sideChatBlockCollapseAria: '收起', sideChatBlockExpand: '展开 {hidden} 行', @@ -1084,6 +1086,8 @@ export const en: Record = { sideChatCancelTitle: 'Abort the running turn (queued work is kept)', sideChatError: 'Side Chat error: {message}', sideChatTurnUsage: 'Input {input} tok · Output {output} tok', + sideChatDeliverables: 'Present files', + sideChatDeliverableOpen: 'Open {name}', sideChatBlockCollapse: 'Collapse', sideChatBlockCollapseAria: 'Collapse', sideChatBlockExpand: 'Expand {hidden} lines', diff --git a/src/client/markdown-images.ts b/src/client/markdown-images.ts index bad10e80..4846735b 100644 --- a/src/client/markdown-images.ts +++ b/src/client/markdown-images.ts @@ -1,13 +1,16 @@ /** - * Markdown-preview local-image resolution. The shared `MarkdownText` (from - * @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s) image - * URLs — relative links are disabled for chat security — so a local image in - * a previewed `.md` (`![alt](./img.png)`, an absolute `/cwd/img.png`, or a - * reference definition) would otherwise fall back to its alt text. This - * dependency-free helper rewrites those destinations into absolute - * `/sidebar/file` media URLs, resolved against the injected transport base so - * a reverse-proxy prefix survives; `MarkdownText` accepts them because they are - * absolute http(s), and the host media route then serves the bytes. + * Local-image resolution for rendered markdown: the shared `MarkdownText` + * (from @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s) + * image URLs — relative links are disabled for chat security — so a local + * image in a previewed `.md` (`![alt](./img.png)`, an absolute `/cwd/img.png`, + * or a reference definition) or in a Side Chat prose row would otherwise fall + * back to its alt text. This dependency-free helper rewrites those + * destinations into absolute `/sidebar/file` media URLs, resolved against the + * injected transport base so a reverse-proxy prefix survives; `MarkdownText` + * accepts them because they are absolute http(s), and the host media route + * then serves the bytes. Relative destinations resolve against the rendered + * file's directory for a document, and against the session workspace root for + * prose ({@link rewriteProseLocalImageUrls}). */ import type { SessionScope } from './api.ts' @@ -47,6 +50,58 @@ export function normalizeLocalPath(path: string): string { return `${root}${out.join(separator)}` } +/** + * Resolve one media destination against the session's media route: local + * (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved + * through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them + * AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and + * empty destinations are returned untouched. Shared by the markdown image rewriter below and by the + * preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same + * allowlist when rendering `` inside HTML blocks). + */ +export function resolveLocalMediaDest( + dest: string, + scope: SessionScope, + filePath: string, + baseUrl: string, +): string { + const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')) + const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1) + return resolveMediaDest(dest, scope, directory, baseUrl) +} + +/** + * One media destination against a base DIRECTORY (already path-separated): + * the shared body of the file and prose variants. `undefined` leaves relative + * destinations untouched — without a base there is nothing to resolve them + * against, and a bare relative URL would just fail the host allowlist. + */ +function resolveMediaDest( + dest: string, + scope: SessionScope, + directory: string | undefined, + baseUrl: string, +): string { + const trimmed = dest.trim() + if (trimmed === '' || trimmed.startsWith('#')) return dest + if (isRemoteUrl(trimmed)) return dest + const absolute = isAbsolutePath(trimmed) + if (!absolute && directory === undefined) return dest + const candidate = absolute ? trimmed : `${directory ?? ''}${trimmed}` + // Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made + // absolute (and prefix-preserving) so the shared MarkdownText http(s) + // allowlist accepts it. + const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) }) + if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd) + return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href +} + +/** The directory a workspace root resolves relative destinations against. */ +function workspaceDirectory(cwd: string | undefined): string | undefined { + if (cwd === undefined || cwd === '') return undefined + return `${cwd.replace(/[\\/]+$/, '')}/` +} + /** * Rewrite markdown image destinations that point at local files into * absolute `/sidebar/file` media URLs. Relative destinations resolve against @@ -70,43 +125,52 @@ export function normalizeLocalPath(path: string): string { * renderers); injected so the core rewrite stays pure and unit-testable. * @returns The markdown with local image destinations rewritten in place. */ -/** - * Resolve one media destination against the session's media route: local - * (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved - * through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them - * AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and - * empty destinations are returned untouched. Shared by the markdown image rewriter below and by the - * preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same - * allowlist when rendering `` inside HTML blocks). - */ -export function resolveLocalMediaDest( - dest: string, - scope: SessionScope, - filePath: string, - baseUrl: string, -): string { - const trimmed = dest.trim() - if (trimmed === '' || trimmed.startsWith('#')) return dest - if (isRemoteUrl(trimmed)) return dest - const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')) - const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1) - const candidate = isAbsolutePath(trimmed) ? trimmed : directory + trimmed - // Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made - // absolute (and prefix-preserving) so the shared MarkdownText http(s) - // allowlist accepts it. - const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) }) - if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd) - return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href -} - export function rewriteLocalImageUrls( text: string, scope: SessionScope, filePath: string, baseUrl: string, ): string { - const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl) + const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')) + const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1) + return rewriteImageDestinations(text, (dest) => resolveMediaDest(dest, scope, directory, baseUrl)) +} +/** + * The prose counterpart of {@link rewriteLocalImageUrls}: a rendered + * conversation row is not a file, so its relative destinations resolve + * against the session workspace root instead of an opened document's + * directory. Absolute local paths, remote URLs and code masking behave + * exactly like the file variant (the shared MarkdownText only renders an + * image whose destination is absolute http(s), so a local destination would + * otherwise fall back to its alt text). + * @param text - The markdown source of one prose row. + * @param scope - The session scope (sessionId + cwd) for the media route. + * @param cwd - The session workspace root; relative destinations resolve + * against it (and stay untouched when it is unknown). + * @param baseUrl - The injected transport base. + * @returns The markdown with local image destinations rewritten in place. + */ +export function rewriteProseLocalImageUrls( + text: string, + scope: SessionScope, + cwd: string | undefined, + baseUrl: string, +): string { + const directory = workspaceDirectory(cwd) + return rewriteImageDestinations(text, (dest) => resolveMediaDest(dest, scope, directory, baseUrl)) +} + +/** + * The masking + destination rewrite both variants share: code regions and + * plain-link reference definitions stay out of it, and only the definitions an + * image actually references are redirected. + * + * Text with no image syntax at all returns untouched: both regexes below key on + * `![`, so the masking pass would only be paid for to be undone. + */ +function rewriteImageDestinations(text: string, resolve: (dest: string) => string): string { + if (!text.includes('![')) return text // Fenced blocks (``` ``` ``` AND `~~~`) and inline code spans are masked so // image-looking text inside documentation examples is never rewritten; the // original text goes back in after the rewrite. diff --git a/src/client/markdown-labels.tsx b/src/client/markdown-labels.tsx index bb4a3037..2447904e 100644 --- a/src/client/markdown-labels.tsx +++ b/src/client/markdown-labels.tsx @@ -5,10 +5,17 @@ * buttons plus a screen-reader-only `labels.footnotes` heading — and the * MarkdownText/CodeBlock are cordis-free, falling back to HARDCODED Chinese * when the labels are omitted, so every render site threads the plugin - * dictionary's localized pair through here (re-evaluated per render). + * dictionary's localized pair through here. * `footnotes` is left empty (the heading is sr-only; give it a real string * only if a locale key ever earns its place in all 19 dictionaries). * + * The nested object is built ONCE per distinct set of label VALUES + * ({@link cachedLabels}): `MarkdownText` is memoized on the `labels` identity + * (its streaming render cache is dropped when the identity changes), so a + * fresh object per render re-parsed every markdown row on every parent + * re-render — a composer keystroke or one streaming push. Callers pass a + * plain value bag and may build that bag inline; identity is never the key. + * * DSH 0.1.7-rc.1 added `labels.code.toolbarLabels` (language name + wrap * toggle + copy). Supplying it is what swaps the legacy info-string banner for * the host's code card, and the three strings are REQUIRED once supplied, so @@ -33,21 +40,58 @@ export interface MarkdownCopyLabels { unwrapLabel: string } +/** The nested `labels` prop the host renderer takes. */ +type HostMarkdownLabels = ComponentProps['labels'] + +/** + * How many distinct label sets the identity cache keeps. The plugin renders + * one label set per locale revision (zh/en plus the better-locale override, + * and one per mounted view), so this is far above the real cardinality; the + * bound only keeps a pathological caller from growing the map forever. + */ +const LABELS_CACHE_CAP = 32 + +/** + * Identity-stable nested label objects, keyed by the five label VALUES. + * + * A `Map` (not a `WeakMap`) on purpose: callers build their `MarkdownCopyLabels` + * bag inline on every render, so object identity is worthless as a key — + * only the rendered strings are. Every entry is a pure function of its key, + * so eviction costs a rebuild, never a wrong label. + */ +const labelsCache = new Map() + +/** The nested host `labels` for one label-value set, shared across renders. */ +function cachedLabels(labels: MarkdownCopyLabels): HostMarkdownLabels { + // JSON keeps the five fields unambiguously separated: a separator character + // would collide with label text that contains it. + const key = JSON.stringify([labels.copyLabel, labels.copiedLabel, labels.codeLabel, labels.wrapLabel, labels.unwrapLabel]) + const cached = labelsCache.get(key) + if (cached !== undefined) return cached + const built: HostMarkdownLabels = { + code: { + copyLabel: labels.copyLabel, + copiedLabel: labels.copiedLabel, + toolbarLabels: { + codeLabel: labels.codeLabel, + wrapLabel: labels.wrapLabel, + unwrapLabel: labels.unwrapLabel, + }, + }, + footnotes: '', + } + if (labelsCache.size >= LABELS_CACHE_CAP) { + const oldest = labelsCache.keys().next() + if (oldest.done !== true) labelsCache.delete(oldest.value) + } + labelsCache.set(key, built) + return built +} + /** MarkdownText props carrying the nested chrome labels. */ export function markdownTextProps(text: string, labels: MarkdownCopyLabels): ComponentProps { return { text, - labels: { - code: { - copyLabel: labels.copyLabel, - copiedLabel: labels.copiedLabel, - toolbarLabels: { - codeLabel: labels.codeLabel, - wrapLabel: labels.wrapLabel, - unwrapLabel: labels.unwrapLabel, - }, - }, - footnotes: '', - }, + labels: cachedLabels(labels), } } diff --git a/src/client/sidechat-transcript.ts b/src/client/sidechat-transcript.ts index a1a17f5f..d745cb2d 100644 --- a/src/client/sidechat-transcript.ts +++ b/src/client/sidechat-transcript.ts @@ -21,6 +21,11 @@ * Failures: a provider/agent error used to end a turn with nothing on screen. * The terminal `turn/end` reason and a failed attempt's embedded finish chunk * both map onto one visible `error` row per turn. + * + * Deliveries: a `present` call maps onto its compact deliverables card (the + * host's own present toolview), and the `deliverables/presented` event that + * the tool appends attaches to that card by `callId` — or stands alone when + * its call is not in the window. */ import type { DiffHunk, ReadBlockLine } from '@deepseek-ai/dsh-client-ui-primitives' import type { SidebarHistoryEntry } from '../context-types.ts' @@ -45,6 +50,14 @@ export type SidechatToolCard = | { type: 'diff'; diffs: DiffHunk[] } | { type: 'read'; label: string; lines: ReadBlockLine[]; totalLines: number; lang?: string } +/** One file a `present` call delivered: its path (absolute from the + * `deliverables/presented` event, session-relative from the call arguments) + * plus the model's own description when it wrote one. */ +export interface SidechatDeliverable { + path: string + description?: string +} + /** One compact transcript row rendered in the thread view. `seq` is the * source event's log sequence — stable row identity for React keys across * polls (streaming caches ride the key, so window slides must not re-key @@ -82,6 +95,11 @@ export type SidechatTranscriptRow = /** Structured render payload (host Block atoms); absent = generic row. */ card?: SidechatToolCard } + /** One `present` delivery (a compact deliverables card instead of a tool + * row). A `deliverables/presented` event with the same `callId` REPLACES + * the call's arguments copy — one card per call, never two. An event with + * no call row in the window (an event-only delivery) still gets its own. */ + | { kind: 'deliverables'; seq: number; callId?: string; files: readonly SidechatDeliverable[] } /** One turn's tail metrics, emitted at `turn/end`: the turn's token usage * (aggregated from `assistant/message.usage`) and wall duration (envelope * time delta from `turn/start`), whichever are computable. */ @@ -209,6 +227,42 @@ function parseArgsObject(args: string | undefined): Record | un } } +/** + * Narrow one delivered-file entry (`{ path, description? }`). The path is + * kept verbatim: the card resolves it against the session cwd on click and + * through the media route on render, so both the call-arguments spelling + * (cwd-relative) and the event spelling (absolute) work unchanged. A + * malformed entry declines the whole list — half a delivery card is worse + * than the generic tool row it falls back to. + */ +function deliverableOf(value: unknown): SidechatDeliverable | undefined { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined + const { path, description } = value as { path?: unknown; description?: unknown } + if (typeof path !== 'string' || path.trim() === '') return undefined + if (description !== undefined && typeof description !== 'string') return undefined + return { path, ...(description !== undefined && description !== '' ? { description } : {}) } +} + +/** The `files` array of a `present` argument object or a + * `deliverables/presented` event, or undefined when the value is not one. */ +function deliverableFiles(value: unknown): SidechatDeliverable[] | undefined { + if (!Array.isArray(value)) return undefined + const files: SidechatDeliverable[] = [] + for (const entry of value) { + const file = deliverableOf(entry) + if (file === undefined) return undefined + files.push(file) + } + return files +} + +/** The delivered files of a `present` tool call, or undefined when its + * arguments name none (the call then renders as the generic tool row). */ +function presentCallFiles(args: string | undefined): SidechatDeliverable[] | undefined { + const files = deliverableFiles(parseArgsObject(args)?.files) + return files !== undefined && files.length > 0 ? files : undefined +} + /** * Call-time card from the raw `tool/call` arguments — the same literal cards * the host's own presenters derive before any result exists: bash shows the @@ -385,6 +439,10 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r const streamRows = new Map() /** tool callId → index of its tool row in `rows` (result pairing). */ const callRows = new Map() + /** present callId → index of its deliverables card in `rows`: the + * `deliverables/presented` event attaches/updates that card instead of + * appending a second one. */ + const presentRows = new Map() /** turn → envelope time of its `turn/start` (turn-tail duration basis). */ const turnStarts = new Map() /** Turns that already rendered a failure row (an attempt error and the @@ -531,6 +589,17 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r const callId = data.callId const name = typeof data.name === 'string' ? data.name : 'tool' const args = typeof data.arguments === 'string' ? data.arguments : undefined + // A present call renders as its deliverables card, not a tool row + // (the host's own present toolview does the same): the arguments are + // the pre-event copy the deliverables/presented event refines below. + if (name === 'present') { + const files = presentCallFiles(args) + if (files !== undefined) { + if (typeof callId === 'string') presentRows.set(callId, rows.length) + rows.push({ kind: 'deliverables', seq: event.seq, ...(typeof callId === 'string' ? { callId } : {}), files }) + break + } + } const card = callCard(name, args) const rowIndex = rows.length if (typeof callId === 'string') callRows.set(callId, rowIndex) @@ -540,6 +609,9 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r case 'tool/result': { const source = data.message as { source?: { callId?: unknown } } | undefined const callId = typeof source?.source?.callId === 'string' ? source.source.callId : undefined + // A present call's result is not a row: its deliverables card already + // shows what was delivered (and the event supersedes that copy). + if (callId !== undefined && presentRows.has(callId)) break const rowIndex = callId === undefined ? undefined : callRows.get(callId) const failed = data.error !== undefined const resultText = resultTextOf(data) @@ -572,6 +644,25 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r } break } + case 'deliverables/presented': { + // The authoritative delivery record (`files[].path` absolute, plus the + // model's descriptions). It attaches to its call's card by callId — + // one card per call — and stands on its own when the call row is not + // in the window (the event is logged after the turn's tool calls, so + // a delta poll may see it alone). + const files = deliverableFiles(data.files) + if (files === undefined || files.length === 0) break + const callId = typeof data.callId === 'string' ? data.callId : undefined + const rowIndex = callId === undefined ? undefined : presentRows.get(callId) + const card = rowIndex === undefined ? undefined : rows[rowIndex] + if (rowIndex !== undefined && card !== undefined && card.kind === 'deliverables') { + rows[rowIndex] = { ...card, files } + break + } + if (callId !== undefined) presentRows.set(callId, rows.length) + rows.push({ kind: 'deliverables', seq: event.seq, ...(callId !== undefined ? { callId } : {}), files }) + break + } default: { break } @@ -610,6 +701,14 @@ function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean return a.name === other.name && a.failed === other.failed && a.args === other.args && a.resultText === other.resultText && a.executing === other.executing } + case 'deliverables': { + const other = b as typeof a + if (a.callId !== other.callId || a.files.length !== other.files.length) return false + return a.files.every((file, index) => { + const peer = other.files[index] + return peer !== undefined && file.path === peer.path && file.description === peer.description + }) + } case 'turnSummary': { const other = b as typeof a return a.inputTokens === other.inputTokens && a.outputTokens === other.outputTokens diff --git a/tests/helpers/sidechat-view-harness.tsx b/tests/helpers/sidechat-view-harness.tsx new file mode 100644 index 00000000..2a34f2bf --- /dev/null +++ b/tests/helpers/sidechat-view-harness.tsx @@ -0,0 +1,206 @@ +/** + * Shared real-`SideChatView` harness for the rendering-parity specs + * (tests/sidechat-markdown-labels.spec.tsx, tests/sidechat-markdown-images.spec.tsx, + * tests/sidechat-present-card.spec.tsx). + * + * Extracted from the inline harness in tests/sidechat-view.spec.tsx: the same + * FakeLocale / sessions-list store / FakeSocket / fetch stub, plus two things + * those specs need — a `live` channel on the wire (the host's + * `assistant/live-chunk` rows, which the transcript route serves separately + * from the durable log) and an observable `betterSidebar` host face so a file + * open can be asserted without touching a real host. + * + * The specs mutate `harness.wire` BEFORE `harness.mount()` — the fetch stub + * closes over the same object, so every route reads the test's current wire. + * + * Import this from a DOM spec (the importing file carries + * `// @vitest-environment jsdom`): it mounts a React root into document.body. + */ +import { vi } from 'vitest' +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct, type RenderedRoot } from '../test-utils.ts' +import { SideChatView } from '../../src/client/SideChatView.tsx' +import { attachLocale } from '../../src/client/locales.ts' +import type { Context, SidebarSessionList } from '../../src/context-types.ts' +import type { SidebarTab } from '../../src/client/state.ts' + +setupReactAct() + +/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */ +class FakeLocale { + active: string = 'zh' + getSnapshot(): { active: string } { + return { active: this.active } + } + subscribe(_fn: () => void): () => void { + return () => {} + } + register(_ns: string, _locale: string, _dict: Record): () => void { + return () => {} + } +} + +/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */ +function makeStore(initial: SidebarSessionList) { + const snapshot = initial + const listeners = new Set<() => void>() + return { + getSnapshot: (): SidebarSessionList => snapshot, + subscribe: (fn: () => void) => { + listeners.add(fn) + return () => { listeners.delete(fn) } + }, + } +} + +/** + * The smallest WebSocket the view's push hook talks to: it only has to keep + * the hook from opening a REAL connection (jsdom's WebSocket would fail + * asynchronously and leave backoff timers behind). + */ +class FakeSocket { + static instances: FakeSocket[] = [] + static readonly OPEN = 1 + static readonly CONNECTING = 0 + readonly url: string + readyState = FakeSocket.CONNECTING + onopen: (() => void) | null = null + onmessage: ((event: { data: string }) => void) | null = null + onclose: (() => void) | null = null + constructor(url: string) { + this.url = url + FakeSocket.instances.push(this) + } + send(_frame: string): void {} + close(): void { this.readyState = 3 } +} + +/** What the plugin's `sidechat.events` / `sidechat.info` / `sidechat.models` + * routes answer for the thread under test. */ +export interface SidechatWire { + /** The thread's own (seed-cut) durable log. */ + events: unknown[] + /** The in-flight attempt's client-only rows (replaced on every pull). */ + live: unknown[] + /** The unclaimed inbox snapshot. */ + pending: unknown[] + info: Record + catalog: Record +} + +/** The host faces the view reaches through `ctx.get('betterSidebar')`. */ +export interface SidechatHost { + openTab: ReturnType + updateTab: ReturnType +} + +export interface SidechatHarness { + /** Mutable wire values; set them before mount(). */ + wire: SidechatWire + host: SidechatHost + /** Render the real SideChatView bound to thread 't1' under session 'root'. */ + mount: () => RenderedRoot + /** Flush React work + the stub's resolved promises (default two rounds). */ + flush: (rounds?: number) => Promise + /** Type into the composer the way a user does (React's value tracker must + * be bypassed, hence the prototype setter). */ + typeComposer: (text: string) => void + composerValue: () => string + /** Detach the locale/globals this harness installed. */ + cleanup: () => void +} + +/** One JSON envelope the fetch stub answers. */ +function jsonResponse(value: unknown): Response { + return { ok: true, status: 200, json: async () => value } as unknown as Response +} + +/** + * Install the fake locale, WebSocket and fetch routing, and return the mount / + * event-poking surface. Call it from `beforeEach`, and `cleanup()` from + * `afterEach`. + */ +export function installSidechatHarness(overrides: Partial = {}): SidechatHarness { + const wire: SidechatWire = { + events: [], + live: [], + pending: [], + info: { live: false, provider: 'deepseek', preset: 'side' }, + catalog: { available: false, groups: [], failures: [] }, + ...overrides, + } + + attachLocale(new FakeLocale()) + FakeSocket.instances = [] + vi.stubGlobal('WebSocket', FakeSocket) + + vi.stubGlobal('fetch', async (url: string | URL) => { + const method = String(url).split('/').pop() + if (method === 'sidechat.events') { + return jsonResponse({ ok: true, value: { events: wire.events, live: wire.live, pending: wire.pending } }) + } + if (method === 'sidechat.info') return jsonResponse({ ok: true, value: wire.info }) + if (method === 'sidechat.models') return jsonResponse({ ok: true, value: wire.catalog }) + if (method === 'sidechat.start') return jsonResponse({ ok: true, value: { childId: 'session-new' } }) + return jsonResponse({ ok: true, value: {} }) + }) + + const host: SidechatHost = { openTab: vi.fn(), updateTab: vi.fn() } + + const store = makeStore({ + byId: { + root: { id: 'root', cwd: '/p', displayTitle: '主会话', running: false }, + t1: { id: 't1', cwd: '/p', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: false }, + }, + projectionsBySession: { + root: { + values: { + subagentCatalog: [{ id: 't1', createdAt: 1_000, mode: 'continuable', label: 'Side: 线程一' }], + }, + state: 'ready', + error: null, + }, + }, + }) + + const ctx = { + sessions: { list: store }, + get: (key: string) => (key === 'betterSidebar' ? host : undefined), + } as unknown as Context + + const tab: SidebarTab = { id: 'tab1', type: 'sidechat', title: '线程一', meta: { threadId: 't1' } } + const props = { ctx, scope: { sessionId: 'root', cwd: '/p' }, tab, visible: true } + + let mounted: RenderedRoot | null = null + const composer = (): HTMLTextAreaElement => { + const field = mounted?.container.querySelector('textarea') ?? null + if (field === null) throw new Error('the composer is missing') + return field + } + + return { + wire, + host, + mount: () => { + mounted = renderRoot(createElement(SideChatView, props)) + return mounted + }, + flush: async (rounds = 2) => { + for (let round = 0; round < rounds; round += 1) await act(async () => {}) + }, + typeComposer: (text: string) => { + const field = composer() + const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set + act(() => { + setter?.call(field, text) + field.dispatchEvent(new Event('input', { bubbles: true })) + }) + }, + composerValue: () => composer().value, + cleanup: () => { + vi.unstubAllGlobals() + attachLocale(undefined) + }, + } +} diff --git a/tests/sidechat-markdown-images.spec.tsx b/tests/sidechat-markdown-images.spec.tsx new file mode 100644 index 00000000..d059d1d6 --- /dev/null +++ b/tests/sidechat-markdown-images.spec.tsx @@ -0,0 +1,127 @@ +// @vitest-environment jsdom +/** + * D2 — local Markdown images inside Side Chat prose (spec: + * docs/plans/2026-10-22-sidechat-render-parity/spec.md, contract C1 / + * deliverable D2). + * + * The host `MarkdownText` only renders an image whose destination is an + * absolute http(s) URL (a relative/local path falls back to its alt text). + * Every Side Chat prose row must therefore rewrite its local image + * destinations onto the plugin's own session-scoped media route + * (`/sidebar/file?sessionId=…&path=…&cwd=…`) BEFORE the host parses the + * markdown — relative paths resolved against the session cwd, absolute local + * paths kept, code regions untouched, remote URLs unchanged. + * + * Rendered through the REAL SideChatView so the whole row pipeline (range + * mapping → markdown surface rewrite → host renderer) is the subject. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' + +/** The user prose: relative image, absolute local image, a fenced example + * that must stay literal, and a remote image that must stay remote. */ +const USER_MD = [ + 'Here are the pictures.', + '', + '![cat](./cat.png)', + '', + '![dog](/p/dog.png)', + '', + '```md', + '![fenced](./fenced.png)', + '```', + '', + '![remote](https://example.com/remote.png)', +].join('\n') + +/** The assistant prose: a bare relative destination (no `./` prefix). */ +const ASSISTANT_MD = '![chart](chart.png)' + +const SESSION_CWD = '/p' +/** The panel's session and the thread it renders are both live sessions; the + * media route may be scoped to either one and both resolve this workspace. */ +const SESSION_IDS = ['root', 't1'] + +/** Parse one img's src as a URL against the jsdom page base. */ +function srcUrl(img: HTMLImageElement): URL { + return new URL(img.getAttribute('src') ?? '', document.baseURI) +} + +/** The media-route image for one absolute local path, if the DOM has it. */ +function localImage(container: HTMLElement, path: string): HTMLImageElement | undefined { + return [...container.querySelectorAll('img')].find((img) => { + const url = srcUrl(img) + return url.pathname.endsWith('/sidebar/file') && url.searchParams.get('path') === path + }) +} + +describe('SideChatView local markdown images (C1)', () => { + let harness: SidechatHarness + + beforeEach(() => { + harness = installSidechatHarness({ + events: [ + { type: 'session/end-seed', seq: 0, time: 0, data: {} }, + { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: USER_MD }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } }, + { + type: 'assistant/message', + seq: 3, + time: 3_000, + data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: ASSISTANT_MD }] } }, + }, + { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } }, + ], + }) + }) + + afterEach(() => { + harness.cleanup() + }) + + it('renders relative and absolute local image destinations as /sidebar/file URLs', async () => { + const view = harness.mount() + await harness.flush() + + const relative = localImage(view.container, `${SESSION_CWD}/cat.png`) + expect(relative, '![cat](./cat.png) must render as an img, not alt text').toBeDefined() + const relativeSrc = relative!.getAttribute('src') ?? '' + // The host renderer only accepts absolute http(s) destinations, so an + // here proves the rewrite produced exactly that. + expect(relativeSrc).toMatch(/^https?:\/\//) + const relativeUrl = srcUrl(relative!) + expect(relativeUrl.searchParams.get('cwd')).toBe(SESSION_CWD) + expect(SESSION_IDS, 'the media route stays session-scoped').toContain(relativeUrl.searchParams.get('sessionId')) + // The same alt text must survive as the image's alt. + expect(relative!.getAttribute('alt')).toBe('cat') + + const absolute = localImage(view.container, `${SESSION_CWD}/dog.png`) + expect(absolute, '![dog](/p/dog.png) must render as an img').toBeDefined() + expect(srcUrl(absolute!).searchParams.get('path')).toBe(`${SESSION_CWD}/dog.png`) + + // The assistant's bare relative destination resolves against the same cwd. + const bare = localImage(view.container, `${SESSION_CWD}/chart.png`) + expect(bare, '![chart](chart.png) must render as an img').toBeDefined() + + view.unmount() + }) + + it('leaves code regions and remote destinations alone', async () => { + const view = harness.mount() + await harness.flush() + + // Fenced code is rendered as its literal text — a rewrite inside the mask + // would have replaced this example with a /sidebar/file URL. + expect(view.container.textContent ?? '').toContain('![fenced](./fenced.png)') + expect( + [...view.container.querySelectorAll('img')].some(img => (img.getAttribute('src') ?? '').includes('fenced.png')), + 'a fenced example must never become an image', + ).toBe(false) + + const remote = [...view.container.querySelectorAll('img')] + .find(img => img.getAttribute('src') === 'https://example.com/remote.png') + expect(remote, 'a remote image keeps rendering unchanged').toBeDefined() + + view.unmount() + }) +}) diff --git a/tests/sidechat-markdown-labels.spec.tsx b/tests/sidechat-markdown-labels.spec.tsx new file mode 100644 index 00000000..d60c2c1c --- /dev/null +++ b/tests/sidechat-markdown-labels.spec.tsx @@ -0,0 +1,200 @@ +// @vitest-environment jsdom +/** + * D1 — Markdown hot path (spec: docs/plans/2026-10-22-sidechat-render-parity/spec.md, + * contract C3 / deliverable D1). + * + * Two behaviors, both deterministic (no timers, no clocks): + * + * 1. `markdownTextProps(text, labels)` must hand the host `MarkdownText` the + * SAME nested `labels` object for equal label values — the host memoizes on + * that identity, so a fresh object per render defeats its `memo` and + * re-parses the whole transcript on every composer keystroke and every + * streaming push. Different label values must still get different objects + * (a single shared object would leak the previous locale's copy). + * + * 2. The real `SideChatView` must stop re-executing `MarkdownText` for rows + * whose markdown did not change, and an UNSETTLED `assistant/live-chunk` + * row must reach it with `streaming === true` while the assembled + * `assistant/message` row does not (streaming is what lets the host keep + * its incremental parse across chunks instead of restarting it). + * + * `MarkdownText` is replaced through the primitives module mock with a counter + * wrapped in `memo` — the exact memo boundary the host ships — so a recorded + * call means the host component was ASKED to re-render (its parser would run). + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ComponentProps } from 'react' +import { markdownTextProps, type MarkdownCopyLabels } from '../src/client/markdown-labels.tsx' +import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' + +/** Every props object the mocked `MarkdownText` was asked to render. */ +const markdownRenders = vi.hoisted(() => ({ + calls: [] as Array<{ text: string; streaming: boolean | undefined }>, +})) + +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => { + const actual = await importOriginal() + const react = await import('react') + type Props = ComponentProps + // Same memo boundary as the host's own export: a call here is a memo MISS. + const CountingMarkdownText = react.memo(function CountingMarkdownText(props: Props) { + markdownRenders.calls.push({ text: props.text, streaming: props.streaming }) + return react.createElement(actual.MarkdownText, props) + }) + return { ...actual, MarkdownText: CountingMarkdownText } +}) + +/** The chrome labels the view threads through every markdown row. */ +const LABELS: MarkdownCopyLabels = { + copyLabel: '复制', + copiedLabel: '已复制', + codeLabel: '代码', + wrapLabel: '换行', + unwrapLabel: '不换行', +} + +/** How many times `MarkdownText` was asked to render exactly this text. */ +function countOf(text: string): number { + return markdownRenders.calls.filter(call => call.text === text).length +} + +/** The last render `MarkdownText` was asked to do for exactly this text. */ +function lastRenderOf(text: string): { text: string; streaming: boolean | undefined } | undefined { + return [...markdownRenders.calls].reverse().find(call => call.text === text) +} + +describe('markdownTextProps label identity (C3)', () => { + it('returns the same nested labels object for equal label values', () => { + const first = markdownTextProps('first body', { ...LABELS }) + const second = markdownTextProps('second body', { ...LABELS }) + // The text is per-call; the labels object is what the host memo compares. + expect(first.text).toBe('first body') + expect(second.text).toBe('second body') + expect(second.labels).toBe(first.labels) + }) + + it('returns different nested labels objects for different label values', () => { + const zh = markdownTextProps('body', LABELS) + const en = markdownTextProps('body', { ...LABELS, copyLabel: 'Copy' }) + expect(en.labels).not.toBe(zh.labels) + // A different value in ANY of the five fields is a different cache entry. + for (const key of ['copyLabel', 'copiedLabel', 'codeLabel', 'wrapLabel', 'unwrapLabel'] as const) { + const changed = markdownTextProps('body', { ...LABELS, [key]: `${LABELS[key]}-other` }) + expect(changed.labels, key).not.toBe(zh.labels) + } + }) + + it('keeps one cache entry per distinct label value (a value seen again reuses its object)', () => { + const first = markdownTextProps('a', { ...LABELS }) + // Interleave other values: a last-only cache would lose the entry below. + markdownTextProps('b', { ...LABELS, copiedLabel: 'Copied' }) + markdownTextProps('c', { ...LABELS, codeLabel: 'Code' }) + const again = markdownTextProps('d', { ...LABELS }) + expect(again.labels).toBe(first.labels) + }) +}) + +describe('SideChatView markdown re-parse (C3)', () => { + /** Three markdown rows that never change during the test. */ + const ROWS = { + user: 'hi-there', + assistant: 'answer-one', + secondUser: 'second-question', + } + + /** A tiny settled conversation: user prose, assistant prose, user prose. */ + function settledConversation(): unknown[] { + return [ + { type: 'session/end-seed', seq: 0, time: 0, data: {} }, + { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: ROWS.user }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } }, + { + type: 'assistant/message', + seq: 3, + time: 3_000, + data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: ROWS.assistant }] } }, + }, + { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } }, + { type: 'user/message', seq: 5, time: 5_000, data: { content: [{ type: 'text', text: ROWS.secondUser }], source: { kind: 'user' } } }, + ] + } + + let harness: SidechatHarness + + beforeEach(() => { + markdownRenders.calls = [] + harness = installSidechatHarness() + }) + + afterEach(() => { + harness.cleanup() + }) + + it('does not re-execute MarkdownText for unchanged rows on a composer keystroke', async () => { + harness.wire.events = settledConversation() + const view = harness.mount() + await harness.flush() + + // Guard: the mock really replaced the host component on these rows (a + // mock that never applied would make the zero-delta assertion vacuous). + for (const text of Object.values(ROWS)) { + expect(countOf(text), `${text} must render through the counted MarkdownText`).toBeGreaterThan(0) + } + + // First keystroke: a warm-up that absorbs any mount-time async churn. + harness.typeComposer('a') + await harness.flush() + const baseline = new Map(Object.values(ROWS).map(text => [text, countOf(text)])) + + // Second keystroke: the rows are untouched, so the host memo must hit. + harness.typeComposer('ab') + await harness.flush() + expect(harness.composerValue()).toBe('ab') // the view really re-rendered + for (const text of Object.values(ROWS)) { + expect(countOf(text), `${text} was re-parsed by an unrelated composer keystroke`).toBe(baseline.get(text)) + } + + view.unmount() + }) + + it('passes streaming to an unsettled live row and not to the settled message', async () => { + const settled = 'settled-answer' + const live = 'live-token' + harness.wire.events = [ + { type: 'session/end-seed', seq: 0, time: 0, data: {} }, + { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'ask' }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } }, + { + type: 'assistant/message', + seq: 3, + time: 3_000, + data: { turn: 1, step: 1, message: { content: [{ type: 'text', text: settled }] } }, + }, + { type: 'turn/end', seq: 4, time: 4_000, data: { turn: 1, reason: 'completed' } }, + // The in-flight attempt: its deltas arrive on the LIVE channel only. + { type: 'turn/start', seq: 5, time: 5_000, data: { turn: 2 } }, + ] + harness.wire.live = [ + { + type: 'assistant/live-chunk', + seq: 100, + time: 9_000, + data: { attemptId: 'a1', turn: 2, step: 1, index: 0, chunk: { type: 'text-delta', text: live, index: 0 } }, + }, + ] + + const view = harness.mount() + await harness.flush() + expect(view.container.textContent ?? '').toContain(live) + + const liveRender = lastRenderOf(live) + expect(liveRender, 'the unsettled live row must reach MarkdownText').toBeDefined() + expect(liveRender!.streaming, 'an unsettled live row must render with streaming').toBe(true) + + const settledRender = lastRenderOf(settled) + expect(settledRender, 'the assembled message must reach MarkdownText').toBeDefined() + expect(settledRender!.streaming ?? false, 'a settled message must not render as streaming').toBe(false) + + view.unmount() + }) +}) diff --git a/tests/sidechat-present-card.spec.tsx b/tests/sidechat-present-card.spec.tsx new file mode 100644 index 00000000..0de26210 --- /dev/null +++ b/tests/sidechat-present-card.spec.tsx @@ -0,0 +1,200 @@ +// @vitest-environment jsdom +/** + * D3 — `present` deliverables card in Side Chat (spec: + * docs/plans/2026-10-22-sidechat-render-parity/spec.md, contract C2 / + * deliverable D3). + * + * Side Chat renders the thread's OWN conversation, so a `present` tool call + * (or the `deliverables/presented` event the tool appends) must surface as a + * compact deliverables card: one entry per file with its basename, optional + * description, a file-type affordance, an image thumbnail through the + * session-scoped `/sidebar/file` route, and a click that opens the file + * through the plugin's own `openSidebarFile` path. One call yields one card; + * the event attaches to the call's card by `callId`; inherited seed events are + * never rendered. + * + * Copy is locale-owned (spec: no hardcoded product text); the shipped + * dictionaries' key parity is enforced by tests/locales.spec.ts, which the + * implementer's new keys must satisfy. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { act } from 'react-dom/test-utils' +import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx' + +const SESSION_CWD = '/p' +/** The panel's session and the thread it renders are both live sessions; a + * session-scoped media route may name either one. */ +const SESSION_IDS = ['root', 't1'] + +/** The `present` tool's arguments (paths relative to the session cwd). */ +const CALL_ARGS = JSON.stringify({ + files: [ + { path: 'report.pdf', description: '季度报告' }, + { path: 'chart.png', description: '流量趋势' }, + ], +}) + +/** A leaf element whose whole visible text is exactly `text`. */ +function leafWithText(container: HTMLElement, text: string): Element | undefined { + return [...container.querySelectorAll('*')] + .find(element => element.children.length === 0 && (element.textContent ?? '').trim() === text) +} + +/** The clickable entries (one per delivered file) naming `name`. */ +function fileRows(container: HTMLElement, name: string): Element[] { + return [...container.querySelectorAll('button, [role="button"], a')] + .filter(element => (element.textContent ?? '').includes(name)) +} + +/** The file-type affordance the file's own row draws (the host's FileTypeIcon + * artwork is an svg, like every glyph this sidebar uses). */ +function iconNear(nameLeaf: Element): SVGElement | null { + let node: Element | null = nameLeaf + for (let depth = 0; depth < 3 && node !== null; depth += 1, node = node.parentElement) { + const svg = node.querySelector('svg') + if (svg !== null) return svg + } + return null +} + +/** The media-route thumbnail for one absolute local path, if the DOM has it. */ +function thumbnail(container: HTMLElement, path: string): HTMLImageElement | undefined { + return [...container.querySelectorAll('img')].find((img) => { + const url = new URL(img.getAttribute('src') ?? '', document.baseURI) + return url.pathname.endsWith('/sidebar/file') && url.searchParams.get('path') === path + }) +} + +/** The `present` call row: turn 1, step 1, call id `c-present`. */ +const PRESENT_CALL = { + type: 'tool/call', + seq: 3, + time: 3_000, + data: { turn: 1, step: 1, callId: 'c-present', name: 'present', arguments: CALL_ARGS }, +} + +describe('SideChatView present deliverables card (C2)', () => { + let harness: SidechatHarness + + beforeEach(() => { + harness = installSidechatHarness() + }) + + afterEach(() => { + harness.cleanup() + }) + + it('renders a compact card from the present call: name, description, type icon, image thumbnail, open action', async () => { + harness.wire.events = [ + { type: 'session/end-seed', seq: 0, time: 0, data: {} }, + { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'present these' }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } }, + PRESENT_CALL, + ] + const view = harness.mount() + await harness.flush() + + // A dedicated basename element (the collapsed tool row's raw JSON would + // not produce one) and the per-file description. + const pdfName = leafWithText(view.container, 'report.pdf') + expect(pdfName, 'the presented file appears by basename').toBeDefined() + expect(view.container.textContent ?? '').toContain('季度报告') + expect(leafWithText(view.container, 'chart.png'), 'every presented file gets an entry').toBeDefined() + expect(view.container.textContent ?? '').toContain('流量趋势') + + // The file-type affordance lives in the file's own row. + expect(iconNear(pdfName!), 'the file row draws a file-type icon').not.toBeNull() + + // An image deliverable gets a thumbnail through the session media route. + const chart = thumbnail(view.container, `${SESSION_CWD}/chart.png`) + expect(chart, 'an image deliverable gets a thumbnail').toBeDefined() + expect(chart!.getAttribute('src')).toMatch(/^https?:\/\//) + const chartUrl = new URL(chart!.getAttribute('src') ?? '', document.baseURI) + expect(chartUrl.pathname).toMatch(/\/sidebar\/file$/) + expect(chartUrl.searchParams.get('cwd')).toBe(SESSION_CWD) + expect(SESSION_IDS, 'the thumbnail route stays session-scoped').toContain(chartUrl.searchParams.get('sessionId')) + + // Clicking the file takes the plugin's own open path with the cwd-resolved + // absolute path (the call's argument was relative). + const pdfRow = fileRows(view.container, 'report.pdf') + expect(pdfRow, 'the file entry is clickable').toHaveLength(1) + await act(async () => { (pdfRow[0] as HTMLElement).click() }) + expect(harness.host.openTab).toHaveBeenCalledTimes(1) + expect(harness.host.openTab).toHaveBeenCalledWith(expect.objectContaining({ + type: 'editor', + path: `${SESSION_CWD}/report.pdf`, + })) + + view.unmount() + }) + + it('renders one card per call and lets the presented event attach to it', async () => { + harness.wire.events = [ + { type: 'session/end-seed', seq: 0, time: 0, data: {} }, + { type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'present these' }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } }, + { ...PRESENT_CALL, data: { ...PRESENT_CALL.data, arguments: JSON.stringify({ files: [{ path: 'report.pdf', description: '来自调用参数' }] }) } }, + { + type: 'tool/result', + seq: 4, + time: 4_000, + data: { + turn: 1, + step: 1, + message: { + source: { kind: 'tool', callId: 'c-present' }, + content: [{ type: 'tool-result', toolCallId: 'c-present', content: [{ type: 'text', text: 'Presented /p/report.pdf' }] }], + }, + }, + }, + { + type: 'deliverables/presented', + seq: 5, + time: 5_000, + data: { turn: 1, callId: 'c-present', files: [{ path: `${SESSION_CWD}/report.pdf`, description: '来自交付事件' }] }, + }, + ] + const view = harness.mount() + await harness.flush() + + // The event's own copy is what the card shows (nothing else in the + // transcript carries that string). + expect(view.container.textContent ?? '').toContain('来自交付事件') + // The call and its event are ONE card, not two. + expect(fileRows(view.container, 'report.pdf'), 'one delivered file, one card entry').toHaveLength(1) + + view.unmount() + }) + + it('renders the thread’s own presented event and never an inherited seed one', async () => { + harness.wire.events = [ + // Inherited from the parent log (before the fork seed marker): the + // thread did not present this file, so it must not render. + { + type: 'deliverables/presented', + seq: 0, + time: 0, + data: { turn: 1, callId: 'c-seed', files: [{ path: `${SESSION_CWD}/seed-only.pdf`, description: 'seed 交付' }] }, + }, + { type: 'session/end-seed', seq: 1, time: 1_000, data: {} }, + { type: 'user/message', seq: 2, time: 2_000, data: { content: [{ type: 'text', text: 'and now?' }], source: { kind: 'user' } } }, + { type: 'turn/start', seq: 3, time: 3_000, data: { turn: 2 } }, + { + type: 'deliverables/presented', + seq: 4, + time: 4_000, + data: { turn: 2, callId: 'c-own', files: [{ path: `${SESSION_CWD}/own-deliverable.pdf`, description: '自己的交付' }] }, + }, + ] + const view = harness.mount() + await harness.flush() + + const text = view.container.textContent ?? '' + expect(text, 'the thread’s own presented event renders a card').toContain('own-deliverable.pdf') + expect(text).toContain('自己的交付') + expect(text, 'an inherited seed delivery never renders').not.toContain('seed-only.pdf') + expect(text).not.toContain('seed 交付') + + view.unmount() + }) +})