@trans-ai/trans-code 0.10.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -240,6 +240,12 @@ ACP 默认权限模式是 `ask`:写文件、改文件、执行命令前会向
240
240
 
241
241
  注入预算 12k 字符,超预算整条省略最低优先级(user > feedback > project > reference)并在提示中注明。记忆目录文件是事实源,`MEMORY.md` 删除后会自动重建。测试与隔离用环境变量 `TRANSCODE_USER_DIR` 覆盖根目录。
242
242
 
243
+ ## 渲染与交互
244
+
245
+ - **静态历史架构**:历史每条只打印一次(Ink `<Static>`),流式输出与输入在底部活动区小面积重绘——打字、生成、长会话都不闪烁;回合进行中活动区只显示流式输出的**尾部窗口**(超出部分顶部注明 `… +N lines`),回合结束完整内容落入历史
246
+ - **`ctrl+o` 展开明细**:多工具回合折叠为一行摘要(`… +N lines (ctrl+o 展开明细)`),按 ctrl+o 将最近一个折叠回合的工具明细展开打印;连按依次展开更早的回合
247
+ - **`/clear` 语义**:已打印的历史无法"收回"——/clear 在下方开始新对话,旧内容保留在终端滚动缓冲中(可自行清屏)
248
+
243
249
  ## 联网工具
244
250
 
245
251
  - **`web_fetch`**:零配置开箱即用。抓 URL 返回可读文本(HTML 剥离为文本 + 标题,text/json 原样,二进制给类型/大小提示);支持 gbk/gb2312 页面解码,512KB / 20k 字符上限,15s 超时
