mirror of
https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-08-29 04:26:38 +00:00
fix(web): replay cursor movements the way a terminal paints them
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.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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`,不对外导出,因此它仍是这两个块的实现细节。
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -156,6 +156,12 @@ export function ToolRow({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{/* 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 && (
|
||||
<div className={css.terminalDescription}>{terminalBody.description}</div>
|
||||
)}
|
||||
{open && (terminalBody !== null
|
||||
? <TerminalBlock {...terminalBody.card} maxLines={CHAT_TERMINAL_MAX_LINES} className={css.terminalBody} />
|
||||
: variant === 'code'
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 <TerminalBlock {...terminal.card} className={css.terminal} />
|
||||
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 && (
|
||||
<div className={css.terminalDescription}>{terminal.description}</div>
|
||||
)}
|
||||
<TerminalBlock {...terminal.card} className={css.terminal} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
// 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 <div className={css.empty}>运行中…</div>
|
||||
|
||||
@@ -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(<GenericToolCard {...ownerProps(settled({
|
||||
callView: callTerminal({ description: 'Terminal 3' }),
|
||||
}))} />)
|
||||
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(<GenericToolCard {...ownerProps(running())} />)
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)。
|
||||
|
||||
## 模型体验
|
||||
|
||||
|
||||
@@ -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, '')
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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)' } },
|
||||
]])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user