fix(sidechat): address rendering review findings

Replace a failed present card with the generic failed tool row; keep one event-authoritative card whichever of the call and its delivered event lands first.

Use the host's real border token for the delivery card; include the visible description in the file button's accessible name and resolve its title path.

Handle CommonMark angle-delimited image destinations and preserve titles; add transcript, prose-rewrite, and DOM regression tests.

Update the change spec with review-driven acceptance commands, status, and evidence.
This commit is contained in:
NolanHo committed 2026-10-23 02:48:13 -07:00
1 parent 909f536eab
commit 6f14792baa
10 files changed
+396 -54

No files matched your search

@@ -2,7 +2,7 @@
type: ChangeSpec
title: Side Chat 渲染对齐与 Markdown 性能
description: 修 Side Chat 的本地 Markdown 图片、present/deliverables 卡片,并让 markdown labels 稳定、live 行走 streaming,消除每行全量重解析。
status: active
status: implemented
---
# Side Chat 渲染对齐与 Markdown 性能
@@ -29,7 +29,8 @@ Side Chat 是插件自建的 compact transcript,不是宿主 chat 的复用视
- Side Chat 的 thread **自身**日志中出现 `present` 工具调用或 `deliverables/presented` 事件时,必须渲染一张 compact deliverables 卡片。
- 卡片每个文件显示:文件类型图标、文件名(basename)、可选 description;图片文件额外显示缩略图(通过已有本地媒体路由);点击文件使用插件已有的 `openSidebarFile` 路径打开。
- 文件数据来源优先级:`deliverables/presented` 事件(含绝对的 `files[].path` / `description`,以 `turn`/`callId` 关联)优先;事件尚未到达时使用 `present` 调用的参数(`files`,按 cwd 解析)。
- 同一个 `present` 调用只出现一张卡片;事件到达时按 `callId` 附着/更新,不重复渲染。
- 同一个 `present` 调用只出现一张卡片;事件到达时按 `callId` 附着/更新,事件先于调用到达时同样只有一张,不重复渲染。
- `present` 调用失败(`tool/result` 带 `data.error`)时不显示交付卡片:回退为通用 failed tool 行并保留错误文本,与该功能上线前的行为一致。
- 继承 seed 中的 `present`/deliverables 事件不得渲染(Side Chat 只显示 thread 自己的对话)。
- 卡片文案必须走 locale 字典,不允许硬编码;新增 key 覆盖全部现有 locale,并通过 locale key 一致性测试。
- 不新增服务端依赖/路由;不引入 `ui-deliverables` 等新的 host peer。
@@ -51,21 +52,21 @@ Side Chat 是插件自建的 compact transcript,不是宿主 chat 的复用视
**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 证据)。
- `pnpm vitest run tests/markdown-copy-labels.spec.tsx tests/sidechat-markdown-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 渲染为 `<img>`,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)。
- `pnpm vitest run tests/markdown-images.spec.ts tests/markdown-crlf.spec.ts tests/sidechat-markdown-images.spec.tsx tests/sidechat-view.spec.tsx` 通过;新增的局部图片 DOM 与 prose 图片改写用例(cwd 变体、angle destination、title 保留)在旧实现上失败(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)。
- `pnpm vitest run tests/sidechat-transcript.spec.ts tests/sidechat-present-card.spec.tsx tests/sidechat-view.spec.tsx tests/locales.spec.ts`(或等价 locale 一致性测试)通过;新增 mapping/DOM 用例(含 failed present、event-first 去重、event-only、同 callId 二次事件、seed cut、row reuse、malformed files)在旧实现上失败(Red)。
- 浏览器验证:Side Chat 显示 present 卡片且点击可打开文件(截图证据)。
- 状态:`- [x]`
@@ -109,8 +110,8 @@ Side Chat 是插件自建的 compact transcript,不是宿主 chat 的复用视
### 基线与工作区
- 插件仓库:`/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 位于仓库根的 `.worktrees/sidechat-render`,分支 `fix/sidechat-render-parity`,基于 `f418302`(PR #1035 已合入)。
- 宿主:独立检出的 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 的验证证据见文末。
@@ -144,21 +145,29 @@ Side Chat 是插件自建的 compact transcript,不是宿主 chat 的复用视
## 验证证据(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)**:
- **聚焦(review 修复后重跑)**:`tests/sidechat-transcript.spec.ts`、`tests/markdown-images.spec.ts`、`tests/sidechat-present-card.spec.tsx`、`tests/sidechat-markdown-labels.spec.tsx`、`tests/sidechat-markdown-images.spec.tsx`、`tests/markdown-crlf.spec.ts`、`tests/sidechat-view.spec.tsx`、`tests/locales.spec.ts` 共 8 files / 124 tests 全绿;`tsc --noEmit`、`eslint .` 干净。
- **RED 证据(review 修复)**:M1a/M1b 的 2 个 mapping 用例在旧 `sidechat-transcript.ts` 上失败;N7 的 5 个 angle/title 用例在旧 `markdown-images.ts` 上失败;修复后全部转绿。
- **审阅驱动回归(2026-10-22 review)**:
- M1a:失败的 `present`(`data.error`)不再显示成功卡片,替换为通用 failed tool 行并保留错误文本;成功结果仍只保留卡片、结果行不渲染。
- M1b:`deliverables/presented` 先于 `tool/call` 时只保留一张事件权威卡片;call-first 亦为一张且事件数据覆盖调用参数;event-only、同 callId 二次事件、seed cut、row reuse、malformed/empty files 均有 mapping 覆盖。
- N7:inline angle destination(含空格路径)与 `"…"`/`'…'` title 保留;reference definition 的 `<…>` 与 title 保留;remote angle destination 不动;prose rewrite 覆盖 cwd 缺省、尾分隔符、Windows cwd、reference image 与 image-then-link 组合。
- N1:卡片按钮 accessible name 含可见 description,`title` 为 cwd 解析后的绝对路径(DOM 断言);S1:卡片边框改用宿主 `--dsw-alias-border-l1`。
- **全量(review 修复轮)**:`vitest run` 223 文件通过 / 1 失败(唯一失败为 `tests/git.spec.ts` 的 2.34.1 环境用例,基线同失败)/ 17 跳过;2717 tests 通过。
- **构建(`909f536` 提交轮 + review 修复轮)**:`pnpm run build` + `pnpm pack` 均成功(tarball 4.6 MB)。
- **浏览器 e2e(`909f536` 提交轮;第二实例,宿主 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` 的 `<img>`(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)。
- **浏览器复验(review 修复,宿主 app 重建后)**:生产 GUI 的 Side Chat 渲染出 `Present files` 卡片,按钮 aria 带描述(`Open README.md: …`、`Open running-whale@2x.png: …`),review 修复后的边框/aria 已确认生效;此前旧标签页/旧 app client 构建的缓存阻塞已定位并解除。
- **性能(jsdom,真实 `SideChatView`)**:`909f536` 200 组件 push 3.60 / keystroke 5.37 ms;review 修复后(`1904ed8`)200 组件 push 5.38 / keystroke 3.18 ms(单次测量噪声;审计基线 101.7–117.8 / 105.1–117.2 ms,约 19–37×);100 组件 2.19 / 1.96 ms、50 组件 2.72 / 1.63 ms;隔离 100 行 0.71 ms、200 行 1.39 ms;labels 引用相等;未变化行的 `MarkdownText` 执行数为 0;8 KB 增长行 22.0 ms(settled)→ 1.01 ms(streaming)。review 修复仅改图片正则/卡片行,未动 labels/streaming 热路径;200 组件数字含单次噪声。
- **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 门)。
- D1 `- [x]`;D2 `- [x]`;D3 `- [x]`;D4 `- [x]`(PR #1044 已开;合并/部署为 owner 门)。
- Review 修复(M1a/M1b/S1/S2/S3/N1–N5/N7)`- [x]`;N6 为 spec 一致的设计说明(绝对本地图片目的地走 session-scoped `/sidebar/file`),无代码改动。
### 待解决
- 无(范围、present 实现方式、图片 rewrite、测量口径均已定;上游 PR/生产为 owner 门,不阻塞实现)。
- 无阻塞;review 修复的浏览器边框/aria 已在宿主 app 重建后的生产 GUI 复验通过;上游 PR #1044 已开,合并/部署为 owner 门。
+1 -1
View File
@@ -390,7 +390,7 @@
flex-direction: column;
gap: 4px;
padding: 6px 8px;
border: 1px solid var(--dsw-alias-hairline);
border: 1px solid var(--dsw-alias-border-l1);
border-radius: 8px;
}
+23 -6
View File
@@ -66,7 +66,7 @@ import {
import { markdownTextProps } from './markdown-labels.tsx'
import { rewriteProseLocalImageUrls } from './markdown-images.ts'
import { hostTransportBase } from './desktop-env.ts'
import { baseName } from './paths.ts'
import { baseName, resolveSidebarPath } from './paths.ts'
import { openSidebarFile } from './sidebar-file.ts'
import { useMarkdownSurface } from './use-markdown-surface.ts'
import { IconHistoryOutline16, IconSaveOutline16 } from './icons.tsx'
@@ -485,6 +485,9 @@ interface RowSurface {
openFile: (path: string) => void
/** The session-scoped media URL of one image deliverable. */
media: (path: string) => string
/** The absolute spelling of one delivered path (the row's title tooltip;
* call-argument paths arrive relative to the session cwd). */
resolvePath: (path: string) => string
}
/** One row renderer (React keys ride the source event seq). `surface` is the
@@ -549,13 +552,18 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu
)
}
case 'deliverables': {
if (row.files.length === 0) return null
return (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatDeliverables}>
<div className={css.sidechatDeliverablesHead}>{t('sideChatDeliverables')}</div>
<ul className={css.sidechatDeliverablesList}>
{row.files.map((file, index) => {
const name = baseName(file.path)
// The visible description is part of the button's accessible
// name too: an `Open {name}` label alone would hide it from
// assistive tech while sighted readers see it.
const openLabel = file.description === undefined
? t('sideChatDeliverableOpen', { name })
: `${t('sideChatDeliverableOpen', { name })}: ${file.description}`
return (
<li key={`${String(index)}:${file.path}`} className={css.sidechatDeliverableItem}>
{/* One row per delivered file: the type glyph (and an image's
@@ -565,8 +573,8 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu
<button
type="button"
className={css.sidechatDeliverable}
title={file.path}
aria-label={t('sideChatDeliverableOpen', { name })}
title={surface.resolvePath(file.path)}
aria-label={openLabel}
onClick={() => { surface.openFile(file.path) }}
>
{classifyFileType(file.path) === 'image'
@@ -751,9 +759,18 @@ export function SideChatView(props: {
/** 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])
/** The absolute spelling of one delivered path for the card's title tooltip
* (the call-argument copy is cwd-relative; the event copy is already
* absolute and passes through unchanged). */
const deliverableTitlePath = useCallback((path: string): string => resolveSidebarPath(scope.cwd, path), [scope.cwd])
const rowSurface = useMemo<RowSurface>(
() => ({ rewrite: rewriteChatText, openFile: openDeliveredFile, media: deliverableMediaUrl }),
[rewriteChatText, openDeliveredFile, deliverableMediaUrl],
() => ({
rewrite: rewriteChatText,
openFile: openDeliveredFile,
media: deliverableMediaUrl,
resolvePath: deliverableTitlePath,
}),
[rewriteChatText, openDeliveredFile, deliverableMediaUrl, deliverableTitlePath],
)
const transcriptRef = useCallback((element: HTMLDivElement | null) => {
scrollRef.current = element
+26 -4
View File
@@ -102,6 +102,17 @@ function workspaceDirectory(cwd: string | undefined): string | undefined {
return `${cwd.replace(/[\\/]+$/, '')}/`
}
/**
* One inline image: alt text, destination, and the optional CommonMark title.
* A destination may be angle-delimited (`<…>` — how the spec carries a path
* containing spaces); the title may be double-quoted, single-quoted or
* parenthesized. Both are preserved by {@link rewriteImageDestinations}.
*/
const INLINE_IMAGE_RE = /!\[([^\]]*)\]\(\s*(<[^>\n]*>|[^)\s]+)(\s+(?:"[^"]*"|'[^']*'|\([^()]*\)))?\s*\)/g
/** A reference definition's destination: angle-delimited or bare. */
const REFERENCE_DEST_RE = /^(\s*\[([^\]]+)\]:\s*)(<[^>]+>|[^\s]+)/gm
/**
* Rewrite markdown image destinations that point at local files into
* absolute `/sidebar/file` media URLs. Relative destinations resolve against
@@ -109,6 +120,9 @@ function workspaceDirectory(cwd: string | undefined): string | undefined {
* local paths pass through. Remote (http/https/data/mailto) and `#`-anchor
* destinations are left untouched for `MarkdownText`. Reference-style images
* (`![x][id]` + `[id]: url`) are covered by rewriting their definition lines.
* A destination may be angle-delimited (`![a](<./cat image.png>)`) and an
* inline image may carry a title (`![a](./x.png "title")`); the delimiter and
* title are preserved while only the destination is rewritten.
*
* Code regions — inline spans AND fenced blocks, the latter opened by ``` ``` ```
* OR `~~~` (see `markdown-code.ts`, the mask both source rewriters share) — are
@@ -176,8 +190,12 @@ function rewriteImageDestinations(text: string, resolve: (dest: string) => strin
// original text goes back in after the rewrite.
const { masked, restore } = maskCodeRegions(text)
const inline = masked.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, alt, dest) => {
return `![${alt}](${resolve(dest)})`
const inline = masked.replace(INLINE_IMAGE_RE, (_match, alt: string, rawDest: string, title: string | undefined) => {
// The resolver decides from the bare destination; `<…>` and the title are
// spelling, not content, so they go back around/after whatever it returns.
const delimited = rawDest.startsWith('<') && rawDest.endsWith('>')
const destination = resolve(delimited ? rawDest.slice(1, -1) : rawDest)
return `![${alt}](${delimited ? `<${destination}>` : destination}${title ?? ''})`
})
// Collect labels referenced by image syntax (full `![alt][id]` and
@@ -194,9 +212,13 @@ function rewriteImageDestinations(text: string, resolve: (dest: string) => strin
imageLabels.add(ref !== undefined && ref !== '' ? ref.toLowerCase() : alt.toLowerCase())
}
const refsRewritten = inline.replace(/^(\s*\[([^\]]+)\]:\s*)(<[^>]+>|[^\s]+)/gm, (match, head: string, label: string, dest: string) => {
const refsRewritten = inline.replace(REFERENCE_DEST_RE, (match, head: string, label: string, rawDest: string) => {
if (!imageLabels.has(label.toLowerCase())) return match
return `${head}${resolve(dest.replace(/^<|>$/g, ''))}`
// `<…>` is what lets a destination carry a space; keep the delimiters the
// source used so a remote destination the resolver left alone still parses.
const delimited = rawDest.startsWith('<') && rawDest.endsWith('>')
const destination = resolve(delimited ? rawDest.slice(1, -1) : rawDest)
return `${head}${delimited ? `<${destination}>` : destination}`
})
return restore(refsRewritten)
+66 -26
View File
@@ -22,10 +22,13 @@
* 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.
* Deliveries: a `present` call maps onto a compact deliverables card, and the
* authoritative `deliverables/presented` event the tool appends attaches to
* that card by `callId` — or stands alone when the call row is outside the
* events route's head cap. One card per call; a FAILED call replaces its card
* with the generic failed tool row. (The host's own `PresentRow` is a status
* disclosure row over the call — its delivery cards come from the turn-tail
* deliverables, not from the call itself.)
*/
import type { DiffHunk, ReadBlockLine } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarHistoryEntry } from '../context-types.ts'
@@ -97,8 +100,10 @@ export type SidechatTranscriptRow =
}
/** 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. */
* the call's arguments copy — one card per call, never two, whichever
* event lands first. An event with no call row in the window (an
* event-only delivery) still gets its own. A FAILED present call delivered
* nothing and renders as the generic failed tool row instead. */
| { 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
@@ -232,8 +237,9 @@ function parseArgsObject(args: string | undefined): Record<string, unknown> | un
* 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.
* malformed entry declines the whole list: the call-arguments path then falls
* back to the generic tool row, while the event path renders no card (an
* event carries no call row of its own to fall back to).
*/
function deliverableOf(value: unknown): SidechatDeliverable | undefined {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
@@ -439,10 +445,11 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
const streamRows = new Map<string, number>()
/** tool callId → index of its tool row in `rows` (result pairing). */
const callRows = new Map<string, number>()
/** 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<string, number>()
/** present callId → its deliverables card: the card row's index plus the
* call's raw arguments (a FAILED result needs them to rebuild the generic
* tool row). A `deliverables/presented` event attaches to this card
* instead of appending a second one, in either arrival order. */
const presentCalls = new Map<string, { rowIndex: number; args: string | undefined }>()
/** turn → envelope time of its `turn/start` (turn-tail duration basis). */
const turnStarts = new Map<number, number>()
/** Turns that already rendered a failure row (an attempt error and the
@@ -589,13 +596,25 @@ 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.
// A present call renders as its deliverables card, not a tool row.
// Its arguments are the pre-event copy a later deliverables/presented
// event refines; when the event already drew the card, keep that card
// and record the arguments only for a possible failed result.
if (name === 'present') {
// Event-first: the deliverables event already drew this call's card
// (the event reached the window before the call). The event is
// authoritative, so keep its files and only record the arguments a
// failed result needs.
if (typeof callId === 'string') {
const existing = presentCalls.get(callId)
if (existing !== undefined) {
presentCalls.set(callId, { ...existing, args })
break
}
}
const files = presentCallFiles(args)
if (files !== undefined) {
if (typeof callId === 'string') presentRows.set(callId, rows.length)
if (typeof callId === 'string') presentCalls.set(callId, { rowIndex: rows.length, args })
rows.push({ kind: 'deliverables', seq: event.seq, ...(typeof callId === 'string' ? { callId } : {}), files })
break
}
@@ -609,12 +628,33 @@ 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
const resultText = resultTextOf(data)
// 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
// shows what was delivered (and the event supersedes that copy). A
// FAILED present delivered nothing, so its card is replaced by the
// generic failed tool row the call rendered before the card existed,
// and the call stops being associated with a card.
const present = callId === undefined ? undefined : presentCalls.get(callId)
if (callId !== undefined && present !== undefined) {
if (data.error !== undefined) {
presentCalls.delete(callId)
const card = rows[present.rowIndex]
if (card !== undefined && card.kind === 'deliverables') {
rows[present.rowIndex] = {
kind: 'tool',
seq: card.seq,
name: 'present',
failed: true,
...(present.args !== undefined ? { args: present.args } : {}),
...(resultText !== '' ? { resultText } : {}),
executing: false,
}
}
}
break
}
const rowIndex = callId === undefined ? undefined : callRows.get(callId)
const failed = data.error !== undefined
const resultText = resultTextOf(data)
if (rowIndex !== undefined) {
const row = rows[rowIndex]
if (row !== undefined && row.kind === 'tool') {
@@ -648,18 +688,18 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
// 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).
// in the window (the events route caps the window's head, so this
// event can be served without its earlier call).
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 }
const existing = callId === undefined ? undefined : presentCalls.get(callId)
const card = existing === undefined ? undefined : rows[existing.rowIndex]
if (existing !== undefined && card !== undefined && card.kind === 'deliverables') {
rows[existing.rowIndex] = { ...card, files }
break
}
if (callId !== undefined) presentRows.set(callId, rows.length)
if (callId !== undefined) presentCalls.set(callId, { rowIndex: rows.length, args: undefined })
rows.push({ kind: 'deliverables', seq: event.seq, ...(callId !== undefined ? { callId } : {}), files })
break
}
+1 -1
View File
@@ -3,7 +3,7 @@
* (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
* Mirrors 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
+99 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { rewriteLocalImageUrls } from '../src/client/markdown-images.ts'
import { rewriteLocalImageUrls, rewriteProseLocalImageUrls } from '../src/client/markdown-images.ts'
import { rewriteLocalMarkdownLinks } from '../src/client/markdown-navigation.ts'
import type { SessionScope } from '../src/client/api.ts'
const ORIGIN = 'http://127.0.0.1:3080'
@@ -127,3 +128,100 @@ describe('rewriteLocalImageUrls', () => {
expect(out).toMatch(/\[pic-def\]:.*\/sidebar\/file/)
})
})
describe('rewriteLocalImageUrls: CommonMark angle destinations and titles (N7)', () => {
const MEDIA = (path: string): string => `${ORIGIN}/sidebar/file?sessionId=abc&path=${encodeURIComponent(path)}&cwd=%2Frepo`
it('rewrites an angle-delimited destination, including its space', () => {
const out = rewriteLocalImageUrls('![a](<./cat image.png>)', scope, '/repo/readme.md', ORIGIN)
// The delimiters are preserved; the URL-encoded path carries the space.
expect(out).toBe(`![a](<${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fcat+image.png&cwd=%2Frepo>)`)
})
it('preserves an optional double-quoted title while rewriting the destination', () => {
const out = rewriteLocalImageUrls('![a](./x.png "the title")', scope, '/repo/readme.md', ORIGIN)
expect(out).toBe(`![a](${MEDIA('/repo/x.png')} "the title")`)
})
it('preserves a multi-line double-quoted title', () => {
const md = '![a](./x.png "line one\nline two")'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toBe(`![a](${MEDIA('/repo/x.png')} "line one\nline two")`)
})
it('preserves a single-quoted title (it would otherwise not be rewritten at all)', () => {
const out = rewriteLocalImageUrls("![a](./x.png 'the title')", scope, '/repo/readme.md', ORIGIN)
expect(out).toBe(`![a](${MEDIA('/repo/x.png')} 'the title')`)
})
it('combines an angle destination with a title', () => {
const out = rewriteLocalImageUrls('![a](<./cat image.png> "the title")', scope, '/repo/readme.md', ORIGIN)
expect(out).toBe(`![a](<${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fcat+image.png&cwd=%2Frepo> "the title")`)
})
it('leaves a remote angle destination and its title untouched', () => {
const md = '![a](<https://example.com/x y.png> "remote")'
expect(rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)).toBe(md)
})
it('rewrites a reference definition with an angle destination, keeping its delimiters and title', () => {
const md = '![logo][logo]\n\n[logo]: <./logo mark.svg> "the logo"'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain(`[logo]: <${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Flogo+mark.svg&cwd=%2Frepo> "the logo"`)
})
})
describe('rewriteProseLocalImageUrls', () => {
const proseScope: SessionScope = { sessionId: 'abc', cwd: '/repo' }
const FILE_URL = (path: string, cwd = '/repo'): string =>
`${ORIGIN}/sidebar/file?sessionId=abc&path=${encodeURIComponent(path)}&cwd=${encodeURIComponent(cwd)}`
it('resolves a relative destination against the prose cwd (the row is not a file)', () => {
const out = rewriteProseLocalImageUrls('![a](./cat.png)', proseScope, '/repo', ORIGIN)
expect(out).toBe(`![a](${FILE_URL('/repo/cat.png')})`)
})
it('leaves relative destinations untouched when the cwd is unknown', () => {
const md = '![a](./cat.png)\n![b](cat.png)'
expect(rewriteProseLocalImageUrls(md, { sessionId: 'abc' }, undefined, ORIGIN)).toBe(md)
})
it('still serves an absolute local image when the cwd is unknown (no cwd param)', () => {
const out = rewriteProseLocalImageUrls('![a](/abs/cat.png)', { sessionId: 'abc' }, undefined, ORIGIN)
expect(out).toBe(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Fabs%2Fcat.png)`)
})
it('tolerates a trailing separator on the cwd', () => {
const out = rewriteProseLocalImageUrls('![a](./cat.png)', proseScope, '/repo/', ORIGIN)
expect(out).toBe(`![a](${FILE_URL('/repo/cat.png')})`)
// Repeated separators collapse the same way.
const repeated = rewriteProseLocalImageUrls('![a](./cat.png)', proseScope, '/repo///', ORIGIN)
expect(repeated).toBe(`![a](${FILE_URL('/repo/cat.png')})`)
})
it('resolves a relative destination against a Windows cwd', () => {
const out = rewriteProseLocalImageUrls('![a](./cat.png)', { sessionId: 'abc', cwd: 'C:\\repo' }, 'C:\\repo\\', ORIGIN)
// A Windows root keeps its drive and backslash spelling after normalization.
expect(decodeURIComponent(out.replace(/\+/g, ' '))).toContain('C:\\repo\\cat.png')
})
it('rewrites a prose reference-style image against the cwd', () => {
const md = '![logo][logo]\n\n[logo]: ./logo.svg'
const out = rewriteProseLocalImageUrls(md, proseScope, '/repo', ORIGIN)
expect(out).toContain(`[logo]: ${FILE_URL('/repo/logo.svg')}`)
expect(out).toContain('![logo][logo]')
})
it('composes with the local-link rewrite: image first, then the link inside its label', () => {
const md = '[![badge](./badge.svg)](./doc.md#intro)\n\n![cat](./cat.png)'
const out = rewriteLocalMarkdownLinks(
rewriteProseLocalImageUrls(md, proseScope, '/repo', ORIGIN),
undefined,
'/repo',
)
// The image destination became a media URL and the enclosing `.md` link is
// still claimed (its heading fragment survives as %23).
expect(out).toContain(`[![badge](${FILE_URL('/repo/badge.svg')})](./doc.md%23intro)`)
expect(out).toContain(`![cat](${FILE_URL('/repo/cat.png')})`)
})
})
+7
View File
@@ -27,6 +27,8 @@ const USER_MD = [
'',
'![dog](/p/dog.png)',
'',
'![spaced](<./cat image.png>)',
'',
'```md',
'![fenced](./fenced.png)',
'```',
@@ -103,6 +105,11 @@ describe('SideChatView local markdown images (C1)', () => {
const bare = localImage(view.container, `${SESSION_CWD}/chart.png`)
expect(bare, '![chart](chart.png) must render as an img').toBeDefined()
// A CommonMark angle destination carries a space in its path through the
// whole pipeline (rewrite → host parse → media route query).
const spaced = localImage(view.container, `${SESSION_CWD}/cat image.png`)
expect(spaced, '![spaced](<./cat image.png>) must render as an img').toBeDefined()
view.unmount()
})
+7 -1
View File
@@ -118,7 +118,13 @@ describe('SideChatView present deliverables card (C2)', () => {
// 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() })
const pdfButton = pdfRow[0] as HTMLElement
// N1: the accessible name carries the visible description, and the title
// tooltip is the cwd-resolved spelling of the (relative) call argument.
expect(pdfButton.getAttribute('aria-label')).toContain('report.pdf')
expect(pdfButton.getAttribute('aria-label')).toContain('季度报告')
expect(pdfButton.getAttribute('title')).toBe(`${SESSION_CWD}/report.pdf`)
await act(async () => { pdfButton.click() })
expect(harness.host.openTab).toHaveBeenCalledTimes(1)
expect(harness.host.openTab).toHaveBeenCalledWith(expect.objectContaining({
type: 'editor',
+143
View File
@@ -477,6 +477,149 @@ describe('tool cards', () => {
})
})
describe('present deliverables rows', () => {
/** The `present` tool's arguments: paths relative to the session cwd. */
const PRESENT_ARGS = JSON.stringify({
files: [
{ path: 'report.pdf', description: 'the report' },
{ path: 'chart.png' },
],
})
/** The authoritative event copy: absolute paths + model descriptions. */
const EVENT_FILES = [
{ path: '/p/report.pdf', description: 'event copy' },
{ path: '/p/chart.png', description: 'the chart' },
]
const seed = entry(ev('session/end-seed', 0))
const presentCall = (seq: number, callId = 'cp', args = PRESENT_ARGS): SidebarHistoryEntry =>
entry(ev('tool/call', seq, { turn: 1, step: 1, callId, name: 'present', arguments: args }))
const presentResult = (
seq: number,
callId = 'cp',
text = 'Presented /p/report.pdf',
extra: Record<string, unknown> = {},
): SidebarHistoryEntry =>
entry(ev('tool/result', seq, { turn: 1, step: 1, message: toolRoleResultMessage(callId, text), ...extra }))
const presentedEvent = (seq: number, callId = 'cp', files: readonly unknown[] = EVENT_FILES): SidebarHistoryEntry =>
entry(ev('deliverables/presented', seq, { turn: 1, callId, files }))
it('keeps the card when the present result succeeds (the result row stays hidden)', () => {
expect(transcriptRows([seed, presentCall(1), presentResult(2)])).toEqual([
{ kind: 'deliverables', seq: 1, callId: 'cp', files: [{ path: 'report.pdf', description: 'the report' }, { path: 'chart.png' }] },
])
})
it('replaces the card with the generic failed tool row when the present call fails (M1a)', () => {
// The tool ran and reported an error (FS_NOT_FOUND and friends): nothing
// was delivered, so the successful-looking card must give way to the
// generic failed row — and the error text must not be dropped.
const rows = transcriptRows([
seed,
presentCall(1),
presentResult(2, 'cp', 'ENOENT: report.pdf', { error: { name: 'FS_NOT_FOUND', code: 'FS_NOT_FOUND' } }),
])
expect(rows).toEqual([{
kind: 'tool',
seq: 1,
name: 'present',
failed: true,
args: PRESENT_ARGS,
resultText: 'ENOENT: report.pdf',
executing: false,
}])
})
it('omits an empty result text on the failed present row', () => {
const rows = transcriptRows([
seed,
presentCall(1),
presentResult(2, 'cp', '', { error: { name: 'FS_NOT_FOUND', code: 'FS_NOT_FOUND' } }),
])
expect(rows).toEqual([{
kind: 'tool',
seq: 1,
name: 'present',
failed: true,
args: PRESENT_ARGS,
executing: false,
}])
})
it('keeps ONE event card when the event precedes a malformed present call', () => {
const malformed = presentCall(2, 'cp', JSON.stringify({ files: [{ path: 7 }] }))
expect(transcriptRows([seed, presentedEvent(1), malformed])).toEqual([
{ kind: 'deliverables', seq: 1, callId: 'cp', files: EVENT_FILES },
])
})
it('keeps ONE card when the presented event precedes its call (event-first, M1b)', () => {
// The events route caps the window's head, so the authoritative event can
// be served before (or without) the call it belongs to.
expect(transcriptRows([seed, presentedEvent(1), presentCall(2)])).toEqual([
{ kind: 'deliverables', seq: 1, callId: 'cp', files: EVENT_FILES },
])
})
it('keeps ONE card when the presented event follows its call (event data authoritative)', () => {
const call = presentCall(1, 'cp', JSON.stringify({ files: [{ path: 'from-args.pdf', description: 'args copy' }] }))
expect(transcriptRows([seed, call, presentedEvent(2)])).toEqual([
{ kind: 'deliverables', seq: 1, callId: 'cp', files: EVENT_FILES },
])
})
it('renders an event-only delivery whose call row is outside the window', () => {
expect(transcriptRows([seed, presentedEvent(1)])).toEqual([
{ kind: 'deliverables', seq: 1, callId: 'cp', files: EVENT_FILES },
])
})
it('updates the SAME card when a second presented event names one callId', () => {
const rows = transcriptRows([
seed,
presentCall(1),
presentedEvent(2),
presentedEvent(3, 'cp', [{ path: '/p/final.pdf' }]),
])
expect(rows).toHaveLength(1)
expect(rows[0]).toMatchObject({ kind: 'deliverables', seq: 1, callId: 'cp' })
expect((rows[0] as Extract<SidechatTranscriptRow, { kind: 'deliverables' }>).files).toEqual([{ path: '/p/final.pdf' }])
})
it('cuts inherited present calls and deliveries with the fork seed', () => {
const rows = transcriptRows([
presentCall(0, 'c-seed'),
presentedEvent(1, 'c-seed', [{ path: '/p/inherited.pdf' }]),
entry(ev('session/end-seed', 2)),
presentedEvent(3, 'c-own', [{ path: '/p/own.pdf' }]),
])
expect(rows).toEqual([{ kind: 'deliverables', seq: 3, callId: 'c-own', files: [{ path: '/p/own.pdf' }] }])
})
it('leaves malformed or empty call files on the generic tool row', () => {
for (const args of [JSON.stringify({ files: [] }), JSON.stringify({ files: [{ path: 7 }] })]) {
expect(transcriptRows([seed, presentCall(1, 'cp', args)])).toEqual([
{ kind: 'tool', seq: 1, name: 'present', failed: false, args, executing: true },
])
}
})
it('re-adopts a deliverables card across pulls and rebuilds it when its files change', () => {
const entries = [seed, presentCall(1), presentedEvent(2)]
const first = transcriptRows(entries)
const second = transcriptRows(entries, first)
expect(second).toEqual(first)
expect(second[0]).toBe(first[0])
const changed = transcriptRows([...entries, presentedEvent(3, 'cp', [{ path: '/p/final.pdf' }])], first)
expect(changed).toHaveLength(1)
expect(changed[0]).not.toBe(first[0])
})
})
describe('usage formatting', () => {
it('formatTokens mirrors the main conversation K/M compaction', () => {
expect(formatTokens(517)).toBe('517')