@@ -0,0 +1,93 @@
1
+ # Static 渲染架构迁移 Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** 历史区迁入 Ink `<Static>`(只印一次),活动区(输入/队列/流式尾部窗口)小面积重绘——全场景消闪烁。
6
+
7
+ **Architecture:** 回合内一切输出写入 `liveOutput`(经既有 32ms 节流),活动区只渲染其**尾部窗口**(rows-10 行 + `… +M lines` 指示);回合结束**单次提交**落地 Static 条目并清空 liveOutput。`history`+`liveOutput` 合并为单一 state(legacy reconciler 下两次提交会闪一帧重复尾巴,spec 裁定 #6)。
8
+
9
+ **Tech Stack:** TypeScript + Bun test;Ink 5 `<Static>`(已装,零新依赖)。
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-22-static-render-design.md`(含 6 条审查裁定,均为约束)
12
+
13
+ ## Global Constraints
14
+
15
+ - Static 语义(Ink 5.2 实测):纯按 `items.length` 增量打印;**条目推入后不可变**(等长变更不重印,可利用——ctrl+o 清 hiddenLines);同批 `setItems([])`+append 会吞条
16
+ - 活动区高度必须 < 终端行数(否则触发 clearTerminal+整史重画):liveOutput 尾部窗口 `rows - 10`,`… +M lines` 指示行
17
+ - 回合落地 = **单次提交**(合并 state);liveOutput 带 ref 镜像(节流 flush 同步读)
18
+ - /clear:清空与确认条目**分批提交**(setTimeout 0);语义 = 下方开新对话(滚动缓冲保留)
19
+ - Banner = 首条 Static 条目(不留在交互帧)
20
+ - ctrl+o = 动作:展开最近含 hiddenLines 的条目(连按回走),展开后清该条 hiddenLines
21
+ - 每任务收尾:`bun test` 全绿 + `bun run typecheck` 通过
22
+
23
+ ## Review Focus
24
+
25
+ 1. **长回复超终端高度** → 尾部窗口使活动区恒 < rows,不触发整史重画(Task 1/2)
26
+ 2. **/clear 同批吞条** → 确认条目分批提交(Task 3)
27
+ 3. **回合落地重复尾巴帧** → 合并 state 单提交(Task 2)
28
+ 4. **压缩失败** → 半截摘要 + ⚠ 合并一条落史,liveOutput 清零不渗下回合(Task 2)
29
+ 5. **ctrl+o 连按** → 逐条回走,已展开条目不再重复(Task 3)
30
+ 6. **resume 重建** → 全量 append 打印;压缩摘要走 liveOutput 后落条目(Task 2/3)
31
+
32
+ ---
33
+
34
+ ### Task 1: 纯函数层(turn-summary 改造 + 尾部窗口)
35
+
36
+ **Files:**
37
+ - Modify: `src/screens/turn-summary.ts`(`renderTurnLog` → `renderCollapsed`;新增 `renderExpansion`)
38
+ - Create: `src/screens/live-view.ts`(`sliceLiveTail`)
39
+ - Test: `src/screens/turn-summary.test.ts`(改造)、`src/screens/live-view.test.ts`
40
+
41
+ **Interfaces:**
42
+
43
+ ```ts
44
+ // turn-summary.ts
45
+ export function renderCollapsed(summary: string, hiddenLines: string[]): string;
46
+ // summary + '\n… +N lines (ctrl+o 展开明细)'(hiddenLines 空则原样)
47
+ export function renderExpansion(entry: { output: string; hiddenLines: string[] }): string;
48
+ // '⚙ 展开明细:' + hiddenLines 全量(无 collapse 提示)
49
+ // live-view.ts
50
+ export function sliceLiveTail(text: string, maxLines: number): { visible: string; hidden: number };
51
+ // 末 maxLines 行;hidden = 被截行数(按非空行计?——按真实行数 split('\n') 计,含空行)
52
+ ```
53
+
54
+ - [ ] **Step 1: 写失败测试**(`renderCollapsed`/`renderExpansion`/`sliceLiveTail` 各行为:计数、边界 maxLines≥总行、空文本),同时改造 turn-summary.test.ts 里 `renderTurnLog` 的三个用例为新 API
55
+ - [ ] **Step 2: 跑测试确认失败**(新 API 不存在)
56
+ - [ ] **Step 3: 实现**;`renderTurnLog` 删除(verbose 开关语义废弃)
57
+ - [ ] **Step 4: 跑测试确认通过 + 全量回归**(REPL 尚未用新 API——先改 turn-summary 会破 REPL 编译?不会:REPL 引用 renderTurnLog,删除即破——**本任务同步把 REPL 内 renderTurnLog 调用点改为 renderCollapsed(折叠行创建时)**,渲染仍走旧 history.map,行为等价)
58
+ - [ ] **Step 5: 提交** `feat: collapsed-line and live-tail pure helpers for static render`
59
+
60
+ ---
61
+
62
+ ### Task 2: 核心迁移(liveOutput + Static + 回合生命周期 + 压缩流)
63
+
64
+ **Files:**
65
+ - Modify: `src/screens/REPL.tsx`(state 合并、事件路由、Static 渲染、runChat/runCompaction 生命周期)
66
+ - Test: 全量回归 + typecheck(纯逻辑在 Task 1;本任务为架构接线)
67
+
68
+ **Interfaces:**
69
+ - Consumes: Task 1 全部;`createStreamThrottler`(既有)
70
+ - Produces: REPL 内部 `chat` 合并 state 与 helpers(`addHistory`/`appendLive`/`landTurn`,签名不变处沿用旧名)
71
+
72
+ - [ ] **Step 1: 合并 state**:`{ history, liveOutput }` 单 useState + `liveOutputRef` 镜像;`streamAppend` 节流目标从 appendChatOutput 改为 appendLive(写 liveOutput)
73
+ - [ ] **Step 2: 回合生命周期**:runChat 开头不再建宿主条目(输入头进活动区);结束在 finally 单次提交落地 `addHistory({input: display, output: liveOutputRef.current(+hiddenLines/摘要), hiddenLines})` 并清 liveOutput;取消/报错文案同入 liveOutput(既有 streamAppend 路径);压缩摘要流(runCompaction)走 liveOutput,成功/失败(合并 ⚠)各自落一条并清零
74
+ - [ ] **Step 3: 渲染**:`<Static items={history>` 为首子(条目渲染 = input 头 + output 纯文本,折叠提示已烙进 output);活动区:`> 输入头(busy 时)` + `sliceLiveTail(liveOutput, rows-10)` + `… +M lines` + liveTool + 队列 + 输入框 + 弹窗;删除旧 history.map 与 verboseTools
75
+ - [ ] **Step 4: resume 压缩摘要同走 liveOutput**;`applyResume` 的末条追加模式改为 liveOutput 承载 + 落条目
76
+ - [ ] **Step 5: 全量回归 + typecheck + 提交** `feat: static history with live-region streaming and tail window`
77
+
78
+ ---
79
+
80
+ ### Task 3: 边缘语义(Banner/clear/ctrl+o)+ README
81
+
82
+ **Files:**
83
+ - Modify: `src/main.tsx`(Banner 移出树,文本经 prop)、`src/screens/REPL.tsx`(seed 首条、/clear 分批、ctrl+o 动作)、`README.md`(ctrl+o 与 /clear 新语义)
84
+ - Test: `src/screens/turn-summary.test.ts` 或新增小测试(ctrl+o 选择的纯函数若有);其余全量回归
85
+
86
+ **Interfaces:**
87
+ - Consumes: Task 1 `renderExpansion`
88
+ - Produces: REPL prop `banner: string`(main.tsx 传入,REPL 初始化 history[0] = banner 条目)
89
+
90
+ - [ ] **Step 1: Banner 入 Static**:main.tsx 去掉 `<Banner>` 包裹,banner 文本作 prop;REPL 初始 history seed 该条目(仅挂载时)
91
+ - [ ] **Step 2: /clear**:setChat 清空后,确认条目 `setTimeout(0)` 分批提交;README 更新语义(滚动缓冲保留)
92
+ - [ ] **Step 3: ctrl+o**:handler 找最后含 hiddenLines 条目 → land 展开条目(renderExpansion)→ 同提交内清该条 hiddenLines(等长变更);README 更新
93
+ - [ ] **Step 4: 全量回归 + typecheck + 提交** `feat: banner-in-static, deferred /clear confirmation, ctrl+o expand action`
@@ -0,0 +1,42 @@
1
+ # Static 渲染架构(全场景消闪烁)— 设计
2
+
3
+ ## 意图
4
+
5
+ 打字、流式输出、长会话全场景消闪烁。根源:历史区与活动区同帧渲染,任何 setState(每敲一个字符、每个 delta)都整屏清除重画。修法:历史区搬进 Ink `<Static>`(每条只印一次,永不重绘),按键与流式只重绘小面积活动区——这正是 Claude Code 的架构。
6
+
7
+ ## 设计
8
+
9
+ **Static 历史区**:`history` 数组渲染进 `<Static items>`;条目 **append-only,推入后不可变**(现架构里 appendChatOutput 对末条追加的写法是唯一的变形点,本设计移除它)。
10
+
11
+ **活动区 `liveOutput`**(新 string state):回合内一切输出——文本 delta、工具结果/diff、折叠摘要行、取消/报错提示——经既有 `streamAppend`(32ms 节流)写入 `liveOutput`;活动区自上而下渲染:`> 输入头` + liveOutput + liveTool 指示 + 队列 + 输入框 + 弹窗。
12
+
13
+ **回合结束**:`addHistory({ input, output: liveOutput, hiddenLines })` 一次性落入 Static,清空 liveOutput。空输出(立即取消)也落条目(含 `(cancelled)`)。
14
+
15
+ **压缩摘要流**(runCompaction 与 resume 压缩):摘要 delta 同样走 liveOutput(前缀"正在提炼前情提要…"),完成后作为一条独立历史条目落入。`applyResume` 现"确认条目先建、摘要流进末条"的模式改为:压缩期间 liveOutput 承载,完成后与确认信息合并落条目。
16
+
17
+ **回合外直写不变**:命令输出、`/search` 流程提示、模式切换横幅、updateNotice 等一次性条目仍直接 `addHistory`(无流变,Static 安全)。
18
+
19
+ **ctrl+o 从开关变动作**:Static 条目印后不可改,"切换展开已打印历史"不可行——改为按下时找**最近一条**含 `hiddenLines` 的历史,补打印展开条目(`addHistory({ input: '', output: renderExpansion(entry) })`);折叠行提示改为 `(ctrl+o 展开明细)`;`verboseTools` state 删除。`renderTurnLog` 收窄为折叠行渲染;新增 `renderExpansion(entry)`。
20
+
21
+ **/clear、/resume 重建**:setHistory 替换/清空后 Static 按新 items 全量打印(append-only 语义不变),无需特判。
22
+
23
+ ## 非目标
24
+
25
+ - fork Ink / 单元格级双缓冲 diff(CCB 路线,重)
26
+ - liveOutput 跨会话保留;队列/补全弹窗变化(本就在活动区)
27
+ - 展开块的再折叠(打印即定稿)
28
+
29
+ ## 备选(已否)
30
+
31
+ - 输入行 setState 节流:打字频率本就低于帧率,闪烁源于单次重绘面积而非频率 — 治不了
32
+ - 维持整帧渲染 + 仅流式节流:0.10.4 已证不彻底(打字仍闪)
33
+ - ctrl+o 保留开关语义、仅对未来回合生效:违背"展开已折叠明细"的使用动机
34
+
35
+ ## 审查后裁定(builder check,实测 Ink 5.2.1 源码后)
36
+
37
+ 1. **活动区尾部窗口(必做)**:回合中 liveOutput 只渲染最后 `终端行数 - 固定件(~10)` 行,顶上加 `… +M lines` 指示行;全文存 ref,回合结束完整落 Static——否则长回复每 32ms 触发 clearTerminal + 整史重画,闪烁以更糟形式回归。
38
+ 2. **/clear 语义变更**:Static 印出内容无法收回(无 fullStaticOutput 重置 API)——/clear = 下方开新对话、滚动缓冲保留旧内容;清空与后续条目分属不同提交批次(同批 setHistory([])+addHistory 会静默吞条,实测确认)。
39
+ 3. **Banner 迁入 Static**:留交互帧会被逐键重绘且钉在历史与输入框之间(实测)——改为首条 Static 条目。
40
+ 4. **ctrl+o 逐条回走**:展开后清除该条 hiddenLines(等长变更,不触发重印);连按依次展开更早折叠回合;折叠行提示字样不可抹,接受。
41
+ 5. **压缩失败**:liveOutput 半截摘要与 ⚠ 提示合并为一条落史,并清空 liveOutput(防渗入下回合)。
42
+ 6. 实现注意:liveOutput 需 ref 镜像(节流 flush 同步读 state 会读到旧值);回合落地与 liveOutput 清空合并为单次提交(legacy reconciler 下两次提交会闪一帧重复尾巴)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.10.3",
3
+ "version": "0.11.0",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/main.tsx CHANGED
@@ -9,32 +9,19 @@ import { autoUpdateNotice } from './upgrade.js';
9
9
  import { VERSION } from './version.js';
10
10
  const DEFAULT_MODEL: string = preferredModelId() ?? 'opus';
11
11
 
12
- function Banner({ modelId, cwd, envLabel }: { modelId: string; cwd: string; envLabel?: string }) {
12
+ /** Startup banner as plain text: printed once as the first Static entry. */
13
+ function bannerText(modelId: string, cwd: string, envLabel?: string): string {
13
14
  const models = getAvailableModels();
14
15
  const current = models.find(m => m.id === modelId);
15
-
16
- const logo = bannerLines('T R A N S C O D E · Multi-model Agent');
17
-
18
- return (
19
- <Box flexDirection="column" marginBottom={1}>
20
- <Text color="cyan" bold>{logo}</Text>
21
- <Box marginTop={1}>
22
- <Text color="green" bold>Trans Code</Text>
23
- <Text> v{VERSION}</Text>
24
- </Box>
25
- <Box>
26
- <Text color="yellow">Model: </Text>
27
- <Text>{envLabel ?? current?.name ?? modelId}</Text>
28
- </Box>
29
- <Box>
30
- <Text color="blue">Dir: </Text>
31
- <Text>{cwd}</Text>
32
- </Box>
33
- <Box marginTop={1}>
34
- <Text dimColor>Type "help" for available commands, "exit" to quit.</Text>
35
- </Box>
36
- </Box>
37
- );
16
+ return [
17
+ bannerLines('T R A N S C O D E · Multi-Model Agent'),
18
+ '',
19
+ `Trans Code v${VERSION}`,
20
+ `Model: ${envLabel ?? current?.name ?? modelId}`,
21
+ `Dir: ${cwd}`,
22
+ '',
23
+ 'Type "help" for available commands, "exit" to quit.',
24
+ ].join('\n');
38
25
  }
39
26
 
40
27
  function App() {
@@ -50,8 +37,9 @@ function App() {
50
37
  return (
51
38
  <Box flexDirection="column">
52
39
  {/* A saved model choice (from the models flow) wins over the env label */}
53
- <Banner modelId={modelId} cwd={cwd} envLabel={preferredModelId() ? undefined : envModelLabel()} />
54
- <REPL ctx={ctx} updateNotice={autoUpdateNotice()} />
40
+
41
+ <REPL
42
+ banner={bannerText(modelId, cwd, preferredModelId() ? undefined : envModelLabel())} ctx={ctx} updateNotice={autoUpdateNotice()} />
55
43
  </Box>
56
44
  );
57
45
  }
@@ -1,4 +1,4 @@
1
- import { Box, Text, useInput, useApp, useStdout } from 'ink';
1
+ import { Box, Static, Text, useInput, useApp, useStdout } from 'ink';
2
2
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
3
3
  import path from 'node:path';
4
4
  import { executeCommand, findCommand, getCommands, type CommandContext } from '../commands.js';
@@ -49,9 +49,11 @@ import {
49
49
  import { resolveSubmitInput } from './submit.js';
50
50
  import { submitSearchApiKey } from './search-setup.js';
51
51
  import { reduceQueue, shouldResumeQueue, type QueueAction } from './input-queue.js';
52
+ import { createStreamThrottler } from './stream-throttle.js';
52
53
  import { historyRule } from './history-rule.js';
53
54
  import { renderDiff } from './diff-render.js';
54
- import { createTurnStats, recordCall, renderTurnLog, shouldCollapse, summaryLine } from './turn-summary.js';
55
+ import { createTurnStats, recordCall, renderCollapsed, renderExpansion, shouldCollapse, summaryLine } from './turn-summary.js';
56
+ import { sliceLiveTail } from './live-view.js';
55
57
  import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
56
58
  import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
57
59
 
@@ -82,11 +84,13 @@ const SEARCH_PROVIDERS: WebSearchConfig['provider'][] = ['tavily', 'brave'];
82
84
 
83
85
  interface REPLProps {
84
86
  ctx: CommandContext;
87
+ /** Startup banner text; printed once as the first Static entry. */
88
+ banner?: string;
85
89
  /** Background auto-update outcome; a non-null message shows as a banner. */
86
90
  updateNotice?: Promise<string | null>;
87
91
  }
88
92
 
89
- export default function REPL({ ctx, updateNotice }: REPLProps) {
93
+ export default function REPL({ ctx, banner, updateNotice }: REPLProps) {
90
94
  const { exit } = useApp();
91
95
  const { stdout } = useStdout();
92
96
  const [input, setInput] = useState('');
@@ -99,7 +103,23 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
99
103
  inputRef.current = next;
100
104
  setInput(next);
101
105
  }, []);
102
- const [history, setHistory] = useState<HistoryEntry[]>([]);
106
+ // Single commit for history + live stream: the legacy reconciler paints
107
+ // per commit, so landing a turn and clearing the live region in two
108
+ // commits flashes one duplicated tail frame (spec ruling #6).
109
+ interface ChatView {
110
+ history: HistoryEntry[];
111
+ liveOutput: string;
112
+ /** Input echo shown at the top of the live region while a turn runs. */
113
+ turnInput: string;
114
+ }
115
+ const [chat, setChat] = useState<ChatView>(() => ({
116
+ // Banner prints once as the first static item (spec ruling #3).
117
+ history: banner ? [{ input: '', output: banner }] : [],
118
+ liveOutput: '',
119
+ turnInput: '',
120
+ }));
121
+ const liveOutputRef = useRef('');
122
+ const turnDisplayRef = useRef('');
103
123
  const [historyIndex, setHistoryIndex] = useState(-1);
104
124
  const [savedInput, setSavedInput] = useState('');
105
125
  const [phase, setPhase] = useState<PromptPhase>('idle');
@@ -149,23 +169,13 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
149
169
  }, []);
150
170
 
151
171
  const addHistory = useCallback((entry: HistoryEntry) => {
152
- setHistory(prev => [...prev, entry]);
172
+ setChat(prev => ({ ...prev, history: [...prev.history, entry] }));
153
173
  }, []);
154
174
 
155
- /** ctrl+o verbose view: collapsed turns show their hidden tool-log detail. */
156
- const [verboseTools, setVerboseTools] = useState(false);
157
-
158
- const attachHiddenLines = useCallback((lines: string[]) => {
159
- setHistory(prev => {
160
- if (prev.length === 0 || lines.length === 0) return prev;
161
- const next = [...prev];
162
- const last = next[next.length - 1];
163
- next[next.length - 1] = {
164
- ...last,
165
- hiddenLines: [...(last.hiddenLines ?? []), ...lines],
166
- };
167
- return next;
168
- });
175
+ /** Turn-time streaming target: the live region (never mutates history). */
176
+ const appendLive = useCallback((chunk: string) => {
177
+ liveOutputRef.current += chunk;
178
+ setChat(prev => ({ ...prev, liveOutput: prev.liveOutput + chunk }));
169
179
  }, []);
170
180
 
171
181
  // Busy-input queue: prompts typed while the agent works. Natural turn end
@@ -202,18 +212,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
202
212
  const sessionPickerRef = useRef<SessionRecord[]>([]);
203
213
  /** Load a record into the live conversation; shared by /resume arg and picker paths. */
204
214
  const applyResume = useCallback(
205
- (record: SessionRecord, inputLine: string) => {
215
+ (record: SessionRecord, _inputLine: string) => {
206
216
  conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
207
217
  conversationTitleRef.current = record.title;
208
218
  summaryRef.current = record.summary ?? null;
209
219
  messagesRef.current = record.messages;
210
220
  toolSessionRef.current = createToolSession(process.cwd());
211
- addHistory({
212
- input: inputLine,
213
- output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
214
- });
221
+ // The confirmation line now lands WITH the streamed digest in
222
+ // resumeWith (live region hosts the digest while compacting).
215
223
  },
216
- [addHistory],
224
+ [],
217
225
  );
218
226
 
219
227
  // @-mention file completion: lazy file list, active query, dismissed flag.
@@ -306,8 +314,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
306
314
  /** Shared resume flow: auto-compact over-long sessions, then load + render. */
307
315
  const resumeWith = async (record: SessionRecord, inputLine: string, keepTurns = DEFAULT_KEEP_TURNS) => {
308
316
  const { turns } = splitTurns(record.messages);
309
- // Load first so the confirmation entry hosts the streamed digest.
310
317
  applyResume(record, inputLine);
318
+ const confirm = `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`;
311
319
  let oldTurns = 0;
312
320
  if (turns.length > keepTurns && process.env.TRANSCODE_MOCK !== '1') {
313
321
  setBusyBoth(true);
@@ -321,14 +329,26 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
321
329
  // Manual success heals the auto-compact breaker too.
322
330
  autoCompactFailuresRef.current = 0;
323
331
  autoCompactWarnedRef.current = false;
332
+ landLive({ input: inputLine, prefix: confirm });
324
333
  } else {
325
- addHistory({ input: '', output: `⚠ 提炼失败(${outcome.error ?? '未知'}),已恢复完整对话。` });
334
+ // Failure: partial digest + warning merged as ONE entry (ruling #5).
335
+ landLive({
336
+ input: inputLine,
337
+ prefix: confirm,
338
+ suffix: `\n⚠ 提炼失败(${outcome.error ?? '未知'}),已恢复完整对话。`,
339
+ });
326
340
  }
327
341
  } catch {
328
- addHistory({ input: '', output: '⚠ 提炼失败,已恢复完整对话。' });
342
+ landLive({
343
+ input: inputLine,
344
+ prefix: confirm,
345
+ suffix: '\n⚠ 提炼失败,已恢复完整对话。',
346
+ });
329
347
  } finally {
330
348
  setBusyBoth(false);
331
349
  }
350
+ } else {
351
+ addHistory({ input: inputLine, output: confirm });
332
352
  }
333
353
  // Restore in the original conversation form: each message becomes a
334
354
  // history entry (rule-framed questions, full-length replies).
@@ -338,16 +358,54 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
338
358
  dragFlush();
339
359
  };
340
360
 
341
- const appendChatOutput = useCallback((chunk: string) => {
342
- setHistory(prev => {
343
- if (prev.length === 0) return prev;
344
- const next = [...prev];
345
- const last = next[next.length - 1];
346
- next[next.length - 1] = { ...last, output: last.output + chunk };
347
- return next;
348
- });
361
+ /**
362
+ * Frame-level coalescing for streaming output. Stock Ink re-renders
363
+ * synchronously per setState, so per-delta appends rewrite the whole
364
+ * history frame dozens of times per second — that is the flicker.
365
+ * Everything within a turn flows through here and is flushed at turn
366
+ * end (order preserved; ≤32ms latency, invisible).
367
+ */
368
+ const streamAppendRef = useRef<ReturnType<typeof createStreamThrottler> | null>(null);
369
+ if (streamAppendRef.current === null) {
370
+ streamAppendRef.current = createStreamThrottler(appendLive, 32);
371
+ }
372
+ const streamAppend = (chunk: string): void => {
373
+ streamAppendRef.current?.push(chunk);
374
+ };
375
+
376
+ /** Show the input echo at the top of the live region while a turn runs. */
377
+ const beginTurnLive = useCallback((display: string) => {
378
+ turnDisplayRef.current = display;
379
+ setChat(prev => ({ ...prev, turnInput: display }));
349
380
  }, []);
350
381
 
382
+ /**
383
+ * Land the streamed live output as one static history entry and clear the
384
+ * live region in a single commit. Flushes the throttler first and builds
385
+ * output = prefix + live + suffix AFTER the flush — never pre-capture the
386
+ * live text at the call site (the tail may sit in the throttler). Ruling #6.
387
+ */
388
+ const landLive = useCallback(
389
+ (entry: {
390
+ input: string;
391
+ prefix?: string;
392
+ suffix?: string;
393
+ output?: string;
394
+ hiddenLines?: string[];
395
+ }) => {
396
+ streamAppendRef.current?.flush();
397
+ const output =
398
+ entry.output ?? `${entry.prefix ?? ''}${liveOutputRef.current}${entry.suffix ?? ''}`;
399
+ liveOutputRef.current = '';
400
+ setChat(prev => ({
401
+ history: [...prev.history, { input: entry.input, output, hiddenLines: entry.hiddenLines }],
402
+ liveOutput: '',
403
+ turnInput: '',
404
+ }));
405
+ },
406
+ [],
407
+ );
408
+
351
409
  /**
352
410
  * One shared compaction run for /resume and /compact: fast-model routing
353
411
  * (routing.compact → fallback current model) with the digest streamed
@@ -357,18 +415,18 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
357
415
  record: SessionRecord,
358
416
  keepTurns: number,
359
417
  ): Promise<{ compressed: boolean; record: SessionRecord; error?: string }> => {
360
- appendChatOutput('\n正在提炼前情提要…\n');
418
+ streamAppend('\n正在提炼前情提要…\n');
361
419
  try {
362
420
  const outcome = await compressSession(
363
421
  record,
364
422
  createModel(getRouting().compact ?? ctx.modelId).model,
365
423
  keepTurns,
366
- (delta) => appendChatOutput(delta),
424
+ (delta) => streamAppend(delta),
367
425
  );
368
- appendChatOutput('\n\n');
426
+ streamAppend('\n\n');
369
427
  return outcome;
370
428
  } catch (error) {
371
- appendChatOutput('\n\n');
429
+ streamAppend('\n\n');
372
430
  return {
373
431
  compressed: false,
374
432
  record,
@@ -408,9 +466,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
408
466
  if (autoCompactFailuresRef.current >= 3) return;
409
467
  if (!shouldAutoCompact(messagesRef.current, cfg)) return;
410
468
  try {
411
- // Dedicated host entry before the question echo, so the digest neither
412
- // mixes into the turn entry nor receives the turn's streamed reply.
413
- addHistory({ input: '', output: '' });
469
+ // Digest streams into the live region; it lands as its own entry here
470
+ // (before the turn's echo) and never mixes into the turn entry.
414
471
  const record = buildSessionRecord({
415
472
  id: conversationRef.current.id,
416
473
  title: conversationTitleRef.current,
@@ -424,8 +481,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
424
481
  if (!outcome.compressed) {
425
482
  // Without an error it is a no-op (≤ keepTurns turns — e.g. one giant
426
483
  // turn over threshold): nothing compressible, skip without touching
427
- // the breaker.
484
+ // the breaker. The streamed banner still lands as a stub entry.
428
485
  if (outcome.error) throw new Error(outcome.error);
486
+ landLive({ input: '' });
429
487
  return;
430
488
  }
431
489
  summaryRef.current = outcome.record.summary ?? null;
@@ -433,6 +491,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
433
491
  saveSession(outcome.record);
434
492
  autoCompactFailuresRef.current = 0;
435
493
  autoCompactWarnedRef.current = false;
494
+ landLive({ input: '' });
436
495
  for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
437
496
  addHistory(entry);
438
497
  }
@@ -440,13 +499,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
440
499
  autoCompactFailuresRef.current += 1;
441
500
  const reason = error instanceof Error ? error.message : String(error);
442
501
  if (autoCompactFailuresRef.current >= 3) {
443
- addHistory({
502
+ landLive({
444
503
  input: '',
445
- output: `⚠ 自动压缩已暂停(连续 3 次失败,最后原因:${reason})。可 /compact 手动压缩或检查 routing.compact 配置。`,
504
+ suffix: `\n⚠ 自动压缩已暂停(连续 3 次失败,最后原因:${reason})。可 /compact 手动压缩或检查 routing.compact 配置。`,
446
505
  });
447
506
  } else if (!autoCompactWarnedRef.current) {
448
507
  autoCompactWarnedRef.current = true;
449
- addHistory({ input: '', output: `⚠ 自动压缩失败(${reason}),本轮继续。` });
508
+ landLive({ input: '', suffix: `\n⚠ 自动压缩失败(${reason}),本轮继续。` });
509
+ } else {
510
+ landLive({ input: '' });
450
511
  }
451
512
  }
452
513
  };
@@ -457,12 +518,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
457
518
  const controller = new AbortController();
458
519
  abortRef.current = controller;
459
520
  await autoCompactIfNeeded();
460
- addHistory({ input: display ?? text, output: '' });
521
+ // No host entry: the input echo lives in the live region and the whole
522
+ // turn lands in <Static> as one immutable entry when it ends.
523
+ beginTurnLive(display ?? text);
461
524
  if (options?.planMode) {
462
- appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
525
+ streamAppend('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
463
526
  }
464
527
 
465
528
  let endedNaturally = false;
529
+ let turnHiddenLines: string[] | undefined;
466
530
  try {
467
531
  const provider =
468
532
  process.env.TRANSCODE_MOCK === '1'
@@ -510,11 +574,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
510
574
  toolSession: toolSessionRef.current,
511
575
  onEvent: event => {
512
576
  if (event.type === 'text') {
513
- appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
577
+ streamAppend(lastWasTool ? `\n${event.text}` : event.text);
514
578
  turnAssistantText += event.text;
515
579
  lastWasTool = false;
516
580
  } else if (event.type === 'max_turns_reached') {
517
- appendChatOutput(
581
+ streamAppend(
518
582
  `\n⚠ 已达轮次上限(${event.maxTurns}),任务未完成。输入"继续"接着做,或调大 TRANSCODE_MAX_TURNS。`,
519
583
  );
520
584
  lastWasTool = true;
@@ -532,10 +596,10 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
532
596
  );
533
597
  if (event.diff) {
534
598
  // Edits and writes stay visible immediately — rare and important.
535
- appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
599
+ streamAppend(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
536
600
  } else if (event.name === 'todo_write' || event.name === 'dispatch_agent') {
537
601
  // Progress state and sub-agent reports: show immediately.
538
- appendChatOutput(`\n${event.output}`);
602
+ streamAppend(`\n${event.output}`);
539
603
  } else {
540
604
  bufferedLines.push(`\n⚙ ${title} ${marker}`);
541
605
  }
@@ -549,10 +613,10 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
549
613
  // Collapsed detail is kept (hiddenLines) so ctrl+o can reveal it.
550
614
  if (shouldCollapse(stats)) {
551
615
  const line = summaryLine(stats);
552
- if (line) appendChatOutput(`\n${line}`);
553
- attachHiddenLines(bufferedLines);
616
+ if (line) streamAppend(`\n${renderCollapsed(line, bufferedLines)}`);
617
+ turnHiddenLines = bufferedLines;
554
618
  } else {
555
- for (const line of bufferedLines) appendChatOutput(line);
619
+ for (const line of bufferedLines) streamAppend(line);
556
620
  }
557
621
 
558
622
  messagesRef.current = result.messages.filter(
@@ -604,17 +668,23 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
604
668
  })();
605
669
  }
606
670
  if (controller.signal.aborted) {
607
- appendChatOutput('\n(cancelled)');
671
+ streamAppend('\n(cancelled)');
608
672
  } else {
609
673
  endedNaturally = true;
610
674
  }
611
675
  } catch (error) {
612
676
  const message = error instanceof Error ? error.message : String(error);
613
- appendChatOutput(`\n⚠ ${message}`);
677
+ streamAppend(`\n⚠ ${message}`);
614
678
  if (/api.?key/i.test(message)) {
615
- appendChatOutput(`\n(run "models" to switch model + set key, or export its env var)`);
679
+ streamAppend(`\n(run "models" to switch model + set key, or export its env var)`);
616
680
  }
617
681
  } finally {
682
+ // Land the whole turn as one immutable static entry and clear the
683
+ // live region in a single commit, then let the queue continue.
684
+ landLive({
685
+ input: turnDisplayRef.current,
686
+ hiddenLines: turnHiddenLines,
687
+ });
618
688
  setBusyBoth(false);
619
689
  abortRef.current = undefined;
620
690
  setLiveTool(null);
@@ -629,7 +699,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
629
699
  }
630
700
  }
631
701
  },
632
- [ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush, applyQueue],
702
+ [ctx.modelId, addHistory, askInTerminal, setBusyBoth, dragFlush, applyQueue, beginTurnLive, landLive],
633
703
  );
634
704
 
635
705
  const enterModelSelect = useCallback(() => {
@@ -967,9 +1037,6 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
967
1037
  messages: messagesRef.current,
968
1038
  summary: summaryRef.current,
969
1039
  });
970
- // Host entry first so the streamed digest renders inside this
971
- // command's own frame (same contract as the resume path).
972
- addHistory({ input: trimmed, output: '' });
973
1040
  const outcome = process.env.TRANSCODE_MOCK === '1'
974
1041
  ? { compressed: false as const, record, error: 'mock 模式无模型' }
975
1042
  : await runCompaction(record, keepN);
@@ -980,15 +1047,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
980
1047
  // Manual success heals the auto-compact breaker too.
981
1048
  autoCompactFailuresRef.current = 0;
982
1049
  autoCompactWarnedRef.current = false;
983
- appendChatOutput(`已压缩:旧 ${turns.length - keepN} 轮提炼为前情提要,保留最近 ${keepN} 轮。`);
1050
+ landLive({
1051
+ input: trimmed,
1052
+ suffix: `已压缩:旧 ${turns.length - keepN} 轮提炼为前情提要,保留最近 ${keepN} 轮。`,
1053
+ });
984
1054
  for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
985
1055
  addHistory(entry);
986
1056
  }
987
1057
  } else {
988
- appendChatOutput(`⚠ 压缩失败(${outcome.error ?? '未知'}),会话保持原样。`);
1058
+ landLive({
1059
+ input: trimmed,
1060
+ suffix: `\n⚠ 压缩失败(${outcome.error ?? '未知'}),会话保持原样。`,
1061
+ });
989
1062
  }
990
1063
  } catch {
991
- appendChatOutput('⚠ 压缩失败,会话保持原样。');
1064
+ landLive({ input: trimmed, suffix: '\n⚠ 压缩失败,会话保持原样。' });
992
1065
  } finally {
993
1066
  setBusyBoth(false);
994
1067
  }
@@ -1031,7 +1104,14 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1031
1104
 
1032
1105
  if (cmdName === 'clear') {
1033
1106
  ctx.clearHistory();
1034
- setHistory([]);
1107
+ setChat(prev => ({ ...prev, history: [] }));
1108
+ // Static output cannot be un-printed: /clear starts a fresh
1109
+ // transcript below (scrollback keeps the old one). The confirmation
1110
+ // lands in a SEPARATE commit — same-batch clear+append gets
1111
+ // swallowed by Static's length-based diff (probe-verified).
1112
+ setTimeout(() => {
1113
+ addHistory({ input: '', output: '已开始新对话。(旧内容保留在终端滚动缓冲中)' });
1114
+ }, 0);
1035
1115
  } else if (result.output) {
1036
1116
  addHistory({ input: trimmed, output: result.output });
1037
1117
  }
@@ -1060,9 +1140,25 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1060
1140
  // eslint-disable-next-line no-console
1061
1141
  console.error(`CB ${JSON.stringify(ch)} ret=${key.return} esc=${key.escape}`);
1062
1142
  }
1063
- // ctrl+o: toggle verbose tool logs (expand/collapse every turn).
1143
+ // ctrl+o: expand the most recent folded turn (repeat presses walk
1144
+ // backwards). Printed static entries never re-render, so expansion
1145
+ // lands as a NEW entry and the source entry drops its hiddenLines
1146
+ // (same-length mutation — Static-safe).
1064
1147
  if (key.ctrl && (ch === 'o' || ch === 'O')) {
1065
- setVerboseTools(v => !v);
1148
+ const history = chat.history;
1149
+ for (let i = history.length - 1; i >= 0; i--) {
1150
+ const entry = history[i];
1151
+ if (entry?.hiddenLines?.length) {
1152
+ const expansion = renderExpansion({ output: entry.output, hiddenLines: entry.hiddenLines });
1153
+ const index = i;
1154
+ setChat(prev => {
1155
+ const next = [...prev.history];
1156
+ next[index] = { ...next[index]!, hiddenLines: undefined };
1157
+ return { ...prev, history: [...next, { input: '', output: expansion }] };
1158
+ });
1159
+ break;
1160
+ }
1161
+ }
1066
1162
  return;
1067
1163
  }
1068
1164
  // @-mention popup: Esc dismisses it instead of exiting the app.
@@ -1339,7 +1435,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1339
1435
  }
1340
1436
 
1341
1437
  if (phase === 'idle' && key.upArrow) {
1342
- const inputs = history.map(h => h.input);
1438
+ const inputs = chat.history.map(h => h.input);
1343
1439
  if (inputs.length === 0) return;
1344
1440
 
1345
1441
  if (historyIndex === -1) {
@@ -1358,7 +1454,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1358
1454
  if (phase === 'idle' && key.downArrow) {
1359
1455
  if (historyIndex === -1) return;
1360
1456
 
1361
- const inputs = history.map(h => h.input);
1457
+ const inputs = chat.history.map(h => h.input);
1362
1458
  const newIndex = historyIndex + 1;
1363
1459
 
1364
1460
  if (newIndex >= inputs.length) {
@@ -1376,6 +1472,17 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1376
1472
  }
1377
1473
  });
1378
1474
 
1475
+ // Live-region tail window: keep the interactive frame shorter than the
1476
+ // terminal or Ink falls back to clearing + repainting everything.
1477
+ // Wrapped-row budget (review finding: Ink counts folded screen rows, so
1478
+ // logical-line budgets blow on long CJK/diff lines): rows-12 with wide
1479
+ // chars measured at 2 columns, columns-2 for paddingX.
1480
+ const liveTail = sliceLiveTail(
1481
+ chat.liveOutput,
1482
+ (stdout?.rows ?? 24) - 12,
1483
+ (stdout?.columns ?? 80) - 2,
1484
+ );
1485
+
1379
1486
  const promptLabel = phase === 'model_select'
1380
1487
  ? 'vendor> '
1381
1488
  : phase === 'model_pick'
@@ -1396,29 +1503,48 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1396
1503
 
1397
1504
  return (
1398
1505
  <Box flexDirection="column" paddingX={1}>
1399
- {history.map((entry, i) => (
1400
- <Box key={i} flexDirection="column">
1401
- {entry.input && (
1402
- <Box flexDirection="column">
1403
- <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1404
- <Box>
1405
- <Text color="green" bold>&gt; </Text>
1406
- <Text color="cyan" bold>{entry.input}</Text>
1506
+ <Static items={chat.history}>
1507
+ {(entry, i) => (
1508
+ <Box key={i} flexDirection="column">
1509
+ {entry.input && (
1510
+ <Box flexDirection="column">
1511
+ <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1512
+ <Box>
1513
+ <Text color="green" bold>&gt; </Text>
1514
+ <Text color="cyan" bold>{entry.input}</Text>
1515
+ </Box>
1516
+ <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1407
1517
  </Box>
1408
- <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1409
- </Box>
1410
- )}
1411
- {entry.output && (
1412
- <Box marginLeft={2}>
1413
- <Text>
1414
- {entry.hiddenLines?.length
1415
- ? renderTurnLog(entry.output, entry.hiddenLines, verboseTools)
1416
- : entry.output}
1417
- </Text>
1418
- </Box>
1419
- )}
1518
+ )}
1519
+ {entry.output && (
1520
+ <Box marginLeft={2}>
1521
+ <Text>{entry.output}</Text>
1522
+ </Box>
1523
+ )}
1524
+ </Box>
1525
+ )}
1526
+ </Static>
1527
+
1528
+ {busy && chat.turnInput && (
1529
+ <Box flexDirection="column">
1530
+ <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1531
+ <Box>
1532
+ <Text color="green" bold>&gt; </Text>
1533
+ <Text color="cyan" bold>{chat.turnInput}</Text>
1534
+ </Box>
1535
+ <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1420
1536
  </Box>
1421
- ))}
1537
+ )}
1538
+ {liveTail.hidden > 0 && (
1539
+ <Box marginLeft={2}>
1540
+ <Text color="gray" dimColor>… +{liveTail.hidden} lines</Text>
1541
+ </Box>
1542
+ )}
1543
+ {liveTail.visible && (
1544
+ <Box marginLeft={2}>
1545
+ <Text>{liveTail.visible}</Text>
1546
+ </Box>
1547
+ )}
1422
1548
 
1423
1549
  {phase === 'permission' && pendingPermissionRef.current && (
1424
1550
  <Box marginLeft={2}>
@@ -3,7 +3,7 @@ import { bannerLines } from './banner.js';
3
3
 
4
4
  describe('bannerLines', () => {
5
5
  test('renders a closed rectangle with aligned sides', () => {
6
- const lines = bannerLines('T R A N S C O D E · Multi-model Agent').split('\n');
6
+ const lines = bannerLines('T R A N S C O D E · Multi-Model Agent').split('\n');
7
7
  expect(lines.length).toBe(3);
8
8
  expect(lines[0]!.startsWith('┌')).toBe(true);
9
9
  expect(lines[0]!.endsWith('┐')).toBe(true);
@@ -0,0 +1,47 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { displayWidth, sliceLiveTail } from './live-view.js';
3
+
4
+ describe('displayWidth', () => {
5
+ test('宽字符(CJK)按 2 列计,ASCII 按 1 列', () => {
6
+ expect(displayWidth('abc')).toBe(3);
7
+ expect(displayWidth('中文')).toBe(4);
8
+ expect(displayWidth('a中b')).toBe(4);
9
+ });
10
+ });
11
+
12
+ describe('sliceLiveTail (wrapped-row aware)', () => {
13
+ test('超窗截尾:visible 为最后若干逻辑行,hidden 为被截逻辑行数', () => {
14
+ const text = Array.from({ length: 12 }, (_, i) => `line-${i}`).join('\n');
15
+ const { visible, hidden } = sliceLiveTail(text, 5, 80);
16
+ expect(visible).toBe('line-7\nline-8\nline-9\nline-10\nline-11');
17
+ expect(hidden).toBe(7);
18
+ });
19
+
20
+ test('折行计入预算:尾部装最新行,装不下的大段被截(按屏幕行计)', () => {
21
+ const longCjk = '中'.repeat(200); // 80 列下 ≈ 5 屏幕行(400 列宽)
22
+ const text = `${longCjk}\nshort\nanother`;
23
+ const { visible, hidden } = sliceLiveTail(text, 6, 80);
24
+ // 尾窗保最新:another(1)+short(1)=2 行;longCjk 占 5 行装不下 → 截
25
+ expect(visible).toBe('short\nanother');
26
+ expect(hidden).toBe(1);
27
+ });
28
+
29
+ test('未超窗原样返回 hidden=0;空文本安全', () => {
30
+ expect(sliceLiveTail('a\nb\nc', 5, 80)).toEqual({ visible: 'a\nb\nc', hidden: 0 });
31
+ expect(sliceLiveTail('', 5, 80)).toEqual({ visible: '', hidden: 0 });
32
+ });
33
+
34
+ test('单逻辑行超预算也至少保留该行(不整行丢弃)', () => {
35
+ const longCjk = '中'.repeat(400); // ≈ 10 屏幕行
36
+ const { visible, hidden } = sliceLiveTail(longCjk, 3, 80);
37
+ expect(visible).toBe(longCjk);
38
+ expect(hidden).toBe(0);
39
+ });
40
+
41
+ test('maxLines 钳制下限 1:退化终端不产生空 visible 与虚高 hidden', () => {
42
+ const text = 'a\nb\nc';
43
+ const { visible, hidden } = sliceLiveTail(text, 0, 80);
44
+ expect(visible).toBe('c');
45
+ expect(hidden).toBe(2);
46
+ });
47
+ });
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Live-region tail windowing. The interactive frame must stay SHORTER than
3
+ * the terminal: once it reaches stdout rows, Ink falls back to
4
+ * clearTerminal + full-history repaint on every render (the flicker this
5
+ * rework kills). During a turn only the tail of the streamed output is
6
+ * shown; the full text lives in a ref and lands in <Static> at turn end.
7
+ *
8
+ * Budgeting counts WRAPPED screen rows (Ink's overflow check uses Yoga
9
+ * layout rows, where wide chars take two columns) — not logical lines.
10
+ */
11
+
12
+ export interface LiveTail {
13
+ visible: string;
14
+ hidden: number;
15
+ }
16
+
17
+ /** Approximate terminal columns taken by a string: CJK/fullwidth count 2. */
18
+ export function displayWidth(text: string): number {
19
+ let width = 0;
20
+ for (const ch of text) {
21
+ width += /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹯＀-⦆¢-₩]/.test(ch)
22
+ ? 2
23
+ : 1;
24
+ }
25
+ return width;
26
+ }
27
+
28
+ function screenRows(line: string, columns: number): number {
29
+ const width = displayWidth(line);
30
+ return Math.max(1, Math.ceil(width / columns));
31
+ }
32
+
33
+ export function sliceLiveTail(text: string, maxLines: number, columns: number): LiveTail {
34
+ if (!text) return { visible: '', hidden: 0 };
35
+ const budget = Math.max(1, maxLines);
36
+ const cols = Math.max(20, columns);
37
+ const lines = text.split('\n');
38
+
39
+ // Walk from the end, accumulating wrapped screen rows until the budget
40
+ // is exhausted. A single line that alone exceeds the budget is still
41
+ // kept (never drop content entirely — the constant margin absorbs it).
42
+ let used = 0;
43
+ let cut = lines.length; // index of first visible line
44
+ for (let i = lines.length - 1; i >= 0; i--) {
45
+ const rows = screenRows(lines[i]!, cols);
46
+ if (used + rows > budget && i !== lines.length - 1) break;
47
+ used += rows;
48
+ cut = i;
49
+ }
50
+ if (cut === 0) return { visible: text, hidden: 0 };
51
+ return { visible: lines.slice(cut).join('\n'), hidden: cut };
52
+ }
@@ -0,0 +1,76 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createStreamThrottler } from './stream-throttle.js';
3
+
4
+ interface Harness {
5
+ push: (chunk: string) => void;
6
+ flush: () => void;
7
+ appended: string[];
8
+ tick: () => void;
9
+ pendingTimer: () => boolean;
10
+ }
11
+
12
+ function harness(intervalMs = 32): Harness {
13
+ const appended: string[] = [];
14
+ let timer: (() => void) | null = null;
15
+ const throttler = createStreamThrottler((text) => appended.push(text), intervalMs, {
16
+ setTimer: (fn) => {
17
+ timer = fn;
18
+ return 0;
19
+ },
20
+ clearTimer: () => {
21
+ timer = null;
22
+ },
23
+ });
24
+ return {
25
+ ...throttler,
26
+ appended,
27
+ tick: () => {
28
+ const fn = timer;
29
+ timer = null;
30
+ fn?.();
31
+ },
32
+ pendingTimer: () => timer !== null,
33
+ };
34
+ }
35
+
36
+ describe('createStreamThrottler', () => {
37
+ test('窗口内多个 delta 合并为一次追加(内容按序拼接)', () => {
38
+ const h = harness();
39
+ h.push('He');
40
+ h.push('llo ');
41
+ h.push('world');
42
+ expect(h.appended).toEqual([]);
43
+ h.tick();
44
+ expect(h.appended).toEqual(['Hello world']);
45
+ });
46
+
47
+ test('定时器窗口外的新 delta 开新窗口', () => {
48
+ const h = harness();
49
+ h.push('a');
50
+ h.tick();
51
+ h.push('b');
52
+ h.push('c');
53
+ h.tick();
54
+ expect(h.appended).toEqual(['a', 'bc']);
55
+ });
56
+
57
+ test('flush 立即排水并取消挂起的定时器;空缓冲 flush 无操作', () => {
58
+ const h = harness();
59
+ h.push('x');
60
+ h.push('y');
61
+ h.flush();
62
+ expect(h.appended).toEqual(['xy']);
63
+ expect(h.pendingTimer()).toBe(false);
64
+ h.flush();
65
+ expect(h.appended).toEqual(['xy']);
66
+ });
67
+
68
+ test('flush 后再 push 正常开新窗口', () => {
69
+ const h = harness();
70
+ h.push('1');
71
+ h.flush();
72
+ h.push('2');
73
+ h.tick();
74
+ expect(h.appended).toEqual(['1', '2']);
75
+ });
76
+ });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Frame-level throttle for streaming output. Stock Ink re-renders
3
+ * synchronously on every setState — per-delta appends (dozens per second,
4
+ * each rewriting the whole history frame) are what makes the screen
5
+ * flicker. Coalescing deltas into one append per interval window cuts the
6
+ * render rate to frame level without changing output content or order.
7
+ */
8
+
9
+ export interface ThrottleTimers {
10
+ setTimer: (fn: () => void, ms: number) => unknown;
11
+ clearTimer: (handle: unknown) => void;
12
+ }
13
+
14
+ const REAL_TIMERS: ThrottleTimers = {
15
+ setTimer: (fn, ms) => setTimeout(fn, ms),
16
+ clearTimer: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
17
+ };
18
+
19
+ export function createStreamThrottler(
20
+ append: (text: string) => void,
21
+ intervalMs = 32,
22
+ timers: ThrottleTimers = REAL_TIMERS,
23
+ ): { push: (chunk: string) => void; flush: () => void } {
24
+ let buffer = '';
25
+ let pending: unknown = null;
26
+
27
+ const drain = (): void => {
28
+ if (pending !== null) {
29
+ timers.clearTimer(pending);
30
+ pending = null;
31
+ }
32
+ if (!buffer) return;
33
+ const text = buffer;
34
+ buffer = '';
35
+ append(text);
36
+ };
37
+
38
+ return {
39
+ push(chunk) {
40
+ buffer += chunk;
41
+ if (pending === null) {
42
+ pending = timers.setTimer(drain, intervalMs);
43
+ }
44
+ },
45
+ flush: drain,
46
+ };
47
+ }
@@ -40,25 +40,23 @@ describe('turn summary', () => {
40
40
  });
41
41
  });
42
42
 
43
- describe('renderTurnLog', () => {
44
- test('折叠:summary + "… +N lines (ctrl+o to expand)",N 数实际行数', async () => {
45
- const { renderTurnLog } = await import('./turn-summary.js');
46
- const hidden = ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓\nextra line', '\n⚙ grep foo ✓'];
47
- expect(renderTurnLog('⚙ 3 tool calls · …', hidden, false)).toBe(
48
- '⚙ 3 tool calls · …\n… +4 lines (ctrl+o to expand)',
49
- );
50
- });
51
43
 
52
- test('展开:明细可见 + "(ctrl+o to collapse)" 提示', async () => {
53
- const { renderTurnLog } = await import('./turn-summary.js');
54
- const out = renderTurnLog('S', ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓'], true);
55
- expect(out).toContain('read_file a.ts');
56
- expect(out).toContain('bash npm test');
57
- expect(out).toContain('(ctrl+o to collapse)');
44
+ describe('static render helpers', () => {
45
+ test('renderCollapsed:summary + "(ctrl+o 展开明细)" 提示;hiddenLines 空则原样', async () => {
46
+ const { renderCollapsed } = await import('./turn-summary.js');
47
+ const hidden = ['\n⚙ read_file a ✓', '\n⚙ bash t ✓', 'extra\nline'];
48
+ const out = renderCollapsed('⚙ 3 tool calls · …', hidden);
49
+ expect(out).toContain('⚙ 3 tool calls · …');
50
+ expect(out).toContain('… +4 lines (ctrl+o 展开明细)');
51
+ expect(renderCollapsed('S', [])).toBe('S');
58
52
  });
59
53
 
60
- test('无明细时原样返回 summary', async () => {
61
- const { renderTurnLog } = await import('./turn-summary.js');
62
- expect(renderTurnLog('S', [], false)).toBe('S');
54
+ test('renderExpansion:全量明细 + 头,无 collapse 提示', async () => {
55
+ const { renderExpansion } = await import('./turn-summary.js');
56
+ const out = renderExpansion({ output: '⚙ 2 tool calls · …', hiddenLines: ['\n⚙ read_file a ✓', '\n⚙ bash t ✓'] });
57
+ expect(out).toContain('展开明细');
58
+ expect(out).toContain('read_file a ✓');
59
+ expect(out).toContain('bash t ✓');
60
+ expect(out).not.toContain('collapse');
63
61
  });
64
62
  });
@@ -34,17 +34,18 @@ export function summaryLine(stats: TurnStats): string {
34
34
  }
35
35
 
36
36
  /**
37
- * Render a collapsed turn's tool log. Non-verbose: the summary line plus a
38
- * "… +N lines (ctrl+o to expand)" affordance; verbose (ctrl+o): the hidden
39
- * detail lines become visible so nothing is permanently unreachable.
37
+ * Collapsed turn line, stamped at creation time (static entries print once
38
+ * and never re-render): summary plus the expand affordance.
40
39
  */
41
- export function renderTurnLog(summary: string, hiddenLines: string[], verbose: boolean): string {
40
+ export function renderCollapsed(summary: string, hiddenLines: string[]): string {
42
41
  if (hiddenLines.length === 0) return summary;
43
- if (verbose) {
44
- return `${summary}\n(ctrl+o to collapse)${hiddenLines.join('')}`;
45
- }
46
42
  const count = hiddenLines
47
43
  .flatMap((line) => line.split('\n'))
48
44
  .filter((line) => line.trim().length > 0).length;
49
- return `${summary}\n… +${count} lines (ctrl+o to expand)`;
45
+ return `${summary}\n… +${count} lines (ctrl+o 展开明细)`;
46
+ }
47
+
48
+ /** ctrl+o action: full detail of a folded turn, printed as a new entry. */
49
+ export function renderExpansion(entry: { output: string; hiddenLines: string[] }): string {
50
+ return `⚙ 展开明细:${entry.hiddenLines.join('')}`;
50
51
  }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
2
- export const VERSION = '0.10.3';
2
+ export const VERSION = '0.11.0';