From 5081697aafe3b54aa26c2f11dcce1324b8602ad0 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 28 Jul 2026 14:58:06 +0800 Subject: [PATCH 01/14] feat(web): render bash tool output as a terminal card The bash tool already declares the `card: 'terminal'` render intent for both its call and its result, and host/connection/runtime already deliver it to the browser as callView/resultView. The Web client ignored it: rows derived from raw args, and the details panel flattened every tool's content into one soft-wrapping `
`. Column-aligned output folded into
a paragraph and a long listing stretched the panel without bound.

`TerminalBlock` (ui-primitives) renders a command as a terminal surface:
a shortened-cwd prompt line, output at `white-space: pre` in a
horizontally scrolling box, a head/tail height cap with an expand
control, an exit-code/signal status pill, and a copy control for the raw
output. ANSI SGR runs are parsed with `anser` and resolved onto `--dsw-*`
theme tokens, with literal rgb kept for values the design system has no
token for. Geometry and fonts mirror CodeBlock; the clipboard write both
need moved into a package-internal `clipboard.ts`.

Both Web render sites for a bash call consume the intent through one
derivation (`terminal-card-model.ts`), so they cannot disagree about a
command, its cwd, or its exit status: the keyed BashRow carries the card
resident below its summary row, and the render-site fallback row keeps it
behind its existing expand control. Rows cap at 8 lines against the
panel's 16.

Inline output in the chat row reverses this package's stated
no-inline-output convention, on the owner's explicit decision; the Agent
Note records the reversal and its bound.

Tests: TerminalBlock/ansi/clipboard unit specs, ui-conversation wiring
specs at every render site, a built-client-graph snapshot covering both
chat-row shapes, and a real-browser e2e asserting the no-wrap layout and
the page's own Clipboard API.
---
 .../2026-07-28-web-terminal-card.i18n.yaml    |   6 +
 .../feature/2026-07-28-web-terminal-card.md   |  65 ++++
 .../2026-07-28-web-terminal-card.zh.md        |  65 ++++
 ...26-web-syntax-highlighting-shiki.i18n.yaml |   6 +-
 ...026-07-26-web-syntax-highlighting-shiki.md |   2 +-
 ...-07-26-web-syntax-highlighting-shiki.zh.md |   2 +-
 apps/web/tests/code-mode-fixture.snapshot.ts  |   6 +-
 apps/web/tests/navigation-panes.e2e.ts        |  46 ++-
 .../navigation-panes/details-open.expected.md |   7 +-
 .../terminal-card.expected.md                 |   3 +
 apps/web/tests/terminal-card.snapshot.ts      | 324 ++++++++++++++++
 .../client/connection/src/client/fixture.ts   |  73 +++-
 .../client/ui-conversation/README.i18n.yaml   |   4 +-
 packages/client/ui-conversation/README.md     |   2 +
 packages/client/ui-conversation/README.zh.md  |   2 +
 .../src/client/chat/GenericToolCard.tsx       |   2 +
 .../src/client/chat/ToolRow.module.css        |  12 +-
 .../src/client/chat/ToolRow.tsx               |  39 +-
 .../client/contract/terminal-card-model.ts    |  83 ++++
 .../src/client/contract/tool-call-model.ts    |   6 +-
 .../client/skeleton/DetailsPanel.module.css   |   6 +
 .../src/client/skeleton/DetailsPanel.tsx      |  79 ++--
 .../client/toolviews/bash-sample.module.css   |  16 +-
 .../src/client/toolviews/bash-sample.tsx      |  51 ++-
 .../tests/chat-tool-row.spec.tsx              |  21 +
 .../tests/terminal-card.spec.tsx              | 359 ++++++++++++++++++
 .../client/ui-primitives/README.i18n.yaml     |   6 +-
 packages/client/ui-primitives/README.md       |   7 +-
 packages/client/ui-primitives/README.zh.md    |   7 +-
 packages/client/ui-primitives/package.json    |   1 +
 packages/client/ui-primitives/src/Pill.tsx    |   4 +-
 .../src/TerminalBlock.module.css              | 101 +++++
 .../ui-primitives/src/TerminalBlock.tsx       | 170 +++++++++
 packages/client/ui-primitives/src/ansi.ts     | 153 ++++++++
 .../client/ui-primitives/src/clipboard.ts     |  48 +++
 packages/client/ui-primitives/src/index.ts    |   2 +
 .../ui-primitives/src/markdown/CodeBlock.tsx  |  40 +-
 .../client/ui-primitives/tests/ansi.spec.ts   | 188 +++++++++
 .../tests/terminal-block.spec.tsx             | 315 +++++++++++++++
 pnpm-lock.yaml                                |   8 +
 40 files changed, 2218 insertions(+), 119 deletions(-)
 create mode 100644 .agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
 create mode 100644 .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
 create mode 100644 .agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
 create mode 100644 apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md
 create mode 100644 apps/web/tests/terminal-card.snapshot.ts
 create mode 100644 packages/client/ui-conversation/src/client/contract/terminal-card-model.ts
 create mode 100644 packages/client/ui-conversation/tests/terminal-card.spec.tsx
 create mode 100644 packages/client/ui-primitives/src/TerminalBlock.module.css
 create mode 100644 packages/client/ui-primitives/src/TerminalBlock.tsx
 create mode 100644 packages/client/ui-primitives/src/ansi.ts
 create mode 100644 packages/client/ui-primitives/src/clipboard.ts
 create mode 100644 packages/client/ui-primitives/tests/ansi.spec.ts
 create mode 100644 packages/client/ui-primitives/tests/terminal-block.spec.tsx

diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
new file mode 100644
index 0000000000..347d5978c0
--- /dev/null
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
+2026-07-28-web-terminal-card.md: 76d5c47054378330da9e9eebb70571925e47f741
+2026-07-28-web-terminal-card.zh.md: 83d5e7f72d9b04358ce4fe1fd9295e5c97045031
diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
new file mode 100644
index 0000000000..76d5c47054
--- /dev/null
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
@@ -0,0 +1,65 @@
+# Agent Note: Web terminal card — the bash render intent reaches the browser
+
+Status: implemented
+
+English | [中文](2026-07-28-web-terminal-card.zh.md)
+
+## Problem
+
+The bash tool declares `card: 'terminal'` for both its call and its result ([render-intent union](../architecture/2026-07-02-tool-render-intent-union.md)): the call view carries the command, an optional model-authored description, and the working directory; the result view carries the output, exit code, and terminating signal. That view already reaches the browser — host, connection, and runtime deliver it onto `ConversationSnapshot` as `callView`/`resultView` — and the TUI already renders it as a `$`-prompt card with an exit line and a head/tail height cap.
+
+The Web client ignored it. `packages/client/ui-conversation/src/client/contract/tool-call-model.ts` derived every row from raw tool args, and `skeleton/DetailsPanel.tsx` flattened every tool's content blocks into one `
` with `white-space: pre-wrap; word-break: break-word`. Two defects followed from soft-wrapping and from having no height bound: multi-column output (`ls`, a table, box drawing) folded into a paragraph and lost the column alignment that is the whole point of that output, and a long single-column listing stretched the details panel to the length of the listing.
+
+## Decision
+
+`TerminalBlock` is a `ui-primitives` component that renders a shell command as a terminal surface, and both Web render sites for a bash call consume the terminal render intent through it: the chat tool row's expanded body and the details panel's Output section. `ui-conversation/src/client/contract/terminal-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a command, its cwd, or its exit status. It returns null — the generic path — whenever neither side declares `card: 'terminal'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how the bash tool's execution errors and background starts keep their existing rendering.
+
+The component's contract:
+
+- **Prompt line.** A shortened cwd label followed by the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`.
+- **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding.
+- **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends.
+- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters, and a carriage return reduces its line to the final redraw, which is what a terminal shows for progress output.
+- **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard.
+
+Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks.
+
+### Inline output in the chat row reverses a stated convention
+
+`chat/ToolRow.tsx` and `contract/tool-call-model.ts` asserted "no inline output ever — full results live in the details panel". Showing the terminal block in the row reverses that, on the owner's explicit decision.
+
+The reason the reversal holds: for a shell command the output *is* the result the user is reading, so routing it exclusively to a panel makes the common case a two-step interaction. A bounded, height-capped, non-wrapping terminal block in the row is what makes a bash-heavy transcript readable in one pass. The old rule's actual concern was a row whose height was unbounded by the length of the output, and the height cap plus expand control is what keeps that from returning.
+
+The remaining bound: the row caps at `CHAT_TERMINAL_MAX_LINES` (8), half the primitive's default, which the panel keeps — the message flow is a summary surface read across many calls, the panel is the single-call reading surface, so the panel stays the place for the full output. Only the terminal intent renders inline; a generic tool's content is still panel-only.
+
+## Alternatives considered
+
+**Render the terminal block only in the details panel.** This keeps the stated no-inline-output convention and needs no reversal to record. Rejected by the owner's explicit decision: a shell command's output is what the user came to read, and putting it one click away costs more than the convention buys. Recorded here as the owner's call, not as a conclusion derived from the codebase.
+
+**Reuse `CodeBlock` with a `console` language instead of a new primitive.** Rejected: `CodeBlock` soft-wraps, which is the defect being fixed, and it has no exit status, no cwd prompt line, no height cap, and no ANSI handling. Adding four terminal-specific concerns to the shared code-fence component would impose them on every markdown fence. The two components share their geometry and font tokens instead, which is the only part where one implementation is correct for both.
+
+**Hand-roll the SGR parser.** Rejected: an SGR parser is exactly the surface [prefer maintained dependencies over hand-rolling](../process/2026-07-26-dependencies-over-hand-rolling.md) says not to own — its edge cases (256-palette and truecolor forms, `reverse`, multi-parameter runs, unterminated sequences) each fail on output nobody produces in a test, so a hand-rolled version stays subtly wrong for a long time. Stated honestly against that policy's bar: `anser` does **not** delete existing owned code. It is a capability addition, which that note distinguishes from a net-deletion simplification; the health and boundary-fit halves of the bar are what it clears. What stays hand-rolled is the part `anser` does not cover: the theme-token color mapping, the non-CSI sanitizing, the carriage-return redraw, and the per-line span folding the height cap slices.
+
+## Consequences
+
+`anser` is a new runtime dependency of `packages/client/ui-primitives`, so every consumer of that package pays for it once. A bash row in the Web chat carries output, which is a deliberate density increase over a summary-only row; the cap is what keeps it bounded, and a tighter cap is a props change, not a redesign.
+
+`TerminalBlock` reads only the terminal view's fields, so it stays a pure function of what the render intent carries — no session lookups, replay-safe like the presenters that produce the view. A UI without the terminal capability still gets the bridge's fenced fallback; nothing about the tool's result shape changed.
+
+Inline rendering is licensed for the terminal intent alone. A future intent that wants it needs its own bound and its own decision, argued against the reason recorded here rather than against the panel-only convention on its own.
+
+## Testing
+
+`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws, and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly.
+
+`packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files.
+
+`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 66 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit recovered from the trailing marker.
+
+`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `details-open.expected.md` golden was refreshed for the panel's new terminal card. That refresh also absorbed a stale `Input json` line and its copy button, which the shiki `CodeBlock` change already on master left behind — verified as failing on a clean rebuilt tree before this change, so it is a correction carried along, not an effect of this one.
+
+## Related
+
+- [Tagged render-intent union for tool-call presentation](../architecture/2026-07-02-tool-render-intent-union.md) — the `card`-tagged vocabulary this consumes; the Web client is now a full consumer of the `terminal` arm rather than of args alone.
+- [Web client syntax highlighting](../process/2026-07-26-web-syntax-highlighting-shiki.md) — owns `CodeBlock` and its shiki arm, and records why tool output deliberately stays unhighlighted; ANSI color here is authored color, not guessed grammar.
+- [Web client architecture](../architecture/2026-07-19-gui-web-client-architecture.md) — the slot and snapshot layering the two render sites sit in.
diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
new file mode 100644
index 0000000000..83d5e7f72d
--- /dev/null
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
@@ -0,0 +1,65 @@
+# Agent Note: Web terminal card — the bash render intent reaches the browser
+
+Status: implemented
+
+[English](2026-07-28-web-terminal-card.md) | 中文
+
+## Problem
+
+bash 工具的调用与结果都声明 `card: 'terminal'`([渲染意图联合类型](../architecture/2026-07-02-tool-render-intent-union.md)):调用视图携带命令、一段可选的模型撰写描述以及工作目录,结果视图携带输出、退出码与终止信号。该视图早已抵达浏览器——host、connection 与 runtime 把它投递到 `ConversationSnapshot` 的 `callView`/`resultView` 上——TUI 也早已把它渲染为带 `$` 提示符的卡片,附退出行与首尾高度上限。
+
+Web client 却对它视而不见。`packages/client/ui-conversation/src/client/contract/tool-call-model.ts` 仅从原始工具参数推导每一行,`skeleton/DetailsPanel.tsx` 则把所有工具的内容块压平进一个 `
`,样式为 `white-space: pre-wrap; word-break: break-word`。软换行加上没有高度约束,带来两个缺陷:多列输出(`ls`、表格、制表符绘图)被折成一段文字,丢掉了这类输出赖以存在的列对齐;而单列的长列表会把详情面板拉长到与列表等长。
+
+## Decision
+
+`TerminalBlock` 是 `ui-primitives` 中把 shell 命令渲染为终端表面的组件,bash 调用在 Web 侧的两个渲染点都经由它消费 terminal 渲染意图:聊天工具行展开后的正文,以及详情面板的 Output 区。`ui-conversation/src/client/contract/terminal-card-model.ts` 是把快照上的 `callView`/`resultView` 这一对转换为该组件 props 的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧。当两侧都不声明 `card: 'terminal'` 时它返回 null,即走 generic 路径——包括本 client 版本不认识的 `card` 取值;当一个已落定调用的结果视图是 generic 时同样返回 null,这正是 bash 工具的执行错误与后台启动得以保持既有渲染的方式。
+
+该组件的契约:
+
+- **提示符行。** 一个缩短的 cwd 标签,其后原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。
+- **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。
+- **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。
+- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM;回车会把所在行归约为最后一次重绘,这正是终端对进度输出的呈现。
+- **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。
+
+几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。
+
+### 聊天行内嵌输出推翻了一条既有约定
+
+`chat/ToolRow.tsx` 与 `contract/tool-call-model.ts` 都断言过「绝不内嵌输出——完整结果在详情面板」。在行内显示终端块推翻了这一点,依据是 owner 的明确决定。
+
+这次推翻成立的理由:对 shell 命令而言,输出**就是**用户要读的结果,把它专门收进面板会让最常见的情形变成两步交互。行内一个有界、限高、不换行的终端块,正是让 bash 密集的 transcript 一遍读完的条件。旧规则真正担心的是行高不受输出长度约束,而高度上限加展开控件正是防止其复现的机制。
+
+余下的约束:行内上限为 `CHAT_TERMINAL_MAX_LINES`(8),是组件默认值的一半,而面板沿用默认值——消息流是跨多次调用阅读的摘要表面,面板才是单次调用的阅读表面,因此面板仍是查看完整输出的地方。只有 terminal 意图内嵌渲染;generic 工具的内容依旧只在面板中。
+
+## Alternatives considered
+
+**只在详情面板渲染终端块。** 这样保留既有的「不内嵌输出」约定,也不需要记录任何推翻。已被 owner 的明确决定否决:shell 命令的输出正是用户来读的东西,把它挪到一次点击之外,代价高于该约定带来的收益。此处记录的是 owner 的裁决,而非从代码库推导出的结论。
+
+**复用 `CodeBlock` 并传入 `console` 语言,而不新建组件。** 已否决:`CodeBlock` 会软换行,而软换行正是本次要修的缺陷,且它没有退出状态、没有 cwd 提示符行、没有高度上限、也不处理 ANSI。把四项终端专属关注点加进共享的代码围栏组件,等于把它们强加给每一个 markdown 围栏。两个组件改为共享几何与字体 token,那是唯一一处「一套实现对两者都正确」的部分。
+
+**手写 SGR 解析器。** 已否决:SGR 解析器恰是[优先采用维护良好的依赖而非手写](../process/2026-07-26-dependencies-over-hand-rolling.md)所指明不该自持的那类实现——它的边界情形(256 色板与 truecolor 形式、`reverse`、多参数分段、未终止的序列)各自只在没人会写进测试的输出上失效,因此手写版本会在很长时间内一直微妙地出错。对照那条策略的门槛如实陈述:`anser` **并未**删除任何既有自持代码。它是一次能力增补,而那条 Agent Note 把这与净删除式的简化区分开来;它清过的是健康度与边界契合这两半门槛。`anser` 未覆盖而仍由我们手写的部分是:主题 token 的颜色映射、非 CSI 序列的剥除、回车重绘,以及供高度上限切片的逐行 span 折叠。
+
+## Consequences
+
+`anser` 成为 `packages/client/ui-primitives` 的一项新运行时依赖,因此该包的每个消费方都为它支付一次。Web 聊天中的 bash 行现在承载输出,相比只有摘要的行,这是有意提高的信息密度;上限是维持其有界的机制,而调紧上限是改一个 prop,不是重新设计。
+
+`TerminalBlock` 只读取 terminal 视图携带的字段,因此它始终是渲染意图内容的纯函数——不查会话状态,与产出该视图的 presenter 一样可安全回放。不具备终端能力的 UI 仍从桥接层拿到围栏式回退;工具的结果形态未作任何改动。
+
+内嵌渲染的许可仅授予 terminal 意图。将来想要内嵌的意图需要有自己的边界与自己的决定,且需针对此处记录的理由来论证,而不是仅针对「只在面板」这条约定本身。
+
+## Testing
+
+`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘,以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。
+
+`packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。
+
+`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 66 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及从末尾标记还原出的非零退出码。
+
+`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `details-open.expected.md` 基准已为面板的新终端卡片重新录制。该次录制同时吸收了一行陈旧的 `Input json` 及其复制按钮——那是 master 上已有的 shiki `CodeBlock` 改动留下的;在干净并重新构建的工作树上验证过它本就失败,因此那是被顺带修正的部分,而非本次改动的影响。
+
+## Related
+
+- [Tagged render-intent union for tool-call presentation](../architecture/2026-07-02-tool-render-intent-union.md)——本次消费的 `card` 标签词汇;Web client 现在是 `terminal` 分支的完整消费方,而不再只消费参数。
+- [Web client syntax highlighting](../process/2026-07-26-web-syntax-highlighting-shiki.md)——它拥有 `CodeBlock` 及其 shiki 分支,并记录了工具输出为何有意不做语法高亮;这里的 ANSI 颜色是作者指定的颜色,不是猜出来的语法。
+- [Web client architecture](../architecture/2026-07-19-gui-web-client-architecture.md)——两个渲染点所处的 slot 与快照分层。
diff --git a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.i18n.yaml
index 9fd37bcedb..72cbbc368f 100644
--- a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.i18n.yaml
+++ b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.i18n.yaml
@@ -1,6 +1,6 @@
 # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
-#   pnpm run verify-translation-pairing --write
-2026-07-26-web-syntax-highlighting-shiki.md: b329e35f1d0ce7b3de454758403a09f67056b5af
-2026-07-26-web-syntax-highlighting-shiki.zh.md: 8e9d1f0d0c38ce64bcb5da1262538da762f70b12
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.md
+2026-07-26-web-syntax-highlighting-shiki.md: 48a1e4c43f19693f90906f210f0ed85db3f31687
+2026-07-26-web-syntax-highlighting-shiki.zh.md: 780b66a309c841c542f873f376226b8da454e050
diff --git a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.md b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.md
index b329e35f1d..48a1e4c43f 100644
--- a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.md
+++ b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.md
@@ -17,7 +17,7 @@ The client rendered every code surface — markdown fences in assistant prose, t
 - **Dependency**: `shiki/core` + `@shikijs/langs`, composed via `createHighlighterCoreSync` with `createJavaScriptRegexEngine({ forgiving: true })` — no oniguruma WASM, no async init, bundle-friendly. Grammar allowlist: `typescript` (embeds JS), `shellscript`, `json` — the languages the harness actually renders; everything else falls back to a geometry-identical plain block, never an error. Prior art: the VitePress site already renders all documentation code through shiki, and TextMate grammars materially beat regex highlighters on TypeScript — the payload that matters here.
 - **Singleton**: `ui-primitives/src/markdown/highlight.ts` creates one `HighlighterCore` per document and exposes `highlightToHtml(code, lang)` (undefined = render plain). Engine + grammar construction is a ~120-175ms long task, so the module pre-warms the singleton in a deferred task at plugin boot (the lazy path stays as the correctness fallback), keeping the cost off the render path where a stream's finalize swap would jank. The alias table is a `Map`, not an object: fence info strings are assistant-authored, so a label like `constructor` must miss instead of resolving an inherited property and crashing shiki. The shared `CodeBlock` component owns both arms; its shiki arm injects the generated span tree via `dangerouslySetInnerHTML` — sanctioned because shiki emits a static span tree computed from the code text (no user HTML passes through, no scripts/handlers), shiki's own documented consumption path.
 - **Theming**: shiki's `createCssVariablesTheme` routes every token color through `--shiki-*` custom properties; the VALUES live in a new `ui-theme/styles/shiki.css` token sheet (light on `:root`, dark on `body[data-ds-dark-theme]` — the same cascade as every other sheet), imported by the shell's `base.css` chain. Component CSS stays tokens-only; no literal color ever enters JS or component sheets. Background/foreground alias the existing markdown code-block tokens so highlighted and plain blocks agree.
-- **Surfaces**: markdown fences (`MarkdownText`'s `pre` component routes single-string fences through `CodeBlock`), the `run_code` expanded program body (ToolRow's code variant, `lang="typescript"`), and the details panel's Input args (`lang="json"`). Output stays plain deliberately — tool output is arbitrary text, and guessing a grammar would mis-highlight more than it helps.
+- **Surfaces**: markdown fences (`MarkdownText`'s `pre` component routes single-string fences through `CodeBlock`), the `run_code` expanded program body (ToolRow's code variant, `lang="typescript"`), and the details panel's Input args (`lang="json"`). Tool output is never syntax-highlighted — it is arbitrary text, and guessing a grammar would mis-highlight more than it helps; a bash card's output carries only the color its own ANSI sequences declare, through [the terminal card](../feature/2026-07-28-web-terminal-card.md).
 
 ## Alternatives considered
 
diff --git a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.zh.md b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.zh.md
index 8e9d1f0d0c..780b66a309 100644
--- a/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.zh.md
+++ b/.agents/notes/implemented/process/2026-07-26-web-syntax-highlighting-shiki.zh.md
@@ -17,7 +17,7 @@ client 过去把每一处代码表面——assistant 正文里的 markdown 围
 - **依赖**:`shiki/core` + `@shikijs/langs`,经 `createHighlighterCoreSync` 搭配 `createJavaScriptRegexEngine({ forgiving: true })` 组装——不带 oniguruma WASM、没有异步初始化、对 bundle 友好。语法(grammar)白名单:`typescript`(内嵌 JS)、`shellscript`、`json`——即 harness 实际会渲染的那几种语言;其余一律回退到几何完全一致的纯文本块,绝不报错。先例:VitePress 站点已经通过 shiki 渲染全部文档代码;而在 TypeScript(正是此处要紧的载荷)上,TextMate 语法实质性优于正则高亮器。
 - **单例**:`ui-primitives/src/markdown/highlight.ts` 为每个 document 创建一个 `HighlighterCore`,并公开 `highlightToHtml(code, lang)`(undefined 即渲染为纯文本)。引擎加语法的构建是一次约 120-175ms 的长任务,因此模块在插件启动时用延迟任务预热单例(惰性路径保留为正确性兜底),把这笔开销挪出渲染路径——否则流式 finalize 交换的那一刻会卡顿。别名表用 `Map` 而非对象:fence 信息串由 assistant 撰写,诸如 `constructor` 这样的标签必须落空,而不是解析到继承属性并让 shiki 崩溃。共享的 `CodeBlock` 组件同时拥有两条分支;其 shiki 分支经 `dangerouslySetInnerHTML` 注入生成的 span 树——此用法获准,因为 shiki 输出的是从代码文本计算出的静态 span 树(不流经任何用户 HTML,没有脚本或事件处理器),这正是 shiki 自身文档载明的消费路径。
 - **主题化**:shiki 的 `createCssVariablesTheme` 让每一种 token 颜色都经由 `--shiki-*` 自定义属性路由;取值本身住在新增的 `ui-theme/styles/shiki.css` token 表里(亮色在 `:root`、暗色在 `body[data-ds-dark-theme]`——层叠方式与其余每张样式表相同),由壳的 `base.css` 导入链引入。组件 CSS 保持只用 token;任何字面颜色都不进入 JS 或组件样式表。背景/前景以别名指向既有的 markdown 代码块 token,使高亮块与纯文本块彼此一致。
-- **表面**:markdown 围栏代码块(`MarkdownText` 的 `pre` 组件把单字符串围栏路由到 `CodeBlock`)、`run_code` 展开后的程序正文(ToolRow 的 code 变体,`lang="typescript"`),以及 details 面板的 Input 参数(`lang="json"`)。输出有意保持纯文本——工具输出是任意文本,硬猜一种语法,带来的误高亮会多于帮助。
+- **表面**:markdown 围栏代码块(`MarkdownText` 的 `pre` 组件把单字符串围栏路由到 `CodeBlock`)、`run_code` 展开后的程序正文(ToolRow 的 code 变体,`lang="typescript"`),以及 details 面板的 Input 参数(`lang="json"`)。工具输出从不做语法高亮——它是任意文本,硬猜一种语法,带来的误高亮会多于帮助;bash 卡片的输出只承载其自身 ANSI 序列声明的颜色,经由[终端卡片](../feature/2026-07-28-web-terminal-card.md)渲染。
 
 ## 曾考虑的替代方案
 
diff --git a/apps/web/tests/code-mode-fixture.snapshot.ts b/apps/web/tests/code-mode-fixture.snapshot.ts
index f53777fff8..101859cc4a 100644
--- a/apps/web/tests/code-mode-fixture.snapshot.ts
+++ b/apps/web/tests/code-mode-fixture.snapshot.ts
@@ -213,9 +213,9 @@ it('trajectory and waterfall surface the run_code sub-calls with real timing', a
   }).toMatchInlineSnapshot(`
     {
       "subCells": [
-        "#51Subbash · {"command":"ls notes","description":"List notes"}+0.8s",
-        "#52Subread · {"path":"notes/demo.txt"}+0.8s",
-        "#53Subread · {"path":"notes/missing.txt"}+0.8s",
+        "#49Subbash · {"command":"ls notes","description":"List notes"}+0.8s",
+        "#50Subread · {"path":"notes/demo.txt"}+0.8s",
+        "#51Subread · {"path":"notes/missing.txt"}+0.8s",
       ],
     }
   `)
diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts
index bbae7363df..b0e340da43 100644
--- a/apps/web/tests/navigation-panes.e2e.ts
+++ b/apps/web/tests/navigation-panes.e2e.ts
@@ -26,6 +26,7 @@ const SEED = join(SNAPSHOT_DIR, 'seed.jsonl')
 const TRAJECTORY_EXPECTED = join(SNAPSHOT_DIR, 'trajectory.expected.md')
 const WATERFALL_EXPECTED = join(SNAPSHOT_DIR, 'waterfall.expected.md')
 const DETAILS_EXPECTED = join(SNAPSHOT_DIR, 'details-open.expected.md')
+const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md')
 const MODE = webSnapshotMode()
 const SEED_ID = 'navigation-panes-web-e2e'
 
@@ -170,9 +171,11 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
     await bashRow.click()
     await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).toBeNull()
     // The open panel shows the selected call's name, arguments, and durable
-    // result (NAVIGATION_OK appears in the chat row too, hence >= 2 total).
+    // result. The chat row carries its own terminal card, so NAVIGATION_OK
+    // appears there too — in the prompt line and in the output.
     await expect.poll(() => page.getByText('NAVIGATION_OK', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
-    // Golden of the open panel: tool name header, Input args, Output result.
+    // Golden of the open panel: tool name header, Input args, and the Output
+    // section's terminal card (prompt line + captured output).
     const snapshot = (await captureStableAria(page, '[class*="detailsCol"]', scaffold.workspaceCwd))
       .split(SEED_ID).join('{{seededId}}')
     await compareOrRefreshGolden(DETAILS_EXPECTED, snapshot, MODE)
@@ -180,11 +183,50 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
     await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).not.toBeNull()
   }, 60_000)
 
+  it.skipIf(MODE === 'record')('renders the bash row as a terminal card in the real browser', async () => {
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-terminal'))
+    await page.getByRole('tab', { name: 'Chat' }).click()
+    // The card is resident in the keyed bash row (no expand gesture): the
+    // recorded command's own output sits in the message flow, derived from the
+    // logged call/result presentations alone.
+    const card = page.locator('[data-sample="bash-global"] ~ [data-terminal], [data-sample="bash-global"] [data-terminal]').first()
+    await card.waitFor({ timeout: 15_000 })
+    // Real layout, not jsdom's stub (which computes no geometry at all):
+    // squeeze the output pane below its content width and the line must keep
+    // its single row and overflow sideways instead of folding. Soft-wrapping
+    // here is what shredded the column alignment this card exists to hold.
+    const layout = await card.locator('[class*="_output_"]').first().evaluate((node) => {
+      const pane = node as HTMLElement
+      const row = pane.querySelector('[class*="_line_"]')
+      if (row === null) throw new Error('output pane has no line')
+      const before = row.offsetHeight
+      const restore = pane.style.width
+      pane.style.width = '8px'
+      const squeezed = { wrapped: row.offsetHeight > before, scrollsSideways: pane.scrollWidth > pane.clientWidth }
+      pane.style.width = restore
+      return { whiteSpace: getComputedStyle(row).whiteSpace, overflowX: getComputedStyle(pane).overflowX, ...squeezed }
+    })
+    expect(layout).toEqual({ whiteSpace: 'pre', overflowX: 'auto', wrapped: false, scrollsSideways: true })
+    // Golden of the card at rest — captured before the copy click, whose
+    // confirmation label self-reverts on a timer and would not hold still.
+    const snapshot = (await captureStableAria(page, '[data-terminal]', scaffold.workspaceCwd))
+      .split(SEED_ID).join('{{seededId}}')
+    await compareOrRefreshGolden(TERMINAL_EXPECTED, snapshot, MODE)
+    // Copy writes the raw output through the browser's own clipboard, which in
+    // a real page is the async Clipboard API rather than the jsdom fallback.
+    await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
+    await card.locator('[class*="_copyButton_"]').first().click()
+    await expect.poll(() => card.locator('[class*="_copyButton_"]').first().textContent(), { timeout: 5_000 })
+      .toBe('复制成功')
+    expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('NAVIGATION_OK')
+  }, 60_000)
+
   it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
     expect(tripwire.pageErrors).toEqual([])
     expect(tripwire.warnings).toEqual([])
     await assertFixtureInventory(SNAPSHOT_DIR, [
       'seed.jsonl', 'trajectory.expected.md', 'waterfall.expected.md', 'details-open.expected.md',
+      'terminal-card.expected.md',
     ])
   })
 })
diff --git a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md b/apps/web/tests/snapshots/navigation-panes/details-open.expected.md
index d69a95eb2d..9eee71468d 100644
--- a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md
+++ b/apps/web/tests/snapshots/navigation-panes/details-open.expected.md
@@ -1,5 +1,8 @@
 - text: bash
 - button "关闭详情"
-- text: Input
+- text: Input json
+- button "复制"
 - code: "{ \"command\": \"echo NAVIGATION_OK\", \"description\": \"Print NAVIGATION_OK\" }"
-- text: Output NAVIGATION_OK
+- text: Output $ echo NAVIGATION_OK
+- button "复制"
+- text: NAVIGATION_OK
diff --git a/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md b/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md
new file mode 100644
index 0000000000..2b81725468
--- /dev/null
+++ b/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md
@@ -0,0 +1,3 @@
+- text: $ echo NAVIGATION_OK
+- button "复制"
+- text: NAVIGATION_OK
diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts
new file mode 100644
index 0000000000..53215f4ba9
--- /dev/null
+++ b/apps/web/tests/terminal-card.snapshot.ts
@@ -0,0 +1,324 @@
+// @vitest-environment jsdom
+// Terminal card snapshot over the BUILT client graph (the code-mode-fixture
+// idiom: real bundles via AppWebEntry, keyless FixtureApiClient transport).
+// Opens the fixture history session and pins the `card: 'terminal'` render
+// intent at both of its conversation render sites, for both chat-row shapes:
+// turn 60's `fx-bash` on the render-site fallback row (expand-gated body) and
+// turn 66's `bash` on the keyed BashRow registration (resident body), plus the
+// details panel's Output section. Turn 66 carries what turn 60's three plain
+// lines cannot — SGR runs resolved to --dsw-* tokens, output past the chat
+// cap, a nested cwd, and a non-zero exit pill.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client'
+import { AppWebEntry } from '@deepseek-ai/dsh-client-web'
+
+const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
+  { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
+  { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
+  { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
+  { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
+  { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
+  { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
+  { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
+  {
+    id: '@deepseek-ai/dsh-client-ui-workspace',
+    dir: 'ui-workspace',
+    url: '/plugins/ui-workspace.js',
+    rev: 'fx',
+    inject: [
+      '@deepseek-ai/dsh-client-runtime',
+      '@deepseek-ai/dsh-client-ui-conversation',
+      '@deepseek-ai/dsh-client-ui-sidebar',
+    ],
+  },
+]
+
+const bundles = new Map(PLUGINS.map(plugin => [
+  plugin.url,
+  readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
+]))
+
+interface FixtureWindow extends Window {
+  __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
+  __ModuleLoader__?: unknown
+}
+
+class ResizeObserverStub {
+  observe(): void {}
+  disconnect(): void {}
+  unobserve(): void {}
+}
+
+const win = window as FixtureWindow
+let unmount: (() => void) | undefined
+
+beforeEach(() => {
+  localStorage.clear()
+  document.title = 'DeepSeek Harness'
+  vi.stubGlobal('ResizeObserver', ResizeObserverStub)
+  vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+    setTimeout(() => { callback(0) }, 0) as unknown as number)
+  vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
+})
+
+afterEach(() => {
+  act(() => { unmount?.() })
+  unmount = undefined
+  cleanup()
+  delete win.__DSH_BOOT__
+  delete win.__ModuleLoader__
+  document.body.innerHTML = ''
+  document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
+  document.title = ''
+  history.replaceState(null, '', '/')
+  vi.unstubAllGlobals()
+})
+
+/** Boot the complete built client graph against the populated fixture branch. */
+function boot(): void {
+  history.replaceState(null, '', '/?fixture')
+  const root = document.createElement('div')
+  root.id = 'root'
+  document.body.appendChild(root)
+  win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
+  act(() => {
+    const entry = new AppWebEntry(root, {
+      fetchBundle: (url) => {
+        const code = bundles.get(url)
+        return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code)
+      },
+      executeBundle: (code) => { (0, eval)(code) },
+    })
+    void entry.run()
+    unmount = () => { entry.dispose() }
+  })
+}
+
+/** Collapse decorative whitespace while preserving the text a user sees. */
+function visibleText(element: Element): string {
+  return (element.textContent ?? '').replace(/\s+/g, ' ').trim()
+}
+
+/**
+ * Read one terminal card's user-visible state. Output lines keep their interior
+ * whitespace: holding column alignment is what this card exists for, so
+ * collapsing runs of spaces would hide the behavior under test.
+ */
+function readCard(card: Element) {
+  const status = card.querySelector('[class*="_status_"]')
+  const expander = card.querySelector('button[aria-expanded]')
+  return {
+    prompt: `${card.querySelector('[class*="_cwd_"]')?.textContent ?? ''} ${card.querySelector('[class*="_command_"]')?.textContent ?? ''}`,
+    status: status === null ? null : status.textContent,
+    copy: card.querySelector('[class*="_copyButton_"]')?.textContent ?? null,
+    lines: [...card.querySelectorAll('[class*="_line_"]')].map(line => line.textContent),
+    expander: expander === null ? null : {
+      label: expander.getAttribute('aria-label'),
+      text: expander.textContent,
+      expanded: expander.getAttribute('aria-expanded'),
+    },
+    // Every color the ANSI parser emits resolves through a --dsw-* token, so
+    // the card follows the theme instead of painting literal terminal rgb.
+    colors: [...new Set([...card.querySelectorAll('span[style]')]
+      .map(span => span.getAttribute('style')))],
+  }
+}
+
+/** Open the fixture history session (the alpha log carrying both bash turns) and wait for its tail. */
+async function openFixtureSession(): Promise {
+  const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
+  // Anchor on the expandable Workspace group row: the title and the blank
+  // session row can both read "fixture".
+  const group = (await within(tree).findAllByText('fixture'))
+    .map(el => el.closest('[role="treeitem"]'))
+    .find(el => el?.getAttribute('aria-expanded') !== null)
+  if (group === null || group === undefined) throw new Error('fixture Workspace group missing')
+  if (group.getAttribute('aria-expanded') === 'false') {
+    fireEvent.click(within(group).getByText('fixture'))
+    await waitFor(() => {
+      expect(group.getAttribute('aria-expanded')).toBe('true')
+    })
+  }
+  fireEvent.click(await within(tree).findByText('Fixture 历史会话'))
+  await waitFor(() => {
+    expect(document.querySelector('[data-sample="bash-global"]')).not.toBeNull()
+  }, { timeout: 10_000 })
+}
+
+/** The keyed BashRow of fixture turn 66 (the one carrying the ANSI sample). */
+function keyedBashRow(): Element {
+  const row = [...document.querySelectorAll('[data-sample="bash-global"]')]
+    .find(node => visibleText(node).includes('pnpm run check'))
+  if (row === undefined) throw new Error('keyed bash row for turn 66 missing')
+  return row
+}
+
+/** The turn-60 fallback row, which reaches the terminal card through GenericToolCard/ToolRow. */
+function fallbackBashRow(): Element {
+  const row = document.querySelector('[data-tool="fx-bash"]')
+  if (row === null) throw new Error('fx-bash fallback row missing')
+  return row
+}
+
+it('renders the keyed bash row with a resident terminal card', async () => {
+  boot()
+  await openFixtureSession()
+
+  const row = keyedBashRow()
+  const card = row.parentElement?.querySelector('[data-terminal]')
+  if (card === null || card === undefined) throw new Error('keyed bash row has no resident terminal card')
+  // The prompt shortens the nested cwd to its last segment, the exit pill
+  // recovers the trailing marker's code, ANSI runs land on theme tokens, and
+  // the chat cap (8) collapses the middle into a head/tail split with an
+  // expander between them.
+  expect(readCard(card)).toMatchInlineSnapshot(`
+    {
+      "colors": [
+        "font-weight: 700;",
+        "color: var(--dsw-alias-state-success-primary);",
+        "color: var(--dsw-alias-state-error-primary);",
+      ],
+      "copy": "复制",
+      "expander": {
+        "expanded": "false",
+        "label": "展开其余 14 行输出",
+        "text": "… 其余 14 行",
+      },
+      "lines": [
+        "Running 4 checks",
+        "✓ typecheck                                          1.82s",
+        "✓ lint                                               0.94s",
+        "✓ duplication                                        2.10s",
+        "markdown/Markdown.tsx       100%     100%        100%         -",
+        "",
+        "1 of 4 checks failed",
+        "[exit code: 1]",
+      ],
+      "prompt": "nested pnpm run check",
+      "status": "退出码 1",
+    }
+  `)
+})
+
+it('the fallback row reaches the same card through its expand control', async () => {
+  boot()
+  await openFixtureSession()
+
+  const row = fallbackBashRow()
+  expect(row.querySelector('[data-terminal]')).toBeNull()
+  const toggle = row.querySelector('button[aria-expanded]')
+  if (toggle === null) throw new Error('fallback row expand control missing')
+  fireEvent.click(toggle)
+  const card = await waitFor(() => {
+    const found = row.querySelector('[data-terminal]')
+    if (found === null) throw new Error('terminal card missing after expanding the fallback row')
+    return found
+  })
+  // Three plain lines under the cap: no ANSI spans, no exit pill, no expander.
+  expect(readCard(card)).toMatchInlineSnapshot(`
+    {
+      "colors": [],
+      "copy": "复制",
+      "expander": null,
+      "lines": [
+        "total 2",
+        "drwxr-xr-x fixture",
+        "-rw-r--r-- demo.txt",
+      ],
+      "prompt": "fixture ls -la",
+      "status": null,
+    }
+  `)
+})
+
+it('the chat card expands the collapsed middle in place, without opening the details panel', async () => {
+  boot()
+  await openFixtureSession()
+
+  const card = keyedBashRow().parentElement?.querySelector('[data-terminal]')
+  if (card === null || card === undefined) throw new Error('resident terminal card missing')
+  const expander = card.querySelector('button[aria-expanded]')
+  if (expander === null) throw new Error('height-cap expander missing')
+  const capped = card.querySelectorAll('[class*="_line_"]').length
+
+  fireEvent.click(expander)
+  await waitFor(() => {
+    expect(card.querySelector('button[aria-expanded]')?.getAttribute('aria-expanded')).toBe('true')
+  })
+  expect({
+    cappedLines: capped,
+    expandedLines: card.querySelectorAll('[class*="_line_"]').length,
+    expanderLabel: card.querySelector('button[aria-expanded]')?.getAttribute('aria-label'),
+    // The card sits outside the summary row's click target, so toggling it
+    // left the details panel shut.
+    detailsOpen: screen.queryByText('Input') !== null,
+  }).toMatchInlineSnapshot(`
+    {
+      "cappedLines": 8,
+      "detailsOpen": false,
+      "expandedLines": 22,
+      "expanderLabel": "收起输出",
+    }
+  `)
+})
+
+it('the details panel Output section renders the same call at full height', async () => {
+  boot()
+  await openFixtureSession()
+
+  fireEvent.click(keyedBashRow())
+  const label = await screen.findByText('Output')
+  const section = label.closest('section')
+  if (section === null) throw new Error('Output section missing')
+  const card = section.querySelector('[data-terminal]')
+  if (card === null) throw new Error('details panel Output is not a terminal card')
+
+  const chatLines = keyedBashRow().parentElement?.querySelectorAll('[class*="_line_"]').length ?? 0
+  expect({
+    ...readCard(card),
+    // The panel keeps the primitive's own allowance (16) against the chat
+    // row's 8, so it shows strictly more of the same output.
+    panelLines: card.querySelectorAll('[class*="_line_"]').length,
+    chatLines,
+  }).toMatchInlineSnapshot(`
+    {
+      "chatLines": 8,
+      "colors": [
+        "font-weight: 700;",
+        "color: var(--dsw-alias-state-success-primary);",
+        "color: var(--dsw-alias-state-error-primary);",
+        "color: var(--dsw-alias-label-tertiary);",
+      ],
+      "copy": "复制",
+      "expander": {
+        "expanded": "false",
+        "label": "展开其余 6 行输出",
+        "text": "… 其余 6 行",
+      },
+      "lines": [
+        "Running 4 checks",
+        "✓ typecheck                                          1.82s",
+        "✓ lint                                               0.94s",
+        "✓ duplication                                        2.10s",
+        "✗ unit                                               8.41s",
+        "",
+        "packages/client/ui-primitives/tests/terminal-block.spec.tsx",
+        "  FAIL caps output at the configured line budget",
+        "CodeBlock.tsx               98.4%    96.2%       100%         41-43",
+        "highlight.ts                100%     100%        100%         -",
+        "Pill.tsx                    100%     100%        100%         -",
+        "StateDot.tsx                100%     100%        100%         -",
+        "markdown/Markdown.tsx       100%     100%        100%         -",
+        "",
+        "1 of 4 checks failed",
+        "[exit code: 1]",
+      ],
+      "panelLines": 16,
+      "prompt": "nested pnpm run check",
+      "status": "退出码 1",
+    }
+  `)
+})
diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts
index 5c7befd8c9..401d3a76a4 100644
--- a/packages/client/connection/src/client/fixture.ts
+++ b/packages/client/connection/src/client/fixture.ts
@@ -46,6 +46,51 @@ const MARKDOWN_FIXTURE = [
 
 const USER_MARKDOWN_LITERAL = '用户字面量:# 不渲染 `code` [link](https://example.com)'
 
+/**
+ * SGR wrapper for the terminal output sample below: authoring the escapes as
+ * `\u001b` keeps literal control bytes out of this source file.
+ * @param code - the SGR parameter (an ANSI color or attribute number).
+ * @param body - the text the attribute applies to.
+ * @returns the body wrapped in the attribute and a reset.
+ */
+function sgr(code: number, body: string): string {
+  return `\u001b[${code}m${body}\u001b[0m`
+}
+
+/**
+ * Terminal output sample for fixture turn 66, authored to carry every feature
+ * the terminal card draws that turn 60's three plain lines cannot reach:
+ * basic-16 SGR foreground runs (green, red, bright-black) that must resolve to
+ * `--dsw-*` tokens, a bold run, column-aligned table rows that must scroll
+ * rather than fold, more than DEFAULT_TERMINAL_MAX_LINES (16) lines so the
+ * height cap collapses the middle, and the trailing `[exit code: N]` marker the
+ * bash tool appends, from which the exit pill is recovered.
+ */
+const TERMINAL_OUTPUT_FIXTURE = [
+  sgr(1, 'Running 4 checks'),
+  `${sgr(32, '\u2713')} typecheck                                          1.82s`,
+  `${sgr(32, '\u2713')} lint                                               0.94s`,
+  `${sgr(32, '\u2713')} duplication                                        2.10s`,
+  `${sgr(31, '\u2717')} unit                                               8.41s`,
+  '',
+  sgr(90, 'packages/client/ui-primitives/tests/terminal-block.spec.tsx'),
+  `  ${sgr(31, 'FAIL')} caps output at the configured line budget`,
+  '    expected 16 lines, received 24',
+  '',
+  'NAME                        LINES    BRANCHES    FUNCTIONS    UNCOVERED',
+  'TerminalBlock.tsx           100%     100%        100%         -',
+  'ansi.ts                     100%     100%        100%         -',
+  'clipboard.ts                100%     100%        100%         -',
+  'CodeBlock.tsx               98.4%    96.2%       100%         41-43',
+  'highlight.ts                100%     100%        100%         -',
+  'Pill.tsx                    100%     100%        100%         -',
+  'StateDot.tsx                100%     100%        100%         -',
+  'markdown/Markdown.tsx       100%     100%        100%         -',
+  '',
+  sgr(31, '1 of 4 checks failed'),
+  '[exit code: 1]',
+].join('\n')
+
 const DEEPSEEK_REASONING = {
   efforts: [
     { id: 'off', name: 'Off' },
@@ -124,7 +169,8 @@ function buildAlphaLog(): SessionEvent[] {
   }
   // Three view-sample turns (60-62) cover the built-in card types. The real filesystem names in
   // turns 62-63 also exercise their dedicated generic-row icon/title/path summaries. `echo` above
-  // stays presenter-less as the unknown fallback.
+  // stays presenter-less as the unknown fallback. Turn 66 is the second terminal sample, carrying
+  // what turn 60's three plain lines cannot (see TERMINAL_OUTPUT_FIXTURE) through the keyed row.
   const toolTurn = (turn: number, name: string, args: string, resultText: string): void => {
     const callId = `fx-call-${turn}`
     push({ type: 'turn/start', data: { turn, trigger: { kind: 'message', source: { kind: 'user' } } } })
@@ -201,6 +247,13 @@ function buildAlphaLog(): SessionEvent[] {
   const callIndex = events.length - 4
   const callTime = events[callIndex]?.time as number
   events.splice(callIndex + 1, 0, { type: 'todo/write', time: callTime + 400, data: { todos: fixtureTodos } })
+  // Turn 66: the terminal sample turn 60's three clean lines cannot cover —
+  // ANSI SGR coloring, output past the terminal card's height cap, a nested
+  // cwd whose prompt label is its last segment, and a non-zero exit recovered
+  // from the trailing marker the bash tool appends. Named `bash`, so it also
+  // covers the keyed toolview row (turn 60's `fx-bash` covers the render-site
+  // fallback row) — the two chat-row shapes the terminal card renders in.
+  toolTurn(66, 'bash', '{"command":"pnpm run check","cwd":"/tmp/fixture/deep/nested"}', TERMINAL_OUTPUT_FIXTURE)
   events.forEach((e, i) => { e.seq = i })
   return events as unknown as SessionEvent[]
 }
@@ -219,7 +272,11 @@ function presentCall(name: string, argsRaw: string): ToolCallView | undefined {
     return undefined
   }
   switch (name) {
+    // Both names present the same terminal card: `fx-bash` lands on the
+    // render-site fallback row, `bash` on the keyed BashRow registration, so
+    // the two chat-row shapes of one render intent are both reachable.
     case 'fx-bash':
+    case 'bash':
       return { card: 'terminal', title: str(args.command), cwd: str(args.cwd, '/tmp/fixture'), description: 'fixture 终端样本' }
     case 'fx-write':
       return {
@@ -235,12 +292,24 @@ function presentCall(name: string, argsRaw: string): ToolCallView | undefined {
   }
 }
 
+/**
+ * Recover the exit status from a trailing `[exit code: N]` marker, mirroring
+ * the real bash tool's `parseExitStatus` (this package must not depend on a
+ * tool package, so the marker contract is re-read rather than imported).
+ * @param text - the rendered result text.
+ * @returns the recovered exit code (0 when the marker is absent).
+ */
+function fixtureExitCode(text: string): number {
+  const marker = /\n\[exit code: (\d+)\]$/.exec(text)
+  return marker?.[1] === undefined ? 0 : Number(marker[1])
+}
+
 function presentResult(name: string, argsRaw: string, resultText: string): ToolResultView | undefined {
   const call = presentCall(name, argsRaw)
   if (call === undefined) return undefined
   switch (call.card) {
     case 'terminal':
-      return { card: 'terminal', output: resultText, exitCode: 0 }
+      return { card: 'terminal', output: resultText, exitCode: fixtureExitCode(resultText) }
     case 'diff':
       return { card: 'diff', diffs: call.diffs }
     case 'generic':
diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml
index c1a6828d5b..dd28591b01 100644
--- a/packages/client/ui-conversation/README.i18n.yaml
+++ b/packages/client/ui-conversation/README.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md
-README.md: 56a445ccfa86e0b11cf5aefc37819a30746f0739
-README.zh.md: a7c160ecdd74074257c9d149630663dacd05c070
+README.md: 1c6912b05e259fa1f4a7096c3a2b82f9f67f5527
+README.zh.md: 157bfafd3a1157420acbb73861cd40d759228743
diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md
index 56a445ccfa..1c6912b05e 100644
--- a/packages/client/ui-conversation/README.md
+++ b/packages/client/ui-conversation/README.md
@@ -10,6 +10,8 @@ The view ring IS a slot: the conversation registration declares the `'conversati
 
 Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and `Write · ` or `Edit · ` summary while retaining the shared row-to-details interaction. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged), and the details panel resolves a selected sub-call id to its full logged args and complete output. Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering.
 
+A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. The keyed `BashRow` carries the card resident below its summary row and outside that row's click target, so copying or expanding the output does not open the details panel; the render-site fallback row keeps it behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed for this intent alone; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)).
+
 Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openDetails`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders).
 
 The todo surfaces are two registrations over that shape, both plain registrant plugins with `inject: ['slots', 'conversation']`. `TodoRow` takes the `'conversation.chat.toolview'` key `todo_write` and summarizes what the call attempted (`/ 已完成 · ` parsed from its args, falling back to the generic summary on malformed or wrongly-shaped model JSON, and keeping the generic dot for non-ok execution states so a cancelled call never reads as a completed update). `TodoDock` takes the `'conversation.input.dock'` list slot at `order: -1` — above the queue rows — and is the durable plan strip: it selects `todos` off the session snapshot and renders `TodoPanel`, which takes the plain list, hides itself while the list is empty, and collapses to a header of title plus `"/ tasks ·  in progress"` (status glyphs are the figma check / progress / dashed-pending set). The dock adapter owns the selection so the panel stays a pure function of its props; the persistent list lives here rather than in the row so the row stays one line. Anything the input-zone composer chain hides (a `conversation.composer` takeover such as ui-question's) hides the whole dock, this strip included.
diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md
index a7c160ecdd..157bfafd3a 100644
--- a/packages/client/ui-conversation/README.zh.md
+++ b/packages/client/ui-conversation/README.zh.md
@@ -10,6 +10,8 @@
 
 通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和 `Write · ` 或 `Edit · ` 摘要,同时保留共享的行到详情交互。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行),details 面板则会根据选中的子调用 id 解析出其完整记录的参数与完整输出。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect`、`Mount temporary Plugin` 和 `Unmount temporary Plugin`;mount 行保留 code 变体的可展开源码渲染。
 
+声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。键控的 `BashRow` 把卡片常驻在摘要行下方、且位于该行点击目标之外,因此复制或展开输出不会打开详情面板;渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出只对该意图开放;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。
+
 工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openDetails`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。
 
 todo 两个面就是在该形状上的两个注册项,都是普通注册方插件,`inject: ['slots', 'conversation']`。`TodoRow` 占用 `'conversation.chat.toolview'` 的 `todo_write` key,摘要该次调用「试图写入」的内容(从其 args 解析出 `<已完成>/<总数> 已完成 · <进行中条目>`;模型 JSON 残缺或形状不对时回落到通用摘要;非 ok 执行状态保留通用状态点,使被取消的调用绝不读成一次已完成的更新)。`TodoDock` 以 `order: -1` 占用 `'conversation.input.dock'` 列表 slot(位于队列行之上),是常驻的计划条:它从会话快照中选取 `todos` 并渲染 `TodoPanel`,后者接收纯列表,在列表为空时自我隐藏,折叠时收成标题加 `"<已完成>/<总数> tasks ·  in progress"` 的表头(状态图标为 figma 的勾选/进行中/虚线未开始一组)。选取由 dock 适配器负责,因此面板保持为其 props 的纯函数;常驻列表放在此处而非行内,行才能保持单行。输入区 composer 链隐藏的一切(例如 ui-question 对 `conversation.composer` 的接管)也会隐藏整个 dock,包括这条计划条。
diff --git a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx
index 5cb2126f34..0bfde97019 100644
--- a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx
+++ b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx
@@ -9,6 +9,7 @@ import {
   IconApiOutline14, IconBrowseOutline16, IconCodeOutline16, IconEditOutline16, IconSearchOutline16, IconThinkOutline14,
 } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { ToolRowOwnerProps } from '../contract/slots.ts'
+import { terminalCardModel } from '../contract/terminal-card-model.ts'
 import { toolRowModel, type ToolRowVariant } from '../contract/tool-call-model.ts'
 import { ToolRow } from './ToolRow.tsx'
 import { IconSparkle16 } from './IconSparkle16.tsx'
@@ -35,6 +36,7 @@ export function GenericToolCard({ toolName, block, openDetails }: ToolRowOwnerPr
       title={model.title}
       summary={model.summary}
       body={model.body}
+      terminal={terminalCardModel(block)}
       state={model.state}
       onOpenDetails={openDetails}
     />
diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css
index 5d44a9260e..d238218d97 100644
--- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css
+++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css
@@ -102,9 +102,13 @@ button.leading {
   color: var(--dsw-alias-label-tertiary);
 }
 
-/* The code variant's expanded body is the run_code program, rendered through
-   the shared CodeBlock (shiki-highlighted TypeScript); only indentation is
-   this row's concern. */
-.codeBody {
+/* The two block-shaped expanded bodies: the code variant's run_code program
+   through CodeBlock (shiki-highlighted TypeScript) and a terminal card's
+   command output through TerminalBlock. Both are drawn by the shared
+   primitive, so only the row's indentation is this file's concern — the margin
+   also replaces each primitive's own standalone vertical spacing with the
+   flow's row rhythm. */
+.codeBody,
+.terminalBody {
   margin: 4px 0 4px 22px;
 }
diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx
index a81c084b8e..91dcfe4a0a 100644
--- a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx
+++ b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx
@@ -1,13 +1,19 @@
 // ToolRow: the single-line tool summary row (figma component set 122:9479) —
 // 16px leading slot (state dot / tool icon, chevron when expanded) + title +
-// separator dot + FILL-truncated summary. Expanded body is indented gray text;
-// no inline output (full results live in the details panel). Expand state is
-// component-local view state; row click hands the selection off to the owner.
+// separator dot + FILL-truncated summary. The collapsed row is always one
+// line; the expanded body is indented gray text, the run_code program through
+// CodeBlock, or — for a call whose render intent is a terminal card — the
+// command's own output through TerminalBlock, capped at
+// CHAT_TERMINAL_MAX_LINES so the message flow stays scannable. The details
+// panel remains the full-height reading surface for the same call. Expand
+// state is component-local view state; row click hands the selection off to
+// the owner.
 
 import { useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react'
 import clsx from 'clsx'
-import { CodeBlock, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
+import { CodeBlock, StateDot, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives'
 import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
+import { CHAT_TERMINAL_MAX_LINES, type TerminalCardModel } from '../contract/terminal-card-model.ts'
 import type { ToolRowState, ToolRowVariant } from '../contract/tool-call-model.ts'
 import css from './ToolRow.module.css'
 
@@ -19,8 +25,15 @@ export interface ToolRowProps {
   icon: ReactNode
   title: string
   summary: string
-  /** Expanded-body text; null = not expandable (leading slot never toggles). */
+  /** Expanded-body text; null = no text body (`terminal` is the other body source). */
   body: string | null
+  /**
+   * Terminal-card material for a call whose render intent is a terminal card
+   * (derived by `terminalCardModel`); it replaces the text body when present.
+   * Null or absent leaves the text body, and a row with neither is not
+   * expandable (its leading slot never toggles).
+   */
+  terminal?: TerminalCardModel | null | undefined
   state: ToolRowState
   /** Makes the row itself the expand control instead of only its leading icon. */
   expandOnRowClick?: boolean | undefined
@@ -46,12 +59,18 @@ export function ToolRow({
   title,
   summary,
   body,
+  terminal,
   state,
   expandOnRowClick = false,
   onOpenDetails,
 }: ToolRowProps) {
   const [expanded, setExpanded] = useState(false)
-  const expandable = body !== null
+  const terminalBody = terminal ?? null
+  const expandable = body !== null || terminalBody !== null
+  // The text arms take the empty string for a null body: a row expandable
+  // only through its terminal material renders the terminal body instead, so
+  // this substitution never shows.
+  const text = body ?? ''
   const open = expanded && expandable
   const rowExpands = expandable && expandOnRowClick
   const toggleExpand = () => {
@@ -99,9 +118,11 @@ export function ToolRow({
           
         )}
       
-      {open && (variant === 'code'
-        ? 
-        : 
{body}
)} + {open && (terminalBody !== null + ? + : variant === 'code' + ? + :
{text}
)} ) } diff --git a/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts new file mode 100644 index 0000000000..a1b274e3f9 --- /dev/null +++ b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts @@ -0,0 +1,83 @@ +/** + * Pure derivation of the terminal-card props from a frozen call slice: the + * `card:'terminal'` render intent the bash tool declares arrives on the + * snapshot as `callView`/`resultView`, and this is the one place that turns + * that pair into what {@link TerminalBlock} draws. Both conversation render + * sites (the chat tool row's expanded body and the details panel's Output + * section) call this, so the command, cwd, output and exit status they show + * are derived once. + * @module + */ +import type { TerminalBlockProps } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ToolCallBlock } from './tool-call-model.ts' + +/** + * Output lines the chat row's expanded terminal body shows before collapsing + * the middle — half the primitive's own default, which the details panel + * keeps. A chat row is a summary surface inside the message flow: the flow + * must stay scannable across many calls, while the details panel is the + * single-call reading surface. A design constant of this UI's row geometry, + * not a deployment choice, so it is fixed here rather than a plugin Config + * field. + */ +export const CHAT_TERMINAL_MAX_LINES = 8 + +/** + * The {@link TerminalBlock} props this derivation owns. Picked off the + * primitive's props so the two stay in step; `home` is absent because the web + * client has no home path for the session host (a cwd renders as its last + * path segment), and `maxLines`/`className` belong to each render site. + */ +export type TerminalCardModel = Pick< + TerminalBlockProps, + 'command' | 'cwd' | 'output' | 'exitCode' | 'signal' | 'running' +> + +/** + * Derive the terminal-card props for a tool call, or null when this call is + * not a terminal card and belongs on the generic path. + * + * The call side supplies the command and its working directory; the result + * side supplies the captured output and exit status. Three cases produce + * null, all of them the documented generic-card default: + * + * - Neither side declares `card:'terminal'` — including a `card` value this + * UI version does not know, which arrives over the wire and therefore + * cannot be trusted to be one of the compiled variants. + * - A settled call whose result view is not a terminal card: the result + * presentation decides how the settled call renders, and the bash tool + * returns a generic fenced card for an execution error or a background + * start, whose text and error styling the generic path preserves. + * + * Window truncation can drop the call head from a settled result (see + * `ToolResultNode.call`/`callView` in dsh-client-runtime), leaving a terminal + * result with no call side. That still renders: the command falls back to the + * result view's replacement title, then to an empty command (the prompt line + * draws bare), and the prompt shows no cwd. + * @param block - RunningToolCall or ToolResultNode off the snapshot caches. + * @returns the terminal-card props, or null for the generic path. + */ +export function terminalCardModel(block: ToolCallBlock): TerminalCardModel | null { + const call = block.callView?.card === 'terminal' ? block.callView : null + if (!('kind' in block)) { + // Running: the call view exists, the result view does not yet. + return call === null ? null : { + command: call.title, + cwd: call.cwd, + output: undefined, + exitCode: undefined, + signal: undefined, + running: true, + } + } + const result = block.resultView?.card === 'terminal' ? block.resultView : null + if (result === null) return null + return { + command: call?.title ?? result.title ?? '', + cwd: call?.cwd, + output: result.output, + exitCode: result.exitCode, + signal: result.signal, + running: false, + } +} diff --git a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts index 5b725df00b..0b1afa8060 100644 --- a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts +++ b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts @@ -1,7 +1,9 @@ /** * Pure row-model derivation for tool summary rows: variant classification, - * one-line summary and expanded-body text from the frozen call slice. No - * inline output ever — full results live in the details panel. + * one-line summary and expanded-body text from the frozen call slice. This + * derivation reads the call ARGUMENTS only; a call whose render intent is a + * terminal card gets its expanded body from the views instead, through + * `terminalCardModel` in terminal-card-model.ts. */ // The block union's defining home is runtime (fold-product types); this // contract only forwards it (type-definition authority stays with the layer diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css index abdece3e25..ef4173735e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css @@ -92,3 +92,9 @@ .code[data-error] { color: var(--dsw-alias-state-error-primary); } + +/* The terminal card sits directly under its section label, so it drops the + primitive's standalone vertical margin; the section owns the spacing. */ +.terminal { + margin: 0; +} diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index 650a95f833..326e765044 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -1,47 +1,59 @@ // DetailsPanel, P-I minimal form: close button + the selected call's args and -// result rendered raw. The three-段 Switch / Prev-Next stepping / See-in- -// trajectory are deferred (ledger). Reads the selection from the shared chat +// result — args as JSON, the result raw except for a terminal-card call, whose +// Output section is the command's terminal card. The three-段 Switch / +// Prev-Next stepping / See-in-trajectory are deferred (ledger). Reads the +// selection from the shared chat // store (conversation writes, this panel reads — the cross-registration // share the store seat exists for) and derives the call material from the // session snapshot — no data of its own. -import { CodeBlock } from '@deepseek-ai/dsh-client-ui-primitives' +import { CodeBlock, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' import { shallowEqual } from '@deepseek-ai/dsh-client-runtime/client' -import type { ConversationSnapshot, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client' +import type { ConversationSnapshot, RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client' import type { DetailsSlotProps } from '../contract/slots.ts' +import { terminalCardModel } from '../contract/terminal-card-model.ts' +import type { ToolCallBlock } from '../contract/tool-call-model.ts' import css from './DetailsPanel.module.css' /** Full props composed by reference from the contract (automatic shares & injected share). */ export type DetailsPanelProps = DetailsSlotProps -/** Selected call material: resolved result node, or the in-flight running call's args. */ +/** + * Selected call material: the call's display name and args plus the frozen + * block slice it came from. `block` is a snapshot-cached reference, so the + * wrapper stays shallow-equal across unrelated snapshot frames; the settled / + * running split is read off it with the `'kind' in block` discrimination + * instead of duplicated as flags. + */ interface CallMaterial { name: string argsRaw: string | null - result: ToolResultNode | null - running: boolean + block: ToolCallBlock +} + +/** Material of a settled result node (native call or run_code sub-dispatch). */ +function settledMaterial(node: ToolResultNode, callId: string): CallMaterial { + return { name: node.call?.name ?? callId, argsRaw: node.call?.argsRaw ?? null, block: node } +} + +/** Material of an in-flight call (native call or run_code sub-dispatch). */ +function runningMaterial(call: RunningToolCall): CallMaterial { + return { name: call.name, argsRaw: call.argsRaw, block: call } } function materialFor(s: ConversationSnapshot, callId: string): CallMaterial | null { for (const node of s.nodes) { - if (node.kind === 'tool-result' && node.callId === callId) { - return { name: node.call?.name ?? callId, argsRaw: node.call?.argsRaw ?? null, result: node, running: false } - } + if (node.kind === 'tool-result' && node.callId === callId) return settledMaterial(node, callId) } const open = s.runningCalls.find(c => c.callId === callId) - if (open !== undefined) { - return { name: open.name, argsRaw: open.argsRaw, result: null, running: true } - } + if (open !== undefined) return runningMaterial(open) // run_code sub-dispatches: the native call-block shapes, so a selected // sub-row resolves through the same material as a native call — the // settled ToolResultNode form, or the RunningToolCall form mid-flight. for (const subs of s.codeDispatches.values()) { for (const sub of subs) { if (sub.callId !== callId) continue - if ('kind' in sub) { - return { name: sub.call?.name ?? callId, argsRaw: sub.call?.argsRaw ?? null, result: sub, running: false } - } - return { name: sub.name, argsRaw: sub.argsRaw, result: null, running: true } + return 'kind' in sub ? settledMaterial(sub, callId) : runningMaterial(sub) } } return null @@ -95,15 +107,7 @@ export function DetailsPanel({ useSession, useStore, closeDetails }: DetailsPane )}
Output
- {/* materialFor invariant: result===null ⇔ running (a settled - material always carries its result node). */} - {material.result === null - ?
运行中…
- : ( -
-                        {renderResult(material.result)}
-                      
- )} +
)} @@ -112,6 +116,29 @@ export function DetailsPanel({ useSession, useStore, closeDetails }: DetailsPane ) } +/** + * The Output section's body for the selected call. A terminal-card call — a + * shell command's call/result views — renders through the shared TerminalBlock + * at the primitive's own full height allowance, so column-aligned output keeps + * its alignment and scrolls sideways instead of folding. Every other call, and + * a running call with no terminal card yet, keeps the flattened text form. + * @param props.material - the selected call's material from {@link materialFor}. + * @returns the Output section's body element. + */ +function OutputBody({ material }: { material: CallMaterial }) { + const terminal = terminalCardModel(material.block) + if (terminal !== null) return + // A settled call always carries the result node the flattened form needs; + // the running shape has no result to flatten. + if (!('kind' in material.block)) return
运行中…
+ const result = material.block + return ( +
+      {renderResult(result)}
+    
+ ) +} + /** Flatten result content blocks to display text (text blocks verbatim, others as JSON). */ function renderResult(node: ToolResultNode): string { const parts: string[] = [] diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css index 9c42e69b59..450eb2301d 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css @@ -1,4 +1,18 @@ -/* Bash toolview: same geometry/tokens as ToolRow (figma Bash · description). */ +/* Bash toolview: same geometry/tokens as ToolRow (figma Bash · description), + plus the terminal card the row stacks under its summary line. */ + +/* Summary line over the terminal card; the summary row keeps its own 24px + height, so the card is a column around it rather than a change to it. */ +.card { + display: flex; + flex-direction: column; +} + +/* Row indentation matches ToolRow's expanded bodies (16px leading + 6px gap), + and replaces the primitive's standalone vertical margin with the flow's. */ +.terminal { + margin: 4px 0 4px 22px; +} .root { display: flex; diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx index 616eee5943..49a5e6c2e4 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx @@ -3,10 +3,18 @@ // Product chrome matches ToolRow / Think (figma: Bash · {description}). // Child sessions keep a scoped badge so session-dimension differentiation stays // observable inside the component (no parallel registry). +// +// A bash call declares the terminal render intent, so this row also renders +// the command's own output through TerminalBlock. This row has no expand +// control (a click goes to the details panel), so its terminal body is +// resident rather than expand-gated as in ToolRow; the block's own height cap +// (CHAT_TERMINAL_MAX_LINES) and internal expander keep a long output from +// taking over the message flow. import type { Context } from 'cordis' -import { IconApiOutline14, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconApiOutline14, StateDot, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' import type { ToolRowProps } from '../contract/slots.ts' +import { CHAT_TERMINAL_MAX_LINES, terminalCardModel } from '../contract/terminal-card-model.ts' import { toolRowModel, type ToolRowState } from '../contract/tool-call-model.ts' import css from './bash-sample.module.css' @@ -29,26 +37,37 @@ function stateStatus(state: ToolRowState): string | null { } } -/** Bash row: icon + Bash · {description}, matching the shared ToolRow chrome. */ +/** + * Bash row: icon + Bash · {description} in the shared ToolRow chrome, with the + * command's terminal card below it. The summary row keeps its own click target + * (the details handoff); the terminal card sits outside that row, so its copy + * and expand controls do not open the details panel. + */ export function BashRow({ toolName, block, openDetails, sessionId, useSessions }: ToolRowProps) { const model = toolRowModel(toolName, block) + const terminal = terminalCardModel(block) const isChild = useSessions(list => list.byId[sessionId]?.parentId !== undefined) const status = stateStatus(model.state) return ( -
- {leadingFor(model.state)} - {status !== null && {status}} - {isChild && scoped} - {model.title} - - {model.summary} +
+
+ {leadingFor(model.state)} + {status !== null && {status}} + {isChild && scoped} + {model.title} + + {model.summary} +
+ {terminal !== null && ( + + )}
) } diff --git a/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx b/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx index 13a74548b4..4a5e80b224 100644 --- a/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx @@ -71,6 +71,11 @@ describe('tool-call-model', () => { expect(toolRowModel('bash', result({ call: null })).body).toBeNull() }) + it('a code row with an empty program falls back to the args JSON envelope', () => { + expect(toolRowModel('run_code', running({ name: 'run_code', argsRaw: '{"code":""}' })).body) + .toBe('{\n "code": ""\n}') + }) + it('gives Cordis lifecycle tools action titles over their generic variants', () => { expect(toolRowModel('cordis_inspect', running({ name: 'cordis_inspect', @@ -139,6 +144,22 @@ describe('ToolRow', () => { expect(view.queryByTestId('tool-icon')).not.toBeNull() }) + it('an expandOnRowClick row toggles from Enter and Space, ignoring other keys', () => { + const view = render() + const row = view.getByRole('button') + fireEvent.keyDown(row, { key: 'Tab' }) + expect(row.getAttribute('aria-expanded')).toBe('false') + fireEvent.keyDown(row, { key: 'Enter' }) + expect(row.getAttribute('aria-expanded')).toBe('true') + fireEvent.keyDown(row, { key: ' ' }) + expect(row.getAttribute('aria-expanded')).toBe('false') + }) + + it('a non-expandable expandOnRowClick row exposes no row button', () => { + const view = render() + expect(view.queryByRole('button')).toBeNull() + }) + it('row click hands off to onOpenDetails; the expand toggle does not', () => { const open = vi.fn() const view = render() diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx new file mode 100644 index 0000000000..1ab75861b5 --- /dev/null +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -0,0 +1,359 @@ +// @vitest-environment jsdom +// The terminal render intent on the web side: the pure terminalCardModel +// derivation over callView/resultView, and both conversation render sites that +// consume it — the chat tool row's expanded body (GenericToolCard / BashRow) +// and the details panel's Output section. + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import type { + ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-client-connection/client' +import type { SelectionTarget, ToolRowOwnerProps, ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { CHAT_TERMINAL_MAX_LINES, terminalCardModel } from '../src/client/contract/terminal-card-model.ts' +import { createChatStore } from '../src/client/stores.ts' +import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx' +import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' +import { BashRow } from '../src/client/toolviews/bash-sample.tsx' + +afterEach(cleanup) + +/** + * Match an output line with its interior whitespace intact: the column + * alignment this card exists to preserve is exactly what the default + * whitespace-collapsing matcher would hide. + */ +const RAW = { normalizer: (text: string) => text } + +const SID = 's1' as SessionId + +const ARGS = '{"command":"ls -la","description":"List files"}' + +/** The bash tool's own call view for a foreground command. */ +const callTerminal = (over?: Partial>): ToolCallView => ({ + card: 'terminal', title: 'ls -la', description: 'List files', ...over, +}) + +/** The bash tool's own result view for a settled foreground command. */ +const resultTerminal = (over?: Partial>): ToolResultView => ({ + card: 'terminal', output: 'a.ts b.ts\nc.ts d.ts\n', exitCode: 0, ...over, +}) + +const running = (over?: Partial): RunningToolCall => ({ + callId: 'c1', name: 'bash', argsRaw: ARGS, + turn: 1, step: 1, time: 1_000, callView: callTerminal(), ...over, +}) + +const settled = (over?: Partial): ToolResultNode => ({ + kind: 'tool-result', seq: 10, time: 2_000, callId: 'c1', + call: { name: 'bash', argsRaw: ARGS }, + callTime: 1_000, + content: [{ type: 'text', text: 'a.ts b.ts\nc.ts d.ts\n' }], isError: false, + callView: callTerminal(), resultView: resultTerminal(), ...over, +}) + +describe('terminalCardModel', () => { + it('derives a running card from the call view alone', () => { + expect(terminalCardModel(running({ callView: callTerminal({ cwd: '/projects/app' }) }))).toEqual({ + command: 'ls -la', cwd: '/projects/app', output: undefined, + exitCode: undefined, signal: undefined, running: true, + }) + }) + + it('derives a settled card from both sides, carrying the exit status', () => { + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '/projects/app' }), + resultView: resultTerminal({ output: 'boom\n', exitCode: 2 }), + }))).toEqual({ + command: 'ls -la', cwd: '/projects/app', output: 'boom\n', + exitCode: 2, signal: undefined, running: false, + }) + expect(terminalCardModel(settled({ + resultView: { card: 'terminal', output: '', signal: 'SIGTERM' }, + }))?.signal).toBe('SIGTERM') + }) + + it('a window-truncated call side falls back to the result title, then to an empty command', () => { + // Truncation drops both the call head and its view (conversation.ts). + const truncated = { call: null, callView: null } + expect(terminalCardModel(settled({ + ...truncated, resultView: resultTerminal({ title: 'ls -la' }), + }))).toMatchObject({ command: 'ls -la', cwd: undefined, running: false }) + expect(terminalCardModel(settled(truncated))).toMatchObject({ command: '', cwd: undefined }) + }) + + it('returns null for every non-terminal call: no views, generic views, unknown cards', () => { + expect(terminalCardModel(running({ callView: null }))).toBeNull() + expect(terminalCardModel(settled({ callView: null, resultView: null }))).toBeNull() + expect(terminalCardModel(running({ callView: { card: 'generic', title: 'read x' } }))).toBeNull() + // A generic result settles a terminal call as a generic card (the bash + // tool's own execution-error and background paths). + expect(terminalCardModel(settled({ resultView: { card: 'generic' } }))).toBeNull() + // A card tag this UI version does not know arrives over the wire; the + // documented generic-card default takes it, not a crash. + const future = { card: 'chart', title: 'plot' } as unknown as ToolCallView + expect(terminalCardModel(running({ callView: future }))).toBeNull() + expect(terminalCardModel(settled({ + callView: future, resultView: { card: 'chart' } as unknown as ToolResultView, + }))).toBeNull() + }) +}) + +describe('chat row terminal body', () => { + const ownerProps = (block: RunningToolCall | ToolResultNode): ToolRowOwnerProps => ({ + callId: 'c1', toolName: 'bash', block, openDetails: vi.fn(), + }) + + it('the expanded body is the command output, capped tighter than the panel', () => { + expect(CHAT_TERMINAL_MAX_LINES).toBeLessThan(16) + const view = render() + // Collapsed: the one-line summary row only, no output. + expect(view.getByText('List files')).toBeTruthy() + expect(view.queryByText(/a\.ts/)).toBeNull() + fireEvent.click(view.container.querySelector('button')!) + expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() + expect(view.getByText('ls -la')).toBeTruthy() + // The args JSON body the generic path would have shown is gone. + expect(view.queryByText(/"command"/)).toBeNull() + }) + + it('the cap collapses a long output inside the row, expandable in place', () => { + const lines = Array.from({ length: CHAT_TERMINAL_MAX_LINES + 3 }, (_, i) => `line-${i}`) + const view = render() + fireEvent.click(view.container.querySelector('button')!) + expect(view.getByText('… 其余 3 行')).toBeTruthy() + expect(view.queryByText('line-5')).toBeNull() + fireEvent.click(view.getByRole('button', { name: '展开其余 3 行输出' })) + expect(view.getByText('line-5')).toBeTruthy() + }) + + it('a running terminal call expands to the prompt line with no output yet', () => { + const view = render() + fireEvent.click(view.container.querySelector('button')!) + expect(view.getByText('ls -la')).toBeTruthy() + expect(view.queryByText('复制')).toBeNull() + }) + + it('a non-terminal call keeps the args-JSON text body', () => { + const view = render() + fireEvent.click(view.container.querySelector('button')!) + expect(view.getByText(/"command"/)).toBeTruthy() + }) + + it('a terminal call with no args still expands, through its terminal body alone', () => { + // Empty args make the text body null; the terminal material carries the row. + const view = render() + fireEvent.click(view.container.querySelector('button')!) + expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() + }) +}) + +describe('BashRow terminal card', () => { + const list = () => createSnapshotStore({ + ids: [SID], + byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, updatedAt: 0 } }, + current: undefined, + phase: 'ready', + }) + + const rowProps = (block: RunningToolCall | ToolResultNode, openDetails = vi.fn()): ToolRowProps => ({ + callId: 'c1', toolName: 'bash', block, openDetails, + sessionId: SID, useSessions: bindSnapshotSelector(list()), + } as unknown as ToolRowProps) + + it('renders the command output under the summary row, without an expand gesture', () => { + const openDetails = vi.fn() + const view = render() + expect(view.getByText('List files')).toBeTruthy() + expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() + // The terminal card sits outside the row's click target: copying does not + // open the details panel. + fireEvent.click(view.getByText('复制')) + expect(openDetails).not.toHaveBeenCalled() + fireEvent.click(view.getByText('List files')) + expect(openDetails).toHaveBeenCalledTimes(1) + }) + + it('a non-terminal bash call (background start) renders the summary row alone', () => { + const view = render() + expect(view.getByText('List files')).toBeTruthy() + expect(view.queryByText(/a\.ts/)).toBeNull() + }) +}) + +describe('DetailsPanel Output section', () => { + function mount(snapshot: ConversationSnapshot, selection: SelectionTarget | null) { + localStorage.clear() + const chat = createChatStore().create() + if (selection !== null) chat.actions.select(selection) + const sessions = createSnapshotStore( + { ids: [], byId: {}, current: undefined, phase: 'ready' }) + const workspaces = createSnapshotStore({ + items: [], state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return render( + snapshot, subscribe: () => () => {} })} + useSessions={bindSnapshotSelector(sessions)} + useWorkspaces={bindSnapshotSelector(workspaces)} + useInput={(() => { throw new Error('unused') })} + inputActions={{ setDraft: () => {}, submit: () => {} }} + useStore={bindSnapshotSelector(chat)} + actions={chat.actions} + closeDetails={vi.fn()} + />, + ) + } + + function snapshot(over: Partial = {}): ConversationSnapshot { + return { + sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(), + pending: [], queue: [], todos: [], running: false, composerPhase: 'active', removed: false, + openState: 'open', openError: null, hasMore: false, loadingOlder: false, + promptError: null, blank: false, lastAgentError: null, ...over, + } + } + + const target: SelectionTarget = { turnSeq: 10, callId: 'c1', toolName: 'bash' } + + it('renders the terminal card at full height, keeping the JSON Input section', () => { + const long = Array.from({ length: 20 }, (_, i) => `row-${i}`) + const view = mount(snapshot({ + nodes: [settled({ resultView: resultTerminal({ output: `${long.join('\n')}\n` }) })], + }), target) + expect(view.getByText(/"command"/)).toBeTruthy() + expect(view.getByText('ls -la')).toBeTruthy() + // The panel takes the primitive's own default cap (16), not the row's. + expect(view.getByText(`… 其余 ${20 - 16} 行`)).toBeTruthy() + expect(view.getByText('row-0')).toBeTruthy() + }) + + it('a running terminal call shows the prompt line, not the 运行中… placeholder', () => { + const view = mount(snapshot({ runningCalls: [running()] }), target) + expect(view.getByText('ls -la')).toBeTruthy() + expect(view.queryByText('运行中…')).toBeNull() + }) + + it('a running non-terminal call keeps the 运行中… placeholder', () => { + const view = mount(snapshot({ runningCalls: [running({ callView: null })] }), target) + expect(view.getByText('运行中…')).toBeTruthy() + }) + + it('a non-terminal result keeps the flattened pre with its error styling', () => { + const view = mount(snapshot({ + nodes: [settled({ + callView: null, resultView: null, isError: true, + content: [{ type: 'text', text: 'permission denied' }], + })], + }), target) + const pre = view.container.querySelector('pre[data-error]') + expect(pre?.textContent).toBe('permission denied') + }) + + it('a run_code sub-dispatch resolves to its own terminal card', () => { + const view = mount(snapshot({ + codeDispatches: new Map([['p1', [settled({ callId: 'c1' })]]]), + }), target) + expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() + }) + + it('a running run_code sub-dispatch resolves through the running material', () => { + const view = mount(snapshot({ + // The leading non-matching sub-call exercises the scan's skip. + codeDispatches: new Map([['p1', [running({ callId: 'other' }), running()]]]), + }), target) + expect(view.getByText('ls -la')).toBeTruthy() + }) + + it('a window-truncated call head titles the panel by callId and drops the Input section', () => { + const view = mount(snapshot({ + nodes: [settled({ call: null, callView: null, resultView: resultTerminal({ title: 'ls -la' }) })], + }), target) + expect(view.getByText('c1')).toBeTruthy() + expect(view.queryByText('Input')).toBeNull() + expect(view.getByText('Output')).toBeTruthy() + }) + + it('scans past other nodes and other calls before reporting the call out of window', () => { + const view = mount(snapshot({ + nodes: [ + { kind: 'assistant', seq: 1, time: 1_000, turn: 1, step: 1, blocks: [] }, + settled({ callId: 'elsewhere' }), + ], + runningCalls: [running({ callId: 'also-elsewhere' })], + }), target) + expect(view.getByText('该调用不在当前窗口内')).toBeTruthy() + }) + + it('no selection at all renders the guidance line and the default title', () => { + const view = mount(snapshot(), null) + expect(view.getByText('详情')).toBeTruthy() + expect(view.getByText('点击消息流中的工具行查看详情')).toBeTruthy() + }) + + it('a step selection without a callId renders the guidance line too', () => { + const view = mount(snapshot(), { turnSeq: 3, stepSeq: 1 }) + expect(view.getByText('点击消息流中的工具行查看详情')).toBeTruthy() + }) + + it('the close button reaches closeDetails', () => { + localStorage.clear() + const chat = createChatStore().create() + const closeDetails = vi.fn() + const snap = snapshot() + const view = render( + snap, subscribe: () => () => {} })} + useSessions={bindSnapshotSelector(createSnapshotStore( + { ids: [], byId: {}, current: undefined, phase: 'ready' }))} + useWorkspaces={bindSnapshotSelector(createSnapshotStore({ + items: [], state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }))} + useInput={(() => { throw new Error('unused') })} + inputActions={{ setDraft: () => {}, submit: () => {} }} + useStore={bindSnapshotSelector(chat)} + actions={chat.actions} + closeDetails={closeDetails} + />, + ) + fireEvent.click(view.getByRole('button', { name: '关闭详情' })) + expect(closeDetails).toHaveBeenCalledTimes(1) + }) + + it('a non-text result block renders as JSON, and an empty result falls back to its error', () => { + const nonText = mount(snapshot({ + nodes: [settled({ + callView: null, resultView: null, + content: [{ type: 'reasoning', text: 'why' }], + })], + }), target) + // Scope to the Output section: the Input section's CodeBlock renders a + //
 of its own, and it comes first in document order.
+    expect(nonText.getByText('Output').closest('section')?.querySelector('pre')?.textContent)
+      .toBe('{\n  "type": "reasoning",\n  "text": "why"\n}')
+    cleanup()
+    const empty = mount(snapshot({
+      nodes: [settled({
+        callView: null, resultView: null, content: [], isError: true,
+        error: { name: 'ToolError', code: 'interrupted' },
+      })],
+    }), target)
+    expect(empty.getByText('ToolError: interrupted')).toBeTruthy()
+  })
+})
diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml
index 6162494def..1eb8a05ba0 100644
--- a/packages/client/ui-primitives/README.i18n.yaml
+++ b/packages/client/ui-primitives/README.i18n.yaml
@@ -1,6 +1,6 @@
 # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
-#   pnpm run verify-translation-pairing --write
-README.md: 58e450451ab64f69762817dfb277b8a888e2177f
-README.zh.md: 6824f3efe4981adf9549941afa7e2f5db2ac005d
+#   pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
+README.md: c9c70f29804ac4e6783486595460bf07499e1dff
+README.zh.md: 254fc5ba5aef553fd447338353a0c5311ddbd98a
diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md
index 58e450451a..c9c70f2980 100644
--- a/packages/client/ui-primitives/README.md
+++ b/packages/client/ui-primitives/README.md
@@ -2,12 +2,16 @@
 
 English | [中文](README.zh.md)
 
-Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, markdown family (MessageText/MarkdownText/JsonBlock). Contract: api-contracts v3 §8.
+Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, markdown family (MessageText/MarkdownText/JsonBlock), TerminalBlock. Contract: api-contracts v3 §8.
 
 ## Markdown rendering
 
 `MarkdownText` renders GFM from untrusted assistant output through React elements. It omits raw HTML, neutralizes relative and non-HTTP(S)/mailto links, opens HTTP(S) links with safe external-link attributes, and renders image alt text without loading remote resources; `MessageText` remains the literal-text primitive for user-authored content. Element spacing, tables, links, and inline code use the same `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` tokens as deepsuite `@deepseek/md`. Fenced blocks render through `CodeBlock` (language banner, copy control, shiki for the registered grammars).
 
+## Terminal output
+
+`TerminalBlock` renders a shell command as a terminal surface: a prompt line (shortened `cwd` label plus the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md).
+
 ## Model Experience
 
 None, as the package renders pure React atoms in the browser; nothing here reaches a model request.
@@ -21,3 +25,4 @@ None; this package neither assembles nor sends a provider request.
 - **Glyph-level icons are redrawn approximations** — the fish logo (and the sparkle held by ui-conversation) come from font glyphs whose vector geometry is not exportable from the local design data; hand-authored recreations stand in until an exact export path exists.
 - **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms.
 - **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface.
+- **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, while cursor movement, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb.
diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md
index 6824f3efe4..254fc5ba5a 100644
--- a/packages/client/ui-primitives/README.zh.md
+++ b/packages/client/ui-primitives/README.zh.md
@@ -2,12 +2,16 @@
 
 [English](README.md) | 中文
 
-纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input,以及 markdown 家族(MessageText/MarkdownText/JsonBlock)。契约:api-contracts v3 §8。
+纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、markdown 家族(MessageText/MarkdownText/JsonBlock),以及 TerminalBlock。契约:api-contracts v3 §8。
 
 ## Markdown 渲染
 
 `MarkdownText` 通过 React 元素渲染来自不受信任 assistant 输出的 GFM。它会省略原始 HTML,使相对链接及非 HTTP(S)/mailto 链接失效,以安全的外部链接属性打开 HTTP(S) 链接,并只渲染图片 alt 文本而不加载远程资源;`MessageText` 仍是用户创作内容使用的字面文本原语。元素间距、表格、链接与行内代码使用与 deepsuite `@deepseek/md` 相同的 `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` token。围栏代码块通过 `CodeBlock` 渲染(语言横幅、复制控件,以及对已注册语法使用 shiki)。
 
+## 终端输出
+
+`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签加命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。
+
 ## 模型体验
 
 无。该包在浏览器中渲染纯 React 原子组件;这里没有任何内容进入模型请求。
@@ -21,3 +25,4 @@
 - **字形级图标是重新绘制的近似版本**:鱼形标志(以及 ui-conversation 持有的闪光图标)来自字体字形,而本地设计数据无法导出其矢量几何;在获得精确导出路径前,使用手工重建版本代替。
 - **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。
 - **StateDot 的 `Active` 变体是设计中的隐藏占位符**:尚未实现;已交付的四种状态(done/warning/ongoing/error)构成完整的 P-I 表层。
+- **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,而光标移动、清屏和备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。
diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json
index 9ce2bc8676..e629626129 100644
--- a/packages/client/ui-primitives/package.json
+++ b/packages/client/ui-primitives/package.json
@@ -21,6 +21,7 @@
   "license": "BSD-3-Clause",
   "dependencies": {
     "@shikijs/langs": "^4.3.1",
+    "anser": "^2.3.5",
     "clsx": "^2.0.0",
     "react": "^18.2.0",
     "react-dom": "^18.2.0",
diff --git a/packages/client/ui-primitives/src/Pill.tsx b/packages/client/ui-primitives/src/Pill.tsx
index 76b9301972..2c3c24c1ad 100644
--- a/packages/client/ui-primitives/src/Pill.tsx
+++ b/packages/client/ui-primitives/src/Pill.tsx
@@ -12,7 +12,9 @@ import css from './Pill.module.css'
  */
 export function Pill({ active = false, className, children, onClick, ...rest }: {
   active?: boolean
-  className?: string
+  // `| undefined` so a caller can forward an optional class straight through
+  // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined).
+  className?: string | undefined
   children?: ReactNode
 } & ButtonHTMLAttributes) {
   if (!onClick) {
diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css
new file mode 100644
index 0000000000..8a4f4a5e60
--- /dev/null
+++ b/packages/client/ui-primitives/src/TerminalBlock.module.css
@@ -0,0 +1,101 @@
+/* Geometry mirrors CodeBlock (12px radius, code-block surface + banner rows,
+   markdown code-block font) so a terminal card and a fenced code block read as
+   one family. The one deliberate divergence: output keeps `white-space: pre`
+   and scrolls horizontally, because folding a column-aligned command's output
+   destroys its alignment. */
+
+.block {
+  --dsl-terminal-radius: 12px;
+  --dsl-terminal-line-height: 22px;
+
+  position: relative;
+  margin: 16px 0;
+  color: var(--dsw-alias-label-primary);
+  background: var(--dsw-alias-markdown-code-block);
+  border-radius: var(--dsl-terminal-radius);
+}
+
+.header {
+  display: flex;
+  align-items: center;
+  gap: 12px;
+  padding: 9px 14px;
+  background: var(--dsw-alias-markdown-code-block-banner);
+  border-top-left-radius: var(--dsl-terminal-radius);
+  border-top-right-radius: var(--dsl-terminal-radius);
+}
+
+/* The prompt row is the only element allowed to shrink; the status pill and
+   the copy control keep their intrinsic width. */
+.prompt {
+  display: flex;
+  align-items: baseline;
+  gap: 8px;
+  min-width: 0;
+  flex: 1;
+  font: var(--dsw-font-markdown-code-block);
+}
+
+.cwd {
+  flex: none;
+  color: var(--dsw-alias-label-tertiary);
+}
+
+.command {
+  min-width: 0;
+  color: var(--dsw-alias-label-primary);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.status {
+  flex: none;
+  color: var(--dsw-alias-state-error-primary);
+}
+
+.copyButton {
+  flex: none;
+  background-color: transparent;
+  border: none;
+  padding: 0;
+  margin: 0;
+  color: var(--dsw-alias-label-secondary);
+  cursor: pointer;
+  font: var(--dsw-font-xs-13);
+}
+
+.output {
+  padding: 12px 14px;
+  font: var(--dsw-font-markdown-code-block);
+  overflow-x: auto;
+  overflow-y: hidden;
+}
+
+/* No wrapping, no word-break: alignment is the payload of terminal output. */
+.line {
+  min-height: var(--dsl-terminal-line-height);
+  white-space: pre;
+}
+
+.expand {
+  display: block;
+  width: 100%;
+  padding: 0;
+  border: none;
+  background-color: transparent;
+  color: var(--dsw-alias-label-tertiary);
+  cursor: pointer;
+  font: inherit;
+  text-align: left;
+}
+
+.expand:hover {
+  color: var(--dsw-alias-label-secondary);
+}
+
+.empty {
+  padding: 12px 14px;
+  font: var(--dsw-font-markdown-code-block);
+  color: var(--dsw-alias-label-tertiary);
+}
diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx
new file mode 100644
index 0000000000..e224e2b1de
--- /dev/null
+++ b/packages/client/ui-primitives/src/TerminalBlock.tsx
@@ -0,0 +1,170 @@
+// TerminalBlock: the terminal surface for a shell command and its output —
+// prompt line (shortened cwd + command), ANSI-colored output, settled exit
+// status, and a copy control for the raw output. Output never soft-wraps:
+// column-aligned output (ls, tables, box drawing) keeps its alignment and
+// scrolls horizontally instead of folding. Colors resolve through --dsw-*
+// tokens; ANSI parsing lives in ansi.ts.
+
+import { useCallback, useMemo, useState } from 'react'
+import clsx from 'clsx'
+import { parseAnsiLines, type AnsiLine } from './ansi.ts'
+import { writeClipboard } from './clipboard.ts'
+import { Pill } from './Pill.tsx'
+import css from './TerminalBlock.module.css'
+
+/**
+ * Output lines shown before the height cap collapses the middle. Matches the
+ * TUI transcript's default tool-output budget so both front ends cut a long
+ * command's output at the same place.
+ */
+export const DEFAULT_TERMINAL_MAX_LINES = 16
+
+export interface TerminalBlockProps {
+  /** The command line, rendered verbatim after the prompt label. */
+  command: string
+  /** Working directory for the prompt label; absent renders a plain `$`. */
+  cwd?: string | undefined
+  /** Absolute home directory, so a cwd equal to it collapses to `~`; absent disables that collapse. */
+  home?: string | undefined
+  /** The command's output text; may contain ANSI escape sequences. */
+  output?: string | undefined
+  /** Settled exit code; a non-zero value renders the status pill. */
+  exitCode?: number | undefined
+  /** Settled terminating signal name; any value renders the status pill, taking precedence over the exit code. */
+  signal?: string | undefined
+  /** The command is still running: the block shows the prompt line alone. */
+  running?: boolean | undefined
+  /** Height cap in output lines before the middle collapses (default {@link DEFAULT_TERMINAL_MAX_LINES}). */
+  maxLines?: number | undefined
+  /** Extra class merged onto the wrapper (callers position; this component draws). */
+  className?: string | undefined
+}
+
+/**
+ * Prompt label for a working directory: `~` for the home directory itself,
+ * otherwise the path's last segment (both separators accepted, trailing
+ * separators ignored), falling back to the path itself when it has no
+ * segment.
+ * @param cwd - the working directory path.
+ * @param home - absolute home directory, when the caller knows it.
+ * @returns the prompt label.
+ */
+function promptLabel(cwd: string, home: string | undefined): string {
+  const trimmed = cwd.replace(/[/\\]+$/, '')
+  if (home !== undefined && trimmed === home.replace(/[/\\]+$/, '')) return '~'
+  const segment = trimmed.split(/[/\\]/).pop()
+  return segment === undefined || segment === '' ? cwd : segment
+}
+
+/**
+ * Status pill text for a settled command, or undefined when the command
+ * settled cleanly (exit 0, no signal) and needs no pill — the same
+ * distinction the bash tool's own exit-status markers draw.
+ * @param exitCode - settled exit code, when known.
+ * @param signal - settled terminating signal name, when known.
+ * @returns the pill text, or undefined for a clean exit.
+ */
+function statusText(exitCode: number | undefined, signal: string | undefined): string | undefined {
+  if (signal !== undefined) return `信号 ${signal}`
+  if (exitCode !== undefined && exitCode !== 0) return `退出码 ${exitCode}`
+  return undefined
+}
+
+/**
+ * Render one parsed output line. Runs without SGR state render as bare text,
+ * so uncolored output carries no span wrappers.
+ * @param line - the line's styled runs.
+ * @returns the line's children.
+ */
+function renderLine(line: AnsiLine) {
+  return line.map((span, index) => span.style === undefined
+    ? span.text
+    : {span.text})
+}
+
+/**
+ * Render a shell command as a terminal surface.
+ * @param props - see {@link TerminalBlockProps}.
+ * @returns the terminal block element.
+ */
+export function TerminalBlock({
+  command,
+  cwd,
+  home,
+  output,
+  exitCode,
+  signal,
+  running = false,
+  maxLines = DEFAULT_TERMINAL_MAX_LINES,
+  className,
+}: TerminalBlockProps) {
+  const text = output ?? ''
+  // A command's output ends with a newline; that terminator is not an extra
+  // blank line to draw or to count against the height cap. The copy control
+  // still copies `text` untouched.
+  const lines = useMemo(() => parseAnsiLines(text.endsWith('\n') ? text.slice(0, -1) : text), [text])
+  const [expanded, setExpanded] = useState(false)
+  const [copied, setCopied] = useState(false)
+
+  const onCopy = useCallback(() => {
+    if (copied) return
+    // The raw output, never the rendered tree: the prompt line and the status
+    // pill are chrome the user did not run.
+    void writeClipboard(text).then((ok) => {
+      if (!ok) return
+      setCopied(true)
+      window.setTimeout(() => { setCopied(false) }, 1000)
+    })
+  }, [copied, text])
+
+  const onToggle = useCallback(() => { setExpanded(value => !value) }, [])
+
+  const status = statusText(exitCode, signal)
+  const empty = text.trim() === ''
+  const hidden = lines.length - maxLines
+  const capped = hidden > 0 && !expanded
+  // Same split arithmetic as the TUI transcript's collapsed tool card, so a
+  // command's head and tail slices agree between the two front ends.
+  const headLines = Math.ceil(maxLines / 2)
+  const tailLines = maxLines - headLines
+
+  return (
+    
+
+
+ {cwd === undefined ? '$' : promptLabel(cwd, home)} + {command} +
+ {status !== undefined && {status}} + {!running && !empty && ( + + )} +
+ {!running && (empty + ?
无输出
+ : ( +
+ {(capped ? lines.slice(0, headLines) : lines).map((line, index) => ( +
{renderLine(line)}
+ ))} + {hidden > 0 && ( + + )} + {capped && lines.slice(lines.length - tailLines).map((line, index) => ( +
{renderLine(line)}
+ ))} +
+ ))} +
+ ) +} diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts new file mode 100644 index 0000000000..e4e2cc13e2 --- /dev/null +++ b/packages/client/ui-primitives/src/ansi.ts @@ -0,0 +1,153 @@ +// ANSI model behind TerminalBlock: anser splits the SGR runs, this module +// resolves each run's colors and decorations into a plain style record and +// folds the runs into per-line span arrays so a height cap can slice whole +// lines. Sequences anser does not turn into color (OSC, cursor movement, +// other C0 controls) are removed before parsing so they never reach the DOM +// as literal characters. + +import Anser from 'anser' +import type { CSSProperties } from 'react' + +/** + * The subset of one anser JSON chunk this module reads. anser's own types + * declare `fg`/`bg` as `string`, but its parser leaves them `null` for a run + * that sets no color, so the null is spelled out here. + */ +interface AnsiChunk { + /** Run text with its SGR codes already removed. */ + content: string + /** Foreground as an `r, g, b` triple, or null when the run sets none. */ + fg: string | null + /** Background as an `r, g, b` triple, or null when the run sets none. */ + bg: string | null + /** SGR attributes in effect for the run, in the order they were declared. */ + decorations: readonly string[] +} + +/** One run of terminal text; `style` is undefined for text that carries no SGR state. */ +export interface AnsiSpan { + /** The run's plain text, free of escape sequences and newlines. */ + text: string + /** Resolved inline style, or undefined when the run needs no wrapper. */ + style: CSSProperties | undefined +} + +/** The spans of one output line, in order. */ +export type AnsiLine = readonly AnsiSpan[] + +/** + * The 8/16 basic ANSI colors, keyed by the whitespace-free `r,g,b` triple + * anser emits for them, mapped onto the theme tokens that carry the same + * semantic. Black and white both resolve to the primary label color so text + * stays legible under either theme instead of matching the surface it sits + * on; bright black takes the tertiary label color (the muted-gray role). + * Magenta and cyan have no token equivalent in this design system and fall + * through to anser's literal rgb, as do all 256-palette and truecolor values. + */ +const TOKEN_BY_BASIC_RGB: Record = { + '0,0,0': 'var(--dsw-alias-label-primary)', + '255,255,255': 'var(--dsw-alias-label-primary)', + '85,85,85': 'var(--dsw-alias-label-tertiary)', + '187,0,0': 'var(--dsw-alias-state-error-primary)', + '255,85,85': 'var(--dsw-alias-state-error-secondary)', + '0,187,0': 'var(--dsw-alias-state-success-primary)', + '0,255,0': 'var(--dsw-alias-state-success-secondary)', + '187,187,0': 'var(--dsw-alias-state-warn-primary)', + '255,255,85': 'var(--dsw-alias-state-warn-secondary)', + '0,0,187': 'var(--dsw-alias-state-business-primary)', + '85,85,255': 'var(--dsw-static-blue-400)', +} + +/** + * CSS for each SGR attribute anser reports. `blink` is deliberately absent — + * animated text is not reproduced. `reverse` never arrives here: anser + * consumes it by swapping the run's foreground and background. Underline and + * strikethrough share `textDecoration`, so in a run declaring both, the + * later declaration wins. + */ +const STYLE_BY_DECORATION: Record = { + bold: { fontWeight: 700 }, + dim: { opacity: 0.7 }, + italic: { fontStyle: 'italic' }, + underline: { textDecoration: 'underline' }, + strikethrough: { textDecoration: 'line-through' }, + hidden: { visibility: 'hidden' }, +} + +/** OSC strings (window title, hyperlinks), with or without their terminator. */ +const OSC_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g + +/** Escape sequences other than CSI: charset selection, single-shift, reset. */ +const NON_CSI_ESCAPE = /\u001b(?!\[)[\u0020-\u002f]*[\u0030-\u007e]?/g + +/** C0 controls with no display meaning here; tab, newline and ESC survive for layout and anser's CSI split. */ +const INERT_CONTROL = /[\u0000-\u0008\u000b-\u001a\u001c-\u001f\u007f]/g + +/** + * Apply carriage-return redraws: within a line, only the text after the last + * `\r` survives, which is what a terminal shows for progress output. A `\r` + * that only terminates a CRLF line is dropped first so those lines keep + * their text. SGR codes preceding a dropped redraw are dropped with it. + * @param text - output text, already free of OSC and non-CSI escapes. + * @returns the text with each line reduced to its final redraw. + */ +function applyCarriageReturns(text: string): string { + return text.split('\n').map((raw) => { + const line = raw.replace(/\r+$/, '') + return line.slice(line.lastIndexOf('\r') + 1) + }).join('\n') +} + +/** + * Remove every escape sequence and control character that carries no color, + * leaving CSI sequences for anser and `\n`/`\t` for layout. + * @param text - raw command output. + * @returns text whose only remaining escapes are CSI sequences. + */ +function sanitize(text: string): string { + const escaped = text.replace(OSC_SEQUENCE, '').replace(NON_CSI_ESCAPE, '') + return applyCarriageReturns(escaped).replace(INERT_CONTROL, '') +} + +/** + * Resolve one run's colors and decorations. + * @param chunk - the anser chunk to style. + * @returns the run's inline style, or undefined when it carries no SGR state. + */ +function resolveStyle(chunk: AnsiChunk): CSSProperties | undefined { + const style: CSSProperties = {} + const background = chunk.bg === null ? undefined : `rgb(${chunk.bg})` + if (background !== undefined) style.backgroundColor = background + if (chunk.fg !== null) { + const literal = `rgb(${chunk.fg})` + // A run that paints its own background keeps anser's literal pair so the + // authored foreground/background contrast survives; a foreground-only run + // maps onto a theme token, which adapts to light and dark surfaces. + style.color = background === undefined + ? TOKEN_BY_BASIC_RGB[chunk.fg.replace(/\s+/g, '')] ?? literal + : literal + } + for (const decoration of chunk.decorations) Object.assign(style, STYLE_BY_DECORATION[decoration]) + return Object.keys(style).length === 0 ? undefined : style +} + +/** + * Parse command output into styled spans grouped by line. + * @param text - raw output text, which may contain ANSI escape sequences. + * @returns one entry per output line (always at least one, possibly empty). + */ +export function parseAnsiLines(text: string): AnsiLine[] { + let current: AnsiSpan[] = [] + const lines: AnsiSpan[][] = [current] + for (const chunk of Anser.ansiToJson(sanitize(text), { json: true, remove_empty: true })) { + const style = resolveStyle(chunk) + for (const [index, part] of chunk.content.split('\n').entries()) { + if (index > 0) { + current = [] + lines.push(current) + } + if (part !== '') current.push({ text: part, style }) + } + } + return lines +} diff --git a/packages/client/ui-primitives/src/clipboard.ts b/packages/client/ui-primitives/src/clipboard.ts new file mode 100644 index 0000000000..c01e802f31 --- /dev/null +++ b/packages/client/ui-primitives/src/clipboard.ts @@ -0,0 +1,48 @@ +// Package-internal clipboard write, shared by every copy control in this +// package (CodeBlock's code copy, TerminalBlock's output copy). Not part of the +// public surface: consumers get the components, not the host detection. + +/** + * Write text to the host clipboard, preferring the async Clipboard API and + * falling back to `execCommand('copy')` on hosts (jsdom, insecure contexts) + * that omit it. + * @param text - the exact text to place on the clipboard. + * @returns true only when the host accepted the write. + */ +export async function writeClipboard(text: string): Promise { + // lib.dom types clipboard non-optional, but insecure contexts omit it — + // that runtime gap is exactly what this guard detects. + /* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition */ + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(text) + return true + } catch { + // Denied permissions / iframe policy — do not claim success. + return false + } + } + // jsdom and older hosts: best-effort execCommand path when present. + // execCommand('copy') is the only clipboard fallback where the async API + // is missing; deprecated but deliberately retained. + /* eslint-disable @typescript-eslint/no-deprecated */ + const exec = typeof document.execCommand === 'function' + ? document.execCommand.bind(document) + : undefined + if (exec === undefined) return false + const el = document.createElement('textarea') + el.value = text + el.setAttribute('readonly', '') + el.style.position = 'fixed' + el.style.left = '-9999px' + document.body.appendChild(el) + el.select() + try { + return exec('copy') + } catch { + return false + } finally { + el.remove() + } + /* eslint-enable @typescript-eslint/no-deprecated */ +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 330a3145bf..dca6374fb8 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -17,6 +17,8 @@ export { FishLogo } from './FishLogo.tsx' export { BrandWordmark } from './BrandWordmark.tsx' export { Tooltip } from './Tooltip.tsx' export type { TooltipSide } from './Tooltip.tsx' +export { TerminalBlock, DEFAULT_TERMINAL_MAX_LINES } from './TerminalBlock.tsx' +export type { TerminalBlockProps } from './TerminalBlock.tsx' export { CodeBlock } from './markdown/CodeBlock.tsx' export { JsonBlock } from './markdown/JsonBlock.tsx' export { MarkdownText } from './markdown/MarkdownText.tsx' diff --git a/packages/client/ui-primitives/src/markdown/CodeBlock.tsx b/packages/client/ui-primitives/src/markdown/CodeBlock.tsx index de6a478af4..9c7e968053 100644 --- a/packages/client/ui-primitives/src/markdown/CodeBlock.tsx +++ b/packages/client/ui-primitives/src/markdown/CodeBlock.tsx @@ -6,6 +6,7 @@ import { useCallback, useMemo, useRef, useState } from 'react' import clsx from 'clsx' +import { writeClipboard } from '../clipboard.ts' import { highlightToHtml } from './highlight.ts' import css from './CodeBlock.module.css' @@ -18,45 +19,6 @@ export interface CodeBlockProps { className?: string | undefined } -/** @returns true only when the host accepted the write. */ -async function writeClipboard(text: string): Promise { - // lib.dom types clipboard non-optional, but insecure contexts omit it — - // that runtime gap is exactly what this guard detects. - /* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition */ - if (navigator.clipboard?.writeText) { - try { - await navigator.clipboard.writeText(text) - return true - } catch { - // Denied permissions / iframe policy — do not claim success. - return false - } - } - // jsdom and older hosts: best-effort execCommand path when present. - // execCommand('copy') is the only clipboard fallback where the async API - // is missing; deprecated but deliberately retained. - /* eslint-disable @typescript-eslint/no-deprecated */ - const exec = typeof document.execCommand === 'function' - ? document.execCommand.bind(document) - : undefined - if (exec === undefined) return false - const el = document.createElement('textarea') - el.value = text - el.setAttribute('readonly', '') - el.style.position = 'fixed' - el.style.left = '-9999px' - document.body.appendChild(el) - el.select() - try { - return exec('copy') - } catch { - return false - } finally { - el.remove() - } - /* eslint-enable @typescript-eslint/no-deprecated */ -} - export function CodeBlock({ code, lang, className }: CodeBlockProps) { const trimmed = code.endsWith('\n') ? code.slice(0, -1) : code const html = useMemo(() => highlightToHtml(trimmed, lang), [trimmed, lang]) diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts new file mode 100644 index 0000000000..57a29d4f33 --- /dev/null +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -0,0 +1,188 @@ +// parseAnsiLines, the ANSI model behind TerminalBlock: anser's SGR runs +// resolved into inline styles and folded into per-line span arrays, with every +// escape and control character that carries no color removed first. The DOM +// side of the same model (which runs get a span wrapper) is in +// terminal-block.spec.tsx. + +import { describe, expect, it } from 'vitest' +import { parseAnsiLines } from '../src/ansi.ts' + +const ESC = '\u001b' + +/** Paint `text` with the SGR `codes`, then reset. */ +function sgr(codes: string, text: string): string { + return `${ESC}[${codes}m${text}${ESC}[0m` +} + +/** The single span of a single-line, single-run parse. */ +function onlySpan(text: string) { + const lines = parseAnsiLines(text) + expect(lines).toHaveLength(1) + expect(lines[0]).toHaveLength(1) + return lines[0]![0]! +} + +describe('parseAnsiLines: text without SGR state', () => { + it('leaves plain text as one unstyled span', () => { + expect(parseAnsiLines('hello')).toEqual([[{ text: 'hello', style: undefined }]]) + }) + + it('returns exactly one empty line for empty input', () => { + expect(parseAnsiLines('')).toEqual([[]]) + }) + + it('splits a multi-line run and drops the empty line between two blocks', () => { + expect(parseAnsiLines('a\n\nb')).toEqual([ + [{ text: 'a', style: undefined }], + [], + [{ text: 'b', style: undefined }], + ]) + }) + + it('keeps tabs, which the terminal surface needs for column layout', () => { + expect(onlySpan('a\tb')).toEqual({ text: 'a\tb', style: undefined }) + }) +}) + +describe('parseAnsiLines: basic colors mapped onto theme tokens', () => { + it.each<[string, string, string]>([ + ['30', 'black', 'var(--dsw-alias-label-primary)'], + ['37', 'white', 'var(--dsw-alias-label-primary)'], + ['90', 'bright black', 'var(--dsw-alias-label-tertiary)'], + ['31', 'red', 'var(--dsw-alias-state-error-primary)'], + ['91', 'bright red', 'var(--dsw-alias-state-error-secondary)'], + ['32', 'green', 'var(--dsw-alias-state-success-primary)'], + ['92', 'bright green', 'var(--dsw-alias-state-success-secondary)'], + ['33', 'yellow', 'var(--dsw-alias-state-warn-primary)'], + ['93', 'bright yellow', 'var(--dsw-alias-state-warn-secondary)'], + ['34', 'blue', 'var(--dsw-alias-state-business-primary)'], + ['94', 'bright blue', 'var(--dsw-static-blue-400)'], + ])('SGR %s (%s) resolves to %s', (code, _name, token) => { + expect(onlySpan(sgr(code, 'x'))).toEqual({ text: 'x', style: { color: token } }) + }) +}) + +describe('parseAnsiLines: colors with no token equivalent', () => { + it.each<[string, string, string]>([ + ['35', 'magenta', 'rgb(187, 0, 187)'], + ['36', 'cyan', 'rgb(0, 187, 187)'], + ['38;5;208', '256-palette orange', 'rgb(255, 135, 0)'], + ['38;2;10;20;30', 'truecolor', 'rgb(10, 20, 30)'], + ])('SGR %s (%s) falls through to %s', (code, _name, literal) => { + expect(onlySpan(sgr(code, 'x')).style).toEqual({ color: literal }) + }) +}) + +describe('parseAnsiLines: backgrounds', () => { + it('sets backgroundColor for a background-only run', () => { + expect(onlySpan(sgr('44', 'x')).style).toEqual({ backgroundColor: 'rgb(0, 0, 187)' }) + }) + + it('keeps the literal foreground when the run paints its own background', () => { + expect(onlySpan(sgr('41;37', 'x')).style).toEqual({ + backgroundColor: 'rgb(187, 0, 0)', + color: 'rgb(255,255,255)', + }) + }) + + it('renders reverse video as the swapped pair anser reports', () => { + expect(onlySpan(sgr('31;7', 'x')).style).toEqual({ + backgroundColor: 'rgb(187, 0, 0)', + color: 'rgb(0, 0, 0)', + }) + }) +}) + +describe('parseAnsiLines: decorations', () => { + it.each<[string, string, Record]>([ + ['1', 'bold', { fontWeight: 700 }], + ['2', 'dim', { opacity: 0.7 }], + ['3', 'italic', { fontStyle: 'italic' }], + ['4', 'underline', { textDecoration: 'underline' }], + ['9', 'strikethrough', { textDecoration: 'line-through' }], + ['8', 'hidden', { visibility: 'hidden' }], + ])('SGR %s (%s) resolves to %o', (code, _name, style) => { + expect(onlySpan(sgr(code, 'x')).style).toEqual(style) + }) + + it('lets the later textDecoration win when a run declares underline and strikethrough', () => { + expect(onlySpan(sgr('4;9', 'x')).style).toEqual({ textDecoration: 'line-through' }) + expect(onlySpan(sgr('9;4', 'x')).style).toEqual({ textDecoration: 'underline' }) + }) + + it('combines a color with several decorations in one style', () => { + expect(onlySpan(sgr('1;3;31', 'x')).style).toEqual({ + color: 'var(--dsw-alias-state-error-primary)', + fontWeight: 700, + fontStyle: 'italic', + }) + }) + + it('reproduces no animation for blink, leaving the run unstyled', () => { + expect(onlySpan(sgr('5', 'x'))).toEqual({ text: 'x', style: undefined }) + }) +}) + +describe('parseAnsiLines: sequences that carry no color', () => { + it('removes an OSC string with its BEL terminator', () => { + expect(onlySpan(`a${ESC}]0;window title\u0007b`)).toEqual({ text: 'ab', style: undefined }) + }) + + it('removes an OSC string terminated by ST', () => { + expect(onlySpan(`a${ESC}]8;;https://example.com${ESC}\\b`)).toEqual({ text: 'ab', style: undefined }) + }) + + it('removes non-CSI escapes such as charset selection and reset', () => { + expect(onlySpan(`x${ESC}(By${ESC}cz`)).toEqual({ text: 'xyz', style: undefined }) + }) + + it('removes inert C0 controls', () => { + expect(onlySpan('\u0000ab\u001fc\u007f')).toEqual({ text: 'abc', style: undefined }) + }) + + it('keeps CSI sequences that only move the cursor out of the text', () => { + expect(onlySpan(`${ESC}[2K${ESC}[1Adone`)).toEqual({ text: 'done', style: undefined }) + }) +}) + +describe('parseAnsiLines: carriage returns', () => { + it('keeps only the last redraw of a line', () => { + expect(onlySpan('10%\r55%\r100%')).toEqual({ text: '100%', style: undefined }) + }) + + it('drops the SGR codes that preceded a discarded redraw', () => { + expect(onlySpan(`${ESC}[31mgone\rkept`)).toEqual({ text: 'kept', style: undefined }) + }) + + it('preserves both lines of a CRLF pair instead of treating it as a redraw', () => { + expect(parseAnsiLines('a\r\r\nb\r\n')).toEqual([ + [{ text: 'a', style: undefined }], + [{ text: 'b', style: undefined }], + [], + ]) + }) + + it('applies the redraw per line, not across the whole text', () => { + expect(parseAnsiLines('one\rtwo\nthree')).toEqual([ + [{ text: 'two', style: undefined }], + [{ text: 'three', style: undefined }], + ]) + }) +}) + +describe('parseAnsiLines: runs spanning lines', () => { + it('carries one run\'s style onto every line it covers', () => { + expect(parseAnsiLines(sgr('32', 'first\nsecond'))).toEqual([ + [{ text: 'first', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + [{ text: 'second', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + ]) + }) + + it('keeps several runs of one line in order', () => { + expect(parseAnsiLines(`plain${sgr('31', 'red')}tail`)).toEqual([[ + { text: 'plain', style: undefined }, + { text: 'red', style: { color: 'var(--dsw-alias-state-error-primary)' } }, + { text: 'tail', style: undefined }, + ]]) + }) +}) diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx new file mode 100644 index 0000000000..87e153a741 --- /dev/null +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -0,0 +1,315 @@ +// @vitest-environment jsdom +// TerminalBlock: the prompt label's cwd shortening, the running/empty/settled +// arms, the exit-status pill, the head/tail height cap and its expand control, +// and the copy control writing the raw output on both the accepted and the +// refused clipboard paths. writeClipboard's own return contract is pinned here +// too, since it is the seam both copy controls in this package share; the +// resolution of ANSI runs into styles is pinned in ansi.spec.ts, so only its +// DOM consequence (which runs get a span wrapper) is asserted here. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { DEFAULT_TERMINAL_MAX_LINES, TerminalBlock } from '../src/index.ts' +import { writeClipboard } from '../src/clipboard.ts' + +const ESC = '\u001b' + +afterEach(cleanup) + +beforeEach(() => { + vi.useRealTimers() +}) + +/** The rendered output rows, one string per visible line (CSS-module class prefix). */ +function outputLines(container: HTMLElement): string[] { + return [...container.querySelectorAll('[class^="_line_"]')].map(row => row.textContent ?? '') +} + +/** `count` numbered output lines, without the terminating newline. */ +function body(count: number): string { + return Array.from({ length: count }, (_value, index) => `line ${index + 1}`).join('\n') +} + +describe('TerminalBlock prompt label', () => { + it('collapses the home directory itself to ~', () => { + render() + expect(screen.getByText('~')).toBeTruthy() + }) + + it('shows only the last segment below home', () => { + render() + expect(screen.getByText('Documents')).toBeTruthy() + }) + + it('ignores trailing separators on both the cwd and home', () => { + const view = render() + expect(view.getByText('~')).toBeTruthy() + view.rerender() + expect(view.getByText('~')).toBeTruthy() + }) + + it('drops trailing separators before taking the last segment', () => { + render() + expect(screen.getByText('Documents')).toBeTruthy() + }) + + it('takes the last segment when no home is known', () => { + render() + expect(screen.getByText('Projects')).toBeTruthy() + }) + + it('collapses a backslash home path to ~', () => { + render() + expect(screen.getByText('~')).toBeTruthy() + }) + + it('falls back to the raw path when it has no segment', () => { + render() + expect(screen.getByText('/')).toBeTruthy() + }) + + it('renders a plain $ with no cwd', () => { + render() + expect(screen.getByText('$')).toBeTruthy() + }) + + it('renders the command verbatim after the label', () => { + render() + expect(screen.getByText('git log --oneline | head -3')).toBeTruthy() + }) +}) + +describe('TerminalBlock states', () => { + it('running shows the command line only: no output, no placeholder, no copy', () => { + const view = render() + expect(view.getByText('sleep 5')).toBeTruthy() + expect(view.queryByText('partial')).toBeNull() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByRole('button')).toBeNull() + expect(view.container.firstElementChild?.getAttribute('data-running')).toBe('') + }) + + it('running still shows a settled-looking status pill when one is supplied', () => { + render() + expect(screen.getByText('信号 SIGINT')).toBeTruthy() + }) + + it('settled with whitespace-only output shows the dimmed placeholder', () => { + const view = render() + expect(view.getByText('无输出')).toBeTruthy() + expect(view.queryByRole('button', { name: '复制' })).toBeNull() + }) + + it('settled with absent output shows the placeholder', () => { + render() + expect(screen.getByText('无输出')).toBeTruthy() + }) + + it('settled with an empty string shows the placeholder', () => { + render() + expect(screen.getByText('无输出')).toBeTruthy() + }) + + it('merges className onto the wrapper', () => { + const view = render() + expect(view.container.firstElementChild?.classList.contains('x')).toBe(true) + expect(view.container.firstElementChild?.hasAttribute('data-running')).toBe(false) + }) + + it('drops the output text terminator instead of drawing a blank line', () => { + const view = render() + expect(outputLines(view.container)).toEqual(['a', 'b']) + }) + + it('keeps a genuinely blank final line when the output ends with two newlines', () => { + const view = render() + expect(outputLines(view.container)).toEqual(['a', 'b', '']) + }) + + it('renders ANSI runs as styled spans and plain text bare', () => { + const view = render() + const span = view.container.querySelector('span[style]') + expect(span?.textContent).toBe('bad') + expect(span?.getAttribute('style')).toContain('--dsw-alias-state-error-primary') + expect(outputLines(view.container)).toEqual(['bad ok']) + }) + + it('renders uncolored output with no span wrappers at all', () => { + const view = render() + expect(view.container.querySelectorAll('[class^="_line_"] span')).toHaveLength(0) + }) +}) + +describe('TerminalBlock status pill', () => { + it('renders no pill for a clean exit', () => { + const view = render() + expect(view.queryByText(/退出码|信号/u)).toBeNull() + }) + + it('renders no pill while the exit status is unknown', () => { + const view = render() + expect(view.queryByText(/退出码|信号/u)).toBeNull() + }) + + it('renders the exit-code pill for a non-zero exit', () => { + render() + expect(screen.getByText('退出码 1')).toBeTruthy() + }) + + it('renders the signal pill, which outranks the exit code', () => { + render() + expect(screen.getByText('信号 SIGKILL')).toBeTruthy() + expect(screen.queryByText(/退出码/u)).toBeNull() + }) +}) + +describe('TerminalBlock height cap', () => { + it('renders every line and no expand control under the cap', () => { + const view = render() + expect(outputLines(view.container)).toHaveLength(4) + expect(view.container.querySelector('[aria-expanded]')).toBeNull() + }) + + it('does not count the output terminator against the cap', () => { + const view = render() + expect(outputLines(view.container)).toHaveLength(4) + expect(view.container.querySelector('[aria-expanded]')).toBeNull() + }) + + it('slices head and tail over the cap and expands on click', () => { + const view = render() + // maxLines 4: head = ceil(4/2) = 2, tail = 4 - 2 = 2, 6 hidden. + expect(outputLines(view.container)).toEqual(['line 1', 'line 2', 'line 9', 'line 10']) + const toggle = view.getByRole('button', { name: '展开其余 6 行输出' }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(toggle.textContent).toBe('… 其余 6 行') + + fireEvent.click(toggle) + expect(outputLines(view.container)).toHaveLength(10) + const collapse = view.getByRole('button', { name: '收起输出' }) + expect(collapse.getAttribute('aria-expanded')).toBe('true') + expect(collapse.textContent).toBe('收起') + + fireEvent.click(collapse) + expect(outputLines(view.container)).toEqual(['line 1', 'line 2', 'line 9', 'line 10']) + }) + + it('renders the head slice alone when the cap leaves no tail', () => { + const view = render() + expect(outputLines(view.container)).toEqual(['line 1']) + expect(view.getByRole('button', { name: '展开其余 4 行输出' })).toBeTruthy() + }) + + it('caps at the documented default when maxLines is absent', () => { + const view = render() + expect(outputLines(view.container)).toHaveLength(DEFAULT_TERMINAL_MAX_LINES) + expect(view.getByRole('button', { name: '展开其余 1 行输出' })).toBeTruthy() + }) +}) + +describe('TerminalBlock copy', () => { + it('copies the raw output, never the prompt line or the pill', async () => { + vi.useFakeTimers() + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const output = `${ESC}[31mbad${ESC}[39m\n` + render() + fireEvent.click(screen.getByRole('button', { name: '复制' })) + // Escape codes, the newline terminator, and nothing of the chrome around them. + expect(writeText).toHaveBeenCalledWith(output) + await act(async () => { + await Promise.resolve() + }) + expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy() + // While the ok label is showing, further clicks are no-ops. + fireEvent.click(screen.getByRole('button', { name: '复制成功' })) + expect(writeText).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1000) + expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + }) + + it('copies the whole output while the height cap hides its middle', async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const output = `${body(10)}\n` + render() + fireEvent.click(screen.getByRole('button', { name: '复制' })) + expect(writeText).toHaveBeenCalledWith(output) + expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy() + }) + + it('does not claim success when the host refuses the write', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + render() + fireEvent.click(screen.getByRole('button', { name: '复制' })) + await act(async () => { + await Promise.resolve() + }) + expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull() + }) +}) + +describe('writeClipboard', () => { + it('reports true after the async Clipboard API accepts the exact text', async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(writeText).toHaveBeenCalledWith('payload') + }) + + it('reports false when the Clipboard API rejects', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + await expect(writeClipboard('payload')).resolves.toBe(false) + }) + + it('selects a detached textarea for the execCommand fallback and removes it after', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + let selected: string | undefined + const exec = vi.fn(() => { + selected = document.querySelector('textarea[readonly]')?.value + return true + }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: exec }) + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(exec).toHaveBeenCalledWith('copy') + expect(selected).toBe('payload') + expect(document.querySelector('textarea')).toBeNull() + }) + + it('reports execCommand\'s own refusal verbatim', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) }) + await expect(writeClipboard('payload')).resolves.toBe(false) + }) + + it('reports false and still removes the textarea when execCommand throws', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { + configurable: true, + value: () => { + throw new Error('denied') + }, + }) + await expect(writeClipboard('payload')).resolves.toBe(false) + expect(document.querySelector('textarea')).toBeNull() + }) + + it('reports false on a host with neither clipboard path', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) + await expect(writeClipboard('payload')).resolves.toBe(false) + }) + + it('reports false when navigator.clipboard exists without writeText', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {} }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) + await expect(writeClipboard('payload')).resolves.toBe(false) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b9538051cd..53791fe2fd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1075,6 +1075,9 @@ importers: '@shikijs/langs': specifier: ^4.3.1 version: 4.3.1 + anser: + specifier: ^2.3.5 + version: 2.3.5 clsx: specifier: ^2.0.0 version: 2.1.1 @@ -7856,6 +7859,9 @@ packages: resolution: {integrity: sha512-OyacJsaeuLUvGWOynNqYc6sx88XvyoG39wMT8SYqL3l9wwaorDW/LPRbUPfhzw0bWsUWzNCZTnFYOrWFBKsUaw==} engines: {node: '>= 14.0.0'} + anser@2.3.5: + resolution: {integrity: sha512-vcZjxvvVoxTeR5XBNJB38oTu/7eDCZlwdz32N1eNgpyPF7j/Z7Idf+CUwQOkKKpJ7RJyjxgLHCM7vdIK0iCNMQ==} + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -12840,6 +12846,8 @@ snapshots: '@algolia/requester-fetch': 5.55.2 '@algolia/requester-node-http': 5.55.2 + anser@2.3.5: {} + ansi-regex@5.0.1: {} ansi-regex@6.2.2: {} From f4c243c75fa2590ddba00273d4c0b12a393a5e5a Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 28 Jul 2026 16:41:04 +0800 Subject: [PATCH 02/14] feat(web): state the run state on the terminal card's prompt line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The terminal card showed no run state: a running command and a settled command that produced no output rendered the same prompt line, so whether a command was still running had to be inferred from the absence of output. Lead the prompt line with a StateDot in three of its states — the spinning ring while running, red for the same exit status that renders the status pill, green for a clean settle. That is the same indicator a tool row's leading icon carries, so a row and its own card cannot disagree about one command; the row/card agreement is pinned in the ui-conversation spec. StateDot is aria-hidden, so a visually hidden text label rides beside it, which is what the refreshed aria goldens now record. The e2e adds what jsdom cannot compute: the dot's color resolves to the green success token through the real theme stylesheet, and the dot precedes the prompt label in document order. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 8 +-- .../2026-07-28-web-terminal-card.zh.md | 8 +-- apps/web/tests/navigation-panes.e2e.ts | 28 ++++++++++ .../navigation-panes/details-open.expected.md | 2 +- .../terminal-card.expected.md | 2 +- apps/web/tests/terminal-card.snapshot.ts | 13 ++++- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../tests/terminal-card.spec.tsx | 22 ++++++++ .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../client/ui-primitives/src/StateDot.tsx | 4 +- .../src/TerminalBlock.module.css | 17 ++++++ .../ui-primitives/src/TerminalBlock.tsx | 33 +++++++++++- .../tests/terminal-block.spec.tsx | 54 ++++++++++++++++++- 18 files changed, 184 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 347d5978c0..98cbad4ffc 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 76d5c47054378330da9e9eebb70571925e47f741 -2026-07-28-web-terminal-card.zh.md: 83d5e7f72d9b04358ce4fe1fd9295e5c97045031 +2026-07-28-web-terminal-card.md: 7dbe688b58e78a8f67fe14809b86a6bfd4f7ce36 +2026-07-28-web-terminal-card.zh.md: 1e8c847e2955605be1a55b45d84fb449ea2a46fd diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 76d5c47054..7dbe688b58 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -16,7 +16,7 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ The component's contract: -- **Prompt line.** A shortened cwd label followed by the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. +- **Prompt line.** A run-state dot, then a shortened cwd label, then the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. The dot is `StateDot` in three of its four states: the spinning ring while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. It leads the line because the first question a reader has about a shell command is whether it is still running, and without the dot that had to be inferred from the absence of output — which a settled command producing no output also looks like. `StateDot` is `aria-hidden`, so a visually hidden text label rides beside it. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. - **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters, and a carriage return reduces its line to the final redraw, which is what a terminal shows for progress output. @@ -50,13 +50,13 @@ Inline rendering is licensed for the terminal intent alone. A future intent that ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws, and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. +`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws, and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, the run-state dot across all three reachable states plus its position ahead of the prompt label, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. -`packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files. +`packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card and its agreement with its own summary row's state dot, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files. `apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 66 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit recovered from the trailing marker. -`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `details-open.expected.md` golden was refreshed for the panel's new terminal card. That refresh also absorbed a stale `Input json` line and its copy button, which the shiki `CodeBlock` change already on master left behind — verified as failing on a clean rebuilt tree before this change, so it is a correction carried along, not an effect of this one. +`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet), and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `details-open.expected.md` golden was refreshed for the panel's new terminal card. That refresh also absorbed a stale `Input json` line and its copy button, which the shiki `CodeBlock` change already on master left behind — verified as failing on a clean rebuilt tree before this change, so it is a correction carried along, not an effect of this one. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index 83d5e7f72d..1e8c847e29 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -16,7 +16,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c 该组件的契约: -- **提示符行。** 一个缩短的 cwd 标签,其后原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。 +- **提示符行。** 一枚运行状态点,其后是缩短的 cwd 标签,再原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。状态点是 `StateDot` 四种状态中的三种:运行期间为旋转圆环,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。它位于行首,因为读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有该状态点时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。`StateDot` 是 `aria-hidden`,因此其旁伴随一处视觉隐藏的文本标签。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 - **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM;回车会把所在行归约为最后一次重绘,这正是终端对进度输出的呈现。 @@ -50,13 +50,13 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘,以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 +`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘,以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关、运行状态点全部三种可达状态及其位于提示符标签之前的位置,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 -`packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。 +`packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片及其与自身摘要行状态点的一致性,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。 `apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 66 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及从末尾标记还原出的非零退出码。 -`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `details-open.expected.md` 基准已为面板的新终端卡片重新录制。该次录制同时吸收了一行陈旧的 `Input json` 及其复制按钮——那是 master 上已有的 shiki `CodeBlock` 改动留下的;在干净并重新构建的工作树上验证过它本就失败,因此那是被顺带修正的部分,而非本次改动的影响。 +`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值);复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `details-open.expected.md` 基准已为面板的新终端卡片重新录制。该次录制同时吸收了一行陈旧的 `Input json` 及其复制按钮——那是 master 上已有的 shiki `CodeBlock` 改动留下的;在干净并重新构建的工作树上验证过它本就失败,因此那是被顺带修正的部分,而非本次改动的影响。 ## Related diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index b0e340da43..1e022489ee 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -207,6 +207,34 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { return { whiteSpace: getComputedStyle(row).whiteSpace, overflowX: getComputedStyle(pane).overflowX, ...squeezed } }) expect(layout).toEqual({ whiteSpace: 'pre', overflowX: 'auto', wrapped: false, scrollsSideways: true }) + // The run-state dot's color is the whole point of it and is the one thing + // jsdom cannot report: --dsw-* tokens resolve only against the real theme + // stylesheet. This command settled cleanly, so the dot must be the green + // success token — a red one here would read as a failed command. + const dot = await card.locator('[class*="_runState_"][data-state]').first().evaluate((node) => { + // The token lives on body, so the probe must sit in the same cascade. + const probe = document.createElement('span') + probe.style.color = 'var(--dsw-alias-state-success-primary)' + document.body.appendChild(probe) + const success = getComputedStyle(probe).color + probe.remove() + return { + state: node.getAttribute('data-state'), + color: getComputedStyle(node as HTMLElement).color, + success, + label: node.parentElement?.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null, + // The dot precedes the prompt label in document order, which is what + // puts it to the left of the `$`. + beforePrompt: node.compareDocumentPosition(node.parentElement!.querySelector('[class*="_cwd_"]')!) + === Node.DOCUMENT_POSITION_FOLLOWING, + } + }) + expect(dot.state).toBe('done') + expect(dot.label).toBe('已完成') + expect(dot.beforePrompt).toBe(true) + // Resolved through the theme token, not a literal hex in the component. + expect(dot.success).toMatch(/^rgb/) + expect(dot.color).toBe(dot.success) // Golden of the card at rest — captured before the copy click, whose // confirmation label self-reverts on a timer and would not hold still. const snapshot = (await captureStableAria(page, '[data-terminal]', scaffold.workspaceCwd)) diff --git a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md b/apps/web/tests/snapshots/navigation-panes/details-open.expected.md index 9eee71468d..d0a753994a 100644 --- a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md +++ b/apps/web/tests/snapshots/navigation-panes/details-open.expected.md @@ -3,6 +3,6 @@ - text: Input json - button "复制" - code: "{ \"command\": \"echo NAVIGATION_OK\", \"description\": \"Print NAVIGATION_OK\" }" -- text: Output $ echo NAVIGATION_OK +- text: Output 已完成 $ echo NAVIGATION_OK - button "复制" - text: NAVIGATION_OK diff --git a/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md b/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md index 2b81725468..abeffe93a8 100644 --- a/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md +++ b/apps/web/tests/snapshots/navigation-panes/terminal-card.expected.md @@ -1,3 +1,3 @@ -- text: $ echo NAVIGATION_OK +- text: 已完成 $ echo NAVIGATION_OK - button "复制" - text: NAVIGATION_OK diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts index 53215f4ba9..80cc4fd2b4 100644 --- a/apps/web/tests/terminal-card.snapshot.ts +++ b/apps/web/tests/terminal-card.snapshot.ts @@ -120,9 +120,14 @@ function readCard(card: Element) { text: expander.textContent, expanded: expander.getAttribute('aria-expanded'), }, + // The run-state dot at the head of the prompt line, by its StateDot state. + runState: card.querySelector('[class*="_runState_"][data-state]')?.getAttribute('data-state') ?? null, + runStateLabel: card.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null, // Every color the ANSI parser emits resolves through a --dsw-* token, so // the card follows the theme instead of painting literal terminal rgb. - colors: [...new Set([...card.querySelectorAll('span[style]')] + // Scoped to the output lines: the run-state dot is an inline-styled span + // too, and its geometry is not an ANSI-resolved color. + colors: [...new Set([...card.querySelectorAll('[class*="_line_"] span[style]')] .map(span => span.getAttribute('style')))], } } @@ -198,6 +203,8 @@ it('renders the keyed bash row with a resident terminal card', async () => { "[exit code: 1]", ], "prompt": "nested pnpm run check", + "runState": "error", + "runStateLabel": "失败", "status": "退出码 1", } `) @@ -229,6 +236,8 @@ it('the fallback row reaches the same card through its expand control', async () "-rw-r--r-- demo.txt", ], "prompt": "fixture ls -la", + "runState": "done", + "runStateLabel": "已完成", "status": null, } `) @@ -318,6 +327,8 @@ it('the details panel Output section renders the same call at full height', asyn ], "panelLines": 16, "prompt": "nested pnpm run check", + "runState": "error", + "runStateLabel": "失败", "status": "退出码 1", } `) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index dd28591b01..677029cf5f 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 1c6912b05e259fa1f4a7096c3a2b82f9f67f5527 -README.zh.md: 157bfafd3a1157420acbb73861cd40d759228743 +README.md: 39d185014c658f490f0a3672ea3d7c99f30d8df2 +README.zh.md: 6b63631287bf420af0985a743f068f27b9c97873 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 1c6912b05e..39d185014c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -10,7 +10,7 @@ The view ring IS a slot: the conversation registration declares the `'conversati Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and `Write · ` or `Edit · ` summary while retaining the shared row-to-details interaction. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged), and the details panel resolves a selected sub-call id to its full logged args and complete output. Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering. -A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. The keyed `BashRow` carries the card resident below its summary row and outside that row's click target, so copying or expanding the output does not open the details panel; the render-site fallback row keeps it behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed for this intent alone; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)). +A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. Both sites therefore also show the card's run-state dot, which is the same `StateDot` semantic a tool row's leading icon carries, so a row and its own card always agree about one command's state. The keyed `BashRow` carries the card resident below its summary row and outside that row's click target, so copying or expanding the output does not open the details panel; the render-site fallback row keeps it behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed for this intent alone; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)). Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openDetails`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 157bfafd3a..6b63631287 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -10,7 +10,7 @@ 通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和 `Write · ` 或 `Edit · ` 摘要,同时保留共享的行到详情交互。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行),details 面板则会根据选中的子调用 id 解析出其完整记录的参数与完整输出。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect`、`Mount temporary Plugin` 和 `Unmount temporary Plugin`;mount 行保留 code 变体的可展开源码渲染。 -声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。键控的 `BashRow` 把卡片常驻在摘要行下方、且位于该行点击目标之外,因此复制或展开输出不会打开详情面板;渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出只对该意图开放;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。 +声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。因此两个渲染点也都显示卡片的运行状态点,它与工具行行首图标承载同一套 `StateDot` 语义,所以一行与其自身的卡片对同一条命令的状态总是一致。键控的 `BashRow` 把卡片常驻在摘要行下方、且位于该行点击目标之外,因此复制或展开输出不会打开详情面板;渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出只对该意图开放;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。 工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openDetails`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index 1ab75861b5..49fcf48d4c 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -28,6 +28,11 @@ afterEach(cleanup) */ const RAW = { normalizer: (text: string) => text } +/** The rendered card's run-state dot state, so a render site cannot silently drop it. */ +function runStateOf(container: HTMLElement): string | null { + return container.querySelector('[data-terminal] [data-state]')?.getAttribute('data-state') ?? null +} + const SID = 's1' as SessionId const ARGS = '{"command":"ls -la","description":"List files"}' @@ -137,6 +142,9 @@ describe('chat row terminal body', () => { fireEvent.click(view.container.querySelector('button')!) expect(view.getByText('ls -la')).toBeTruthy() expect(view.queryByText('复制')).toBeNull() + // The card states its own run state: a running command reads as running + // even though it has no output yet to distinguish it from an empty settle. + expect(runStateOf(view.container)).toBe('ongoing') }) it('a non-terminal call keeps the args-JSON text body', () => { @@ -183,6 +191,19 @@ describe('BashRow terminal card', () => { expect(openDetails).toHaveBeenCalledTimes(1) }) + // The row's leading StateDot and the card's run-state dot describe the same + // command, so a running row whose card claimed 'done' would be a contradiction + // the reader sees on one line. + it('agrees with the summary row about the run state', () => { + const runningView = render() + expect(runningView.container.querySelector('[data-variant="bash"]')?.getAttribute('data-state')).toBe('running') + expect(runStateOf(runningView.container)).toBe('ongoing') + cleanup() + const settledView = render() + expect(settledView.container.querySelector('[data-variant="bash"]')?.getAttribute('data-state')).toBe('ok') + expect(runStateOf(settledView.container)).toBe('done') + }) + it('a non-terminal bash call (background start) renders the summary row alone', () => { const view = render( { const view = mount(snapshot({ runningCalls: [running()] }), target) expect(view.getByText('ls -la')).toBeTruthy() expect(view.queryByText('运行中…')).toBeNull() + expect(runStateOf(view.container)).toBe('ongoing') }) it('a running non-terminal call keeps the 运行中… placeholder', () => { diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 1eb8a05ba0..78281969f3 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: c9c70f29804ac4e6783486595460bf07499e1dff -README.zh.md: 254fc5ba5aef553fd447338353a0c5311ddbd98a +README.md: b0387debbecb713b1e4af2b1497e81ddda083a51 +README.zh.md: d04a34951422c9cdd02421759a4e29672b1f7a54 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index c9c70f2980..b0387debbe 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: a prompt line (shortened `cwd` label plus the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: a prompt line (a run-state `StateDot` ahead of the shortened `cwd` label, then the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. The dot reaches three of `StateDot`'s states — the spinning ring while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries a visually hidden text label because `StateDot` is `aria-hidden`. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 254fc5ba5a..d04a349514 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签加命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签之前是一枚运行状态 `StateDot`,其后是命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。该状态点用到 `StateDot` 的三种状态——`running` 期间为旋转圆环,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它同时携带一处视觉隐藏的文本标签。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 diff --git a/packages/client/ui-primitives/src/StateDot.tsx b/packages/client/ui-primitives/src/StateDot.tsx index c4117673ba..6bc4cdba5c 100644 --- a/packages/client/ui-primitives/src/StateDot.tsx +++ b/packages/client/ui-primitives/src/StateDot.tsx @@ -19,8 +19,8 @@ export type StateDotState = 'done' | 'warning' | 'ongoing' | 'error' */ export function StateDot({ state, size = 10, className }: { state: StateDotState - size?: number - className?: string + size?: number | undefined + className?: string | undefined }) { const gradientId = useId() if (state === 'ongoing') { diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index 8a4f4a5e60..6d470ec634 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -36,6 +36,23 @@ font: var(--dsw-font-markdown-code-block); } +/* The dot sits on the prompt row's baseline box, which is a code-font line, so + it is centered against that line's box rather than sitting on the baseline. */ +.runState { + flex: none; + align-self: center; +} + +/* The dot is aria-hidden; this is its text label for assistive technology. */ +.runStateLabel { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + .cwd { flex: none; color: var(--dsw-alias-label-tertiary); diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index e224e2b1de..5431f3c443 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -1,6 +1,6 @@ // TerminalBlock: the terminal surface for a shell command and its output — -// prompt line (shortened cwd + command), ANSI-colored output, settled exit -// status, and a copy control for the raw output. Output never soft-wraps: +// prompt line (run-state dot + shortened cwd + command), ANSI-colored output, +// settled exit status, and a copy control for the raw output. Output never soft-wraps: // column-aligned output (ls, tables, box drawing) keeps its alignment and // scrolls horizontally instead of folding. Colors resolve through --dsw-* // tokens; ANSI parsing lives in ansi.ts. @@ -10,6 +10,7 @@ import clsx from 'clsx' import { parseAnsiLines, type AnsiLine } from './ansi.ts' import { writeClipboard } from './clipboard.ts' import { Pill } from './Pill.tsx' +import { StateDot, type StateDotState } from './StateDot.tsx' import css from './TerminalBlock.module.css' /** @@ -70,6 +71,31 @@ function statusText(exitCode: number | undefined, signal: string | undefined): s return undefined } +/** + * Run-state indicator for the command, shown at the head of the prompt line so + * the card states whether the command is still running without the reader + * having to infer it from the presence of output. Three of {@link StateDotState}'s + * four states are reachable: the spinning ring while running (the same + * indicator a running tool row's leading icon uses, so the row and its card + * never disagree), green for a clean settle, red for a signal or a non-zero + * exit — the same status distinction {@link statusText} draws for the pill. A + * settled command whose exit status never reached the view counts as a clean + * settle: the view says it finished and says nothing went wrong. + * @param running - the command has not settled. + * @param exitCode - settled exit code, when known. + * @param signal - settled terminating signal name, when known. + * @returns the dot's state and its text label, since the dot is aria-hidden. + */ +function runState( + running: boolean, + exitCode: number | undefined, + signal: string | undefined, +): { state: StateDotState; label: string } { + if (running) return { state: 'ongoing', label: '运行中' } + if (statusText(exitCode, signal) !== undefined) return { state: 'error', label: '失败' } + return { state: 'done', label: '已完成' } +} + /** * Render one parsed output line. Runs without SGR state render as bare text, * so uncolored output carries no span wrappers. @@ -120,6 +146,7 @@ export function TerminalBlock({ const onToggle = useCallback(() => { setExpanded(value => !value) }, []) const status = statusText(exitCode, signal) + const state = runState(running, exitCode, signal) const empty = text.trim() === '' const hidden = lines.length - maxLines const capped = hidden > 0 && !expanded @@ -132,6 +159,8 @@ export function TerminalBlock({
+ + {state.label} {cwd === undefined ? '$' : promptLabel(cwd, home)} {command}
diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index 87e153a741..fd928f48d5 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom // TerminalBlock: the prompt label's cwd shortening, the running/empty/settled -// arms, the exit-status pill, the head/tail height cap and its expand control, +// arms, the prompt line's run-state dot, the exit-status pill, the head/tail height cap and its expand control, // and the copy control writing the raw output on both the accepted and the // refused clipboard paths. writeClipboard's own return contract is pinned here // too, since it is the seam both copy controls in this package share; the @@ -25,6 +25,15 @@ function outputLines(container: HTMLElement): string[] { return [...container.querySelectorAll('[class^="_line_"]')].map(row => row.textContent ?? '') } +/** The prompt line's run-state dot: its StateDot state plus the hidden text label beside it. */ +function runStateOf(container: HTMLElement): { state: string | null; label: string | undefined } { + const dot = container.querySelector('[class*="_runState_"][data-state]') + return { + state: dot?.getAttribute('data-state') ?? null, + label: container.querySelector('[class^="_runStateLabel_"]')?.textContent ?? undefined, + } +} + /** `count` numbered output lines, without the terminating newline. */ function body(count: number): string { return Array.from({ length: count }, (_value, index) => `line ${index + 1}`).join('\n') @@ -128,7 +137,8 @@ describe('TerminalBlock states', () => { it('renders ANSI runs as styled spans and plain text bare', () => { const view = render() - const span = view.container.querySelector('span[style]') + // Scoped to a line: the prompt line's run-state dot is a styled span too. + const span = view.container.querySelector('[class^="_line_"] span[style]') expect(span?.textContent).toBe('bad') expect(span?.getAttribute('style')).toContain('--dsw-alias-state-error-primary') expect(outputLines(view.container)).toEqual(['bad ok']) @@ -163,6 +173,46 @@ describe('TerminalBlock status pill', () => { }) }) +describe('TerminalBlock run-state dot', () => { + it('shows the spinning ring and its running label while the command runs', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'ongoing', label: '运行中' }) + }) + + it('shows the done dot for a clean settled exit', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'done', label: '已完成' }) + }) + + it('counts a settled command with no exit status as a clean settle', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'done', label: '已完成' }) + }) + + it('shows the error dot for a non-zero exit', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'error', label: '失败' }) + }) + + it('shows the error dot for a signal, whatever the exit code says', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'error', label: '失败' }) + }) + + // The dot precedes the prompt label, which is what makes it read as the + // state OF this command rather than of the card's chrome. + it('places the dot ahead of the prompt label and the command', () => { + const view = render() + const prompt = view.container.querySelector('[class^="_prompt_"]') + expect([...prompt!.children].map(node => node.textContent)).toEqual(['', '已完成', 'app', 'ls']) + }) + + it('keeps the running dot even while a settled-looking status pill is supplied', () => { + const view = render() + expect(runStateOf(view.container)).toEqual({ state: 'ongoing', label: '运行中' }) + }) +}) + describe('TerminalBlock height cap', () => { it('renders every line and no expand control under the cap', () => { const view = render() From 9d2f7f43625904605a5ed5d9cf3c417db5db122a Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 28 Jul 2026 17:08:40 +0800 Subject: [PATCH 03/14] docs(web): describe the running dot as the chase master now renders Master replaced StateDot's ongoing ring with a pixel-art chase, so the prompt line's run-state description named an indicator that no longer exists. Same fix in the note, both READMEs, and the test name. --- .../feature/2026-07-28-web-terminal-card.i18n.yaml | 4 ++-- .../notes/implemented/feature/2026-07-28-web-terminal-card.md | 2 +- .../implemented/feature/2026-07-28-web-terminal-card.zh.md | 2 +- packages/client/ui-primitives/README.i18n.yaml | 4 ++-- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/TerminalBlock.tsx | 2 +- packages/client/ui-primitives/tests/terminal-block.spec.tsx | 2 +- 8 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 98cbad4ffc..9739ef195a 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 7dbe688b58e78a8f67fe14809b86a6bfd4f7ce36 -2026-07-28-web-terminal-card.zh.md: 1e8c847e2955605be1a55b45d84fb449ea2a46fd +2026-07-28-web-terminal-card.md: 0c10e867afe6a9cc7085206709ae94df54bc4ed0 +2026-07-28-web-terminal-card.zh.md: e680f34bc5852430e00a5970389be0280b086f3b diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 7dbe688b58..0c10e867af 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -16,7 +16,7 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ The component's contract: -- **Prompt line.** A run-state dot, then a shortened cwd label, then the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. The dot is `StateDot` in three of its four states: the spinning ring while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. It leads the line because the first question a reader has about a shell command is whether it is still running, and without the dot that had to be inferred from the absence of output — which a settled command producing no output also looks like. `StateDot` is `aria-hidden`, so a visually hidden text label rides beside it. +- **Prompt line.** A run-state dot, then a shortened cwd label, then the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. The dot is `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. It leads the line because the first question a reader has about a shell command is whether it is still running, and without the dot that had to be inferred from the absence of output — which a settled command producing no output also looks like. `StateDot` is `aria-hidden`, so a visually hidden text label rides beside it. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. - **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters, and a carriage return reduces its line to the final redraw, which is what a terminal shows for progress output. diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index 1e8c847e29..e680f34bc5 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -16,7 +16,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c 该组件的契约: -- **提示符行。** 一枚运行状态点,其后是缩短的 cwd 标签,再原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。状态点是 `StateDot` 四种状态中的三种:运行期间为旋转圆环,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。它位于行首,因为读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有该状态点时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。`StateDot` 是 `aria-hidden`,因此其旁伴随一处视觉隐藏的文本标签。 +- **提示符行。** 一枚运行状态点,其后是缩短的 cwd 标签,再原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。状态点是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。它位于行首,因为读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有该状态点时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。`StateDot` 是 `aria-hidden`,因此其旁伴随一处视觉隐藏的文本标签。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 - **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM;回车会把所在行归约为最后一次重绘,这正是终端对进度输出的呈现。 diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 78281969f3..495831a377 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: b0387debbecb713b1e4af2b1497e81ddda083a51 -README.zh.md: d04a34951422c9cdd02421759a4e29672b1f7a54 +README.md: bc880333157f5cb790cbaf854b01aaf8ea6c1cc9 +README.zh.md: 6593e4518d09eaccee7e55874b1162943c5eb3bd diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index b0387debbe..bc88033315 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: a prompt line (a run-state `StateDot` ahead of the shortened `cwd` label, then the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. The dot reaches three of `StateDot`'s states — the spinning ring while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries a visually hidden text label because `StateDot` is `aria-hidden`. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: a prompt line (a run-state `StateDot` ahead of the shortened `cwd` label, then the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. The dot reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries a visually hidden text label because `StateDot` is `aria-hidden`. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index d04a349514..6593e4518d 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签之前是一枚运行状态 `StateDot`,其后是命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。该状态点用到 `StateDot` 的三种状态——`running` 期间为旋转圆环,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它同时携带一处视觉隐藏的文本标签。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签之前是一枚运行状态 `StateDot`,其后是命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。该状态点用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它同时携带一处视觉隐藏的文本标签。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index 5431f3c443..c5278dd7df 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -75,7 +75,7 @@ function statusText(exitCode: number | undefined, signal: string | undefined): s * Run-state indicator for the command, shown at the head of the prompt line so * the card states whether the command is still running without the reader * having to infer it from the presence of output. Three of {@link StateDotState}'s - * four states are reachable: the spinning ring while running (the same + * four states are reachable: the running chase (the same * indicator a running tool row's leading icon uses, so the row and its card * never disagree), green for a clean settle, red for a signal or a non-zero * exit — the same status distinction {@link statusText} draws for the pill. A diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index fd928f48d5..486aac1197 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -174,7 +174,7 @@ describe('TerminalBlock status pill', () => { }) describe('TerminalBlock run-state dot', () => { - it('shows the spinning ring and its running label while the command runs', () => { + it('shows the running chase and its running label while the command runs', () => { const view = render() expect(runStateOf(view.container)).toEqual({ state: 'ongoing', label: '运行中' }) }) From a00678a44452df0dd341eabe4ad47804470ebcb0 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 28 Jul 2026 18:48:57 +0800 Subject: [PATCH 04/14] feat(web): give a multi-line command one prompt row per line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `command` carrying two shell commands on two lines rendered as one row: `.command` had `white-space: nowrap`, so the two collapsed into a single ellipsized line that read as one command with stray arguments. Render one prompt row per command line, and move the run-state dot out of flow into a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's text metrics to line up. The dot stays exactly one per card, on the first row. The exit status the view carries is the whole call's and bash reports no per-command status, so a dot per line would assert, of a line that succeeded inside a failing call, that the line itself failed. The single visually hidden label keeps the same scope, since one label per row would read to assistive technology as several distinct outcomes. Fixture turn 60's command becomes two lines, so the built-bundle snapshot pins the layout and its dot distribution (`dotsPerPromptRow: [1, 0]`), and the e2e adds that the dot starts left of the card surface — geometry jsdom cannot compute. Both READMEs now also record that this package's user-facing copy is inline Chinese, since zero-cordis atoms have no route to `ctx.locale`; extracting it belongs to the repo-wide localization work. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 9 +++-- .../2026-07-28-web-terminal-card.zh.md | 9 +++-- apps/web/tests/navigation-panes.e2e.ts | 9 ++++- apps/web/tests/terminal-card.snapshot.ts | 32 ++++++++++++++-- .../client/connection/src/client/fixture.ts | 4 +- .../tests/terminal-card.spec.tsx | 11 ++++++ .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 3 +- packages/client/ui-primitives/README.zh.md | 3 +- .../src/TerminalBlock.module.css | 37 ++++++++++++++----- .../ui-primitives/src/TerminalBlock.tsx | 21 +++++++++-- .../tests/terminal-block.spec.tsx | 29 ++++++++++++++- 13 files changed, 140 insertions(+), 35 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 9739ef195a..ca4d5e62e1 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 0c10e867afe6a9cc7085206709ae94df54bc4ed0 -2026-07-28-web-terminal-card.zh.md: e680f34bc5852430e00a5970389be0280b086f3b +2026-07-28-web-terminal-card.md: 7a4672e110cb4333df8d7a29a772de8bf2717d84 +2026-07-28-web-terminal-card.zh.md: df49ef45e000a464715635ca32e42848994fc7ff diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 0c10e867af..7a4672e110 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -16,7 +16,8 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ The component's contract: -- **Prompt line.** A run-state dot, then a shortened cwd label, then the command verbatim. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. The dot is `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. It leads the line because the first question a reader has about a shell command is whether it is still running, and without the dot that had to be inferred from the absence of output — which a settled command producing no output also looks like. `StateDot` is `aria-hidden`, so a visually hidden text label rides beside it. +- **Prompt lines, one per command line.** Each line of the command gets its own row: label, then that line verbatim. A `command` carrying two shell commands on two lines therefore reads as the two commands it is, instead of collapsing into one ellipsized row. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. A trailing newline is a terminator, not an empty final command. +- **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's own text metrics to line up with it. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. - **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters, and a carriage return reduces its line to the final redraw, which is what a terminal shows for progress output. @@ -50,13 +51,13 @@ Inline rendering is licensed for the terminal intent alone. A future intent that ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws, and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, the run-state dot across all three reachable states plus its position ahead of the prompt label, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. +`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws, and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, the run-state dot across all three reachable states plus its position ahead of the prompt label, the one-row-per-command-line prompt and its single dot on the first row, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. `packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card and its agreement with its own summary row's state dot, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files. -`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 66 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit recovered from the trailing marker. +`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 66 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes, and turn 60's command was made two lines so the built-bundle snapshot pins the per-line prompt and its single dot (`dotsPerPromptRow: [1, 0]`); that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit recovered from the trailing marker. -`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet), and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `details-open.expected.md` golden was refreshed for the panel's new terminal card. That refresh also absorbed a stale `Input json` line and its copy button, which the shiki `CodeBlock` change already on master left behind — verified as failing on a clean rebuilt tree before this change, so it is a correction carried along, not an effect of this one. +`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet) and starts to the left of the card surface itself, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `details-open.expected.md` golden was refreshed for the panel's new terminal card. That refresh also absorbed a stale `Input json` line and its copy button, which the shiki `CodeBlock` change already on master left behind — verified as failing on a clean rebuilt tree before this change, so it is a correction carried along, not an effect of this one. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index e680f34bc5..df49ef45e0 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -16,7 +16,8 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c 该组件的契约: -- **提示符行。** 一枚运行状态点,其后是缩短的 cwd 标签,再原样跟随命令。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。状态点是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。它位于行首,因为读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有该状态点时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。`StateDot` 是 `aria-hidden`,因此其旁伴随一处视觉隐藏的文本标签。 +- **提示符行,每条命令行一行。** 命令的每一行各占一行:标签,其后原样跟随该行。因此一个在两行上承载两条 shell 命令的 `command` 就读作它本身的两条命令,而不是被压成一行并省略号截断。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。末尾换行是终止符,不是一条空的末命令。 +- **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片表面左侧预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 - **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM;回车会把所在行归约为最后一次重绘,这正是终端对进度输出的呈现。 @@ -50,13 +51,13 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘,以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关、运行状态点全部三种可达状态及其位于提示符标签之前的位置,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 +`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘,以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关、运行状态点全部三种可达状态及其位于提示符标签之前的位置、每条命令行一行的提示区及其位于第一行的单枚状态点,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 `packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片及其与自身摘要行状态点的一致性,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。 -`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 66 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及从末尾标记还原出的非零退出码。 +`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 66 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态,并把第 60 轮的命令改为两行,使构建产物快照钉住逐行提示区及其单枚状态点(`dotsPerPromptRow: [1, 0]`);该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及从末尾标记还原出的非零退出码。 -`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值);复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `details-open.expected.md` 基准已为面板的新终端卡片重新录制。该次录制同时吸收了一行陈旧的 `Input json` 及其复制按钮——那是 master 上已有的 shiki `CodeBlock` 改动留下的;在干净并重新构建的工作树上验证过它本就失败,因此那是被顺带修正的部分,而非本次改动的影响。 +`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值),且其起点位于卡片表面本身的左侧;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `details-open.expected.md` 基准已为面板的新终端卡片重新录制。该次录制同时吸收了一行陈旧的 `Input json` 及其复制按钮——那是 master 上已有的 shiki `CodeBlock` 改动留下的;在干净并重新构建的工作树上验证过它本就失败,因此那是被顺带修正的部分,而非本次改动的影响。 ## Related diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 1e022489ee..2883371bdb 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -222,16 +222,23 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { state: node.getAttribute('data-state'), color: getComputedStyle(node as HTMLElement).color, success, - label: node.parentElement?.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null, + // One label per card (the state is the call's), so it hangs off the + // prompt column rather than the row the dot sits in. + label: node.closest('[class*="_prompt_"]')?.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null, // The dot precedes the prompt label in document order, which is what // puts it to the left of the `$`. beforePrompt: node.compareDocumentPosition(node.parentElement!.querySelector('[class*="_cwd_"]')!) === Node.DOCUMENT_POSITION_FOLLOWING, + // The dot is out of flow in the card's left gutter, so it starts to the + // left of the card surface itself — the geometry jsdom cannot compute. + leftOfCard: (node as HTMLElement).getBoundingClientRect().left + < node.closest('[data-terminal]')!.getBoundingClientRect().left, } }) expect(dot.state).toBe('done') expect(dot.label).toBe('已完成') expect(dot.beforePrompt).toBe(true) + expect(dot.leftOfCard).toBe(true) // Resolved through the theme token, not a literal hex in the component. expect(dot.success).toMatch(/^rgb/) expect(dot.color).toBe(dot.success) diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts index 80cc4fd2b4..b6e53d972f 100644 --- a/apps/web/tests/terminal-card.snapshot.ts +++ b/apps/web/tests/terminal-card.snapshot.ts @@ -111,7 +111,14 @@ function readCard(card: Element) { const status = card.querySelector('[class*="_status_"]') const expander = card.querySelector('button[aria-expanded]') return { - prompt: `${card.querySelector('[class*="_cwd_"]')?.textContent ?? ''} ${card.querySelector('[class*="_command_"]')?.textContent ?? ''}`, + // One entry per command line: a multi-line command is one row per line. + prompt: [...card.querySelectorAll('[class*="_promptLine_"]')].map(row => + `${row.querySelector('[class*="_cwd_"]')?.textContent ?? ''} ${row.querySelector('[class*="_command_"]')?.textContent ?? ''}`), + // Dots per prompt row: exactly one, on the first row — the exit status the + // view carries is the whole call's, so a dot per line would assert a + // per-line outcome bash does not report. + dotsPerPromptRow: [...card.querySelectorAll('[class*="_promptLine_"]')].map(row => + row.querySelectorAll('[data-state]').length), status: status === null ? null : status.textContent, copy: card.querySelector('[class*="_copyButton_"]')?.textContent ?? null, lines: [...card.querySelectorAll('[class*="_line_"]')].map(line => line.textContent), @@ -187,6 +194,9 @@ it('renders the keyed bash row with a resident terminal card', async () => { "color: var(--dsw-alias-state-error-primary);", ], "copy": "复制", + "dotsPerPromptRow": [ + 1, + ], "expander": { "expanded": "false", "label": "展开其余 14 行输出", @@ -202,7 +212,9 @@ it('renders the keyed bash row with a resident terminal card', async () => { "1 of 4 checks failed", "[exit code: 1]", ], - "prompt": "nested pnpm run check", + "prompt": [ + "nested pnpm run check", + ], "runState": "error", "runStateLabel": "失败", "status": "退出码 1", @@ -229,13 +241,20 @@ it('the fallback row reaches the same card through its expand control', async () { "colors": [], "copy": "复制", + "dotsPerPromptRow": [ + 1, + 0, + ], "expander": null, "lines": [ "total 2", "drwxr-xr-x fixture", "-rw-r--r-- demo.txt", ], - "prompt": "fixture ls -la", + "prompt": [ + "fixture ls -la", + "fixture echo done", + ], "runState": "done", "runStateLabel": "已完成", "status": null, @@ -302,6 +321,9 @@ it('the details panel Output section renders the same call at full height', asyn "color: var(--dsw-alias-label-tertiary);", ], "copy": "复制", + "dotsPerPromptRow": [ + 1, + ], "expander": { "expanded": "false", "label": "展开其余 6 行输出", @@ -326,7 +348,9 @@ it('the details panel Output section renders the same call at full height', asyn "[exit code: 1]", ], "panelLines": 16, - "prompt": "nested pnpm run check", + "prompt": [ + "nested pnpm run check", + ], "runState": "error", "runStateLabel": "失败", "status": "退出码 1", diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 401d3a76a4..55907be48a 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -185,7 +185,9 @@ function buildAlphaLog(): SessionEvent[] { push({ type: 'step/end', data: { turn, step: 0 } }) push({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } }) } - toolTurn(60, 'fx-bash', '{"command":"ls -la","cwd":"/tmp/fixture"}', 'total 2\ndrwxr-xr-x fixture\n-rw-r--r-- demo.txt') + // A two-line command, so the fixture covers the terminal card's one-row-per- + // command-line prompt (and that the card still marks the call exactly once). + toolTurn(60, 'fx-bash', '{"command":"ls -la\\necho done","cwd":"/tmp/fixture"}', 'total 2\ndrwxr-xr-x fixture\n-rw-r--r-- demo.txt') toolTurn(61, 'fx-write', '{"path":"notes/demo.txt","content":"hello fixture\\n"}', 'wrote notes/demo.txt') toolTurn(62, 'edit', '{"file_path":"notes/demo.txt","old_string":"hello","new_string":"hello fixture"}', '已编辑') toolTurn(63, 'write', '{"file_path":"notes/new-demo.txt","content":"hello fixture\\n"}', '已写入') diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index 49fcf48d4c..e6ff5e7eed 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -137,6 +137,17 @@ describe('chat row terminal body', () => { expect(view.getByText('line-5')).toBeTruthy() }) + it('renders a multi-line command as one prompt row per line', () => { + const view = render() + fireEvent.click(view.container.querySelector('button')!) + const rows = view.container.querySelectorAll('[class^="_promptLine_"]') + expect([...rows].map(row => row.textContent)).toEqual(['$ls -la', '$echo done']) + // Still one dot for the call, on the first row. + expect(view.container.querySelectorAll('[data-terminal] [data-state]')).toHaveLength(1) + }) + it('a running terminal call expands to the prompt line with no output yet', () => { const view = render() fireEvent.click(view.container.querySelector('button')!) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 495831a377..753c33fdea 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: bc880333157f5cb790cbaf854b01aaf8ea6c1cc9 -README.zh.md: 6593e4518d09eaccee7e55874b1162943c5eb3bd +README.md: 9e5384f84c3714d327b7b4ceaba8fb0a2cd67e7b +README.zh.md: 9f2a362e4a1e03bffde1d7b218bf94ed41ffd168 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index bc88033315..9e5384f84c 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: a prompt line (a run-state `StateDot` ahead of the shortened `cwd` label, then the command), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. The dot reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries a visually hidden text label because `StateDot` is `aria-hidden`. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience @@ -25,4 +25,5 @@ None; this package neither assembles nor sends a provider request. - **Glyph-level icons are redrawn approximations** — the fish logo (and the sparkle held by ui-conversation) come from font glyphs whose vector geometry is not exportable from the local design data; hand-authored recreations stand in until an exact export path exists. - **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms. - **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface. +- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, and `CodeBlock`'s copy control are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. - **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, while cursor movement, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 6593e4518d..9f2a362e4a 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:提示行(缩短后的 `cwd` 标签之前是一枚运行状态 `StateDot`,其后是命令)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。该状态点用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它同时携带一处视觉隐藏的文本标签。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签,其后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 @@ -25,4 +25,5 @@ - **字形级图标是重新绘制的近似版本**:鱼形标志(以及 ui-conversation 持有的闪光图标)来自字体字形,而本地设计数据无法导出其矢量几何;在获得精确导出路径前,使用手工重建版本代替。 - **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。 - **StateDot 的 `Active` 变体是设计中的隐藏占位符**:尚未实现;已交付的四种状态(done/warning/ongoing/error)构成完整的 P-I 表层。 +- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件,以及 `CodeBlock` 的复制控件全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 - **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,而光标移动、清屏和备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。 diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index 6d470ec634..aec2971921 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -7,17 +7,23 @@ .block { --dsl-terminal-radius: 12px; --dsl-terminal-line-height: 22px; + /* Reserved strip to the left of the card for the per-line run-state dots. + The dots sit outside the card surface, so a reader scans command state + down one column without the dots competing with the commands themselves. */ + --dsl-terminal-gutter: 30px; position: relative; - margin: 16px 0; + margin: 16px 0 16px var(--dsl-terminal-gutter); color: var(--dsw-alias-label-primary); background: var(--dsw-alias-markdown-code-block); border-radius: var(--dsl-terminal-radius); } +/* Top-aligned: the status pill and copy control stay on the first prompt row + however many command lines the card carries. */ .header { display: flex; - align-items: center; + align-items: flex-start; gap: 12px; padding: 9px 14px; background: var(--dsw-alias-markdown-code-block-banner); @@ -25,22 +31,33 @@ border-top-right-radius: var(--dsl-terminal-radius); } -/* The prompt row is the only element allowed to shrink; the status pill and - the copy control keep their intrinsic width. */ +/* One row per command line. The prompt column is the only element allowed to + shrink; the status pill and the copy control keep their intrinsic width. */ .prompt { display: flex; - align-items: baseline; - gap: 8px; + flex-direction: column; min-width: 0; flex: 1; font: var(--dsw-font-markdown-code-block); } -/* The dot sits on the prompt row's baseline box, which is a code-font line, so - it is centered against that line's box rather than sitting on the baseline. */ +.promptLine { + position: relative; + display: flex; + align-items: baseline; + gap: 8px; + min-width: 0; + line-height: var(--dsl-terminal-line-height); +} + +/* Out of flow in the gutter, so a dot neither indents its command nor depends + on the command's own text metrics to line up with it. Centered against the + row's line box rather than sitting on the code font's baseline. */ .runState { - flex: none; - align-self: center; + position: absolute; + left: calc(-1 * var(--dsl-terminal-gutter)); + top: 50%; + transform: translateY(-50%); } /* The dot is aria-hidden; this is its text label for assistive technology. */ diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index c5278dd7df..3ae7ca7113 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -147,6 +147,13 @@ export function TerminalBlock({ const status = statusText(exitCode, signal) const state = runState(running, exitCode, signal) + // A multi-line command gets one prompt row per line, so a two-command shell + // snippet reads as the two commands it is instead of collapsing into one + // ellipsized row. A trailing newline is a terminator, not an empty command. + const commandLines = useMemo(() => { + const body = command.endsWith('\n') ? command.slice(0, -1) : command + return body.split('\n') + }, [command]) const empty = text.trim() === '' const hidden = lines.length - maxLines const capped = hidden > 0 && !expanded @@ -159,10 +166,18 @@ export function TerminalBlock({
- {state.label} - {cwd === undefined ? '$' : promptLabel(cwd, home)} - {command} + {commandLines.map((line, index) => ( +
+ {/* One dot for the card, on the first row: the exit status the + view carries is the whole call's, and bash reports no + per-command status, so a dot per row would assert a + per-line outcome nothing here knows. */} + {index === 0 && } + {cwd === undefined ? '$' : promptLabel(cwd, home)} + {line} +
+ ))}
{status !== undefined && {status}} {!running && !empty && ( diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index 486aac1197..dd9af07b8e 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -34,6 +34,11 @@ function runStateOf(container: HTMLElement): { state: string | null; label: stri } } +/** The prompt rows as `
{open && (terminalBody !== null - ? + ? : variant === 'code' ? :
{text}
)} diff --git a/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts index bf832e2961..a1439c6bc1 100644 --- a/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts +++ b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts @@ -28,10 +28,21 @@ export const CHAT_TERMINAL_MAX_LINES = 8 * client has no home path for the session host (a cwd renders as its last * path segment), and `maxLines`/`className` belong to each render site. */ -export type TerminalCardModel = Pick< - TerminalBlockProps, - 'command' | 'cwd' | 'output' | 'exitCode' | 'signal' | 'running' -> +export interface TerminalCardModel { + /** + * The props {@link TerminalBlock} draws. Held as a nested object so a render + * site spreads exactly the primitive's own surface and can never leak a + * neighbouring field into it. + */ + card: Pick + /** + * The call view's model-authored description, which the contract defines as + * rendering ABOVE the card (the card itself has no description slot). Absent + * when the presenter supplied none, or when the window dropped the call side; + * a row then keeps its args-derived summary. + */ + description: string | undefined +} /** * Resolve a terminal view's working directory the way the render-intent @@ -47,8 +58,41 @@ export type TerminalCardModel = Pick< */ function resolveTerminalCwd(viewCwd: string | undefined, sessionCwd: string | undefined): string | undefined { if (viewCwd === undefined || viewCwd === '') return sessionCwd - if (sessionCwd === undefined || sessionCwd === '') return viewCwd - return resolveToolPath(sessionCwd, viewCwd) + if (sessionCwd === undefined || sessionCwd === '') return normalizeSegments(viewCwd) + return normalizeSegments(resolveToolPath(sessionCwd, viewCwd)) +} + +/** + * Collapse `.` and `..` segments so the prompt label names the directory the + * command actually ran in. The bash executor resolves the workdir before + * running, so a joined `/w/app/..` must display as `w`, not as `..`. Separators + * are preserved as authored (a Windows path keeps its backslashes) because this + * value is only ever displayed; a `..` that would climb past the root is + * dropped, which is what a filesystem does with it. + * @param path - a joined or absolute path, possibly carrying `.`/`..` segments. + * @returns the same path with those segments resolved. + */ +function normalizeSegments(path: string): string { + if (!/(?:^|[/\\])\.\.?(?:[/\\]|$)/.test(path)) return path + const backslashed = path.includes('\\') && !path.includes('/') + const separator = backslashed ? '\\' : '/' + const leading = /^[/\\]/.test(path) ? separator : '' + const drive = /^[A-Za-z]:/.exec(path)?.[0] ?? '' + const kept: string[] = [] + for (const segment of path.slice(drive.length).split(/[/\\]/)) { + if (segment === '' || segment === '.') continue + if (segment === '..') { + // Nothing to climb from: at a root the segment is dropped, matching the + // filesystem; on a relative path the `..` has to stay, since it is still + // meaningful against a cwd this function cannot see. + if (kept.length > 0 && kept[kept.length - 1] !== '..') kept.pop() + else if (leading === '' && drive === '') kept.push(segment) + continue + } + kept.push(segment) + } + const body = kept.join(separator) + return drive === '' ? `${leading}${body}` : `${drive}${leading === '' ? separator : leading}${body}` } /** @@ -82,25 +126,31 @@ export function terminalCardModel(block: ToolCallBlock, sessionCwd?: string): Te if (!('kind' in block)) { // Running: the call view exists, the result view does not yet. return call === null ? null : { - command: call.title, - cwd: resolveTerminalCwd(call.cwd, sessionCwd), - output: undefined, - exitCode: undefined, - signal: undefined, - running: true, + description: call.description, + card: { + command: call.title, + cwd: resolveTerminalCwd(call.cwd, sessionCwd), + output: undefined, + exitCode: undefined, + signal: undefined, + running: true, + }, } } const result = block.resultView?.card === 'terminal' ? block.resultView : null if (result === null) return null return { - // The result's title REPLACES the pending one when the tool supplies it - // (the presentation contract's replacement-title rule); the call title is - // what a result without one keeps. - command: result.title ?? call?.title ?? '', - cwd: resolveTerminalCwd(call?.cwd, sessionCwd), - output: result.output, - exitCode: result.exitCode, - signal: result.signal, - running: false, + description: call?.description, + card: { + // The result's title REPLACES the pending one when the tool supplies it + // (the presentation contract's replacement-title rule); the call title is + // what a result without one keeps. + command: result.title ?? call?.title ?? '', + cwd: resolveTerminalCwd(call?.cwd, sessionCwd), + output: result.output, + exitCode: result.exitCode, + signal: result.signal, + running: false, + }, } } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index a7add10328..630334eae7 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -135,7 +135,7 @@ export function DetailsPanel({ useSession, useSessions, sessionId, useStore, clo */ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | undefined }) { const terminal = terminalCardModel(material.block, cwd) - if (terminal !== null) return + if (terminal !== null) return // A settled call always carries the result node the flattened form needs; // the running shape has no result to flatten. if (!('kind' in material.block)) return
运行中…
diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx index 6800e79180..1e6e9183fc 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx @@ -64,10 +64,12 @@ export function BashRow({ toolName, block, sessionId, useSessions }: ToolRowProp {isChild && scoped} {model.title} - {model.summary} + {/* The terminal presenter's description is the contractual + above-card summary; it outranks the args-derived one. */} + {terminal?.description ?? model.summary}
{terminal !== null && ( - + )}
) diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index 0b3ba5e849..7df9de7f36 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -63,8 +63,11 @@ const settled = (over?: Partial): ToolResultNode => ({ describe('terminalCardModel', () => { it('derives a running card from the call view alone', () => { expect(terminalCardModel(running({ callView: callTerminal({ cwd: '/projects/app' }) }))).toEqual({ - command: 'ls -la', cwd: '/projects/app', output: undefined, - exitCode: undefined, signal: undefined, running: true, + description: 'List files', + card: { + command: 'ls -la', cwd: '/projects/app', output: undefined, + exitCode: undefined, signal: undefined, running: true, + }, }) }) @@ -73,12 +76,15 @@ describe('terminalCardModel', () => { callView: callTerminal({ cwd: '/projects/app' }), resultView: resultTerminal({ output: 'boom\n', exitCode: 2 }), }))).toEqual({ - command: 'ls -la', cwd: '/projects/app', output: 'boom\n', - exitCode: 2, signal: undefined, running: false, + description: 'List files', + card: { + command: 'ls -la', cwd: '/projects/app', output: 'boom\n', + exitCode: 2, signal: undefined, running: false, + }, }) expect(terminalCardModel(settled({ resultView: { card: 'terminal', output: '', signal: 'SIGTERM' }, - }))?.signal).toBe('SIGTERM') + }))?.card.signal).toBe('SIGTERM') }) it('takes the result view\'s replacement title over the pending one', () => { @@ -87,30 +93,75 @@ describe('terminalCardModel', () => { expect(terminalCardModel(settled({ callView: callTerminal({ title: 'pnpm run check' }), resultView: resultTerminal({ title: 'pnpm run check --filter web' }), - }))?.command).toBe('pnpm run check --filter web') + }))?.card.command).toBe('pnpm run check --filter web') // Without one, the call's title is what the card keeps. - expect(terminalCardModel(settled())?.command).toBe('ls -la') + expect(terminalCardModel(settled())?.card.command).toBe('ls -la') }) it('resolves the cwd against the session workspace the way the bridge must', () => { // Omitted workdir — the common bash call — IS the session workspace. - expect(terminalCardModel(settled(), '/w/app')?.cwd).toBe('/w/app') + expect(terminalCardModel(settled(), '/w/app')?.card.cwd).toBe('/w/app') // A relative workdir joins under it. expect(terminalCardModel(settled({ callView: callTerminal({ cwd: 'packages/ui' }), - }), '/w/app')?.cwd).toBe('/w/app/packages/ui') + }), '/w/app')?.card.cwd).toBe('/w/app/packages/ui') // An absolute one is used as-is. expect(terminalCardModel(settled({ callView: callTerminal({ cwd: '/srv/other' }), - }), '/w/app')?.cwd).toBe('/srv/other') + }), '/w/app')?.card.cwd).toBe('/srv/other') // With no session cwd there is nothing to resolve against: a relative path // stays as authored and an omitted one stays absent (a bare `$` prompt). expect(terminalCardModel(settled({ callView: callTerminal({ cwd: 'packages/ui' }), - }))?.cwd).toBe('packages/ui') - expect(terminalCardModel(settled())?.cwd).toBeUndefined() + }))?.card.cwd).toBe('packages/ui') + expect(terminalCardModel(settled())?.card.cwd).toBeUndefined() // The running arm resolves identically. - expect(terminalCardModel(running(), '/w/app')?.cwd).toBe('/w/app') + expect(terminalCardModel(running(), '/w/app')?.card.cwd).toBe('/w/app') + }) + + it('normalizes a relative workdir so the label names the directory actually used', () => { + // The bash executor resolves the workdir before running, so `..` against + // /w/app runs in /w — the card must say `w`, not `..`. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '..' }), + }), '/w/app')?.card.cwd).toBe('/w') + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '.' }), + }), '/w/app')?.card.cwd).toBe('/w/app') + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '../sibling' }), + }), '/w/app')?.card.cwd).toBe('/w/sibling') + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: './nested/../other' }), + }), '/w/app')?.card.cwd).toBe('/w/app/other') + // A `..` that would climb past the root is dropped, as a filesystem does. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '../../..' }), + }), '/w')?.card.cwd).toBe('/') + // An absolute path carrying segments normalizes too. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '/srv/./app/../other' }), + }), '/w/app')?.card.cwd).toBe('/srv/other') + // A Windows path keeps its separators. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: 'C:\\ws\\app\\..' }), + }), '/w')?.card.cwd).toBe('C:\\ws') + // Without a session cwd a relative `..` has nothing to resolve against, so + // it survives as authored rather than being silently dropped. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '../elsewhere' }), + }))?.card.cwd).toBe('../elsewhere') + }) + + it('carries the call view\'s description, which the contract renders above the card', () => { + expect(terminalCardModel(settled())?.description).toBe('List files') + expect(terminalCardModel(running())?.description).toBe('List files') + // A presenter that supplies none, and a window-truncated call side, both + // leave it absent so the row keeps its args-derived summary. + expect(terminalCardModel(settled({ + callView: { card: 'terminal', title: 'ls' }, + }))?.description).toBeUndefined() + expect(terminalCardModel(settled({ call: null, callView: null }))?.description).toBeUndefined() }) it('a window-truncated call side falls back to the result title, then to an empty command', () => { @@ -118,8 +169,8 @@ describe('terminalCardModel', () => { const truncated = { call: null, callView: null } expect(terminalCardModel(settled({ ...truncated, resultView: resultTerminal({ title: 'ls -la' }), - }))).toMatchObject({ command: 'ls -la', cwd: undefined, running: false }) - expect(terminalCardModel(settled(truncated))).toMatchObject({ command: '', cwd: undefined }) + }))?.card).toMatchObject({ command: 'ls -la', cwd: undefined, running: false }) + expect(terminalCardModel(settled(truncated))?.card).toMatchObject({ command: '', cwd: undefined }) }) it('returns null for every non-terminal call: no views, generic views, unknown cards', () => { @@ -244,6 +295,23 @@ describe('BashRow terminal card', () => { expect(runStateOf(settledView.container)).toBe('done') }) + it('shows the terminal presenter\'s description instead of the args summary', () => { + // `terminal_send`-style presenters author a description the args do not + // repeat; the contract puts it above the card, which is this row's summary. + const view = render() + expect(view.getByText('Terminal 3')).toBeTruthy() + expect(view.queryByText('List files')).toBeNull() + }) + + it('keeps the args-derived summary when the presenter authored no description', () => { + const view = render() + expect(view.getByText('List files')).toBeTruthy() + }) + it('a non-terminal bash call (background start) renders the summary row alone', () => { const view = render( { expect(pre?.textContent).toBe('permission denied') }) - it('a run_code sub-dispatch resolves to its own terminal card', () => { + // The panel resolves a sub-dispatch through the same material as a native + // call, so a sub-call that DID carry terminal views would render the card. + // The shipped wire cannot produce that yet: `session.ts` folds + // `tool/code-dispatch(-start)` with `callView: null`/`resultView: null`, and + // the host's `viewFor` only presents top-level `tool/call`/`tool/result`. This + // pins the resolution path with views injected directly, and the arm below + // pins what the shipped path actually shows today. + it('a run_code sub-dispatch resolves to its own terminal card once views reach it', () => { const view = mount(snapshot({ codeDispatches: new Map([['p1', [settled({ callId: 'c1' })]]]), }), target) expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() }) + it('a sub-dispatch as the wire actually delivers it (no views) keeps the flattened form', () => { + const view = mount(snapshot({ + codeDispatches: new Map([['p1', [settled({ callId: 'c1', callView: null, resultView: null })]]]), + }), target) + // No terminal card: the generic path renders the result text in the Output + // section's
 (the Input section has its own, hence the scoping).
+    expect(view.container.querySelector('[data-terminal]')).toBeNull()
+    const output = view.getByText('Output').closest('section')
+    expect(output?.querySelector('pre')?.textContent).toContain('a.ts  b.ts')
+  })
+
   it('a running run_code sub-dispatch resolves through the running material', () => {
     const view = mount(snapshot({
       // The leading non-matching sub-call exercises the scan's skip.

From 0f70886e0c3dfc4afe0f1d3f18e0a6cc892e2b60 Mon Sep 17 00:00:00 2001
From: Chinesezjc 
Date: Wed, 29 Jul 2026 12:10:34 +0800
Subject: [PATCH 06/14] fix(web): label only the first prompt row with the
 working directory
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

A multi-line command repeated the cwd label on every prompt row, which
states something the view does not know: it carries ONE working directory —
where the call started — and a `cd` in the command moves later lines
elsewhere. `cd ~` then `ls` rendered both rows labelled with the session
workspace while `ls` actually listed the home directory.

The label now appears on the first row only, and later rows keep a bare `$`
so they still read as prompts. Same reasoning as the run-state dot: neither
a per-line directory nor a per-line exit status exists to report.

The built-bundle snapshot records the effect on fixture turn 60's two-line
command (`fixture echo done` becomes `$ echo done`).
---
 .../feature/2026-07-28-web-terminal-card.i18n.yaml     |  4 ++--
 .../feature/2026-07-28-web-terminal-card.md            |  2 +-
 .../feature/2026-07-28-web-terminal-card.zh.md         |  2 +-
 apps/web/tests/terminal-card.snapshot.ts               |  2 +-
 packages/client/ui-primitives/README.i18n.yaml         |  4 ++--
 packages/client/ui-primitives/README.md                |  2 +-
 packages/client/ui-primitives/README.zh.md             |  2 +-
 packages/client/ui-primitives/src/TerminalBlock.tsx    | 10 +++++++++-
 .../client/ui-primitives/tests/terminal-block.spec.tsx |  8 ++++++++
 9 files changed, 26 insertions(+), 10 deletions(-)

diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
index 022c4f84ed..0f5c43ff36 100644
--- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
-2026-07-28-web-terminal-card.md: 8e4701b49373af3495c6f424c4ae2777f5bfcb75
-2026-07-28-web-terminal-card.zh.md: 07341ca942864281390f3820db88388fd61cef0e
+2026-07-28-web-terminal-card.md: 4bf5ee4e7899dceacbc56aced3289647ee42cd82
+2026-07-28-web-terminal-card.zh.md: a7baf5a84364994e938f7c12c368c8202832544a
diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
index 8e4701b493..4bf5ee4e78 100644
--- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md
@@ -16,7 +16,7 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/
 
 The component's contract:
 
-- **Prompt lines, one per command line.** Each line of the command gets its own row: label, then that line verbatim. A `command` carrying two shell commands on two lines therefore reads as the two commands it is, instead of collapsing into one ellipsized row. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. A trailing newline is a terminator, not an empty final command.
+- **Prompt lines, one per command line.** Each line of the command gets its own row: label, then that line verbatim. A `command` carrying two shell commands on two lines therefore reads as the two commands it is, instead of collapsing into one ellipsized row. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. A trailing newline is a terminator, not an empty final command. Only the FIRST row carries the label: the view knows one working directory — where the call started — and a later line may run somewhere else entirely, since a `cd` in the command is enough to move it. Repeating the label down the rows would state a directory per line that nothing here knows, which is the same reason the run-state dot appears once. Later rows keep a bare `$` so they still read as prompts.
 - **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's own text metrics to line up with it. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes.
 - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding.
 - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends.
diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
index 07341ca942..a7baf5a843 100644
--- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
+++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md
@@ -16,7 +16,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c
 
 该组件的契约:
 
-- **提示符行,每条命令行一行。** 命令的每一行各占一行:标签,其后原样跟随该行。因此一个在两行上承载两条 shell 命令的 `command` 就读作它本身的两条命令,而不是被压成一行并省略号截断。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。末尾换行是终止符,不是一条空的末命令。
+- **提示符行,每条命令行一行。** 命令的每一行各占一行:标签,其后原样跟随该行。因此一个在两行上承载两条 shell 命令的 `command` 就读作它本身的两条命令,而不是被压成一行并省略号截断。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。末尾换行是终止符,不是一条空的末命令。只有**第一行**携带该标签:视图只知道一个工作目录——调用开始处的那个——而后面的行完全可能在别处运行,命令里一个 `cd` 就足以改变它。把标签在各行重复,等于陈述一个此处无人知晓的逐行目录,这与运行状态点只出现一次是同一个理由。其余行保留一个裸 `$`,因此它们仍读作提示符。
 - **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片表面左侧预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。
 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。
 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。
diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts
index 0154a3d7fd..82d94b251d 100644
--- a/apps/web/tests/terminal-card.snapshot.ts
+++ b/apps/web/tests/terminal-card.snapshot.ts
@@ -264,7 +264,7 @@ it('the fallback row reaches the same card through its expand control', async ()
       ],
       "prompt": [
         "fixture ls -la",
-        "fixture echo done",
+        "$ echo done",
       ],
       "runState": "done",
       "runStateLabel": "已完成",
diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml
index 772851ea82..ad22a9f734 100644
--- a/packages/client/ui-primitives/README.i18n.yaml
+++ b/packages/client/ui-primitives/README.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
-README.md: 5d71aa920707462f953ed4eb5572b0530b8d0ed2
-README.zh.md: 7c59ed3d3bacbac06a0123e6ff93023a1bcbd028
+README.md: 4222aac4fa1d9c89a3d3c702ee8391fba1eef178
+README.zh.md: e7a5b5ad57048bc59872963b0068c6f88fc772f8
diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md
index 5d71aa9207..4222aac4fa 100644
--- a/packages/client/ui-primitives/README.md
+++ b/packages/client/ui-primitives/README.md
@@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/
 
 ## Terminal output
 
-`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage-return redraws and backspace overwrites resolve as a terminal performs them before inert controls are stripped; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md).
+`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage-return redraws and backspace overwrites resolve as a terminal performs them before inert controls are stripped; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md).
 
 ## Model Experience
 
diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md
index 7c59ed3d3b..e7a5b5ad57 100644
--- a/packages/client/ui-primitives/README.zh.md
+++ b/packages/client/ui-primitives/README.zh.md
@@ -10,7 +10,7 @@
 
 ## 终端输出
 
-`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签,其后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车重绘与退格覆盖会按终端的行为先行结算,之后才剥除无显示意义的控制符;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。
+`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车重绘与退格覆盖会按终端的行为先行结算,之后才剥除无显示意义的控制符;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。
 
 ## 模型体验
 
diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx
index 3ae7ca7113..0932f4a7f0 100644
--- a/packages/client/ui-primitives/src/TerminalBlock.tsx
+++ b/packages/client/ui-primitives/src/TerminalBlock.tsx
@@ -174,7 +174,15 @@ export function TerminalBlock({
                   per-command status, so a dot per row would assert a
                   per-line outcome nothing here knows. */}
               {index === 0 && }
-              {cwd === undefined ? '$' : promptLabel(cwd, home)}
+              {/* The cwd labels the CALL, so only its first row carries it. The
+                  view knows one working directory — where the call started —
+                  and a later line may well run somewhere else (a `cd` in the
+                  command is enough), so repeating the label down the rows would
+                  assert a directory per line that nothing here knows. Later
+                  rows keep a bare `$` to stay aligned as prompts. */}
+              
+                {index > 0 || cwd === undefined ? '$' : promptLabel(cwd, home)}
+              
               {line}
             
))} diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index 74352f6fba..d1162fcb7f 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -212,6 +212,14 @@ describe('TerminalBlock run-state dot', () => { expect([...row!.children].map(node => node.textContent)).toEqual(['', 'app', 'ls']) }) + // The cwd labels the call, not each line: a `cd` in the command moves later + // lines elsewhere, so repeating the label would state a directory per line + // that the view does not know. + it('labels only the first row with the cwd, leaving later rows a bare $', () => { + const view = render() + expect(promptRows(view.container)).toEqual(['appcd ~', '$ls']) + }) + it('gives a multi-line command one row per line', () => { const view = render() expect(promptRows(view.container)).toEqual(['$echo one', '$echo two']) From bbe1481a9ecd4b4d85dc4954b343696b534c4d49 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 13:10:44 +0800 Subject: [PATCH 07/14] fix(web): keep escapes, UNC roots, and truncated cwd honest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four review findings. Two are defects the previous two rounds introduced, which the existing tests did not catch: A backspace erased raw bytes, so one landing after an SGR reset ate part of the escape: `\x1b[31mabc\x1b[0m\b\bXY` left `\x1b[` and repainted the rest of the line with whatever the remainder parsed as. Backspaces now resolve over VISIBLE characters — a CSI sequence is one indivisible unit a backspace steps over on its way to the last printed character, so the surviving text keeps the color its run authored. The cwd normalizer popped a UNC share root: `\\server\share` with a `..` became `/server`, losing the separators too. A UNC path's server and share are its root, and Windows cannot climb above a share, so they are split off and the remainder collapses against that root. The other two are gaps the earlier fixes left: The render-site fallback row still passed the args-derived summary, so any terminal-declaring tool without its own keyed row (`terminal_send`) lost the contract's above-card description. It now prefers the description exactly as BashRow does. A settled call read `call?.cwd`, which cannot tell "the call omitted a cwd" from "the paging window dropped the call head". The second case has no cwd anywhere and the original call may have used an explicit workdir, so it now draws a bare `$` instead of naming the session workspace. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 4 +- .../2026-07-28-web-terminal-card.zh.md | 4 +- .../src/client/chat/GenericToolCard.tsx | 7 ++- .../client/contract/terminal-card-model.ts | 53 +++++++++++++++---- .../tests/terminal-card.spec.tsx | 36 +++++++++++++ packages/client/ui-primitives/src/ansi.ts | 49 ++++++++++++++--- .../client/ui-primitives/tests/ansi.spec.ts | 18 +++++++ 8 files changed, 150 insertions(+), 25 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 0f5c43ff36..0d805c8de0 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 4bf5ee4e7899dceacbc56aced3289647ee42cd82 -2026-07-28-web-terminal-card.zh.md: a7baf5a84364994e938f7c12c368c8202832544a +2026-07-28-web-terminal-card.md: 87cb40331bca6a1bfcdd4e8ecd9bbe69c6572be0 +2026-07-28-web-terminal-card.zh.md: ab5a35d6f76427cf1e0338d8491bd3485cb41302 diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 4bf5ee4e78..87cb40331b 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -12,7 +12,7 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ ## Decision -`TerminalBlock` is a `ui-primitives` component that renders a shell command as a terminal surface, and both Web render sites for a bash call consume the terminal render intent through it: the chat tool row's expanded body and the details panel's Output section. `ui-conversation/src/client/contract/terminal-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a command, its cwd, or its exit status. It returns null — the generic path — whenever neither side declares `card: 'terminal'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how the bash tool's execution errors and background starts keep their existing rendering. Two duties the render-intent contract assigns to the UI bridge land here rather than in the tool: a settled result's `title` REPLACES the pending one, and the working directory resolves against the session workspace — an absolute view cwd is used as-is, a relative one joins under the workspace, and an omitted one IS the workspace, which is the common case for a bash call with no `workdir`. A pure presenter cannot see the session cwd, which is why the resolution belongs at this seam; each render site supplies the cwd off the session list row. The resolved path also normalizes its `.`/`..` segments, because the bash executor resolves the workdir before running: a `..` against `/w/app` runs in `/w`, so the prompt label has to read `w` rather than `..`. The call view's `description` rides the same derivation, since the contract renders it above the card and it must outrank the row's args-derived summary. +`TerminalBlock` is a `ui-primitives` component that renders a shell command as a terminal surface, and both Web render sites for a bash call consume the terminal render intent through it: the chat tool row's expanded body and the details panel's Output section. `ui-conversation/src/client/contract/terminal-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a command, its cwd, or its exit status. It returns null — the generic path — whenever neither side declares `card: 'terminal'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how the bash tool's execution errors and background starts keep their existing rendering. Two duties the render-intent contract assigns to the UI bridge land here rather than in the tool: a settled result's `title` REPLACES the pending one, and the working directory resolves against the session workspace — an absolute view cwd is used as-is, a relative one joins under the workspace, and an omitted one IS the workspace, which is the common case for a bash call with no `workdir`. A pure presenter cannot see the session cwd, which is why the resolution belongs at this seam; each render site supplies the cwd off the session list row. Only a PRESENT call view can mean "omitted, so use the workspace": when the paging window drops the call head there is no cwd anywhere — the result view carries none — and the original call may have used an explicit workdir, so the prompt draws a bare `$` rather than naming a directory it cannot know. The resolved path also normalizes its `.`/`..` segments, because the bash executor resolves the workdir before running: a `..` against `/w/app` runs in `/w`, so the prompt label has to read `w` rather than `..`. A UNC path's `server` and `share` are part of its root rather than poppable segments, since Windows cannot climb above a share. The call view's `description` rides the same derivation, since the contract renders it above the card and it must outrank the row's args-derived summary. The component's contract: @@ -20,7 +20,7 @@ The component's contract: - **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's own text metrics to line up with it. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. -- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Two cursor movements resolve before that strip, because their effect on the visible text has to land before the characters expressing them are dropped: a carriage return reduces its line to the final redraw, and a backspace overwrites the character before it, so `abc` followed by two backspaces and `XY` reads `aXY` as a terminal draws it. Both are per-line, so neither reaches across a newline. +- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Two cursor movements resolve before that strip, because their effect on the visible text has to land before the characters expressing them are dropped: a carriage return reduces its line to the final redraw, and a backspace overwrites the character before it, so `abc` followed by two backspaces and `XY` reads `aXY` as a terminal draws it. Both are per-line, so neither reaches across a newline. A backspace steps over CSI sequences rather than erasing their bytes: a sequence moves no cursor, and eating part of one would corrupt it and repaint everything after with whatever the mangled remainder parses as, so it walks back to the last PRINTED character and drops that instead — the surviving text keeps the color its run authored. - **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks. diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index a7baf5a843..ab5a35d6f7 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -12,7 +12,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c ## Decision -`TerminalBlock` 是 `ui-primitives` 中把 shell 命令渲染为终端表面的组件,bash 调用在 Web 侧的两个渲染点都经由它消费 terminal 渲染意图:聊天工具行展开后的正文,以及详情面板的 Output 区。`ui-conversation/src/client/contract/terminal-card-model.ts` 是把快照上的 `callView`/`resultView` 这一对转换为该组件 props 的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧。当两侧都不声明 `card: 'terminal'` 时它返回 null,即走 generic 路径——包括本 client 版本不认识的 `card` 取值;当一个已落定调用的结果视图是 generic 时同样返回 null,这正是 bash 工具的执行错误与后台启动得以保持既有渲染的方式。渲染意图契约交给 UI 桥接层的两项职责也落在这里,而不在工具侧:已落定结果的 `title` **替换**待定标题;工作目录针对会话 workspace 解析——视图给出的绝对路径原样使用,相对路径在 workspace 之下拼接,省略则**就是** workspace,而这正是不带 `workdir` 的 bash 调用的常见情形。纯 presenter 看不到会话 cwd,因此该解析属于这道接缝;两个渲染点各自从会话列表行取出 cwd 传入。解析后的路径还会归一化其 `.`/`..` 段,因为 bash 执行器在运行前就已解析 workdir:相对 `/w/app` 的 `..` 实际运行在 `/w`,因此提示标签必须读作 `w` 而不是 `..`。调用视图的 `description` 走同一处推导,因为契约把它渲染在卡片上方,且它必须优先于该行由参数推导出的摘要。 +`TerminalBlock` 是 `ui-primitives` 中把 shell 命令渲染为终端表面的组件,bash 调用在 Web 侧的两个渲染点都经由它消费 terminal 渲染意图:聊天工具行展开后的正文,以及详情面板的 Output 区。`ui-conversation/src/client/contract/terminal-card-model.ts` 是把快照上的 `callView`/`resultView` 这一对转换为该组件 props 的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧。当两侧都不声明 `card: 'terminal'` 时它返回 null,即走 generic 路径——包括本 client 版本不认识的 `card` 取值;当一个已落定调用的结果视图是 generic 时同样返回 null,这正是 bash 工具的执行错误与后台启动得以保持既有渲染的方式。渲染意图契约交给 UI 桥接层的两项职责也落在这里,而不在工具侧:已落定结果的 `title` **替换**待定标题;工作目录针对会话 workspace 解析——视图给出的绝对路径原样使用,相对路径在 workspace 之下拼接,省略则**就是** workspace,而这正是不带 `workdir` 的 bash 调用的常见情形。纯 presenter 看不到会话 cwd,因此该解析属于这道接缝;两个渲染点各自从会话列表行取出 cwd 传入。只有**存在**的调用视图才能表示「省略了 cwd,因此取 workspace」:当分页窗口丢掉调用头时,任何地方都不再有 cwd——结果视图并不携带它——而原调用完全可能使用过一个显式 workdir,因此提示行绘制一个裸 `$`,而不是命名一个它无法知晓的目录。解析后的路径还会归一化其 `.`/`..` 段,因为 bash 执行器在运行前就已解析 workdir:相对 `/w/app` 的 `..` 实际运行在 `/w`,因此提示标签必须读作 `w` 而不是 `..`。UNC 路径的 `server` 与 `share` 属于其根,而非可弹出的路径段,因为 Windows 无法越过一个共享向上。调用视图的 `description` 走同一处推导,因为契约把它渲染在卡片上方,且它必须优先于该行由参数推导出的摘要。 该组件的契约: @@ -20,7 +20,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c - **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片表面左侧预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 -- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。两种光标移动在该剥除之前先行结算,因为它们对可见文本的作用必须先落地,之后才能丢弃表达它们的那些字符:回车把所在行归约为最后一次重绘,退格覆盖它前面的字符——于是 `abc` 后接两个退格再接 `XY` 读作 `aXY`,与终端的绘制一致。两者都按行结算,因此都不会跨越换行。 +- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。两种光标移动在该剥除之前先行结算,因为它们对可见文本的作用必须先落地,之后才能丢弃表达它们的那些字符:回车把所在行归约为最后一次重绘,退格覆盖它前面的字符——于是 `abc` 后接两个退格再接 `XY` 读作 `aXY`,与终端的绘制一致。两者都按行结算,因此都不会跨越换行。退格会跨过 CSI 序列,而不是擦掉它的字节:序列本身不移动光标,吃掉它的一部分会破坏该序列,并让其后的一切按被损坏的残余重新着色,因此退格回退到最后一个**已打印**字符并删除它——存活下来的文本保留其所在分段所声明的颜色。 - **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。 diff --git a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx index 5b93d66e32..ce55d84f57 100644 --- a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx +++ b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx @@ -28,6 +28,7 @@ const VARIANT_ICONS: Record = { export function GenericToolCard({ toolName, block, cwd, openFile }: ToolRowOwnerProps) { const model = toolRowModel(toolName, block, cwd) + const terminal = terminalCardModel(block, cwd) const singleFile = model.filePath !== undefined return ( 0 && kept[kept.length - 1] !== '..') kept.pop() - else if (leading === '' && drive === '') kept.push(segment) + else if (!rooted) kept.push(segment) continue } kept.push(segment) } - const body = kept.join(separator) - return drive === '' ? `${leading}${body}` : `${drive}${leading === '' ? separator : leading}${body}` + return kept.join(separator) } /** @@ -146,7 +174,12 @@ export function terminalCardModel(block: ToolCallBlock, sessionCwd?: string): Te // (the presentation contract's replacement-title rule); the call title is // what a result without one keeps. command: result.title ?? call?.title ?? '', - cwd: resolveTerminalCwd(call?.cwd, sessionCwd), + // Only a PRESENT call view can mean "omitted the cwd, so use the + // workspace". When the window dropped the call head there is no cwd + // anywhere — the result view carries none — and the original call may + // well have used an explicit workdir, so the prompt draws a bare `$` + // rather than naming a directory this card cannot know. + cwd: call === null ? undefined : resolveTerminalCwd(call.cwd, sessionCwd), output: result.output, exitCode: result.exitCode, signal: result.signal, diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index 7df9de7f36..dd096c6e91 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -153,6 +153,32 @@ describe('terminalCardModel', () => { }))?.card.cwd).toBe('../elsewhere') }) + it('keeps a UNC server and share as an unpoppable root', () => { + // Windows cannot climb above a share, so `..` from the share root stays put. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '..' }), + }), '\\\\server\\share')?.card.cwd).toBe('\\\\server\\share') + // Below the share it pops normally, keeping the UNC separators. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '..' }), + }), '\\\\server\\share\\app')?.card.cwd).toBe('\\\\server\\share') + // Several `..` cannot escape the root either. + expect(terminalCardModel(settled({ + callView: callTerminal({ cwd: '../../..' }), + }), '\\\\server\\share\\app')?.card.cwd).toBe('\\\\server\\share') + }) + + it('draws a bare $ when the window dropped the call head, rather than guessing', () => { + // A truncated call carries no cwd anywhere: the result view has none, and + // the original call may have used an explicit workdir. Falling back to the + // session workspace here would name a directory the card cannot know. + expect(terminalCardModel(settled({ + call: null, callView: null, resultView: resultTerminal({ title: 'ls -la' }), + }), '/w/app')?.card.cwd).toBeUndefined() + // A present call view that omits its cwd still means the workspace. + expect(terminalCardModel(settled(), '/w/app')?.card.cwd).toBe('/w/app') + }) + it('carries the call view\'s description, which the contract renders above the card', () => { expect(terminalCardModel(settled())?.description).toBe('List files') expect(terminalCardModel(running())?.description).toBe('List files') @@ -231,6 +257,16 @@ describe('chat row terminal body', () => { expect(view.container.querySelectorAll('[data-terminal] [data-state]')).toHaveLength(1) }) + it('the fallback row shows the presenter description, not the args summary', () => { + // Any terminal-declaring tool without its own keyed row lands here, so the + // contract's above-card description has to win at this render site as well. + const view = render() + expect(view.getByText('Terminal 3')).toBeTruthy() + expect(view.queryByText('List files')).toBeNull() + }) + it('a running terminal call expands to the prompt line with no output yet', () => { const view = render() fireEvent.click(view.container.querySelector('button')!) diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index bf05d0d2c8..115d3faffc 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -114,14 +114,49 @@ function applyCarriageReturns(text: string): string { */ function applyBackspaces(text: string): string { if (!text.includes('\u0008')) return text - return text.split('\n').map((line) => { - const kept: string[] = [] - for (const char of line) { - if (char === '\u0008') kept.pop() - else kept.push(char) + return text.split('\n').map(applyBackspacesToLine).join('\n') +} + +/** + * One line's backspaces, resolved over VISIBLE characters only. A CSI sequence + * moves no cursor, so it must survive intact: erasing its bytes would corrupt + * the sequence and repaint the rest of the output with whatever the mangled + * remainder parses as. The sequences are therefore held as indivisible units + * that a backspace steps over on its way to the last printed character, and a + * unit already erased stays erased so a run's own color still applies to what + * remains of it. + * @param line - one output line, still carrying its CSI sequences. + * @returns the line with each backspace applied to the character before it. + */ +function applyBackspacesToLine(line: string): string { + if (!line.includes('\u0008')) return line + const units: { text: string; visible: boolean }[] = [] + // Same shape anser splits on: CSI ... final byte. Matched here so a sequence + // is one unit rather than a run of erasable characters. + const csi = /\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*[\u0040-\u007e]/g + let at = 0 + for (const match of line.matchAll(csi)) { + for (const char of line.slice(at, match.index)) units.push({ text: char, visible: true }) + units.push({ text: match[0], visible: false }) + at = match.index + match[0].length + } + for (const char of line.slice(at)) units.push({ text: char, visible: true }) + + const kept: { text: string; visible: boolean }[] = [] + for (const unit of units) { + if (unit.visible && unit.text === '\u0008') { + // Walk back past any escapes to the last printed character and drop it, + // keeping those escapes so the surviving text stays styled as authored. + for (let index = kept.length - 1; index >= 0; index--) { + if (kept[index]?.visible !== true) continue + kept.splice(index, 1) + break + } + continue } - return kept.join('') - }).join('\n') + kept.push(unit) + } + return kept.map(unit => unit.text).join('') } /** diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index 0fd4f6391e..76af75a565 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -184,6 +184,24 @@ describe('parseAnsiLines: backspaces', () => { ]) }) + it('steps over an SGR sequence instead of erasing its bytes', () => { + // `abc` reset then two backspaces then `XY`: erasing the reset's bytes would + // corrupt it and repaint the rest of the line with whatever the remainder + // parses as. The visible result is `aXY`, still red, with the reset intact. + expect(parseAnsiLines(`${sgr('31', 'abc')}${BS}${BS}XY`)).toEqual([[ + { text: 'a', style: { color: 'var(--dsw-alias-state-error-primary)' } }, + { text: 'XY', style: undefined }, + ]]) + }) + + it('erases across a style boundary without dropping the styles between', () => { + // The backspace reaches back past the reset to the last printed character. + expect(parseAnsiLines(`${sgr('32', 'ok')}${ESC}[31m${BS}bad`)).toEqual([[ + { text: 'o', style: { color: 'var(--dsw-alias-state-success-primary)' } }, + { text: 'bad', style: { color: 'var(--dsw-alias-state-error-primary)' } }, + ]]) + }) + it('applies the overwrite after a carriage-return redraw, not before', () => { // The redraw wins first; the backspace then erases inside what survived. expect(onlySpan(`old\rnew${BS}`)).toEqual({ text: 'ne', style: undefined }) From f378873b22e8142c8625f42664f5cc3eee93cca4 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 14:39:21 +0800 Subject: [PATCH 08/14] fix(web): replay cursor movements the way a terminal paints them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Carriage return and backspace only MOVE the cursor; neither erases. Both of my earlier approximations were wrong, and I checked each case against a real terminal rather than reasoning about it: `100%\rOK` shows `OK0%`, not `OK` — the redraw is shorter than the frame beneath it, so the tail stands. `abc\b` still shows `abc`, not `ab` — a trailing backspace has nothing to overwrite. `\x1b[31mgone\rkept` paints `kept` RED, because a carriage return does not reset the graphic state, which one of my own tests had asserted the opposite of. Both now replay into a per-line column buffer with SGR state stamped per column, as a terminal stores it per cell. That gives the partial-overwrite case its real result too: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red, since `ok` reached only two of the three cells. The presenter description now also renders at every site. An expanded row draws it itself — the collapsed summary is hidden while open, so otherwise the description was visible only collapsed, the opposite of "above the card" — and the details panel draws it above the card as well. Three of my own tests encoded the wrong semantics and were corrected with their behavior, and the emit loop's gap-filling arm was removed as unreachable: `\r` and backspace only move left, so no column can be unwritten. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 4 +- .../2026-07-28-web-terminal-card.zh.md | 4 +- .../src/client/chat/ToolRow.module.css | 8 ++ .../src/client/chat/ToolRow.tsx | 6 + .../client/skeleton/DetailsPanel.module.css | 8 ++ .../src/client/skeleton/DetailsPanel.tsx | 13 +- .../tests/terminal-card.spec.tsx | 24 ++++ .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/ansi.ts | 136 +++++++++--------- .../client/ui-primitives/tests/ansi.spec.ts | 52 +++++-- 13 files changed, 182 insertions(+), 85 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 0d805c8de0..6927b58937 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 87cb40331bca6a1bfcdd4e8ecd9bbe69c6572be0 -2026-07-28-web-terminal-card.zh.md: ab5a35d6f76427cf1e0338d8491bd3485cb41302 +2026-07-28-web-terminal-card.md: 284c91cc936c1e757f20f0d0d8afbe4b4c0afc42 +2026-07-28-web-terminal-card.zh.md: 3ffcf232942eed883f44da583c68455715d347ce diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 87cb40331b..284c91cc93 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -12,7 +12,7 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ ## Decision -`TerminalBlock` is a `ui-primitives` component that renders a shell command as a terminal surface, and both Web render sites for a bash call consume the terminal render intent through it: the chat tool row's expanded body and the details panel's Output section. `ui-conversation/src/client/contract/terminal-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a command, its cwd, or its exit status. It returns null — the generic path — whenever neither side declares `card: 'terminal'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how the bash tool's execution errors and background starts keep their existing rendering. Two duties the render-intent contract assigns to the UI bridge land here rather than in the tool: a settled result's `title` REPLACES the pending one, and the working directory resolves against the session workspace — an absolute view cwd is used as-is, a relative one joins under the workspace, and an omitted one IS the workspace, which is the common case for a bash call with no `workdir`. A pure presenter cannot see the session cwd, which is why the resolution belongs at this seam; each render site supplies the cwd off the session list row. Only a PRESENT call view can mean "omitted, so use the workspace": when the paging window drops the call head there is no cwd anywhere — the result view carries none — and the original call may have used an explicit workdir, so the prompt draws a bare `$` rather than naming a directory it cannot know. The resolved path also normalizes its `.`/`..` segments, because the bash executor resolves the workdir before running: a `..` against `/w/app` runs in `/w`, so the prompt label has to read `w` rather than `..`. A UNC path's `server` and `share` are part of its root rather than poppable segments, since Windows cannot climb above a share. The call view's `description` rides the same derivation, since the contract renders it above the card and it must outrank the row's args-derived summary. +`TerminalBlock` is a `ui-primitives` component that renders a shell command as a terminal surface, and both Web render sites for a bash call consume the terminal render intent through it: the chat tool row's expanded body and the details panel's Output section. `ui-conversation/src/client/contract/terminal-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a command, its cwd, or its exit status. It returns null — the generic path — whenever neither side declares `card: 'terminal'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how the bash tool's execution errors and background starts keep their existing rendering. Two duties the render-intent contract assigns to the UI bridge land here rather than in the tool: a settled result's `title` REPLACES the pending one, and the working directory resolves against the session workspace — an absolute view cwd is used as-is, a relative one joins under the workspace, and an omitted one IS the workspace, which is the common case for a bash call with no `workdir`. A pure presenter cannot see the session cwd, which is why the resolution belongs at this seam; each render site supplies the cwd off the session list row. Only a PRESENT call view can mean "omitted, so use the workspace": when the paging window drops the call head there is no cwd anywhere — the result view carries none — and the original call may have used an explicit workdir, so the prompt draws a bare `$` rather than naming a directory it cannot know. The resolved path also normalizes its `.`/`..` segments, because the bash executor resolves the workdir before running: a `..` against `/w/app` runs in `/w`, so the prompt label has to read `w` rather than `..`. A UNC path's `server` and `share` are part of its root rather than poppable segments, since Windows cannot climb above a share. The call view's `description` rides the same derivation, since the contract renders it above the card and it must outrank the row's args-derived summary. All three render sites draw it: both chat-row shapes and the details panel. An expanded row draws it itself, because the collapsed summary is hidden while a row is open — without that the description would only ever be visible collapsed, which is the opposite of what "above the card" means. The component's contract: @@ -20,7 +20,7 @@ The component's contract: - **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's own text metrics to line up with it. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. -- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Two cursor movements resolve before that strip, because their effect on the visible text has to land before the characters expressing them are dropped: a carriage return reduces its line to the final redraw, and a backspace overwrites the character before it, so `abc` followed by two backspaces and `XY` reads `aXY` as a terminal draws it. Both are per-line, so neither reaches across a newline. A backspace steps over CSI sequences rather than erasing their bytes: a sequence moves no cursor, and eating part of one would corrupt it and repaint everything after with whatever the mangled remainder parses as, so it walks back to the last PRINTED character and drops that instead — the surviving text keeps the color its run authored. +- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color. - **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks. diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index ab5a35d6f7..3ffcf23294 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -12,7 +12,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c ## Decision -`TerminalBlock` 是 `ui-primitives` 中把 shell 命令渲染为终端表面的组件,bash 调用在 Web 侧的两个渲染点都经由它消费 terminal 渲染意图:聊天工具行展开后的正文,以及详情面板的 Output 区。`ui-conversation/src/client/contract/terminal-card-model.ts` 是把快照上的 `callView`/`resultView` 这一对转换为该组件 props 的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧。当两侧都不声明 `card: 'terminal'` 时它返回 null,即走 generic 路径——包括本 client 版本不认识的 `card` 取值;当一个已落定调用的结果视图是 generic 时同样返回 null,这正是 bash 工具的执行错误与后台启动得以保持既有渲染的方式。渲染意图契约交给 UI 桥接层的两项职责也落在这里,而不在工具侧:已落定结果的 `title` **替换**待定标题;工作目录针对会话 workspace 解析——视图给出的绝对路径原样使用,相对路径在 workspace 之下拼接,省略则**就是** workspace,而这正是不带 `workdir` 的 bash 调用的常见情形。纯 presenter 看不到会话 cwd,因此该解析属于这道接缝;两个渲染点各自从会话列表行取出 cwd 传入。只有**存在**的调用视图才能表示「省略了 cwd,因此取 workspace」:当分页窗口丢掉调用头时,任何地方都不再有 cwd——结果视图并不携带它——而原调用完全可能使用过一个显式 workdir,因此提示行绘制一个裸 `$`,而不是命名一个它无法知晓的目录。解析后的路径还会归一化其 `.`/`..` 段,因为 bash 执行器在运行前就已解析 workdir:相对 `/w/app` 的 `..` 实际运行在 `/w`,因此提示标签必须读作 `w` 而不是 `..`。UNC 路径的 `server` 与 `share` 属于其根,而非可弹出的路径段,因为 Windows 无法越过一个共享向上。调用视图的 `description` 走同一处推导,因为契约把它渲染在卡片上方,且它必须优先于该行由参数推导出的摘要。 +`TerminalBlock` 是 `ui-primitives` 中把 shell 命令渲染为终端表面的组件,bash 调用在 Web 侧的两个渲染点都经由它消费 terminal 渲染意图:聊天工具行展开后的正文,以及详情面板的 Output 区。`ui-conversation/src/client/contract/terminal-card-model.ts` 是把快照上的 `callView`/`resultView` 这一对转换为该组件 props 的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧。当两侧都不声明 `card: 'terminal'` 时它返回 null,即走 generic 路径——包括本 client 版本不认识的 `card` 取值;当一个已落定调用的结果视图是 generic 时同样返回 null,这正是 bash 工具的执行错误与后台启动得以保持既有渲染的方式。渲染意图契约交给 UI 桥接层的两项职责也落在这里,而不在工具侧:已落定结果的 `title` **替换**待定标题;工作目录针对会话 workspace 解析——视图给出的绝对路径原样使用,相对路径在 workspace 之下拼接,省略则**就是** workspace,而这正是不带 `workdir` 的 bash 调用的常见情形。纯 presenter 看不到会话 cwd,因此该解析属于这道接缝;两个渲染点各自从会话列表行取出 cwd 传入。只有**存在**的调用视图才能表示「省略了 cwd,因此取 workspace」:当分页窗口丢掉调用头时,任何地方都不再有 cwd——结果视图并不携带它——而原调用完全可能使用过一个显式 workdir,因此提示行绘制一个裸 `$`,而不是命名一个它无法知晓的目录。解析后的路径还会归一化其 `.`/`..` 段,因为 bash 执行器在运行前就已解析 workdir:相对 `/w/app` 的 `..` 实际运行在 `/w`,因此提示标签必须读作 `w` 而不是 `..`。UNC 路径的 `server` 与 `share` 属于其根,而非可弹出的路径段,因为 Windows 无法越过一个共享向上。调用视图的 `description` 走同一处推导,因为契约把它渲染在卡片上方,且它必须优先于该行由参数推导出的摘要。三个渲染点都会绘制它:两种聊天行形态与详情面板。展开后的行自行绘制它,因为一行处于展开态时其折叠摘要是隐藏的——否则该描述将只在折叠时可见,这与「位于卡片上方」的含义正好相反。 该组件的契约: @@ -20,7 +20,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c - **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片表面左侧预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 -- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。两种光标移动在该剥除之前先行结算,因为它们对可见文本的作用必须先落地,之后才能丢弃表达它们的那些字符:回车把所在行归约为最后一次重绘,退格覆盖它前面的字符——于是 `abc` 后接两个退格再接 `XY` 读作 `aXY`,与终端的绘制一致。两者都按行结算,因此都不会跨越换行。退格会跨过 CSI 序列,而不是擦掉它的字节:序列本身不移动光标,吃掉它的一部分会破坏该序列,并让其后的一切按被损坏的残余重新着色,因此退格回退到最后一个**已打印**字符并删除它——存活下来的文本保留其所在分段所声明的颜色。 +- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因。 - **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。 diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css index bf1e238e23..0c1f674262 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css @@ -182,6 +182,14 @@ button.leading { also replaces each primitive's own standalone vertical spacing with the flow's row rhythm. */ .codeBody, +/* Indented to the terminal body's own column, so the description reads as the + card's heading rather than as another summary row. */ +.terminalDescription { + margin: 4px 0 0 22px; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xs-13); +} + .terminalBody { margin: 4px 0 4px 22px; } diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx index 30ef595397..d4fae4f6c5 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx @@ -156,6 +156,12 @@ export function ToolRow({ )}
+ {/* The terminal presenter's description belongs ABOVE the card per the + render-intent contract, so an expanded terminal row keeps showing it + even though the collapsed summary is hidden while open. */} + {open && terminalBody?.description !== undefined && ( +
{terminalBody.description}
+ )} {open && (terminalBody !== null ? : variant === 'code' diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css index ef4173735e..0ddc58e30b 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css @@ -95,6 +95,14 @@ /* The terminal card sits directly under its section label, so it drops the primitive's standalone vertical margin; the section owns the spacing. */ +/* Above the card, which is where the render-intent contract puts a terminal + call's description; the panel has no summary row to carry it. */ +.terminalDescription { + margin: 0 0 6px; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xs-13); +} + .terminal { margin: 0; } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index 630334eae7..9fc5a04ff6 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -135,7 +135,18 @@ export function DetailsPanel({ useSession, useSessions, sessionId, useStore, clo */ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | undefined }) { const terminal = terminalCardModel(material.block, cwd) - if (terminal !== null) return + if (terminal !== null) { + // The contract renders the presenter's description above the card, and the + // panel has no summary row to carry it, so it is drawn here. + return ( + <> + {terminal.description !== undefined && ( +
{terminal.description}
+ )} + + + ) + } // A settled call always carries the result node the flattened form needs; // the running shape has no result to flatten. if (!('kind' in material.block)) return
运行中…
diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index dd096c6e91..3ac9ad2f1c 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -267,6 +267,19 @@ describe('chat row terminal body', () => { expect(view.queryByText('List files')).toBeNull() }) + it('keeps the presenter description visible once the terminal card is expanded', () => { + // The contract puts the description ABOVE the card. The collapsed summary is + // hidden while a row is open, so an expanded terminal row has to draw it + // itself or the description would only ever be visible collapsed. + const view = render() + expect(view.getByText('Terminal 3')).toBeTruthy() + fireEvent.click(view.container.querySelector('button')!) + expect(view.container.querySelector('[data-terminal]')).not.toBeNull() + expect(view.getByText('Terminal 3')).toBeTruthy() + }) + it('a running terminal call expands to the prompt line with no output yet', () => { const view = render() fireEvent.click(view.container.querySelector('button')!) @@ -421,6 +434,17 @@ describe('DetailsPanel Output section', () => { expect(second.getByRole('button', { name: '展开其余 4 行输出' })).toBeTruthy() }) + it('renders the presenter description above the card', () => { + const view = mount(snapshot({ + nodes: [settled({ callView: callTerminal({ description: 'Terminal 3' }) })], + }), target) + const description = view.getByText('Terminal 3') + const card = view.container.querySelector('[data-terminal]') + expect(card).not.toBeNull() + // Above, not below: document order is what places it as the card's heading. + expect(description.compareDocumentPosition(card!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + }) + it('resolves the prompt cwd against the session workspace', () => { const view = mount(snapshot({ nodes: [settled()] }), target, '/w/app') // No workdir in the call view: the prompt label is the workspace basename. diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index ad22a9f734..3e81b076a4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 4222aac4fa1d9c89a3d3c702ee8391fba1eef178 -README.zh.md: e7a5b5ad57048bc59872963b0068c6f88fc772f8 +README.md: 3e77cb1955972db602b4e751a52a45cf5f5f349d +README.zh.md: 19e02c3e466afcbddd0d19ad6644887d3a53ca10 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 4222aac4fa..3e77cb1955 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage-return redraws and backspace overwrites resolve as a terminal performs them before inert controls are stripped; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage return and backspace replay into a per-line column buffer before inert controls are stripped, since both only move the cursor (so `100%` + CR + `OK` shows `OK0%`), with SGR state stamped per column as a terminal stores it per cell; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index e7a5b5ad57..19e02c3e46 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车重绘与退格覆盖会按终端的行为先行结算,之后才剥除无显示意义的控制符;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车与退格在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为两者都只移动光标(所以 `100%` 加回车再加 `OK` 显示为 `OK0%`),且 SGR 状态按列打戳,与终端按单元格存储颜色一致;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index 115d3faffc..1d7dd87796 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -82,95 +82,99 @@ const NON_CSI_ESCAPE = /\u001b(?!\[)[\u0020-\u002f]*[\u0030-\u007e]?/g /** * C0 controls with no display meaning here. Tab, newline, backspace and ESC - * survive: the first two for layout, backspace for its overwrite, ESC for - * anser's CSI split. + * survive: the first two for layout, backspace for the cursor replay, ESC + * for anser's CSI split. */ const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g /** - * Apply carriage-return redraws: within a line, only the text after the last - * `\r` survives, which is what a terminal shows for progress output. A `\r` - * that only terminates a CRLF line is dropped first so those lines keep - * their text. SGR codes preceding a dropped redraw are dropped with it. - * @param text - output text, already free of OSC and non-CSI escapes. - * @returns the text with each line reduced to its final redraw. - */ -function applyCarriageReturns(text: string): string { - return text.split('\n').map((raw) => { - const line = raw.replace(/\r+$/, '') - return line.slice(line.lastIndexOf('\r') + 1) - }).join('\n') -} - -/** - * Apply backspaces as the cursor-left-then-overwrite a terminal performs, so - * `abc` followed by two backspaces and `XY` reads `aXY` instead of keeping the - * characters it overwrote. Progress meters and captured PTY output use - * backspace this way. Resolved per line, so a backspace neither eats the - * newline before it nor reaches into the previous line's tail; one at a line - * start has nothing to erase. - * @param text - output text, already reduced to its carriage-return redraws. - * @returns the text with each backspace resolved against the character before it. - */ -function applyBackspaces(text: string): string { - if (!text.includes('\u0008')) return text - return text.split('\n').map(applyBackspacesToLine).join('\n') -} - -/** - * One line's backspaces, resolved over VISIBLE characters only. A CSI sequence - * moves no cursor, so it must survive intact: erasing its bytes would corrupt - * the sequence and repaint the rest of the output with whatever the mangled - * remainder parses as. The sequences are therefore held as indivisible units - * that a backspace steps over on its way to the last printed character, and a - * unit already erased stays erased so a run's own color still applies to what - * remains of it. + * Replay one line's cursor movements the way a terminal paints it, into a + * column buffer. Carriage return and backspace only MOVE the cursor — neither + * erases anything — so what a reader sees is whatever each column last had + * written to it. That distinction is the whole point of doing this as a buffer + * rather than as string surgery: `100%\rOK` shows `OK0%` because the redraw is + * shorter than the frame beneath it, and a trailing `abc\b` still shows `abc` + * because nothing ever overwrote the `c`. + * + * A CSI sequence occupies no column; it changes the state that the NEXT writes + * are stamped with, which is how a terminal stores color per cell. `red bad` + * then three backspaces then `ok` therefore shows `okd` with the `d` still red: + * `ok` overwrote two cells and the third kept the state it was written with. + * The columns are re-emitted as runs, so anser sees that same styling. * @param line - one output line, still carrying its CSI sequences. - * @returns the line with each backspace applied to the character before it. + * @returns the line as the terminal would have it after every movement. */ -function applyBackspacesToLine(line: string): string { - if (!line.includes('\u0008')) return line - const units: { text: string; visible: boolean }[] = [] - // Same shape anser splits on: CSI ... final byte. Matched here so a sequence - // is one unit rather than a run of erasable characters. +function replayLine(line: string): string { + // Same shape anser splits on, so a sequence is one unit here as well. const csi = /\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*[\u0040-\u007e]/g + /** Per column: the SGR state in force when it was written, and its character. */ + const columns: { sgr: string; char: string }[] = [] + let cursor = 0 + // SGR state accumulates as the line is scanned, exactly as a terminal tracks + // it: each cell is stamped with whatever was in force at the moment of the + // write, so a later redraw cannot restyle the cells it does not reach. + let sgr = '' let at = 0 + + const consume = (chunk: string): void => { + for (const char of chunk) { + if (char === '\r') { cursor = 0; continue } + if (char === '\u0008') { cursor = Math.max(0, cursor - 1); continue } + columns[cursor] = { sgr, char } + cursor++ + } + } + for (const match of line.matchAll(csi)) { - for (const char of line.slice(at, match.index)) units.push({ text: char, visible: true }) - units.push({ text: match[0], visible: false }) + consume(line.slice(at, match.index)) + // A reset clears the accumulated state; anything else adds to it. + sgr = /^\u001b\[0?m$/.test(match[0]) ? '' : sgr + match[0] at = match.index + match[0].length } - for (const char of line.slice(at)) units.push({ text: char, visible: true }) + consume(line.slice(at)) - const kept: { text: string; visible: boolean }[] = [] - for (const unit of units) { - if (unit.visible && unit.text === '\u0008') { - // Walk back past any escapes to the last printed character and drop it, - // keeping those escapes so the surviving text stays styled as authored. - for (let index = kept.length - 1; index >= 0; index--) { - if (kept[index]?.visible !== true) continue - kept.splice(index, 1) - break - } - continue + // Re-emit the columns, opening a run only where its SGR state changes and + // closing the previous one, so anser sees the same styling a terminal shows. + // No index can be missing: `\r` and backspace only move the cursor LEFT, so + // every column up to the furthest write has been written at least once. + let out = '' + let active = '' + for (const column of columns) { + if (column.sgr !== active) { + if (active !== '') out += '\u001b[0m' + out += column.sgr + active = column.sgr } - kept.push(unit) + out += column.char } - return kept.map(unit => unit.text).join('') + return active === '' ? out : `${out}\u001b[0m` +} + +/** + * Replay every line's cursor movements. A `\r` that only terminates a CRLF line + * is dropped first, so those lines keep their text instead of being redrawn onto + * themselves. + * @param text - output text, already free of OSC and non-CSI escapes. + * @returns the text with each line painted as the terminal would. + */ +function applyCursorMovements(text: string): string { + return text.split('\n') + .map(raw => raw.replace(/\r+$/, '')) + .map(line => (/[\r\u0008]/.test(line) ? replayLine(line) : line)) + .join('\n') } /** * Remove every escape sequence and control character that carries no color, - * leaving CSI sequences for anser and `\n`/`\t` for layout. Carriage-return - * redraws and backspace overwrites resolve first: both are cursor movements - * whose effect on the visible text must land before the characters that - * expressed them are dropped. + * leaving CSI sequences for anser and `\n`/`\t` for layout. Cursor movements + * (carriage return, backspace) replay first, since their effect on the visible + * text must land before the characters that expressed them are dropped. * @param text - raw command output. * @returns text whose only remaining escapes are CSI sequences. */ function sanitize(text: string): string { const escaped = text.replace(OSC_SEQUENCE, '').replace(NON_CSI_ESCAPE, '') - return applyBackspaces(applyCarriageReturns(escaped)).replace(INERT_CONTROL, '') + return applyCursorMovements(escaped).replace(INERT_CONTROL, '') } /** diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index 76af75a565..801484d6a7 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -151,8 +151,26 @@ describe('parseAnsiLines: carriage returns', () => { expect(onlySpan('10%\r55%\r100%')).toEqual({ text: '100%', style: undefined }) }) - it('drops the SGR codes that preceded a discarded redraw', () => { - expect(onlySpan(`${ESC}[31mgone\rkept`)).toEqual({ text: 'kept', style: undefined }) + it('leaves the tail of a longer frame standing under a shorter redraw', () => { + // Verified against a real terminal: `100%\rOK` paints `OK0%`. A carriage + // return only moves the cursor, so the two columns the redraw never reaches + // still hold the frame beneath — truncating to the last `\r` would lose them. + expect(onlySpan('100%\rOK')).toEqual({ text: 'OK0%', style: undefined }) + expect(onlySpan('abcdef\rXY')).toEqual({ text: 'XYcdef', style: undefined }) + }) + + it('clamps a backspace run at the line start rather than going negative', () => { + // More backspaces than characters: the cursor stops at column 0, so the + // following write simply overwrites from there. + expect(onlySpan(`ab${BS}${BS}${BS}${BS}xyz`)).toEqual({ text: 'xyz', style: undefined }) + }) + + it('keeps SGR state in force across a redraw, as a terminal does', () => { + // Verified against a real terminal: `\x1b[31mgone\rkept` paints `kept` RED. + // A carriage return moves the cursor; it does not reset the graphic state, + // so the redraw inherits the color the discarded frame was written with. + expect(onlySpan(`${ESC}[31mgone\rkept`)) + .toEqual({ text: 'kept', style: { color: 'var(--dsw-alias-state-error-primary)' } }) }) it('preserves both lines of a CRLF pair instead of treating it as a redraw', () => { @@ -184,6 +202,17 @@ describe('parseAnsiLines: backspaces', () => { ]) }) + it('treats a trailing backspace as a cursor move, not a delete', () => { + // Verified against a real terminal: `abc\b` still shows `abc`. Only a later + // write overwrites; a backspace with nothing after it erases nothing. + expect(onlySpan(`abc${BS}`)).toEqual({ text: 'abc', style: undefined }) + // Same at a line boundary: the newline ends the line before any overwrite. + expect(parseAnsiLines(`abc${BS}\ndef`)).toEqual([ + [{ text: 'abc', style: undefined }], + [{ text: 'def', style: undefined }], + ]) + }) + it('steps over an SGR sequence instead of erasing its bytes', () => { // `abc` reset then two backspaces then `XY`: erasing the reset's bytes would // corrupt it and repaint the rest of the line with whatever the remainder @@ -202,14 +231,21 @@ describe('parseAnsiLines: backspaces', () => { ]]) }) - it('applies the overwrite after a carriage-return redraw, not before', () => { - // The redraw wins first; the backspace then erases inside what survived. - expect(onlySpan(`old\rnew${BS}`)).toEqual({ text: 'ne', style: undefined }) + it('replays a redraw and a trailing backspace as pure cursor moves', () => { + // Verified against a real terminal: `old\rnew\b` shows `new`. The redraw + // repaints all three columns and the trailing backspace only moves the + // cursor left — nothing overwrites the `w`, so nothing is lost. + expect(onlySpan(`old\rnew${BS}`)).toEqual({ text: 'new', style: undefined }) }) - it('keeps the run\'s style while erasing its own characters', () => { - expect(onlySpan(sgr('31', `bad${BS}${BS}${BS}ok`))) - .toEqual({ text: 'ok', style: { color: 'var(--dsw-alias-state-error-primary)' } }) + it('overwrites only the columns the later write reaches, keeping the rest styled', () => { + // Verified against a real terminal: red `bad`, three backspaces, then `ok` + // shows `okd` — the cursor returned to column 0 and `ok` overwrote two of + // the three columns, so the untouched `d` keeps the run's red. + expect(parseAnsiLines(`${sgr('31', 'bad')}${BS}${BS}${BS}ok`)).toEqual([[ + { text: 'ok', style: undefined }, + { text: 'd', style: { color: 'var(--dsw-alias-state-error-primary)' } }, + ]]) }) }) From 43de478d103d693cee23dace01efada8c8bb4862 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 15:36:16 +0800 Subject: [PATCH 09/14] fix(web): model erase-in-line, tab stops, and cross-line SGR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six findings. Each terminal-semantics case was checked in a real terminal (tmux, reading back the painted screen) before changing anything: `100%\r\x1b[KOK` shows `OK`. Modelling the `\r` without its erase left the previous frame's tail standing — a regression against the old truncate, since `\r\x1b[K` is the single idiom every spinner and progress bar writes. Erase is now part of the same replay, in all three parameter forms. `a\tb\rXY` shows `XY b`. Counting a tab as one column produced `XYb` and destroyed the alignment this card exists to hold, so the cursor now advances by terminal columns: tabs reach the next 8-column stop and a wide character takes two cells. `\x1b[31mabc\rX\nnext` paints BOTH lines red. A newline does not reset the graphic state, so state threads from one replayed line to the next instead of closing at each line end. Only `m` accumulates into a cell's style now. Folding cursor and erase sequences in grew the state string per redraw and emitted boundaries anser had to discard. The empty check reads the parsed lines the card renders rather than the raw text: output that is only escapes or control bytes survives `trim()` yet parses to nothing, and drew blank rows plus a copy control for invisible bytes instead of the placeholder. The gutter is the card's own left padding rather than a margin. Every render site rewrites `margin` wholesale for its own indent, which silently cancelled the reservation and let a container clip the dot. The fixture sample no longer carries an `[exit code: 1]` line: the real bash presenter consumes that marker precisely because the card shows the exit as its own pill, so the built-bundle snapshot had pinned a frame showing it twice — one the product path cannot produce. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 10 +- .../2026-07-28-web-terminal-card.zh.md | 10 +- apps/web/tests/navigation-panes.e2e.ts | 18 ++- apps/web/tests/terminal-card.snapshot.ts | 8 +- .../client/connection/src/client/fixture.ts | 8 +- .../src/TerminalBlock.module.css | 30 +++-- .../ui-primitives/src/TerminalBlock.tsx | 7 +- packages/client/ui-primitives/src/ansi.ts | 107 ++++++++++++++---- .../client/ui-primitives/tests/ansi.spec.ts | 66 +++++++++++ .../tests/terminal-block.spec.tsx | 11 ++ 11 files changed, 224 insertions(+), 55 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 6927b58937..14580fce67 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 284c91cc936c1e757f20f0d0d8afbe4b4c0afc42 -2026-07-28-web-terminal-card.zh.md: 3ffcf232942eed883f44da583c68455715d347ce +2026-07-28-web-terminal-card.md: 3ebbc38a2875a8a3c0fc6c771e282ca7974ad905 +2026-07-28-web-terminal-card.zh.md: 0523b5220a5b856551a95f4a7c36770da21c6906 diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 284c91cc93..3ebbc38a28 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -17,11 +17,11 @@ The Web client ignored it. `packages/client/ui-conversation/src/client/contract/ The component's contract: - **Prompt lines, one per command line.** Each line of the command gets its own row: label, then that line verbatim. A `command` carrying two shell commands on two lines therefore reads as the two commands it is, instead of collapsing into one ellipsized row. The label is the cwd's last path segment, or `~` when the cwd equals the `home` prop — a browser has no `$HOME`, so the caller supplies the absolute home directory and the collapse simply does not apply without it. A view with no cwd renders a plain `$`. A trailing newline is a terminator, not an empty final command. Only the FIRST row carries the label: the view knows one working directory — where the call started — and a later line may run somewhere else entirely, since a `cd` in the command is enough to move it. Repeating the label down the rows would state a directory per line that nothing here knows, which is the same reason the run-state dot appears once. Later rows keep a bare `$` so they still read as prompts. -- **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter reserved to the left of the card surface, so it neither indents its command nor depends on the command's own text metrics to line up with it. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. +- **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter the card reserves as its OWN left padding, so it neither indents its command nor depends on the command's text metrics to line up. The reservation is padding rather than margin because every render site rewrites `margin` wholesale to set its own indent, which silently cancelled a margin-based gutter and let a container clip the dot. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. -- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color. -- **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. +- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color, and why SGR state threads from one line to the next rather than closing at each newline. Erase-in-line is part of the same replay, because `\r\x1b[K` is the single idiom every spinner and progress bar writes — modelling the `\r` alone left the previous frame's tail standing, which is text the terminal never showed. Only `m` accumulates into a cell's style; a cursor or erase sequence must not, or the state string grows per redraw and emits boundaries anser has to discard. The cursor advances by terminal columns, so a tab reaches the next 8-column stop and a wide character takes two: `a\tb` then a redraw of `XY` shows `XY b`, since a two-character redraw cannot reach column 8. +- **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder — judged on the parsed lines the card renders, not on the raw text, since output that is only escapes or control bytes survives a `trim()` yet parses to nothing visible and would otherwise draw blank rows plus a copy control for invisible bytes. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks. @@ -55,11 +55,11 @@ Inline rendering is licensed for the terminal intent alone. A future intent that ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, per-line carriage-return redraws and backspace overwrites (including a backspace stopping at a line start and resolving after a redraw), and CRLF preservation. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, the run-state dot across all three reachable states plus its position ahead of the prompt label, the one-row-per-command-line prompt and its single dot on the first row, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. +`packages/client/ui-primitives/tests/ansi.spec.ts` pins the parse layer: token mapping for the basic colors, literal rgb for the values with no token, the background-run pair, every decoration and the `textDecoration` collision between two of them, the sanitizing of OSC strings and non-CSI escapes and inert controls, the cursor replay (redraws leaving a longer frame's tail standing, a trailing backspace erasing nothing, erase-in-line in all three parameter forms, tab stops, wide characters, SGR threading across lines, and a cursor/erase sequence never entering a cell style), and CRLF preservation. Each replay case was checked against a real terminal first. `packages/client/ui-primitives/tests/terminal-block.spec.tsx` pins the component: cwd shortening, the running/empty/settled arms, signal outranking exit code, the trailing-newline terminator rule, the head/tail cap with its `aria-expanded` toggle, the run-state dot across all three reachable states plus its position ahead of the prompt label, the one-row-per-command-line prompt and its single dot on the first row, and the copy control asserting raw output on both the accepted and refused clipboard paths, plus `writeClipboard` directly. `packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the result title replacing the pending one, the cwd resolving against the session workspace across all four of its cases, the panel resetting the card's expand state when the selection changes, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card and its agreement with its own summary row's state dot, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files. -`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 65 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes, and turn 60's command was made two lines so the built-bundle snapshot pins the per-line prompt and its single dot (`dotsPerPromptRow: [1, 0]`). That terminal turn is ordered BEFORE the todo turn on purpose: the standing plan retires at the next `turn/start`, so appending it after would have emptied the dock's plan strip and taken the todo surfaces' own coverage with it; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit recovered from the trailing marker. +`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 65 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes, and turn 60's command was made two lines so the built-bundle snapshot pins the per-line prompt and its single dot (`dotsPerPromptRow: [1, 0]`). That terminal turn is ordered BEFORE the todo turn on purpose: the standing plan retires at the next `turn/start`, so appending it after would have emptied the dock's plan strip and taken the todo surfaces' own coverage with it; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit authored beside the sample. The sample's body deliberately carries NO `[exit code: N]` line: the real bash presenter consumes that marker out of the body precisely because the card shows the exit as its own pill, so leaving it in would pin a frame showing the exit twice — one the product path cannot produce. `apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet) and starts to the left of the card surface itself, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `terminal-card.expected.md` golden records the resolved workspace in the prompt row, which is what a bash call with no `workdir` must show instead of a bare `$`. diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index 3ffcf23294..0523b5220a 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -17,11 +17,11 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c 该组件的契约: - **提示符行,每条命令行一行。** 命令的每一行各占一行:标签,其后原样跟随该行。因此一个在两行上承载两条 shell 命令的 `command` 就读作它本身的两条命令,而不是被压成一行并省略号截断。标签取 cwd 的最后一段路径,当 cwd 等于 `home` prop 时取 `~`——浏览器没有 `$HOME`,因此由调用方提供绝对家目录,不提供时该折叠不生效。视图不带 cwd 时渲染一个纯 `$`。末尾换行是终止符,不是一条空的末命令。只有**第一行**携带该标签:视图只知道一个工作目录——调用开始处的那个——而后面的行完全可能在别处运行,命令里一个 `cd` 就足以改变它。把标签在各行重复,等于陈述一个此处无人知晓的逐行目录,这与运行状态点只出现一次是同一个理由。其余行保留一个裸 `$`,因此它们仍读作提示符。 -- **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片表面左侧预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 +- **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片以**自身左内边距**预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。该预留用 padding 而非 margin,是因为每个渲染点都会整条重写 `margin` 来设定自己的缩进——那会静默取消基于 margin 的落区,并让容器把状态点裁掉。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 -- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因。 -- **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 +- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因,以及 SGR 状态会从一行延续到下一行、而不是在每个换行处关闭的原因。行内擦除属于同一次重放,因为 `\r\x1b[K` 是每个 spinner 与进度条都会写的同一个惯用法——只建模 `\r` 会让上一帧的尾巴留在原处,那是终端从未显示过的文本。只有 `m` 会累加进单元格样式;光标或擦除序列不能累加,否则状态串会随每次重绘线性增长,并发出 anser 只能丢弃的边界。光标按终端列推进,因此制表符前进到下一个 8 列制表位、宽字符占两列:`a\tb` 之后用 `XY` 重绘显示为 `XY b`,因为两个字符的重绘到不了第 8 列。 +- **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字——该判定读的是卡片实际渲染的解析行,而非原始文本,因为只含转义或控制字节的输出能通过 `trim()` 却解析不出任何可见内容,否则就会画出一片空行外加一个把不可见字节写进剪贴板的复制控件。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。 @@ -55,11 +55,11 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c ## Testing -`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、逐行的回车重绘与退格覆盖(含退格停在行首、以及退格在重绘之后结算),以及 CRLF 的保留。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关、运行状态点全部三种可达状态及其位于提示符标签之前的位置、每条命令行一行的提示区及其位于第一行的单枚状态点,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 +`packages/client/ui-primitives/tests/ansi.spec.ts` 固定解析层:基本色的 token 映射、无对应 token 取值的字面 rgb、带背景分段的前后景配对、每一项装饰以及其中两项之间的 `textDecoration` 冲突、OSC 串与非 CSI 转义及无显示意义控制符的剥除、光标重放(较短重绘让上一帧尾巴留存、末尾退格不擦除任何东西、行内擦除的全部三种参数形式、制表位、宽字符、SGR 跨行延续,以及光标/擦除序列绝不进入单元格样式),以及 CRLF 的保留。每一条重放用例都先对照真实终端核实过。`packages/client/ui-primitives/tests/terminal-block.spec.tsx` 固定组件:cwd 缩短、运行中/空/已落定三条分支、信号优先于退出码、末尾终止符规则、首尾高度上限及其 `aria-expanded` 开关、运行状态点全部三种可达状态及其位于提示符标签之前的位置、每条命令行一行的提示区及其位于第一行的单枚状态点,以及复制控件在剪贴板接受与拒绝两条路径上都断言原始输出,另有对 `writeClipboard` 的直接固定。 `packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、结果标题替换待定标题、cwd 针对会话 workspace 解析的全部四种情形、切换选中调用时面板重置卡片展开态、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片及其与自身摘要行状态点的一致性,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。 -`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 65 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态,并把第 60 轮的命令改为两行,使构建产物快照钉住逐行提示区及其单枚状态点(`dotsPerPromptRow: [1, 0]`)。该终端轮有意排在 todo 轮**之前**:站立计划会在下一次 `turn/start` 时退役,若追加在其后就会让 dock 的计划条变空,并连带毁掉 todo 表面自身的覆盖;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及从末尾标记还原出的非零退出码。 +`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 65 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态,并把第 60 轮的命令改为两行,使构建产物快照钉住逐行提示区及其单枚状态点(`dotsPerPromptRow: [1, 0]`)。该终端轮有意排在 todo 轮**之前**:站立计划会在下一次 `turn/start` 时退役,若追加在其后就会让 dock 的计划条变空,并连带毁掉 todo 表面自身的覆盖;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及在样本旁另行标注的非零退出码。样本正文有意**不含** `[exit code: N]` 行:真实的 bash presenter 正是因为卡片以徽章单独呈现退出状态,才把该标记从正文中消费掉;若保留它,钉住的将是一帧把退出状态显示两次的画面——而产品路径产不出这一帧。 `apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值),且其起点位于卡片表面本身的左侧;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `terminal-card.expected.md` 基准记录了提示行中已解析的 workspace——这正是不带 `workdir` 的 bash 调用应当显示的内容,而非一个裸 `$`。 diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 12ec836e90..96117c21bf 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -220,16 +220,24 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { // puts it to the left of the `$`. beforePrompt: node.compareDocumentPosition(node.parentElement!.querySelector('[class*="_cwd_"]')!) === Node.DOCUMENT_POSITION_FOLLOWING, - // The dot is out of flow in the card's left gutter, so it starts to the - // left of the card surface itself — the geometry jsdom cannot compute. - leftOfCard: (node as HTMLElement).getBoundingClientRect().left - < node.closest('[data-terminal]')!.getBoundingClientRect().left, + // The dot lives in the card's OWN left padding, so it sits inside the + // card box yet left of the prompt text. Owning the reservation as padding + // rather than margin is what keeps a consumer's own margin from + // cancelling it and letting a container clip the dot — geometry jsdom + // cannot compute. + insideCard: (node as HTMLElement).getBoundingClientRect().left + >= (node.closest('[data-terminal]')?.getBoundingClientRect().left ?? Infinity), + leftOfPrompt: (node as HTMLElement).getBoundingClientRect().right + <= (node.closest('[class*="_promptLine_"]') + ?.querySelector('[class*="_cwd_"]') + ?.getBoundingClientRect().left ?? -Infinity), } }) expect(dot.state).toBe('done') expect(dot.label).toBe('已完成') expect(dot.beforePrompt).toBe(true) - expect(dot.leftOfCard).toBe(true) + expect(dot.insideCard).toBe(true) + expect(dot.leftOfPrompt).toBe(true) // Resolved through the theme token, not a literal hex in the component. expect(dot.success).toMatch(/^rgb/) expect(dot.color).toBe(dot.success) diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts index 82d94b251d..3d4d81169c 100644 --- a/apps/web/tests/terminal-card.snapshot.ts +++ b/apps/web/tests/terminal-card.snapshot.ts @@ -210,18 +210,18 @@ it('renders the keyed bash row with a resident terminal card', async () => { ], "expander": { "expanded": "false", - "label": "展开其余 14 行输出", - "text": "… 其余 14 行", + "label": "展开其余 13 行输出", + "text": "… 其余 13 行", }, "lines": [ "Running 4 checks", "✓ typecheck 1.82s", "✓ lint 0.94s", "✓ duplication 2.10s", + "StateDot.tsx 100% 100% 100% -", "markdown/Markdown.tsx 100% 100% 100% -", "", "1 of 4 checks failed", - "[exit code: 1]", ], "prompt": [ "nested pnpm run check", @@ -298,7 +298,7 @@ it('the chat card expands the collapsed middle in place, without opening the det { "cappedLines": 8, "detailsOpen": false, - "expandedLines": 22, + "expandedLines": 21, "expanderLabel": "收起输出", } `) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index e649abc9e7..e5a235973f 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -97,8 +97,11 @@ function sgr(code: number, body: string): string { * basic-16 SGR foreground runs (green, red, bright-black) that must resolve to * `--dsw-*` tokens, a bold run, column-aligned table rows that must scroll * rather than fold, more than DEFAULT_TERMINAL_MAX_LINES (16) lines so the - * height cap collapses the middle, and the trailing `[exit code: N]` marker the - * bash tool appends, from which the exit pill is recovered. + * height cap collapses the middle. The exit status is authored separately in + * TERMINAL_EXIT_STATUS and deliberately absent from this text: the real bash + * presenter CONSUMES its `[exit code: N]` marker out of the body, because a + * terminal card shows the exit as its own pill and leaving the marker in would + * render it twice (packages/bash/tool-bash/src/render.ts). */ const TERMINAL_OUTPUT_FIXTURE = [ sgr(1, 'Running 4 checks'), @@ -122,7 +125,6 @@ const TERMINAL_OUTPUT_FIXTURE = [ 'markdown/Markdown.tsx 100% 100% 100% -', '', sgr(31, '1 of 4 checks failed'), - '[exit code: 1]', ].join('\n') /** diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index d5fa1ea34f..8b7cede2fc 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -7,13 +7,18 @@ .block { --dsl-terminal-radius: 12px; --dsl-terminal-line-height: 22px; - /* Reserved strip to the left of the card for the per-line run-state dots. - The dots sit outside the card surface, so a reader scans command state - down one column without the dots competing with the commands themselves. */ + /* The card's own left inset, holding the run-state dot in a column of its own + so it never competes with the commands for horizontal space. */ --dsl-terminal-gutter: 30px; position: relative; - margin: 16px 0 16px var(--dsl-terminal-gutter); + margin: 16px 0; + /* The gutter is the card's OWN padding, not a margin: every consumer rewrites + `margin` wholesale (each render site sets its own indent), which silently + cancelled the reservation and let the dot fall outside the card into a + container that clips it. Owning the reservation here keeps the invariant + with the component that depends on it. */ + padding-left: var(--dsl-terminal-gutter); color: var(--dsw-alias-label-primary); background: var(--dsw-alias-markdown-code-block); border-radius: var(--dsl-terminal-radius); @@ -25,7 +30,9 @@ display: flex; align-items: flex-start; gap: 12px; - padding: 9px 14px; + /* No left padding: the card's gutter already insets this row, and the banner + background still has to span the full surface. */ + padding: 9px 14px 9px 0; background: var(--dsw-alias-markdown-code-block-banner); border-top-left-radius: var(--dsl-terminal-radius); border-top-right-radius: var(--dsl-terminal-radius); @@ -50,12 +57,13 @@ line-height: var(--dsl-terminal-line-height); } -/* Out of flow in the gutter, so a dot neither indents its command nor depends - on the command's own text metrics to line up with it. Centered against the - row's line box rather than sitting on the code font's baseline. */ +/* Out of flow inside the card's own gutter padding, so the reservation and the + dot move together and no consumer margin can pull them apart; the dot neither + indents its command nor depends on the command's text metrics to line up. + Centered against the row's line box, not the code font's baseline. */ .runState { position: absolute; - left: calc(-1 * var(--dsl-terminal-gutter)); + left: calc(-1 * var(--dsl-terminal-gutter) + 8px); top: 50%; transform: translateY(-50%); } @@ -103,7 +111,7 @@ } .output { - padding: 12px 14px; + padding: 12px 14px 12px 0; font: var(--dsw-font-markdown-code-block); overflow-x: auto; overflow-y: hidden; @@ -132,7 +140,7 @@ } .empty { - padding: 12px 14px; + padding: 12px 14px 12px 0; font: var(--dsw-font-markdown-code-block); color: var(--dsw-alias-label-tertiary); } diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index 0932f4a7f0..1d56050b3c 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -154,7 +154,12 @@ export function TerminalBlock({ const body = command.endsWith('\n') ? command.slice(0, -1) : command return body.split('\n') }, [command]) - const empty = text.trim() === '' + // Read from the parsed lines the card actually renders, not from the raw text: + // output that is only escapes or control bytes (a lone reset, an OSC title, an + // erase) survives `text.trim()` yet parses to nothing visible. Judging it on + // the raw text drew an output box of blank rows plus a copy control for + // invisible bytes, and hid the placeholder that belongs there. + const empty = lines.every(line => line.every(span => span.text.trim() === '')) const hidden = lines.length - maxLines const capped = hidden > 0 && !expanded // Same split arithmetic as the TUI transcript's collapsed tool card, so a diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index 1d7dd87796..57c49300f0 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -87,6 +87,33 @@ const NON_CSI_ESCAPE = /\u001b(?!\[)[\u0020-\u002f]*[\u0030-\u007e]?/g */ const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g +/** Terminal tab stop width; a tab advances to the next multiple of this. */ +const TAB_WIDTH = 8 + +/** + * Characters a terminal advances two columns for: CJK scripts, fullwidth forms, + * CJK punctuation, and the emoji/symbol blocks a command's output realistically + * carries. + */ +const WIDE_CHAR = new RegExp( + '\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}' + + '|[\\u{1f300}-\\u{1faff}\\u{2600}-\\u{27bf}\\uff01-\\uff60\\u3000-\\u303e]', + 'u', +) + +/** + * Whether a character occupies two terminal columns (CJK, fullwidth forms, + * emoji). Covers the ranges a command's output realistically carries; a + * narrower guess would misalign the columns this card exists to preserve. + * @param char - one character from the output. + * @returns true when the terminal advances two columns for it. + */ +function isWide(char: string): boolean { + const code = char.codePointAt(0) + if (code === undefined || code < 0x1100) return false + return WIDE_CHAR.test(char) +} + /** * Replay one line's cursor movements the way a terminal paints it, into a * column buffer. Carriage return and backspace only MOVE the cursor — neither @@ -104,42 +131,70 @@ const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g * @param line - one output line, still carrying its CSI sequences. * @returns the line as the terminal would have it after every movement. */ -function replayLine(line: string): string { +function replayLine(line: string, entrySgr: string): { text: string; sgr: string } { // Same shape anser splits on, so a sequence is one unit here as well. - const csi = /\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*[\u0040-\u007e]/g + const csi = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*([\u0040-\u007e])/g /** Per column: the SGR state in force when it was written, and its character. */ - const columns: { sgr: string; char: string }[] = [] + const columns: ({ sgr: string; char: string } | undefined)[] = [] let cursor = 0 // SGR state accumulates as the line is scanned, exactly as a terminal tracks // it: each cell is stamped with whatever was in force at the moment of the - // write, so a later redraw cannot restyle the cells it does not reach. - let sgr = '' + // write, so a later redraw cannot restyle the cells it does not reach. It + // enters carrying the previous line's state, since a newline does not reset it. + let sgr = entrySgr let at = 0 const consume = (chunk: string): void => { for (const char of chunk) { if (char === '\r') { cursor = 0; continue } if (char === '\u0008') { cursor = Math.max(0, cursor - 1); continue } + if (char === '\t') { + // A tab advances to the next 8-column stop, leaving the cells it skips + // as they were — which is how a redraw can leave a tabbed column + // standing. Column alignment is the whole point of this card. + const stop = cursor + TAB_WIDTH - (cursor % TAB_WIDTH) + for (; cursor < stop; cursor++) columns[cursor] ??= { sgr, char: ' ' } + continue + } columns[cursor] = { sgr, char } cursor++ + // A wide character occupies two columns; the trailing one is a spacer the + // terminal keeps blank, so a later write there cannot split the glyph. + if (isWide(char)) { columns[cursor] = { sgr, char: '' }; cursor++ } } } for (const match of line.matchAll(csi)) { consume(line.slice(at, match.index)) - // A reset clears the accumulated state; anything else adds to it. - sgr = /^\u001b\[0?m$/.test(match[0]) ? '' : sgr + match[0] at = match.index + match[0].length + // Both groups are mandatory in the pattern, so destructuring types them as + // strings without a fallback that could never run. + const params = String(match[1]) + const final = String(match[2]) + if (final === 'K') { + // Erase in line: the fixed companion of `\r` in every spinner and progress + // bar. Without it a shorter redraw leaves the previous frame's tail + // standing, which is text the terminal never showed. `1` blanks the + // columns before the cursor rather than dropping them, since the cursor + // does not move and a later write can still land past them. + if (params === '1') for (let index = 0; index < cursor; index++) columns[index] = { sgr, char: ' ' } + else columns.length = params === '2' ? 0 : cursor + continue + } + // Only SGR carries graphic state; every other final byte is a cursor or + // erase action that must not be accumulated into a cell's style. + if (final !== 'm') continue + sgr = /^0?$/.test(params) ? '' : sgr + match[0] } consume(line.slice(at)) - // Re-emit the columns, opening a run only where its SGR state changes and - // closing the previous one, so anser sees the same styling a terminal shows. - // No index can be missing: `\r` and backspace only move the cursor LEFT, so - // every column up to the furthest write has been written at least once. + // Re-emit the columns, opening a run only where its SGR state changes, so + // anser sees the same styling a terminal shows. A `\x1b[2K` can leave holes + // before the cursor, which a terminal paints as blanks. let out = '' - let active = '' - for (const column of columns) { + let active = entrySgr + for (const slot of columns) { + const column = slot ?? { sgr: '', char: ' ' } if (column.sgr !== active) { if (active !== '') out += '\u001b[0m' out += column.sgr @@ -147,21 +202,35 @@ function replayLine(line: string): string { } out += column.char } - return active === '' ? out : `${out}\u001b[0m` + // The state at the line's end continues onto the next line, so it is returned + // rather than closed off with a reset here. + return { text: out, sgr: active } } /** * Replay every line's cursor movements. A `\r` that only terminates a CRLF line * is dropped first, so those lines keep their text instead of being redrawn onto - * themselves. + * themselves. SGR state threads across lines: a newline does not reset it, so a + * run opened before a redraw still colors the lines after it. * @param text - output text, already free of OSC and non-CSI escapes. * @returns the text with each line painted as the terminal would. */ function applyCursorMovements(text: string): string { - return text.split('\n') - .map(raw => raw.replace(/\r+$/, '')) - .map(line => (/[\r\u0008]/.test(line) ? replayLine(line) : line)) - .join('\n') + const replayed: string[] = [] + let sgr = '' + for (const raw of text.split('\n')) { + const line = raw.replace(/\r+$/, '') + // A line with no cursor movement or erase needs no replay — its tabs stay + // literal for `white-space: pre` to lay out — but its own SGR still has to + // be tracked so a later line that DOES replay enters with the right state. + // Tabs only need column arithmetic where a redraw can land on them, which is + // exactly the replayed case. An erase counts: `\x1b[1K` blanks columns even + // with no `\r` beside it. + const result = replayLine(line, sgr) + replayed.push(/\r|\u0008|\u001b\[[0-9]*K/.test(line) ? result.text : line) + sgr = result.sgr + } + return replayed.join('\n') } /** diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index 801484d6a7..e73d741167 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -249,6 +249,72 @@ describe('parseAnsiLines: backspaces', () => { }) }) +describe('parseAnsiLines: erase and column arithmetic', () => { + it('erases the rest of the line, the fixed companion of a redraw', () => { + // Verified in a real terminal: `100%\r\x1b[KOK` shows `OK`. Every spinner and + // progress bar writes `\r\x1b[K`; without the erase the previous frame's tail + // stands and the card shows text the terminal never displayed. + expect(onlySpan(`100%\r${ESC}[KOK`)).toEqual({ text: 'OK', style: undefined }) + // The parameterless form and `0` are the same erase. + expect(onlySpan(`100%\r${ESC}[0KOK`)).toEqual({ text: 'OK', style: undefined }) + }) + + it('erases the whole line for the 2K form and to the cursor for 1K', () => { + expect(onlySpan(`ab\r${ESC}[2Kxy`)).toEqual({ text: 'xy', style: undefined }) + // 1K clears left of the cursor without moving it, so those columns read as + // blanks — verified in a real terminal, which shows ` |` for this input. + expect(onlySpan(`abcd${ESC}[1K|`)).toEqual({ text: ' |', style: undefined }) + }) + + it('paints columns a 2K dropped as blanks when a later write lands past them', () => { + // 2K clears the line but leaves the cursor where it was, so writing there + // leaves the columns before it unwritten — blanks, as a terminal shows. + expect(onlySpan(`abcd${ESC}[2Kx`)).toEqual({ text: ' x', style: undefined }) + }) + + it('advances a redraw cursor by tab stops, leaving a tabbed column standing', () => { + // Verified in a real terminal: `a\tb\rXY` shows `XY b` — the `b` sits at + // column 8, which a two-character redraw cannot reach. Counting the tab as + // one column would have produced `XYb` and destroyed the alignment. + expect(onlySpan('a\tb\rXY')).toEqual({ text: 'XY b', style: undefined }) + }) + + it('counts a wide character as the two columns a terminal advances', () => { + // `中` occupies two cells, so a two-character redraw covers exactly it. + expect(onlySpan('中x\rab')).toEqual({ text: 'abx', style: undefined }) + }) + + it('does not accumulate a cursor or erase sequence into a cell style', () => { + // Only SGR carries graphic state. An erase folded into the style string + // would grow it per redraw and emit boundaries anser has to discard. + expect(parseAnsiLines(`${ESC}[31ma\r${ESC}[Kb`)).toEqual([[ + { text: 'b', style: { color: 'var(--dsw-alias-state-error-primary)' } }, + ]]) + }) +}) + +describe('parseAnsiLines: SGR across lines', () => { + it('carries active state past a newline, as a terminal does', () => { + // Verified in a real terminal: `\x1b[31mabc\rX\nnext` paints BOTH lines red. + // A newline does not reset the graphic state, so a replayed line must hand + // its state to the next one instead of closing it off. + expect(parseAnsiLines(`${ESC}[31mabc\rX\nnext`)).toEqual([ + [{ text: 'Xbc', style: { color: 'var(--dsw-alias-state-error-primary)' } }], + [{ text: 'next', style: { color: 'var(--dsw-alias-state-error-primary)' } }], + ]) + }) + + it('tracks state through a line that needs no replay', () => { + // The middle line has no movement, so it is not replayed — but its own SGR + // still has to reach the line after it. + expect(parseAnsiLines(`a\r${ESC}[32mb\nplain\nc`)).toEqual([ + [{ text: 'b', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + [{ text: 'plain', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + [{ text: 'c', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + ]) + }) +}) + describe('parseAnsiLines: runs spanning lines', () => { it('carries one run\'s style onto every line it covers', () => { expect(parseAnsiLines(sgr('32', 'first\nsecond'))).toEqual([ diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index d1162fcb7f..6b712414c5 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -124,6 +124,17 @@ describe('TerminalBlock states', () => { expect(screen.getByText('无输出')).toBeTruthy() }) + it('treats output that renders nothing visible as empty', () => { + // A lone reset, an OSC title, an erase: all survive `text.trim()` yet parse + // to nothing. Judging emptiness on the raw text drew a box of blank rows + // plus a copy control for invisible bytes, and hid the placeholder. + const view = render() + expect(view.getByText('无输出')).toBeTruthy() + expect(view.queryByText('复制')).toBeNull() + view.rerender() + expect(view.getByText('无输出')).toBeTruthy() + }) + it('merges className onto the wrapper', () => { const view = render() expect(view.container.firstElementChild?.classList.contains('x')).toBe(true) From b588060b90c85d13803a8d49d824a3e4355cc554 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 16:10:37 +0800 Subject: [PATCH 10/14] fix(web): close a run at the line end and count columns correctly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eight findings, each terminal case verified in a real terminal first: `\x1b[32mdone\rok\x1b[0m` then `plain` shows `okne` green and `plain` in the DEFAULT color. The replay returned the last written cell's state, so a reset landing after the final write vanished from both the text and the returned state — and every build tool writes exactly that shape, so the color leaked onto all later output. The replay now converges to the state the scan ended in, which is also what it hands to the next line. `abcd\b\x1b[1K|` shows ` |`: CSI 1K erases THROUGH the cursor column, and the loop stopped before it. The erase mode also reads only the first parameter now, since a terminal treats `1;2K` exactly as `1K`. `éx\rYZ` shows `YZ`: a combining mark takes no column, so it attaches to the cell already written instead of advancing the cursor and leaving the `x` standing. `中x\rA` shows `A x`: overwriting a wide character's lead cell leaves its spacer as a blank rather than closing the gap, which would shift everything after it one column left. The banner lost its span when the gutter became padding — a plain block child only reaches the content box, so the reserved column was painted in the body color and the card's top-left radius drawn in it. Invisible in the light theme, where banner and body share a token; visible in the dark one. The header now pulls back across the gutter and re-insets by the same amount. The replay trigger matches the same CSI shape the parser accepts, so a form like `\x1b[1;2K` can no longer skip its own erase, and `replayLine`'s JSDoc documents its new parameter and returned pair. Docs: four places still described the dot as sitting left of the card surface, which stopped being true when the gutter became the card's own padding, and two fixture comments still referenced the exit marker that was deliberately removed. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 6 +- .../2026-07-28-web-terminal-card.zh.md | 6 +- apps/web/tests/terminal-card.snapshot.ts | 9 ++- .../client/connection/src/client/fixture.ts | 2 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../src/TerminalBlock.module.css | 12 ++- packages/client/ui-primitives/src/ansi.ts | 76 ++++++++++++++----- .../client/ui-primitives/tests/ansi.spec.ts | 41 ++++++++++ 11 files changed, 127 insertions(+), 37 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 14580fce67..7a7f6e3720 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: 3ebbc38a2875a8a3c0fc6c771e282ca7974ad905 -2026-07-28-web-terminal-card.zh.md: 0523b5220a5b856551a95f4a7c36770da21c6906 +2026-07-28-web-terminal-card.md: f580e3c8c17b8701ae223ea3ed910fa57b915278 +2026-07-28-web-terminal-card.zh.md: eb48fd3a1bcff9599b138630113460fe867a6aef diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index 3ebbc38a28..f580e3c8c1 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -20,7 +20,7 @@ The component's contract: - **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter the card reserves as its OWN left padding, so it neither indents its command nor depends on the command's text metrics to line up. The reservation is padding rather than margin because every render site rewrites `margin` wholesale to set its own indent, which silently cancelled a margin-based gutter and let a container clip the dot. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. -- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color, and why SGR state threads from one line to the next rather than closing at each newline. Erase-in-line is part of the same replay, because `\r\x1b[K` is the single idiom every spinner and progress bar writes — modelling the `\r` alone left the previous frame's tail standing, which is text the terminal never showed. Only `m` accumulates into a cell's style; a cursor or erase sequence must not, or the state string grows per redraw and emits boundaries anser has to discard. The cursor advances by terminal columns, so a tab reaches the next 8-column stop and a wide character takes two: `a\tb` then a redraw of `XY` shows `XY b`, since a two-character redraw cannot reach column 8. +- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color, and why SGR state threads from one line to the next rather than closing at each newline. Erase-in-line is part of the same replay, because `\r\x1b[K` is the single idiom every spinner and progress bar writes — modelling the `\r` alone left the previous frame's tail standing, which is text the terminal never showed. Only `m` accumulates into a cell's style; a cursor or erase sequence must not, or the state string grows per redraw and emits boundaries anser has to discard. A run also has to CLOSE: the replay converges to the state the scan ended in, not the last written cell's, because a reset after the final write changes no cell yet ends the run — without that a line finishing in `\x1b[0m` leaked its color onto every later line. The cursor advances by terminal columns, so a tab reaches the next 8-column stop, a wide character takes two (its spacer blanking rather than closing the gap once the lead cell is overwritten), and a combining mark takes none: `a\tb` then a redraw of `XY` shows `XY b`, since a two-character redraw cannot reach column 8. - **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder — judged on the parsed lines the card renders, not on the raw text, since output that is only escapes or control bytes survives a `trim()` yet parses to nothing visible and would otherwise draw blank rows plus a copy control for invisible bytes. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks. @@ -59,9 +59,9 @@ Inline rendering is licensed for the terminal intent alone. A future intent that `packages/client/ui-conversation/tests/terminal-card.spec.tsx` pins the wiring at every render site: `terminalCardModel`'s derivation and each of its null arms, the result title replacing the pending one, the cwd resolving against the session workspace across all four of its cases, the panel resetting the card's expand state when the selection changes, the chat row's expand-gated body against the panel's full-height one, `BashRow`'s resident card and its agreement with its own summary row's state dot, and the panel's Output section including the run_code sub-dispatch and the out-of-window head. That file is written against no gate pressure — `packages/client/ui-conversation/src/*` sits on the coverage `exclude` list in `vitest.config.ts`, so a coverage run over this package measures none of these files. -`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 65 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes, and turn 60's command was made two lines so the built-bundle snapshot pins the per-line prompt and its single dot (`dotsPerPromptRow: [1, 0]`). That terminal turn is ordered BEFORE the todo turn on purpose: the standing plan retires at the next `turn/start`, so appending it after would have emptied the dock's plan strip and taken the todo surfaces' own coverage with it; that turn also carries what turn 60's three clean lines cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit authored beside the sample. The sample's body deliberately carries NO `[exit code: N]` line: the real bash presenter consumes that marker out of the body precisely because the card shows the exit as its own pill, so leaving it in would pin a frame showing the exit twice — one the product path cannot produce. +`apps/web/tests/terminal-card.snapshot.ts` pins the assembled application over the built client bundles: the same render intent at both conversation render sites and in both chat-row shapes, because a bash call reaches a resident card only through the keyed `BashRow` registration and every other terminal-declaring tool name lands on the render-site fallback row, whose body is expand-gated. Fixture turn 65 was named `bash` and turn 60 left as `fx-bash` so one fixture covers both shapes, and turn 60's command was made two lines so the built-bundle snapshot pins the per-line prompt and its single dot (`dotsPerPromptRow: [1, 0]`). That terminal turn is ordered BEFORE the todo turn on purpose: the standing plan retires at the next `turn/start`, so appending it after would have emptied the dock's plan strip and taken the todo surfaces' own coverage with it; that turn also carries what turn 60's two prompt rows cannot — SGR runs resolved to `--dsw-*` tokens, output past the chat cap, a nested cwd, and a non-zero exit authored beside the sample. The sample's body deliberately carries NO `[exit code: N]` line: the real bash presenter consumes that marker out of the body precisely because the card shows the exit as its own pill, so leaving it in would pin a frame showing the exit twice — one the product path cannot produce. -`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet) and starts to the left of the card surface itself, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `terminal-card.expected.md` golden records the resolved workspace in the prompt row, which is what a bash call with no `workdir` must show instead of a bare `$`. +`apps/web/tests/navigation-panes.e2e.ts` adds the real-browser scenario over its existing `echo NAVIGATION_OK` bash call, asserting what jsdom cannot compute: squeezing the output pane below its content width leaves the line at one row and gives the pane horizontal overflow, the run-state dot resolves to the green success token rather than to a literal color (a `--dsw-*` var has no computed value at all without the real theme stylesheet) and sits inside the card box yet left of the prompt label, which is the invariant the gutter padding owns, and the copy control reaches the page's own async Clipboard API rather than the `execCommand` fallback. Its `terminal-card.expected.md` golden records the resolved workspace in the prompt row, which is what a bash call with no `workdir` must show instead of a bare `$`. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index 0523b5220a..eb48fd3a1b 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -20,7 +20,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c - **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片以**自身左内边距**预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。该预留用 padding 而非 margin,是因为每个渲染点都会整条重写 `margin` 来设定自己的缩进——那会静默取消基于 margin 的落区,并让容器把状态点裁掉。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 -- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因,以及 SGR 状态会从一行延续到下一行、而不是在每个换行处关闭的原因。行内擦除属于同一次重放,因为 `\r\x1b[K` 是每个 spinner 与进度条都会写的同一个惯用法——只建模 `\r` 会让上一帧的尾巴留在原处,那是终端从未显示过的文本。只有 `m` 会累加进单元格样式;光标或擦除序列不能累加,否则状态串会随每次重绘线性增长,并发出 anser 只能丢弃的边界。光标按终端列推进,因此制表符前进到下一个 8 列制表位、宽字符占两列:`a\tb` 之后用 `XY` 重绘显示为 `XY b`,因为两个字符的重绘到不了第 8 列。 +- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因,以及 SGR 状态会从一行延续到下一行、而不是在每个换行处关闭的原因。行内擦除属于同一次重放,因为 `\r\x1b[K` 是每个 spinner 与进度条都会写的同一个惯用法——只建模 `\r` 会让上一帧的尾巴留在原处,那是终端从未显示过的文本。只有 `m` 会累加进单元格样式;光标或擦除序列不能累加,否则状态串会随每次重绘线性增长,并发出 anser 只能丢弃的边界。一个分段也必须**收束**:重放收敛到扫描结束时的状态,而不是最后一个被写入单元格的状态——因为最后一次写入之后的 reset 不改变任何单元格,却结束了该分段;没有这一步,以 `\x1b[0m` 结尾的行会把颜色泄漏到其后所有行。光标按终端列推进,因此制表符前进到下一个 8 列制表位、宽字符占两列(其续列在首列被覆盖后变为空白而非合拢),组合标记不占列:`a\tb` 之后用 `XY` 重绘显示为 `XY b`,因为两个字符的重绘到不了第 8 列。 - **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字——该判定读的是卡片实际渲染的解析行,而非原始文本,因为只含转义或控制字节的输出能通过 `trim()` 却解析不出任何可见内容,否则就会画出一片空行外加一个把不可见字节写进剪贴板的复制控件。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。 @@ -59,9 +59,9 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c `packages/client/ui-conversation/tests/terminal-card.spec.tsx` 固定每个渲染点上的接线:`terminalCardModel` 的推导及其每一处 null 分支、结果标题替换待定标题、cwd 针对会话 workspace 解析的全部四种情形、切换选中调用时面板重置卡片展开态、对话行受展开控制的输出体与面板的全高输出体的对比、`BashRow` 的常驻卡片及其与自身摘要行状态点的一致性,以及面板 Output 区段(含 run_code 子派发与超出窗口的调用头)。该文件在没有门禁压力的情况下写成——`packages/client/ui-conversation/src/*` 位于 `vitest.config.ts` 的覆盖率 `exclude` 列表中,因此覆盖率运行不会统计其中任何文件。 -`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 65 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态,并把第 60 轮的命令改为两行,使构建产物快照钉住逐行提示区及其单枚状态点(`dotsPerPromptRow: [1, 0]`)。该终端轮有意排在 todo 轮**之前**:站立计划会在下一次 `turn/start` 时退役,若追加在其后就会让 dock 的计划条变空,并连带毁掉 todo 表面自身的覆盖;该轮还承载第 60 轮三行干净输出无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及在样本旁另行标注的非零退出码。样本正文有意**不含** `[exit code: N]` 行:真实的 bash presenter 正是因为卡片以徽章单独呈现退出状态,才把该标记从正文中消费掉;若保留它,钉住的将是一帧把退出状态显示两次的画面——而产品路径产不出这一帧。 +`apps/web/tests/terminal-card.snapshot.ts` 在构建后的客户端产物上固定组装完整的应用:同一渲染意图在两个对话渲染点、以及两种对话行形态下的表现——因为 bash 调用只有经由带键的 `BashRow` 注册才得到常驻卡片,而其他任何声明 terminal 的工具名都落到渲染点兜底行上,其输出体受展开控制。fixture 第 65 轮改名为 `bash`、第 60 轮保留 `fx-bash`,于是一份 fixture 覆盖两种形态,并把第 60 轮的命令改为两行,使构建产物快照钉住逐行提示区及其单枚状态点(`dotsPerPromptRow: [1, 0]`)。该终端轮有意排在 todo 轮**之前**:站立计划会在下一次 `turn/start` 时退役,若追加在其后就会让 dock 的计划条变空,并连带毁掉 todo 表面自身的覆盖;该轮还承载第 60 轮两个提示行无法覆盖的部分——解析到 `--dsw-*` token 的 SGR 分段、超出对话上限的输出、嵌套 cwd,以及在样本旁另行标注的非零退出码。样本正文有意**不含** `[exit code: N]` 行:真实的 bash presenter 正是因为卡片以徽章单独呈现退出状态,才把该标记从正文中消费掉;若保留它,钉住的将是一帧把退出状态显示两次的画面——而产品路径产不出这一帧。 -`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值),且其起点位于卡片表面本身的左侧;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `terminal-card.expected.md` 基准记录了提示行中已解析的 workspace——这正是不带 `workdir` 的 bash 调用应当显示的内容,而非一个裸 `$`。 +`apps/web/tests/navigation-panes.e2e.ts` 在其既有的 `echo NAVIGATION_OK` bash 调用上新增真实浏览器场景,断言 jsdom 无法计算的部分:把输出面板挤压到窄于内容宽度后,行仍保持单行且面板产生横向溢出;运行状态点解析为绿色的 success token,而不是字面颜色(没有真实主题样式表时,`--dsw-*` 变量根本不产生计算值),且它位于卡片盒之内、提示标签之左——这正是那道 gutter 内边距所拥有的不变量;复制控件走的是页面自身的异步 Clipboard API,而非 `execCommand` 兜底路径。其 `terminal-card.expected.md` 基准记录了提示行中已解析的 workspace——这正是不带 `workdir` 的 bash 调用应当显示的内容,而非一个裸 `$`。 ## Related diff --git a/apps/web/tests/terminal-card.snapshot.ts b/apps/web/tests/terminal-card.snapshot.ts index 3d4d81169c..088a6e8326 100644 --- a/apps/web/tests/terminal-card.snapshot.ts +++ b/apps/web/tests/terminal-card.snapshot.ts @@ -193,10 +193,11 @@ it('renders the keyed bash row with a resident terminal card', async () => { const row = keyedBashRow() const card = row.parentElement?.querySelector('[data-terminal]') if (card === null || card === undefined) throw new Error('keyed bash row has no resident terminal card') - // The prompt shortens the nested cwd to its last segment, the exit pill - // recovers the trailing marker's code, ANSI runs land on theme tokens, and - // the chat cap (8) collapses the middle into a head/tail split with an - // expander between them. + // The prompt shortens the nested cwd to its last segment, the exit pill comes + // from the sample's authored exit status (its body deliberately carries no + // `[exit code: N]` marker, since the real presenter consumes that one), ANSI + // runs land on theme tokens, and the chat cap (8) collapses the middle into a + // head/tail split with an expander between them. expect(readCard(card)).toMatchInlineSnapshot(` { "colors": [ diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index e5a235973f..f4b13f7c99 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -92,7 +92,7 @@ function sgr(code: number, body: string): string { } /** - * Terminal output sample for fixture turn 66, authored to carry every feature + * Terminal output sample for fixture turn 65, authored to carry every feature * the terminal card draws that turn 60's two prompt rows cannot reach: * basic-16 SGR foreground runs (green, red, bright-black) that must resolve to * `--dsw-*` tokens, a bold run, column-aligned table rows that must scroll diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 3e81b076a4..17ef845b9e 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 3e77cb1955972db602b4e751a52a45cf5f5f349d -README.zh.md: 19e02c3e466afcbddd0d19ad6644887d3a53ca10 +README.md: fda45aaea8e6ad640c0002cf34e654d49e63582a +README.zh.md: 94e99b838e102266fb3b5868d3ceb06ae0633b15 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 3e77cb1955..fda45aaea8 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter to the left of the card surface. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage return and backspace replay into a per-line column buffer before inert controls are stripped, since both only move the cursor (so `100%` + CR + `OK` shows `OK0%`), with SGR state stamped per column as a terminal stores it per cell; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage return and backspace replay into a per-line column buffer before inert controls are stripped, since both only move the cursor (so `100%` + CR + `OK` shows `OK0%`), with SGR state stamped per column as a terminal stores it per cell; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 19e02c3e46..94e99b838e 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片表面左侧的落区中。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车与退格在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为两者都只移动光标(所以 `100%` 加回车再加 `OK` 显示为 `OK0%`),且 SGR 状态按列打戳,与终端按单元格存储颜色一致;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车与退格在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为两者都只移动光标(所以 `100%` 加回车再加 `OK` 显示为 `OK0%`),且 SGR 状态按列打戳,与终端按单元格存储颜色一致;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index 8b7cede2fc..704ea0e808 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -30,9 +30,15 @@ display: flex; align-items: flex-start; gap: 12px; - /* No left padding: the card's gutter already insets this row, and the banner - background still has to span the full surface. */ - padding: 9px 14px 9px 0; + /* Pulled back across the card's gutter padding so the banner background and + its top-left radius span the FULL surface, then re-inset by the same amount + so the prompt text and the dot keep their positions. A plain block child + only reaches the content box, which left the gutter column painted in the + body color and drew the card's top-left corner in it — invisible in the + light theme, where banner and body share a token, and visible in the dark + one, where they do not. */ + margin-left: calc(-1 * var(--dsl-terminal-gutter)); + padding: 9px 14px 9px var(--dsl-terminal-gutter); background: var(--dsw-alias-markdown-code-block-banner); border-top-left-radius: var(--dsl-terminal-radius); border-top-right-radius: var(--dsl-terminal-radius); diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index 57c49300f0..9f1adde2f9 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -87,9 +87,24 @@ const NON_CSI_ESCAPE = /\u001b(?!\[)[\u0020-\u002f]*[\u0030-\u007e]?/g */ const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g +/** + * Lines whose cursor movements have to be replayed: a carriage return, a + * backspace, or an erase-in-line. The erase pattern matches the SAME CSI shape + * `replayLine` parses (parameters may carry `;` and intermediate bytes), so a + * form like `\x1b[1;2K` cannot slip past this guard and skip its own erase. + */ +const NEEDS_REPLAY = /\r|\u0008|\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*K/ + /** Terminal tab stop width; a tab advances to the next multiple of this. */ const TAB_WIDTH = 8 +/** + * Combining marks and other zero-width code points: a terminal advances no + * column for them, so `e` + U+0301 occupies one cell and a two-column redraw + * covers both code points. + */ +const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}\u200b-\u200f\u2060]$/u + /** * Characters a terminal advances two columns for: CJK scripts, fullwidth forms, * CJK punctuation, and the emoji/symbol blocks a command's output realistically @@ -129,13 +144,16 @@ function isWide(char: string): boolean { * `ok` overwrote two cells and the third kept the state it was written with. * The columns are re-emitted as runs, so anser sees that same styling. * @param line - one output line, still carrying its CSI sequences. - * @returns the line as the terminal would have it after every movement. + * @param entrySgr - SGR state in force when the line begins, since a newline + * does not reset it. + * @returns the line as the terminal would have it after every movement, plus the + * SGR state at its end for the next line to enter with. */ function replayLine(line: string, entrySgr: string): { text: string; sgr: string } { // Same shape anser splits on, so a sequence is one unit here as well. const csi = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*([\u0040-\u007e])/g /** Per column: the SGR state in force when it was written, and its character. */ - const columns: ({ sgr: string; char: string } | undefined)[] = [] + const columns: ({ sgr: string; char: string; spacer?: boolean } | undefined)[] = [] let cursor = 0 // SGR state accumulates as the line is scanned, exactly as a terminal tracks // it: each cell is stamped with whatever was in force at the moment of the @@ -156,11 +174,20 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string for (; cursor < stop; cursor++) columns[cursor] ??= { sgr, char: ' ' } continue } + if (ZERO_WIDTH.test(char)) { + // No column of its own: it attaches to the cell already written, so a + // redraw that covers that cell covers the mark with it. + const at = Math.max(0, cursor - 1) + const base = columns[at] + if (base !== undefined) columns[at] = { sgr: base.sgr, char: base.char + char } + continue + } columns[cursor] = { sgr, char } cursor++ - // A wide character occupies two columns; the trailing one is a spacer the - // terminal keeps blank, so a later write there cannot split the glyph. - if (isWide(char)) { columns[cursor] = { sgr, char: '' }; cursor++ } + // A wide character occupies two columns; the trailing one is a spacer, + // marked so that overwriting the lead cell leaves a blank behind instead + // of closing the gap and shifting everything after it left. + if (isWide(char)) { columns[cursor] = { sgr, char: '', spacer: true }; cursor++ } } } @@ -174,11 +201,15 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string if (final === 'K') { // Erase in line: the fixed companion of `\r` in every spinner and progress // bar. Without it a shorter redraw leaves the previous frame's tail - // standing, which is text the terminal never showed. `1` blanks the - // columns before the cursor rather than dropping them, since the cursor - // does not move and a later write can still land past them. - if (params === '1') for (let index = 0; index < cursor; index++) columns[index] = { sgr, char: ' ' } - else columns.length = params === '2' ? 0 : cursor + // standing, which is text the terminal never showed. `1` blanks from the + // line start THROUGH the cursor column (inclusive, per the CSI spec) + // rather than dropping those cells, since the cursor does not move and a + // later write can still land past them. + // Only the FIRST parameter selects the mode; a terminal ignores the rest + // (`1;2K` erases exactly as `1K` does — verified against a real terminal). + const mode = params.split(';')[0] ?? '' + if (mode === '1') for (let index = 0; index <= cursor; index++) columns[index] = { sgr, char: ' ' } + else columns.length = mode === '2' ? 0 : cursor continue } // Only SGR carries graphic state; every other final byte is a cursor or @@ -193,18 +224,29 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string // before the cursor, which a terminal paints as blanks. let out = '' let active = entrySgr - for (const slot of columns) { - const column = slot ?? { sgr: '', char: ' ' } + for (let index = 0; index < columns.length; index++) { + const column = columns[index] ?? { sgr: '', char: ' ' } if (column.sgr !== active) { if (active !== '') out += '\u001b[0m' out += column.sgr active = column.sgr } - out += column.char + // A spacer still holds its column. While its lead cell survives, the wide + // glyph spans both and the spacer emits nothing; once a later write replaced + // that lead, the terminal blanks the spacer instead of closing the gap, so + // emitting nothing would shift everything after it one column left. + const leadIntact = index > 0 && isWide(columns[index - 1]?.char ?? '') + out += column.spacer === true && !leadIntact ? ' ' : column.char } - // The state at the line's end continues onto the next line, so it is returned - // rather than closed off with a reset here. - return { text: out, sgr: active } + // Converge to the state the SCAN ended in, not the last written cell's: a + // sequence after the final write (the `\x1b[0m` closing a colored line) changes + // no cell yet still ends the run, and it has to reach both the DOM and the + // next line. Without this a line ending in a reset leaked its color onward. + if (active !== sgr) { + if (active !== '') out += '\u001b[0m' + out += sgr + } + return { text: out, sgr } } /** @@ -227,7 +269,7 @@ function applyCursorMovements(text: string): string { // exactly the replayed case. An erase counts: `\x1b[1K` blanks columns even // with no `\r` beside it. const result = replayLine(line, sgr) - replayed.push(/\r|\u0008|\u001b\[[0-9]*K/.test(line) ? result.text : line) + replayed.push(NEEDS_REPLAY.test(line) ? result.text : line) sgr = result.sgr } return replayed.join('\n') diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index e73d741167..2de9634406 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -293,6 +293,47 @@ describe('parseAnsiLines: erase and column arithmetic', () => { }) }) +describe('parseAnsiLines: line-end state and column widths', () => { + it('closes a run whose reset lands after the last written cell', () => { + // Verified in a real terminal: `\x1b[32mdone\rok\x1b[0m` then `plain` shows + // `okne` GREEN and `plain` in the DEFAULT color. The reset changes no cell, + // so returning the last cell's state leaked green onto every later line — + // and this exact shape (`\r\x1b[K\x1b[32m✓ built\x1b[0m`) is what every + // build tool writes. + expect(parseAnsiLines(`${ESC}[32mdone\rok${ESC}[0m\nplain`)).toEqual([ + [{ text: 'okne', style: { color: 'var(--dsw-alias-state-success-primary)' } }], + [{ text: 'plain', style: undefined }], + ]) + }) + + it('erases through the cursor column for 1K, not up to it', () => { + // Verified in a real terminal: `abcd\b\x1b[1K|` shows ` |` — the `d` under + // the cursor is erased too, which the CSI spec calls inclusive. + expect(onlySpan(`abcd${BS}${ESC}[1K|`)).toEqual({ text: ' |', style: undefined }) + }) + + it('gives a combining mark no column of its own', () => { + // Verified in a real terminal: `é` (e + U+0301) then `x`, redrawn with `YZ`, + // shows `YZ`. Counting the mark as a column left the `x` standing. + expect(onlySpan('e\u0301x\rYZ')).toEqual({ text: 'YZ', style: undefined }) + }) + + it('blanks a wide character\'s spacer once its lead cell is overwritten', () => { + // Verified in a real terminal: `中x` redrawn with `A` shows `A x` — the wide + // glyph's second cell becomes a blank rather than closing the gap, so the + // `x` keeps column 3. + expect(onlySpan('中x\rA')).toEqual({ text: 'A x', style: undefined }) + // Covering both of its columns leaves no spacer behind. + expect(onlySpan('中x\rab')).toEqual({ text: 'abx', style: undefined }) + }) + + it('replays an erase whose parameters carry a semicolon', () => { + // The replay guard has to match the same CSI shape the parser accepts, or a + // form like `\x1b[1;2K` skips the replay and its erase never happens. + expect(onlySpan(`abcd${ESC}[1;2K|`)).toEqual({ text: ' |', style: undefined }) + }) +}) + describe('parseAnsiLines: SGR across lines', () => { it('carries active state past a newline, as a terminal does', () => { // Verified in a real terminal: `\x1b[31mabc\rX\nnext` paints BOTH lines red. From 4145cd7075ecf32a50f4e477768e25aa37257e2c Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 16:20:01 +0800 Subject: [PATCH 11/14] test(web): cover the cursor replay's remaining branches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's coverage gate caught `ansi.ts` at 95.31% branches. My local check had scoped coverage to that one file, which measures a different test set than the gate does — the gate is the authority and it was right. Three branches. Two are now pinned, each verified in a real terminal first: `ab\r` + U+0301 + `x` shows `xb` — the redraw leaves the cursor at column 0, so a combining mark has no cell to attach to and the terminal shows nothing for it. It also revealed that the mark was kept when `cursor` was 0, which is fixed. `ab\rX\x1b[31m` then a plain line shows `Xb` unstyled and the next line RED: the mirror of the reset case, where the scan ends styled while the last cell is not, so the convergence has to OPEN the run at the line end for it to reach the following line. The third was `?? ''` on a `String.split` result, which always yields at least one element — removed rather than tested, since no input can reach it. --- packages/client/ui-primitives/src/ansi.ts | 9 ++++---- .../client/ui-primitives/tests/ansi.spec.ts | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index 9f1adde2f9..a26d1f2dc7 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -177,9 +177,10 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string if (ZERO_WIDTH.test(char)) { // No column of its own: it attaches to the cell already written, so a // redraw that covers that cell covers the mark with it. - const at = Math.max(0, cursor - 1) - const base = columns[at] - if (base !== undefined) columns[at] = { sgr: base.sgr, char: base.char + char } + // With no cell to attach to (line start, or straight after a redraw to + // column 0) a terminal shows nothing rather than a lone accent. + const base = cursor > 0 ? columns[cursor - 1] : undefined + if (base !== undefined) columns[cursor - 1] = { sgr: base.sgr, char: base.char + char } continue } columns[cursor] = { sgr, char } @@ -207,7 +208,7 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string // later write can still land past them. // Only the FIRST parameter selects the mode; a terminal ignores the rest // (`1;2K` erases exactly as `1K` does — verified against a real terminal). - const mode = params.split(';')[0] ?? '' + const mode = String(params.split(';')[0]) if (mode === '1') for (let index = 0; index <= cursor; index++) columns[index] = { sgr, char: ' ' } else columns.length = mode === '2' ? 0 : cursor continue diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index 2de9634406..e06e4a0179 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -9,6 +9,8 @@ import { parseAnsiLines } from '../src/ansi.ts' const ESC = '\u001b' const BS = '\u0008' +/** A combining acute accent: zero-width, so it takes no terminal column. */ +const ACCENT = '\u0301' /** Paint `text` with the SGR `codes`, then reset. */ function sgr(codes: string, text: string): string { @@ -318,6 +320,27 @@ describe('parseAnsiLines: line-end state and column widths', () => { expect(onlySpan('e\u0301x\rYZ')).toEqual({ text: 'YZ', style: undefined }) }) + it('drops a combining mark left with no cell to attach to by a redraw', () => { + // Verified in a real terminal: `ab` then CR then U+0301 then `x` shows `xb`. + // The redraw puts the cursor at column 0, so the mark has no preceding cell + // and the terminal shows nothing for it rather than a lone accent. + expect(onlySpan(`ab\r${ACCENT}x`)).toEqual({ text: 'xb', style: undefined }) + // A mark with no movement on its line never reaches the replay at all: it + // is width business, not a cursor move, so it stays as authored. + expect(onlySpan(`${ACCENT}abc`)).toEqual({ text: `${ACCENT}abc`, style: undefined }) + }) + + it('carries a colour opened after the last write onto the next line', () => { + // The mirror of the reset case, verified in a real terminal: `ab` CR `X` then + // `\x1b[31m` with nothing after it shows `Xb` UNSTYLED and the next line red. + // The scan ends styled while the last cell is not, so the convergence has to + // open the run at the line end for it to reach the following line. + expect(parseAnsiLines(`ab\rX${ESC}[31m\nnext`)).toEqual([ + [{ text: 'Xb', style: undefined }], + [{ text: 'next', style: { color: 'var(--dsw-alias-state-error-primary)' } }], + ]) + }) + it('blanks a wide character\'s spacer once its lead cell is overwritten', () => { // Verified in a real terminal: `中x` redrawn with `A` shows `A x` — the wide // glyph's second cell becomes a blank rather than closing the gap, so the From fdcb45b619896fce2b87d805286d8072dfcdb87e Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 16:42:10 +0800 Subject: [PATCH 12/14] fix(web): bound the SGR state and follow real terminal widths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nine findings, one critical. Terminal cases verified in a real terminal first. CRITICAL: cells held the accumulated SGR history, so every state boundary re-emitted the whole chain — output switching color without a full reset emitted O(n^2) characters. Measured: 3200 such cells produced 25 MB, and the reviewer's ~90 KB alternating-color case is well under bash's own output cap. State is now a normalized record (foreground, background, attribute set) with one canonical sequence per boundary, so the emitted text is linear in cells; the 90 KB case parses in 36 ms. That also makes the attribute closers every chalk-based tool writes actually close: `\x1b[1mbold\x1b[22mplain` leaves the following write PLAIN, which a real terminal confirms. Width follows emoji presentation, not the U+2600-U+27BF block: `A✓B` redrawn with `XY` shows `XYB`, so the check every progress line writes is ONE column. Taking the block as wide misaligned exactly the output this card exists for. Writing over either half of a wide pair blanks the other, since a terminal cannot leave one cell of a two-cell glyph standing. `line\n\x1b[0m` does not end in a newline as a string yet its last parsed line holds nothing visible, so the terminator check now reads the parsed lines — it had added a blank row and inflated the collapse count. A line with no cursor movement no longer builds a column buffer at all; only its SGR is folded, so an `ls -R` or a 5k-line log allocates nothing per character. The `.terminalDescription` rule had been inserted into an existing grouped selector, silently giving `.codeBody` description typography and changing its bottom margin from 4px to 0 — a pre-existing surface this PR does not own. Split out, `.codeBody`'s margin restored. Three comments contradicted their code: the fixture's exit-marker line (still claiming recovery from a marker deliberately removed), `bash-sample`'s header (still routing a click to the details panel, and calling the consumer's cap the block's own), and a DetailsPanel comment stacked above the wrong rule. The ui-primitives README documented only the CR/BS half of the replay, so a reader would expect `OK0%` where `100%\r\x1b[KOK` renders `OK`. --- .../2026-07-28-web-terminal-card.i18n.yaml | 4 +- .../feature/2026-07-28-web-terminal-card.md | 2 +- .../2026-07-28-web-terminal-card.zh.md | 2 +- .../client/connection/src/client/fixture.ts | 6 +- .../src/client/chat/ToolRow.module.css | 14 +- .../client/skeleton/DetailsPanel.module.css | 4 +- .../src/client/toolviews/bash-sample.tsx | 10 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 4 +- packages/client/ui-primitives/README.zh.md | 4 +- .../ui-primitives/src/TerminalBlock.tsx | 16 +- packages/client/ui-primitives/src/ansi.ts | 192 ++++++++++++++---- .../client/ui-primitives/tests/ansi.spec.ts | 69 +++++++ .../tests/terminal-block.spec.tsx | 9 + 14 files changed, 274 insertions(+), 66 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml index 7a7f6e3720..d9ed8345dc 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-web-terminal-card.md -2026-07-28-web-terminal-card.md: f580e3c8c17b8701ae223ea3ed910fa57b915278 -2026-07-28-web-terminal-card.zh.md: eb48fd3a1bcff9599b138630113460fe867a6aef +2026-07-28-web-terminal-card.md: 14896b1d88e5cfd2e4c58830c7a1bca1e54ed823 +2026-07-28-web-terminal-card.zh.md: 16c9004f8f80b720b25b76ba5c04f308b0fccbaf diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md index f580e3c8c1..14896b1d88 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md @@ -20,7 +20,7 @@ The component's contract: - **One run-state dot for the call, on the first row.** `StateDot` in three of its four states: the chase while running, red for the exit status that also renders the pill, green for a clean settle — the same indicator a tool row's leading icon uses, so a row and its own card cannot disagree about one command. The dot exists because the first question a reader has about a shell command is whether it is still running, and without it that had to be inferred from the absence of output — which a settled command producing no output also looks like. It sits out of flow in a gutter the card reserves as its OWN left padding, so it neither indents its command nor depends on the command's text metrics to line up. The reservation is padding rather than margin because every render site rewrites `margin` wholesale to set its own indent, which silently cancelled a margin-based gutter and let a container clip the dot. Exactly one dot, whatever the line count: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per line would assert of a line that succeeded inside a failing call that the line itself failed. The single visually hidden text label carries the same scope, since `StateDot` is `aria-hidden` and one label per row would read to assistive technology as several distinct outcomes. - **No soft wrapping.** Output lines are `white-space: pre` inside a horizontally scrolling box. Column alignment survives; a long line scrolls instead of folding. - **Height cap with an expand control.** Output longer than `DEFAULT_TERMINAL_MAX_LINES` (16) lines shows `ceil(max/2)` head lines plus the remaining tail lines, with a button in between that reports the hidden count and expands. The count is of parsed lines after the trailing output terminator is dropped, so an N-line output ending in a newline is N lines. The split arithmetic is the same as the TUI transcript's collapsed tool card (`packages/ui/tui/src/components/transcript.ts`), so one command's head and tail slices agree between the two front ends. -- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color, and why SGR state threads from one line to the next rather than closing at each newline. Erase-in-line is part of the same replay, because `\r\x1b[K` is the single idiom every spinner and progress bar writes — modelling the `\r` alone left the previous frame's tail standing, which is text the terminal never showed. Only `m` accumulates into a cell's style; a cursor or erase sequence must not, or the state string grows per redraw and emits boundaries anser has to discard. A run also has to CLOSE: the replay converges to the state the scan ended in, not the last written cell's, because a reset after the final write changes no cell yet ends the run — without that a line finishing in `\x1b[0m` leaked its color onto every later line. The cursor advances by terminal columns, so a tab reaches the next 8-column stop, a wide character takes two (its spacer blanking rather than closing the gap once the lead cell is overwritten), and a combining mark takes none: `a\tb` then a redraw of `XY` shows `XY b`, since a two-character redraw cannot reach column 8. +- **ANSI color.** `anser` splits the SGR runs; `ui-primitives/src/ansi.ts` resolves each run into an inline style rendered as React spans. A foreground-only run maps the basic 16 colors onto `--dsw-*` theme tokens so authored color stays legible under both themes; a run that paints its own background keeps anser's literal rgb for both so its intended contrast survives, as do 256-palette, truecolor, and the two basic colors this design system has no token for. Sequences that carry no color (OSC strings, non-CSI escapes, inert C0 controls) are stripped before parsing so they never reach the DOM as literal characters. Cursor movements resolve before that strip, into a per-line column buffer rather than by string surgery, because carriage return and backspace only MOVE the cursor — neither erases anything, so what a reader sees is whatever each column last had written to it. `100%` then a carriage return and `OK` shows `OK0%`, since the redraw is shorter than the frame beneath it; a trailing `abc` plus a backspace still shows `abc`, since nothing overwrote the `c`; `abc` plus two backspaces and `XY` shows `aXY`. Each of these was checked against a real terminal, because the earlier truncate-and-delete approximations looked right and were not. SGR state is stamped per column as a terminal stores it per cell, so a partial overwrite keeps each surviving character's own color: red `bad`, three backspaces, then `ok` shows `okd` with the `d` still red. A CSI sequence occupies no column and changes only the state later writes are stamped with, which is also why a carriage return does not reset color, and why SGR state threads from one line to the next rather than closing at each newline. Erase-in-line is part of the same replay, because `\r\x1b[K` is the single idiom every spinner and progress bar writes — modelling the `\r` alone left the previous frame's tail standing, which is text the terminal never showed. Only `m` accumulates into a cell's style; a cursor or erase sequence must not, or the state string grows per redraw and emits boundaries anser has to discard. SGR is held per cell as a NORMALIZED record (foreground, background, attribute set), not as the sequence history: accumulating raw sequences made every state boundary re-emit the whole chain, so output that switches color without a full reset emitted O(n^2) characters — 3200 such cells produced 25 MB and a `RangeError` well under bash's own output cap. The record also lets the attribute closers every chalk-based tool writes (`39`, `49`, `22`, `24`, …) actually close their attribute, and each boundary emits one canonical sequence for the state it opens. A run also has to CLOSE: the replay converges to the state the scan ended in, not the last written cell's, because a reset after the final write changes no cell yet ends the run — without that a line finishing in `\x1b[0m` leaked its color onto every later line. The cursor advances by terminal columns, so a tab reaches the next 8-column stop, a wide character takes two (its spacer blanking rather than closing the gap once the lead cell is overwritten), and a combining mark takes none. Width follows emoji PRESENTATION rather than the U+2600-U+27BF block: `\u2713`, the check every progress line writes, is one column, so treating the block as wide misaligned exactly the output this card exists for. Writing over either half of a wide pair blanks the other, since a terminal cannot leave one cell of a two-cell glyph standing: `a\tb` then a redraw of `XY` shows `XY b`, since a two-character redraw cannot reach column 8. - **Exit status and copy.** A non-zero exit code or a signal renders a status pill, matching the exit-status distinction the bash tool's own renderer draws; a clean exit renders none, and settled empty output renders a dimmed placeholder — judged on the parsed lines the card renders, not on the raw text, since output that is only escapes or control bytes survives a `trim()` yet parses to nothing visible and would otherwise draw blank rows plus a copy control for invisible bytes. The copy control copies the raw output text, not the rendered tree, so the prompt line and the pill stay out of the clipboard. Geometry, radius, and fonts mirror `CodeBlock`, so a terminal card and a fenced code block match visually; `white-space: pre` plus horizontal scroll is the deliberate divergence. The clipboard write both components need moved out of `CodeBlock` into a package-internal `src/clipboard.ts`, unexported so it stays an implementation detail of the two blocks. diff --git a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md index eb48fd3a1b..16c9004f8f 100644 --- a/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md @@ -20,7 +20,7 @@ Web client 却对它视而不见。`packages/client/ui-conversation/src/client/c - **整次调用一枚运行状态点,位于第一行。** 它是 `StateDot` 四种状态中的三种:运行期间为追逐动画,与渲染状态徽章相同的退出状态为红色,干净落定为绿色——与工具行行首图标使用同一个指示器,因此一行与其自身的卡片不可能对同一条命令产生分歧。该状态点存在的理由是:读者对一条 shell 命令的第一个问题就是它是否仍在运行;没有它时,这一点只能从「没有输出」推断,而一条落定后无输出的命令看起来也一样。它以脱离文档流的方式落在卡片以**自身左内边距**预留的落区里,因此既不会缩进其命令,也不依赖命令自身的文本度量来与之对齐。该预留用 padding 而非 margin,是因为每个渲染点都会整条重写 `margin` 来设定自己的缩进——那会静默取消基于 margin 的落区,并让容器把状态点裁掉。无论有多少行,都只有一枚:视图携带的退出状态属于整次调用,而 bash 不报告逐条命令的状态,因此每行一枚状态点就等于在断言——一条在失败调用中其实成功了的命令行自身失败了。那一处视觉隐藏的文本标签具有相同的作用域,因为 `StateDot` 是 `aria-hidden`,而每行一个标签会被辅助技术读成好几个各自独立的结果。 - **不软换行。** 输出行使用 `white-space: pre`,置于横向滚动的容器内。列对齐得以保留;长行滚动,而非折行。 - **高度上限与展开控件。** 输出超过 `DEFAULT_TERMINAL_MAX_LINES`(16)行时,显示 `ceil(max/2)` 行首部加余下的尾部行数,中间是一个按钮,报告被隐藏的行数并可展开。计数针对的是剥除输出末尾终止符之后解析出的行,因此以换行结尾的 N 行输出就是 N 行。切分算法与 TUI transcript 折叠态工具卡片(`packages/ui/tui/src/components/transcript.ts`)完全一致,因此同一条命令的首尾切片在两个前端之间吻合。 -- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因,以及 SGR 状态会从一行延续到下一行、而不是在每个换行处关闭的原因。行内擦除属于同一次重放,因为 `\r\x1b[K` 是每个 spinner 与进度条都会写的同一个惯用法——只建模 `\r` 会让上一帧的尾巴留在原处,那是终端从未显示过的文本。只有 `m` 会累加进单元格样式;光标或擦除序列不能累加,否则状态串会随每次重绘线性增长,并发出 anser 只能丢弃的边界。一个分段也必须**收束**:重放收敛到扫描结束时的状态,而不是最后一个被写入单元格的状态——因为最后一次写入之后的 reset 不改变任何单元格,却结束了该分段;没有这一步,以 `\x1b[0m` 结尾的行会把颜色泄漏到其后所有行。光标按终端列推进,因此制表符前进到下一个 8 列制表位、宽字符占两列(其续列在首列被覆盖后变为空白而非合拢),组合标记不占列:`a\tb` 之后用 `XY` 重绘显示为 `XY b`,因为两个字符的重绘到不了第 8 列。 +- **ANSI 颜色。** `anser` 切分 SGR 分段;`ui-primitives/src/ansi.ts` 把每段解析为内联样式,渲染成 React span。只设前景色的分段把基本 16 色映射到 `--dsw-*` 主题 token,使作者指定的颜色在两种主题下都可读;自行绘制背景的分段则前后景都保留 anser 给出的字面 rgb,以保住它意图中的对比度,256 色板、truecolor 以及本设计系统没有对应 token 的两种基本色同样如此。不承载颜色的转义序列(OSC 串、非 CSI 转义、无显示意义的 C0 控制符)在解析前被剥除,因此绝不会以字面字符抵达 DOM。光标移动在该剥除之前先行结算,且落在逐行的列缓冲里而不是靠字符串手术,因为回车与退格**只移动**光标——两者都不擦除任何东西,所以读者看到的就是每一列最后被写入的内容。`100%` 后接回车再接 `OK` 显示为 `OK0%`,因为这次重绘比它下面的帧更短;末尾 `abc` 加一个退格仍显示 `abc`,因为没有任何东西覆盖过那个 `c`;`abc` 加两个退格再接 `XY` 显示 `aXY`。这些用例都对照真实终端核实过,因为先前「截断加删除」的近似看起来是对的,实际并不对。SGR 状态按列打戳,与终端按单元格存储颜色的方式一致,因此部分覆盖会保留每个存活字符自身的颜色:红色 `bad`、三个退格、再写 `ok`,显示为 `okd` 且那个 `d` 仍是红的。CSI 序列不占列,只改变后续写入被打上的状态——这也正是回车不会重置颜色的原因,以及 SGR 状态会从一行延续到下一行、而不是在每个换行处关闭的原因。行内擦除属于同一次重放,因为 `\r\x1b[K` 是每个 spinner 与进度条都会写的同一个惯用法——只建模 `\r` 会让上一帧的尾巴留在原处,那是终端从未显示过的文本。只有 `m` 会累加进单元格样式;光标或擦除序列不能累加,否则状态串会随每次重绘线性增长,并发出 anser 只能丢弃的边界。SGR 按单元格以**归一化记录**保存(前景、背景、属性集合),而不是序列历史:累积原始序列会让每个状态边界重新发射整条链,因此不做完整 reset 的换色输出会发射 O(n^2) 个字符——3200 个这样的单元格产生 25 MB 并最终 `RangeError`,远低于 bash 自身的输出上限。该记录也让所有 chalk 系工具写出的属性闭合码(`39`、`49`、`22`、`24` 等)真正闭合其属性,且每个边界只为它开启的状态发射一条规范序列。一个分段也必须**收束**:重放收敛到扫描结束时的状态,而不是最后一个被写入单元格的状态——因为最后一次写入之后的 reset 不改变任何单元格,却结束了该分段;没有这一步,以 `\x1b[0m` 结尾的行会把颜色泄漏到其后所有行。光标按终端列推进,因此制表符前进到下一个 8 列制表位、宽字符占两列(其续列在首列被覆盖后变为空白而非合拢),组合标记不占列。宽度依据 emoji **presentation** 而非 U+2600–U+27BF 整个区块:`\u2713`——每条进度行都会写的对勾——只占一列,把该区块整体当作双宽恰好会错位这张卡片赖以存在的那类输出。写入宽字符对的任一半都会把另一半清成空白,因为终端无法让一个双格字形只留下一格:`a\tb` 之后用 `XY` 重绘显示为 `XY b`,因为两个字符的重绘到不了第 8 列。 - **退出状态与复制。** 非零退出码或信号渲染一枚状态徽章,与 bash 工具自身渲染器所作的退出状态区分一致;干净退出不渲染徽章,落定后的空输出渲染一处变暗的占位文字——该判定读的是卡片实际渲染的解析行,而非原始文本,因为只含转义或控制字节的输出能通过 `trim()` 却解析不出任何可见内容,否则就会画出一片空行外加一个把不可见字节写进剪贴板的复制控件。复制控件复制的是原始输出文本而非渲染后的树,因此提示符行与徽章不会进入剪贴板。 几何尺寸、圆角与字体沿用 `CodeBlock`,因此终端卡片与围栏代码块在视觉上一致;`white-space: pre` 加横向滚动是有意的分歧。两个组件都需要的剪贴板写入从 `CodeBlock` 中提取到包内部的 `src/clipboard.ts`,不对外导出,因此它仍是这两个块的实现细节。 diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index f4b13f7c99..68d3374291 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -284,8 +284,10 @@ function buildAlphaLog(): SessionEvent[] { ] // Turn 65: the terminal sample turn 60's two clean prompt rows cannot cover — // ANSI SGR coloring, output past the terminal card's height cap, a nested cwd - // whose prompt label is its last segment, and a non-zero exit recovered from - // the trailing marker the bash tool appends. Named `bash`, so it also covers + // whose prompt label is its last segment, and a non-zero exit authored beside + // the sample in TERMINAL_EXIT_STATUS — its body deliberately carries no + // `[exit code: N]` marker, since the real presenter consumes that one out of + // the body. Named `bash`, so it also covers // the keyed toolview row (turn 60's `fx-bash` covers the render-site fallback // row) — the two chat-row shapes the terminal card renders in. // diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css index 0c1f674262..4ff289388e 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css @@ -182,14 +182,16 @@ button.leading { also replaces each primitive's own standalone vertical spacing with the flow's row rhythm. */ .codeBody, -/* Indented to the terminal body's own column, so the description reads as the - card's heading rather than as another summary row. */ +.terminalBody { + margin: 4px 0 4px 22px; +} + +/* Indented to the body's own column so the description reads as the card's + heading rather than as another summary row, and sits tight against the card + below it. Its own rule: grouping it with a body would put description + typography on a `CodeBlock` wrapper and change that body's spacing. */ .terminalDescription { margin: 4px 0 0 22px; color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xs-13); } - -.terminalBody { - margin: 4px 0 4px 22px; -} diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css index 0ddc58e30b..143174fe42 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css @@ -93,8 +93,6 @@ color: var(--dsw-alias-state-error-primary); } -/* The terminal card sits directly under its section label, so it drops the - primitive's standalone vertical margin; the section owns the spacing. */ /* Above the card, which is where the render-intent contract puts a terminal call's description; the panel has no summary row to carry it. */ .terminalDescription { @@ -103,6 +101,8 @@ font: var(--dsw-font-xs-13); } +/* The terminal card sits directly under its section label, so it drops the + primitive's standalone vertical margin; the section owns the spacing. */ .terminal { margin: 0; } diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx index 1e6e9183fc..c9385cab04 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx @@ -6,10 +6,12 @@ // // A bash call declares the terminal render intent, so this row also renders // the command's own output through TerminalBlock. This row has no expand -// control (a click goes to the details panel), so its terminal body is -// resident rather than expand-gated as in ToolRow; the block's own height cap -// (CHAT_TERMINAL_MAX_LINES) and internal expander keep a long output from -// taking over the message flow. +// control and is not a details-panel target either (tool rows stopped being +// one), so its terminal body is resident rather than expand-gated as in +// ToolRow, and the card's own copy and expand controls are the row's only +// interactions. CHAT_TERMINAL_MAX_LINES is passed as `maxLines` — the chat +// flow's tighter cap over the block's own default of 16 — and the block's +// internal expander keeps a long output from taking over the message flow. import type { Context } from 'cordis' import { IconApiOutline14, StateDot, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 17ef845b9e..9c58403c04 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: fda45aaea8e6ad640c0002cf34e654d49e63582a -README.zh.md: 94e99b838e102266fb3b5868d3ceb06ae0633b15 +README.md: 1236054d5a05464c43ad1bb0dcbe52b09281e68a +README.zh.md: 51d3c7a3f3dd46e487a3031cfa1f3d93bace336a diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index fda45aaea8..1236054d5a 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -10,7 +10,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Terminal output -`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; carriage return and backspace replay into a per-line column buffer before inert controls are stripped, since both only move the cursor (so `100%` + CR + `OK` shows `OK0%`), with SGR state stamped per column as a terminal stores it per cell; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; cursor movements replay into a per-line column buffer before inert controls are stripped, since carriage return and backspace only MOVE the cursor: `100%` + CR + `OK` alone shows `OK0%`, while the `\x1b[K` a spinner writes with its redraw erases the tail so `100%\r\x1b[KOK` shows `OK`. Erase-in-line is honored in all three parameter forms, the cursor advances by terminal columns (8-column tab stops, two for emoji and CJK, none for a combining mark), and SGR state is normalized per cell as a terminal stores it, threading across lines and closing at the state the line ended in; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). ## Model Experience @@ -26,4 +26,4 @@ None; this package neither assembles nor sends a provider request. - **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms. - **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface. - **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, and `CodeBlock`'s copy control are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. -- **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, while cursor movement, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb. +- **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, and so are the in-line cursor movements a progress line uses — carriage return, backspace, erase-in-line, tab stops and character width. Absolute cursor positioning, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 94e99b838e..51d3c7a3f3 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -10,7 +10,7 @@ ## 终端输出 -`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;回车与退格在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为两者都只移动光标(所以 `100%` 加回车再加 `OK` 显示为 `OK0%`),且 SGR 状态按列打戳,与终端按单元格存储颜色一致;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;光标移动在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为回车与退格**只移动**光标:单是 `100%` 加回车再加 `OK` 显示为 `OK0%`,而 spinner 随重绘写出的 `\x1b[K` 会擦掉尾巴,因此 `100%\r\x1b[KOK` 显示为 `OK`。行内擦除的三种参数形式都被遵循,光标按终端列推进(8 列制表位;emoji 与 CJK 占两列;组合标记不占列),SGR 状态按单元格归一化存储,与终端一致,并跨行延续、在行结束时的状态处收束;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 ## 模型体验 @@ -26,4 +26,4 @@ - **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。 - **StateDot 的 `Active` 变体是设计中的隐藏占位符**:尚未实现;已交付的四种状态(done/warning/ongoing/error)构成完整的 P-I 表层。 - **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件,以及 `CodeBlock` 的复制控件全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 -- **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,而光标移动、清屏和备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。 +- **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,进度行所用的行内光标移动同样被遵循——回车、退格、行内擦除、制表位与字符宽度。绝对光标定位、清屏与备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。 diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index 1d56050b3c..c707711f69 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -126,9 +126,19 @@ export function TerminalBlock({ }: TerminalBlockProps) { const text = output ?? '' // A command's output ends with a newline; that terminator is not an extra - // blank line to draw or to count against the height cap. The copy control - // still copies `text` untouched. - const lines = useMemo(() => parseAnsiLines(text.endsWith('\n') ? text.slice(0, -1) : text), [text]) + // blank line to draw or to count against the height cap. The check runs on the + // PARSED lines rather than on the raw text, because a reset after the final + // newline (`line\n\x1b[0m`) leaves the string not ending in one while still + // producing a last line with nothing visible in it. A genuinely blank final + // line — the double newline — survives, since it has a real empty line before + // the terminator. The copy control still copies `text` untouched. + const lines = useMemo(() => { + const parsed = parseAnsiLines(text) + const last = parsed[parsed.length - 1] + const terminated = parsed.length > 1 && last !== undefined + && last.every(span => span.text === '') + return terminated ? parsed.slice(0, -1) : parsed + }, [text]) const [expanded, setExpanded] = useState(false) const [copied, setCopied] = useState(false) diff --git a/packages/client/ui-primitives/src/ansi.ts b/packages/client/ui-primitives/src/ansi.ts index a26d1f2dc7..9eeba29e12 100644 --- a/packages/client/ui-primitives/src/ansi.ts +++ b/packages/client/ui-primitives/src/ansi.ts @@ -95,6 +95,9 @@ const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g */ const NEEDS_REPLAY = /\r|\u0008|\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*K/ +/** SGR sequences alone, for folding state through a line that needs no replay. */ +const SGR_SEQUENCE = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*m/g + /** Terminal tab stop width; a tab advances to the next multiple of this. */ const TAB_WIDTH = 8 @@ -107,12 +110,18 @@ const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}\u200b-\u200f\u2060]$/u /** * Characters a terminal advances two columns for: CJK scripts, fullwidth forms, - * CJK punctuation, and the emoji/symbol blocks a command's output realistically - * carries. + * CJK punctuation, and characters with emoji presentation. Text-presentation + * symbols (`\u2713`, `\u26a0` and the rest of U+2600-U+27BF) are ONE column and + * must stay out of this set. */ const WIDE_CHAR = new RegExp( '\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}' - + '|[\\u{1f300}-\\u{1faff}\\u{2600}-\\u{27bf}\\uff01-\\uff60\\u3000-\\u303e]', + // Emoji presentation only: the U+2600-U+27BF symbol block is mostly SINGLE + // width — `\u2713` (the check every progress line writes, this fixture + // included) advances one column, verified against a real terminal, so taking + // the whole block as wide misaligned exactly the output this card exists for. + + '|\\p{Emoji_Presentation}' + + '|[\\uff01-\\uff60\\u3000-\\u303e]', 'u', ) @@ -129,6 +138,87 @@ function isWide(char: string): boolean { return WIDE_CHAR.test(char) } +/** + * A cell's graphic state, normalized. Held as fields rather than as the raw + * sequence history because a terminal tracks CURRENT state, not a transcript: + * accumulating sequences made each state boundary re-emit the whole chain, so + * output that switches color without a full reset emitted O(n^2) characters + * (3200 such cells produced 25 MB and eventually a `RangeError`). It also makes + * the attribute closers every chalk-based tool writes — `39`, `49`, `22`, `23`, + * `24`, `27`, `29` — actually close their attribute instead of appending to it. + */ +interface SgrState { + fg: string + bg: string + /** Attribute parameters in force, e.g. `1` (bold) or `4` (underline). */ + attrs: readonly string[] +} + +/** The default state: no color, no attributes. */ +const SGR_NONE: SgrState = { fg: '', bg: '', attrs: [] } + +/** Attribute closers, mapped to the opener parameters each one turns off. */ +const ATTR_CLOSERS: Record = { + 22: ['1', '2'], 23: ['3'], 24: ['4'], 25: ['5', '6'], 27: ['7'], 28: ['8'], 29: ['9'], +} + +/** + * Fold one SGR sequence's parameters into the state it produces. + * @param state - state in force before the sequence. + * @param params - the sequence's raw parameter string (`31`, `1;4`, `38;5;208`). + * @returns the state the sequence leaves in force. + */ +function foldSgr(state: SgrState, params: string): SgrState { + const codes = params === '' ? ['0'] : params.split(';') + let next = state + for (let index = 0; index < codes.length; index++) { + const code = String(codes[index]) + if (code === '' || code === '0') { next = SGR_NONE; continue } + // Extended color: `38;5;N` / `38;2;R;G;B` and the `48` background pair + // consume their own arguments, so they are taken whole. + if (code === '38' || code === '48') { + const kind = codes[index + 1] ?? '' + const span = kind === '2' ? 4 : kind === '5' ? 2 : 0 + const value = codes.slice(index, index + span + 1).join(';') + next = code === '38' ? { ...next, fg: value } : { ...next, bg: value } + index += span + continue + } + const closes = ATTR_CLOSERS[code] + if (closes !== undefined) { + next = { ...next, attrs: next.attrs.filter(attr => !closes.includes(attr)) } + continue + } + const numeric = Number(code) + if (code === '39') { next = { ...next, fg: '' }; continue } + if (code === '49') { next = { ...next, bg: '' }; continue } + if ((numeric >= 30 && numeric <= 37) || (numeric >= 90 && numeric <= 97)) { next = { ...next, fg: code }; continue } + if ((numeric >= 40 && numeric <= 47) || (numeric >= 100 && numeric <= 107)) { next = { ...next, bg: code }; continue } + if (!next.attrs.includes(code)) next = { ...next, attrs: [...next.attrs, code] } + } + return next +} + +/** + * Render a state as the one canonical sequence that establishes it from the + * default, so a boundary emits a bounded string no matter how the state was + * reached. + * @param state - the state to open. + * @returns the SGR sequence, or the empty string for the default state. + */ +function openSgr(state: SgrState): string { + const codes = [...state.attrs] + if (state.fg !== '') codes.push(state.fg) + if (state.bg !== '') codes.push(state.bg) + return codes.length === 0 ? '' : `\u001b[${codes.join(';')}m` +} + +/** Whether two states are the same, so a boundary is only emitted on a change. */ +function sameSgr(a: SgrState, b: SgrState): boolean { + return a.fg === b.fg && a.bg === b.bg && a.attrs.length === b.attrs.length + && a.attrs.every((attr, index) => attr === b.attrs[index]) +} + /** * Replay one line's cursor movements the way a terminal paints it, into a * column buffer. Carriage return and backspace only MOVE the cursor — neither @@ -149,19 +239,29 @@ function isWide(char: string): boolean { * @returns the line as the terminal would have it after every movement, plus the * SGR state at its end for the next line to enter with. */ -function replayLine(line: string, entrySgr: string): { text: string; sgr: string } { +function replayLine(line: string, entrySgr: SgrState): { text: string; sgr: SgrState } { // Same shape anser splits on, so a sequence is one unit here as well. const csi = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*([\u0040-\u007e])/g - /** Per column: the SGR state in force when it was written, and its character. */ - const columns: ({ sgr: string; char: string; spacer?: boolean } | undefined)[] = [] + /** Per column: the state in force when it was written, and its character. */ + const columns: (Cell | undefined)[] = [] let cursor = 0 - // SGR state accumulates as the line is scanned, exactly as a terminal tracks - // it: each cell is stamped with whatever was in force at the moment of the - // write, so a later redraw cannot restyle the cells it does not reach. It - // enters carrying the previous line's state, since a newline does not reset it. + // State is tracked exactly as a terminal tracks it: each cell is stamped with + // whatever was in force at the moment of the write, so a later redraw cannot + // restyle the cells it does not reach. It enters carrying the previous line's + // state, since a newline does not reset it. let sgr = entrySgr let at = 0 + /** Clear a cell and, for a wide pair, its partner: a terminal erases both. */ + const clear = (index: number, fill: string): void => { + const cell = columns[index] + if (cell?.spacer === true && index > 0) columns[index - 1] = { sgr, char: fill } + else if (cell !== undefined && isWide(cell.char) && columns[index + 1]?.spacer === true) { + columns[index + 1] = { sgr, char: fill } + } + columns[index] = { sgr, char: fill } + } + const consume = (chunk: string): void => { for (const char of chunk) { if (char === '\r') { cursor = 0; continue } @@ -176,13 +276,16 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string } if (ZERO_WIDTH.test(char)) { // No column of its own: it attaches to the cell already written, so a - // redraw that covers that cell covers the mark with it. - // With no cell to attach to (line start, or straight after a redraw to - // column 0) a terminal shows nothing rather than a lone accent. + // redraw that covers that cell covers the mark with it. With no cell to + // attach to (line start, or straight after a redraw to column 0) a + // terminal shows nothing rather than a lone accent. const base = cursor > 0 ? columns[cursor - 1] : undefined if (base !== undefined) columns[cursor - 1] = { sgr: base.sgr, char: base.char + char } continue } + // Writing over either half of a wide pair blanks the other half, since a + // terminal cannot leave one cell of a two-cell glyph standing. + clear(cursor, ' ') columns[cursor] = { sgr, char } cursor++ // A wide character occupies two columns; the trailing one is a spacer, @@ -205,31 +308,31 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string // standing, which is text the terminal never showed. `1` blanks from the // line start THROUGH the cursor column (inclusive, per the CSI spec) // rather than dropping those cells, since the cursor does not move and a - // later write can still land past them. - // Only the FIRST parameter selects the mode; a terminal ignores the rest - // (`1;2K` erases exactly as `1K` does — verified against a real terminal). + // later write can still land past them. Only the FIRST parameter selects + // the mode; a terminal ignores the rest (`1;2K` erases exactly as `1K`). const mode = String(params.split(';')[0]) - if (mode === '1') for (let index = 0; index <= cursor; index++) columns[index] = { sgr, char: ' ' } + if (mode === '1') for (let index = 0; index <= cursor; index++) clear(index, ' ') else columns.length = mode === '2' ? 0 : cursor continue } // Only SGR carries graphic state; every other final byte is a cursor or - // erase action that must not be accumulated into a cell's style. + // erase action that must not affect a cell's style. if (final !== 'm') continue - sgr = /^0?$/.test(params) ? '' : sgr + match[0] + sgr = foldSgr(sgr, params) } consume(line.slice(at)) - // Re-emit the columns, opening a run only where its SGR state changes, so - // anser sees the same styling a terminal shows. A `\x1b[2K` can leave holes - // before the cursor, which a terminal paints as blanks. + // Re-emit the columns, opening a run only where its state changes, so anser + // sees the same styling a terminal shows. Each boundary emits ONE canonical + // sequence for the state it opens, which is what keeps the output linear in + // the number of cells however the state was reached. let out = '' let active = entrySgr for (let index = 0; index < columns.length; index++) { - const column = columns[index] ?? { sgr: '', char: ' ' } - if (column.sgr !== active) { - if (active !== '') out += '\u001b[0m' - out += column.sgr + const column = columns[index] ?? { sgr: SGR_NONE, char: ' ' } + if (!sameSgr(column.sgr, active)) { + if (!sameSgr(active, SGR_NONE)) out += '\u001b[0m' + out += openSgr(column.sgr) active = column.sgr } // A spacer still holds its column. While its lead cell survives, the wide @@ -243,13 +346,21 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string // sequence after the final write (the `\x1b[0m` closing a colored line) changes // no cell yet still ends the run, and it has to reach both the DOM and the // next line. Without this a line ending in a reset leaked its color onward. - if (active !== sgr) { - if (active !== '') out += '\u001b[0m' - out += sgr + if (!sameSgr(active, sgr)) { + if (!sameSgr(active, SGR_NONE)) out += '\u001b[0m' + out += openSgr(sgr) } return { text: out, sgr } } +/** One replayed column: the state it was written with, and its character. */ +interface Cell { + sgr: SgrState + char: string + /** The trailing half of a wide character's two-column pair. */ + spacer?: boolean +} + /** * Replay every line's cursor movements. A `\r` that only terminates a CRLF line * is dropped first, so those lines keep their text instead of being redrawn onto @@ -260,18 +371,21 @@ function replayLine(line: string, entrySgr: string): { text: string; sgr: string */ function applyCursorMovements(text: string): string { const replayed: string[] = [] - let sgr = '' + let sgr = SGR_NONE for (const raw of text.split('\n')) { const line = raw.replace(/\r+$/, '') - // A line with no cursor movement or erase needs no replay — its tabs stay - // literal for `white-space: pre` to lay out — but its own SGR still has to - // be tracked so a later line that DOES replay enters with the right state. - // Tabs only need column arithmetic where a redraw can land on them, which is - // exactly the replayed case. An erase counts: `\x1b[1K` blanks columns even - // with no `\r` beside it. - const result = replayLine(line, sgr) - replayed.push(NEEDS_REPLAY.test(line) ? result.text : line) - sgr = result.sgr + if (NEEDS_REPLAY.test(line)) { + const result = replayLine(line, sgr) + replayed.push(result.text) + sgr = result.sgr + continue + } + // No cursor movement: the line needs no column buffer, and painting one + // would allocate a cell per character of output this card never redraws — + // an `ls -R` or a 5k-line log. Only its own SGR has to be folded, so a later + // line that DOES replay enters with the right state. + replayed.push(line) + for (const match of line.matchAll(SGR_SEQUENCE)) sgr = foldSgr(sgr, String(match[1])) } return replayed.join('\n') } diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index e06e4a0179..d3efd5ffb3 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -357,6 +357,75 @@ describe('parseAnsiLines: line-end state and column widths', () => { }) }) +describe('parseAnsiLines: bounded state and true widths', () => { + it('emits one canonical sequence per boundary however the state was reached', () => { + // Colors that never fully reset used to accumulate raw sequence history per + // cell, so every boundary re-emitted the whole chain: 3200 such cells + // produced 25 MB and eventually a RangeError. The state is normalized now, + // so the emitted text stays linear in the number of cells. + let input = '' + for (let index = 0; index < 2000; index += 1) input += `${ESC}[3${index % 6 + 1}mx` + const emitted = parseAnsiLines(`${input}\rz`)[0] ?? [] + expect(emitted.reduce((total, span) => total + span.text.length, 0)).toBe(2000) + }) + + it('closes an attribute with its closer instead of appending to the state', () => { + // `1` then `22` is bold then not-bold, which every chalk-based tool writes; + // appending both left the cell bold and grew the chain. + // Verified in a real terminal: the `22` closes the bold, so the `x` written + // after the redraw is PLAIN. Appending both left it bold and grew the chain. + expect(parseAnsiLines(`${ESC}[1mbold${ESC}[22mplain\r${ESC}[Kx`)).toEqual([[ + { text: 'x', style: undefined }, + ]]) + expect(parseAnsiLines(`${ESC}[1mA${ESC}[22mB`)).toEqual([[ + { text: 'A', style: { fontWeight: 700 } }, + { text: 'B', style: undefined }, + ]]) + }) + + it('folds extended colors, backgrounds and every attribute closer', () => { + // The 256-palette and truecolor forms consume their own arguments, so the + // fold has to take them whole rather than as separate codes. + expect(parseAnsiLines(`${ESC}[38;5;208mA\r${ESC}[KB`)).toEqual([[ + { text: 'B', style: { color: 'rgb(255, 135, 0)' } }, + ]]) + expect(parseAnsiLines(`${ESC}[38;2;10;20;30mA\r${ESC}[KB`)).toEqual([[ + { text: 'B', style: { color: 'rgb(10, 20, 30)' } }, + ]]) + // A background survives the same way, and `49` closes it. + expect(parseAnsiLines(`${ESC}[41mA${ESC}[49mB\r${ESC}[KC`)).toEqual([[ + { text: 'C', style: undefined }, + ]]) + // Each closer drops only its own attribute: `4` underline closed by `24` + // while the italic opened before it stays in force. + expect(parseAnsiLines(`${ESC}[3;4mA${ESC}[24mB\r${ESC}[KC`)).toEqual([[ + { text: 'C', style: { fontStyle: 'italic' } }, + ]]) + // `39` closes a foreground without touching the background. + expect(parseAnsiLines(`${ESC}[31;42mA${ESC}[39mB\r${ESC}[KC`)).toEqual([[ + { text: 'C', style: { backgroundColor: 'rgb(0, 187, 0)' } }, + ]]) + }) + + it('treats a text-presentation symbol as one column', () => { + // Verified in a real terminal: `A✓B` redrawn with `XY` shows `XYB`, so the + // check mark is ONE column. Taking the whole U+2600-U+27BF block as wide + // misaligned exactly the progress output this card exists to show. + expect(onlySpan('A\u2713B\rXY')).toEqual({ text: 'XYB', style: undefined }) + // An emoji-presentation character is two, so the same redraw leaves a blank. + expect(onlySpan('A\u{1f600}B\rXY')).toEqual({ text: 'XY B', style: undefined }) + }) + + it('blanks both halves of a wide pair when either is overwritten', () => { + // A terminal cannot leave one cell of a two-cell glyph standing, so writing + // over the spacer clears the lead as well. + // Verified in a real terminal: two wide chars, CR, then `A` shows `A ` and + // the second glyph — writing the lead cell blanks its spacer, so the column + // stays occupied rather than collapsing. + expect(onlySpan('\u4e2d\u4e2d\rA')).toEqual({ text: 'A \u4e2d', style: undefined }) + }) +}) + describe('parseAnsiLines: SGR across lines', () => { it('carries active state past a newline, as a terminal does', () => { // Verified in a real terminal: `\x1b[31mabc\rX\nnext` paints BOTH lines red. diff --git a/packages/client/ui-primitives/tests/terminal-block.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.spec.tsx index 6b712414c5..13121351a8 100644 --- a/packages/client/ui-primitives/tests/terminal-block.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.spec.tsx @@ -146,6 +146,15 @@ describe('TerminalBlock states', () => { expect(outputLines(view.container)).toEqual(['a', 'b']) }) + it('drops the output terminator even when a reset follows the final newline', () => { + // `line\n\x1b[0m` does not end in a newline as a string, yet its last parsed + // line holds nothing visible — a common shape, since tools close their color + // after the last line. Judging the terminator on the raw text added a blank + // row and inflated both the card height and the collapse count. + const view = render() + expect(outputLines(view.container)).toEqual(['a', 'b']) + }) + it('keeps a genuinely blank final line when the output ends with two newlines', () => { const view = render() expect(outputLines(view.container)).toEqual(['a', 'b', '']) From dffb5c888ff57fb9ffca481e3792653d8edf6874 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 29 Jul 2026 16:48:26 +0800 Subject: [PATCH 13/14] test(web): cover the normalized SGR fold and the wide-pair clear MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's coverage gate rejected `ansi.ts` after the state normalization: the new fold carries shapes the existing cases never reached. Added, each expectation checked against a real terminal where the terminal is the authority — three of my first guesses were wrong and the implementation was right: - `48;2;R;G;B` (the extended-background arm and its 4-parameter span), a bright foreground and background (`91`/`101`, which resolve to `--dsw-*` tokens rather than literal rgb), a `38` with no kind byte, re-opening an attribute already in force, and the bare `\x1b[m` reset. - Clearing a wide pair from the spacer side: `中x\r\bA` shows `A x`, since the backspace clamps at column 0 and writing the lead blanks its spacer instead of letting the `x` slide left. An erase reaching the lead does the same, so `中x\x1b[1K|` shows three blanks before the bar. --- .../client/ui-primitives/tests/ansi.spec.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index d3efd5ffb3..1231acb459 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -407,6 +407,27 @@ describe('parseAnsiLines: bounded state and true widths', () => { ]]) }) + it('folds the remaining SGR shapes the model has to carry', () => { + // A 48-background in extended form, so the `48` arm and the `2`-span both run. + expect(parseAnsiLines(`${ESC}[48;2;1;2;3mA\r${ESC}[KB`)).toEqual([[ + { text: 'B', style: { backgroundColor: 'rgb(1, 2, 3)' } }, + ]]) + // A bright foreground and a bright background, the 90-97 / 100-107 arms. + expect(parseAnsiLines(`${ESC}[91mA\r${ESC}[KB`)).toEqual([[ + { text: 'B', style: { color: 'var(--dsw-alias-state-error-secondary)' } }, + ]]) + expect(parseAnsiLines(`${ESC}[101mA\r${ESC}[KB`)).toEqual([[ + { text: 'B', style: { backgroundColor: 'rgb(255, 85, 85)' } }, + ]]) + // An extended form with no recognized kind byte consumes nothing extra. + expect(parseAnsiLines(`${ESC}[38mA\r${ESC}[KB`)).toEqual([[{ text: 'B', style: undefined }]]) + // Re-opening an attribute already in force does not duplicate it, and a bare + // `\x1b[m` resets exactly as `\x1b[0m` does. + expect(parseAnsiLines(`${ESC}[1m${ESC}[1mA${ESC}[mB\r${ESC}[KC`)).toEqual([[ + { text: 'C', style: undefined }, + ]]) + }) + it('treats a text-presentation symbol as one column', () => { // Verified in a real terminal: `A✓B` redrawn with `XY` shows `XYB`, so the // check mark is ONE column. Taking the whole U+2600-U+27BF block as wide @@ -416,6 +437,17 @@ describe('parseAnsiLines: bounded state and true widths', () => { expect(onlySpan('A\u{1f600}B\rXY')).toEqual({ text: 'XY B', style: undefined }) }) + it('clears a wide pair from either side, including through an erase', () => { + // Verified in a real terminal (`A x`): the redraw puts the cursor at column + // 0, the backspace clamps there, and writing `A` over the wide lead blanks + // its spacer rather than letting the `x` slide left. + expect(onlySpan(`\u4e2dx\r${BS}A`)).toEqual({ text: 'A x', style: undefined }) + // An erase reaching the lead blanks its spacer through the same helper. + // Verified in a real terminal (` |`): 1K blanks through the cursor column, + // so the wide glyph's two cells and the `x` all become blanks. + expect(onlySpan(`\u4e2dx${ESC}[1K|`)).toEqual({ text: ' |', style: undefined }) + }) + it('blanks both halves of a wide pair when either is overwritten', () => { // A terminal cannot leave one cell of a two-cell glyph standing, so writing // over the spacer clears the lead as well. From c54bbc0f7efe3b1041d83148ffedaed3b283a972 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Wed, 29 Jul 2026 19:38:43 +0800 Subject: [PATCH 14/14] test(web): cover the spacer-write and dead-lead spacer branches --- packages/client/ui-primitives/tests/ansi.spec.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/client/ui-primitives/tests/ansi.spec.ts b/packages/client/ui-primitives/tests/ansi.spec.ts index 1231acb459..008165f5ab 100644 --- a/packages/client/ui-primitives/tests/ansi.spec.ts +++ b/packages/client/ui-primitives/tests/ansi.spec.ts @@ -448,6 +448,21 @@ describe('parseAnsiLines: bounded state and true widths', () => { expect(onlySpan(`\u4e2dx${ESC}[1K|`)).toEqual({ text: ' |', style: undefined }) }) + it('clears the lead when the write lands on the spacer itself', () => { + // Two backspaces from after `中x` stop ON the wide glyph's second cell; + // writing there blanks the lead through the spacer side of the pair clear, + // so the glyph cannot survive as half a character. + expect(onlySpan(`中x${BS}${BS}A`)).toEqual({ text: ' Ax', style: undefined }) + }) + + it('keeps a surviving spacer as a blank when its lead was replaced by a spacer', () => { + // `好` written over the first glyph's spacer puts its own spacer on the + // second glyph's lead cell — a write that goes down without a pair clear. + // The second glyph's spacer survives with a dead lead and must emit a + // blank, or everything after it shifts one column left. + expect(onlySpan(`中中${BS}${BS}${BS}好`)).toEqual({ text: ' 好 ', style: undefined }) + }) + it('blanks both halves of a wide pair when either is overwritten', () => { // A terminal cannot leave one cell of a two-cell glyph standing, so writing // over the spacer clears the lead as well.