Skip to content

fix(cli): reduce retained interactive tool output memory - #4971

Merged
wenshao merged 10 commits into
QwenLM:mainfrom
kkhomej33-netizen:zach/reduce-interactive-output-memory
Jun 19, 2026
Merged

wenshao merged 10 commits into
QwenLM:mainfrom
kkhomej33-netizen:zach/reduce-interactive-output-memory

Conversation

@kkhomej33-netizen

@kkhomej33-netizen kkhomej33-netizen commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Reduces how much large tool-output display data the interactive CLI retains after rendering. Oversized display metadata is compacted before it is stored in scheduler state, live UI history, chat recording metadata, and subagent display summaries. Foreground PTY terminal resources are also disposed on natural shell exit, and retained terminal scrollback for display snapshots is bounded.

Why it's needed

Long interactive sessions can accumulate large display-only copies of tool output even after the model-facing tool result has already moved on. Heavy research tasks that run large shell commands, file diffs, MCP output, or nested agents can therefore grow process memory far beyond what the active conversation needs. Bounding these retained UI/history copies keeps the session usable without changing model-facing tool results or normal-sized display output.

Reviewer Test Plan

How to verify

Run the focused unit suites for retained tool display metadata and PTY cleanup: cd packages/core && npx vitest run src/services/shellExecutionService.test.ts src/core/coreToolScheduler.test.ts src/utils/toolResultDisplayCompaction.test.ts src/services/chatRecordingService.test.ts, and cd packages/cli && npx vitest run src/ui/hooks/useToolScheduler.test.ts. Then run package checks from the checkout: npm run build, cd packages/core && npm run typecheck, cd packages/cli && npm run typecheck, and touched-file lint with npx eslint for the files changed in this PR. Reviewers can also reproduce manually by running a long interactive session with large shell output, large file diffs, and nested agent/tool output, then confirming the CLI keeps rendered previews while retained history metadata is bounded.

Evidence (Before & After)

Non-visual memory-retention change. Before: UI/history paths could retain full oversized resultDisplay strings, nested agent tool-call payload fields, large file diff metadata, long ANSI terminal snapshots, and foreground PTY terminal resources after natural shell exit. After: unit tests assert generic display strings are compacted to a bounded head/tail preview, nested agent summaries drop non-rendered args, responseParts, and result payloads, saved chat metadata compacts large display data without mutating the original input, live output stored by the scheduler is compacted, CLI display history receives compacted metadata, and natural-exit PTY resources are disposed.

Tested on

OS Status
🍏 macOS ✅
🪟 Windows ⚠️
🐧 Linux ⚠️

Environment (optional)

macOS with Node.js v22.22.2 and npm 10.9.7. npm run build completed locally. packages/core and packages/cli typecheck passed after the workspace build generated local package declarations. Full npm run preflight was not run because this checkout currently has unrelated full-repo lint warnings outside the touched files; the touched files were linted directly and passed.

Risk & Scope

  • Main risk or tradeoff: very large display-only history entries now keep a compact head/tail preview instead of retaining the entire rendered payload in memory. Normal-sized output is unchanged, and model-facing tool results are not truncated by this PR.
  • Not validated / out of scope: local Windows/Linux validation and full preflight. This PR does not implement model-context tool-output truncation or disk offload; that is separate from retained interactive display metadata and is related to feat(core): layered tool-output truncation, per-message budget, per-tool limits #4880.
  • Breaking changes / migration notes: no intended breaking changes.

Linked Issues

Related to #4179 and #4182. Also related to, but separate from, #4880 because this PR bounds retained interactive display metadata rather than model-facing tool output.

中文说明

这个 PR 做了什么

减少交互式 CLI 在渲染之后继续保留的大型工具输出展示数据。超大的展示元数据会在进入 scheduler state、实时 UI 历史、聊天录制元数据和 subagent 展示摘要之前被压缩。前台 PTY 在 shell 自然退出时也会释放 terminal 资源,并且用于展示快照的 terminal scrollback 会被限制在固定范围内。

为什么需要

长时间交互会话可能会积累大量仅用于展示的工具输出副本,即使面向模型的工具结果已经继续向前推进。执行大型 shell 命令、大型文件 diff、MCP 输出或嵌套 agent/tool 输出的重型研究任务,可能因此让进程内存增长到远超当前对话实际需要的规模。限制这些 UI/history 保留副本,可以让会话保持可用,同时不改变面向模型的工具结果,也不改变普通大小输出的展示。

Reviewer 测试计划

如何验证

运行 retained tool display metadata 和 PTY cleanup 的聚焦单测:cd packages/core && npx vitest run src/services/shellExecutionService.test.ts src/core/coreToolScheduler.test.ts src/utils/toolResultDisplayCompaction.test.ts src/services/chatRecordingService.test.ts,以及 cd packages/cli && npx vitest run src/ui/hooks/useToolScheduler.test.ts。然后在 checkout 中运行包检查:npm run build、cd packages/core && npm run typecheck、cd packages/cli && npm run typecheck,并对本 PR 修改的文件直接运行 npx eslint。Reviewer 也可以通过一个长时间交互会话手动复现:运行大型 shell 输出、大型文件 diff、嵌套 agent/tool 输出,并确认 CLI 仍展示预览,同时保留在 history metadata 里的内容有上限。

证据(Before & After)

这是非视觉类的内存保留优化。Before:UI/history 路径可能保留完整的超大 resultDisplay 字符串、嵌套 agent tool-call payload 字段、大型 file diff 元数据、很长的 ANSI terminal 快照,以及 shell 自然退出后的前台 PTY terminal 资源。After:单测断言通用展示字符串会被压缩成有上限的 head/tail preview,嵌套 agent 摘要会丢弃不参与渲染的 args、responseParts 和 result payload,保存的聊天元数据会在不修改原始输入的情况下压缩大型展示数据,scheduler 存储的 live output 会被压缩,CLI 展示历史接收到的是压缩后的元数据,并且自然退出的 PTY 资源会被释放。

测试平台

见上方 OS 表(🍏 macOS 已测;🪟 Windows / 🐧 Linux 未在本地测试,交由 CI)。

运行环境(可选)

macOS,Node.js v22.22.2,npm 10.9.7。npm run build 已在本地完成。workspace build 生成本地包声明后,packages/core 和 packages/cli 的 typecheck 都通过。没有运行完整 npm run preflight,因为这个 checkout 当前在未触碰文件中有与本 PR 无关的全仓 lint warning;本 PR 修改的文件已直接 lint 并通过。

风险与范围

  • 主要风险或权衡:特别大的 display-only 历史条目现在会保留紧凑的 head/tail preview,而不是在内存中保留完整渲染 payload。普通大小输出不变,并且这个 PR 不会截断面向模型的工具结果。
  • 未验证 / 范围外:本地 Windows/Linux 验证和完整 preflight。这个 PR 不实现模型上下文中的工具输出截断或落盘 offload;那与 retained interactive display metadata 是不同问题,并且与 feat(core): layered tool-output truncation, per-message budget, per-tool limits #4880 相关。
  • 破坏性改动 / 迁移说明:没有预期的破坏性改动。

关联 Issues

Related to #4179 and #4182. Also related to, but separate from, #4880 because this PR bounds retained interactive display metadata rather than model-facing tool output.

Refs #2128

responseParts: event.responseParts,
...(typeof event.resultDisplay === 'string'
? { resultDisplay: event.resultDisplay }
: {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping responseParts and only storing resultDisplay when it is a string silently degrades non-interactive (JSON / stream-JSON) output for subagent tool calls.

nonInteractiveHelpers.ts reads from AgentResultDisplay.toolCalls to emit tool_use and tool_result events:

  • buildRequest uses toolCall.args || {} — with args removed on line 881, all subagent tool_use events now carry input: {}.
  • buildResponse uses toolCall.responseParts || [] — with responseParts removed here, all subagent tool_result events now carry empty responseParts.
  • hasResultContent returns false when resultDisplay is not a string and responseParts is absent and status is success. For subagent tool calls whose resultDisplay is a FileDiff (edit tool) or AnsiOutputDisplay (shell commands that return structured output), the tool_result event is silently dropped.

Suggestion: keep responseParts on the completed entry (or always store resultDisplay regardless of type) so that non-interactive consumers can still emit complete subagent tool results. The memory savings from dropping args on the executing entry and compacting resultDisplay strings are valid; the issue is specifically the total loss of result data for non-string displays.

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Thanks, this was a good catch. I pushed fe6140005 to address it.

What changed:

  • CoreToolScheduler now compacts only the retained scheduler state; outputUpdateHandler receives the raw output payload again so JSON/stream-JSON event consumers are not degraded.
  • The React scheduler compacts live output before storing it in TUI state.
  • Subagent tool-call protocol payloads (args / responseParts) are preserved in non-interactive mode, while interactive display state still omits them to avoid retaining large duplicate payloads.

Verification:

  • packages/core: npx vitest run src/core/coreToolScheduler.test.ts src/tools/agent/agent.test.ts src/utils/toolResultDisplayCompaction.test.ts src/services/chatRecordingService.test.ts (321 tests passed)
  • packages/cli: npx vitest run src/ui/hooks/useToolScheduler.test.ts src/utils/nonInteractiveHelpers.test.ts (80 tests passed)
  • packages/core: npm run typecheck
  • packages/cli: npm run typecheck
  • touched-file npx eslint ...
  • root npm run build and npm run bundle
  • interactive memory harness against the bundled CLI with a local fake OpenAI server and real TUI shell mode (!): 40 rounds x 1MB shell output stayed bounded at ready 211.4MB / peak 624.3MB / final 617.7MB; 8 rounds x 4MB stayed at ready 219.5MB / peak 518.0MB / final 514.7MB.

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Follow-up after re-running the memory repro more strictly: the earlier 40-round run was not heavy enough.

Red test on the pre-optimization baseline (fork/main, fb1432cf5): interactive TUI shell mode, 120 rounds x 1MB shell output, using the bundled CLI and a local fake OpenAI server. Result: ready 213.9MB, peak/final 811.6MB, and the next prompt hit Context is too large to send safely after automatic compression because shell-mode output was still accumulated in session history.

After 66550b58b: the same 120 rounds x 1MB repro no longer hits context-too-large, the fake server receives the next request, and RSS is ready 206.8MB, peak 645.5MB, final 642.7MB.

Additional fix in this commit: interactive shell mode now compacts the UI history result and stores only a small head/tail summary in model history. Added a focused unit test covering both retained UI output and model-history output.

Verification after this follow-up:

  • packages/cli: npx vitest run src/ui/hooks/shellCommandProcessor.test.ts src/ui/hooks/useToolScheduler.test.ts src/utils/nonInteractiveHelpers.test.ts (101 tests passed)
  • packages/core: npx vitest run src/core/coreToolScheduler.test.ts src/tools/agent/agent.test.ts src/utils/toolResultDisplayCompaction.test.ts src/services/chatRecordingService.test.ts (321 tests passed)
  • packages/cli: npm run typecheck
  • packages/core: npm run typecheck
  • touched-file npx eslint ...
  • root npm run build and npm run bundle

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Correction to my previous follow-up: Context is too large is not a memory metric, and changing shell output stored in model history would be a functional behavior change rather than a pure memory optimization.

I pushed 09264a6cf to restore the previous shell model-history behavior: shell-mode output passed to GeminiClient.addHistory still uses the existing 10k-prefix truncation. The new unit test now asserts that this behavior remains unchanged while only the retained UI history display is compacted.

Updated RSS-only comparison for the same interactive shell repro (120 rounds x 1MB output):

  • Baseline fork/main (fb1432cf5): ready 213.9MB, peak/final 811.6MB
  • Current PR (09264a6cf): ready 209.5MB, peak/final 706.4MB

The context-too-large error still appears in that extreme repro, as expected, because model context behavior is intentionally preserved. I am treating the RSS delta as the memory evidence, not the context-size error.

Re-verified after the correction:

  • packages/cli: npx vitest run src/ui/hooks/shellCommandProcessor.test.ts src/ui/hooks/useToolScheduler.test.ts src/utils/nonInteractiveHelpers.test.ts (101 tests passed)
  • packages/cli: npm run typecheck
  • touched shell processor ESLint
  • root npm run build and npm run bundle

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Update after re-checking the memory evidence:

I found that my earlier full TUI RSS harness was not a clean proof for this follow-up. After tightening the harness, the full pty path did not reliably exercise the retained-history issue because it mostly observes terminal screen-state output. I am no longer treating those earlier TUI RSS numbers as the primary evidence.

I added one more commit, 78a80b5a4 fix(cli): release truncated shell output backing strings, for a more specific retention case: shell model history still keeps the same 10k-prefix semantics, but the truncated prefix is now copied so a sliced string cannot retain the full large shell output backing storage.

Focused red/green memory bench, using the real useShellCommandProcessor path with 120 rounds x 1MB shell outputs and retained UI history:

  • Before this commit (09264a6cf): retained UI chars 3,840,000, heap delta 118.4MB, RSS delta 123.7MB
  • After this commit (78a80b5a4): retained UI chars 3,840,000, heap delta 11.5MB, RSS delta 19.6MB

The retained UI text stays compact in both cases, so the remaining large heap growth was from the model-history 10k substring retaining the original large output. The new commit keeps model-visible text unchanged while releasing that backing storage.

Verification after the update:

  • packages/cli: npx vitest run src/ui/hooks/shellCommandProcessor.test.ts src/ui/hooks/useToolScheduler.test.ts src/utils/nonInteractiveHelpers.test.ts -> 101 passed
  • packages/core: npx vitest run src/core/coreToolScheduler.test.ts src/tools/agent/agent.test.ts src/utils/toolResultDisplayCompaction.test.ts -> 294 passed
  • npm run typecheck --workspace=packages/cli -> passed
  • npm run typecheck --workspace=packages/core -> passed
  • npm install / build / bundle completed in the PR worktree, with existing VSCode companion lint warnings only

@kkhomej33-netizen
kkhomej33-netizen force-pushed the zach/reduce-interactive-output-memory branch from 15037c4 to 00368f9 Compare June 12, 2026 02:34
];
}

function compactAnsiLine(line: AnsiLine): AnsiLine {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] compactAnsiOutput has zero test coverage. AnsiOutputDisplay is the primary display type for shell commands in interactive mode — both branches (≤200 lines passthrough and >200 lines truncation with marker line) are untested. A bug here could crash or corrupt the React renderer for any shell command producing >200 lines of output.

Consider adding at least two test cases: one with an AnsiOutputDisplay under the line limit (verify per-line compactAnsiLine is applied), and one exceeding 200 lines (verify the marker line appears, line count is bounded, and tail lines are retained).

— qwen3.7-max via Qwen Code /review

description: compactStringForHistory(
description,
MAX_RETAINED_AGENT_FIELD_CHARS,
),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] compactTodoResultDisplay, compactPlanResultDisplay, and compactMcpToolProgressData have zero test coverage. Combined with the compactAnsiOutput gap above, 5 out of 7 compact* functions lack tests. Each has distinct branching logic (map over todos, conditional message compaction, different char limits) that is entirely uncovered.

Consider adding one test case per display type, each with a field exceeding its respective limit, verifying the compacted output is within bounds and the marker is present.

— qwen3.7-max via Qwen Code /review

if (isMcpToolProgressData(resultDisplay)) {
return compactMcpToolProgressData(resultDisplay) as T;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] compactToolResultDisplayForHistory does not handle TaskListResultDisplay (type 'task_list') or TeamResultDisplay (type 'team'). Both types are part of the ToolResultDisplay union but fall through to return resultDisplay unchanged, bypassing compaction entirely. TaskListResultDisplay.tasks[].subject is an unbounded string that could grow large.

Consider adding an isTaskListResultDisplay guard and compacting the subject field of each task entry (similar to compactTodoResultDisplay), or adding a comment explaining the deliberate exclusion if these types are expected to always be small.

— qwen3.7-max via Qwen Code /review

allowProposedApi: true,
cols,
rows,
scrollback: MAX_LIVE_TERMINAL_SCROLLBACK_LINES,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Headless terminal scrollback is reduced from xterm.js default (1000) to MAX_LIVE_TERMINAL_SCROLLBACK_LINES (200). The primary replay path (replayTerminalOutput) creates its own terminal, so the main path is unaffected. However, the fallback serialization path (~line 1797: serializeTerminalToText(headlessTerminal) when replayTerminalOutput throws) now truncates output beyond 200 lines where previously up to 1000 lines were preserved — a silent data regression in a rare but real fallback path.

Consider either using replayTerminalOutput with the raw buffer in the fallback path, or documenting the trade-off explicitly.

— qwen3.7-max via Qwen Code /review

(ptyInfo?.name as 'node-pty' | 'lydell-node-pty') ?? 'node-pty',
});
} finally {
try {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] headlessTerminal.dispose() is added in the background-promote finally block, but no test verifies it is called. The natural-exit dispose IS tested (line 315: terminalDisposeSpy), but the promote path — which is the specific leak this PR aims to fix — has no disposal assertion.

Consider adding a vi.spyOn(Terminal.prototype, 'dispose') assertion in the existing background-promote test to verify terminal disposal after the promote resolves.

— qwen3.7-max via Qwen Code /review

@wenshao

wenshao commented Jun 12, 2026

Copy link
Copy Markdown
Collaborator

🧪 Local runtime verification (built CLI + real model, tmux, with a latest-main control build) — ✅ PASS (no regressions; compaction verified at the deterministic surface; honest null result on short-session RSS)

Built the PR head (db646b8, 7 commits) and a control build of latest main (c491f33), then drove both dist/cli.js builds through identical interactive workloads in tmux with a real model, measuring process RSS at fixed checkpoints and inspecting the retained artifacts the PR targets. Scratch dir surface; worker-process baselines were near-identical (202–204 MB), so the comparison is clean.

Workloads (identical on both builds, model-driven through the real TUI):

  • Shell-heavy: 3 × seq 1 800000 (≈6.2 MB stdout each) + printf 'alpha\nbeta\n' control
  • Edit-heavy (fresh sessions): generate a 1.29 MB big.txt, then 3 × Edit-tool single-line edits (each FileDiff carries ~1.29 MB originalContent/newContent)
  • Probes: model-fidelity check, Esc mid-38 MB output, pane resize mid-stream

What the deterministic surface shows (chat-recording JSONL on disk)

Same workload, per-tool-call retained resultDisplay:

Artifact main control PR build
Large shell output (string display) 70,343 chars, no marker exactly 32,000 chars + [... truncated from 70343 characters for CLI history display ...]
printf (10 chars) verbatim verbatim, no marker — normal-sized output untouched
Edit-tool FileDiff (1.29 MB contents) 16,000 chars + truncatedForSession: true 16,000 chars + truncatedForSession: true, plus faithful length metadata (origContentLength: 1288895, …)

Two honest observations fall out of that table:

  1. The PR's compaction works exactly as designed where it's deterministically observable: oversized generic string displays go from 70 K retained to a bounded 32 K head/tail with an honest marker; small output is byte-identical.
  2. FileDiff compaction at the recording layer already existed on main (same 16 K + truncatedForSession came back on the control build). The PR's novel coverage for FileDiff/agent displays is at the in-memory retention points (scheduler state, live UI history, subagent summaries) — which a black-box run can't directly inspect; their correctness rides on this PR's unit suites, which is precisely what those cover.

RSS measurements (the headline claim, measured honestly)

Worker-process RSS at identical checkpoints:

shell-heavy:  main 202→405→668→832→869 MB   |   PR 202→398→597→864→871 MB
edit-heavy:   main 202→353→356→413→568 MB   |   PR 204→359→362→426→575 MB

No measurable RSS difference at this session scale — in either direction. That is a null result, not a refutation: the per-call retained-display delta this PR removes (~38 KB per big shell call; a few MB per huge-diff edit) is far below the V8/xterm transient churn (±50 MB between identical checkpoints) that dominates short-session RSS on both builds. The benefit this PR claims is cumulative over long sessions (e.g. 100 large-diff edits ≈ hundreds of MB of display copies on main vs ≈ tens of KB compacted) — a 3-edit review session cannot surface it through RSS, and I'd rather report that than dress up GC noise as a win. What the numbers do establish: the compaction adds no observable cost or regression.

Functional checks (all on the PR build)

  1. ✅ Huge seq output → TUI renders the usual bounded live tail; the pre-existing "Output too long and was saved to: ~/.qwen/tmp/.../run_shell_command_*.output" model-side offload path is intact; UI stays responsive.
  2. ✅ Model fidelity: ran seq 1 9000 && echo MAGIC-LAST-LINE-XYZQ (display 70,343 chars → compacted to 32 K, marker confirms it hit this call), then asked the model for the exact last line → it answered MAGIC-LAST-LINE-XYZQ. Display compaction did not touch the model-facing result.
  3. ✅ Normal-size control: printf display recorded at 10 chars, no marker.
  4. 🔍 Esc mid-seq 1 5000000 (≈38 MB) → clean "Request cancelled.", session healthy afterwards; pane resize mid-stream → no corruption.
  5. 🔍 8+ shell executions including the cancelled 38 MB one → no PTY-related errors or hangs (the natural-exit PTY disposal / 200-line live scrollback changes aren't separately distinguishable in black-box RSS at this scale; no regression observed).

Notes for the record

  • The shell display string entering retention was already pre-bounded to ~70 K by the terminal-replay snapshot before this PR — so for plain shell output the per-call saving is ~38 KB. The multi-MB wins live in the FileDiff / agent-display paths and across long sessions.
  • Total recording size for the identical edit-only workload: main 155,084 bytes vs PR 154,312 bytes — consistent with "recording-layer FileDiff compaction pre-existed; the PR's disk-visible delta is the generic-string bound".
  • PR head is ~20 commits behind a fast-moving main; control was latest main at test time (c491f33). No conflicts surfaced in behavior, but a rebase before merge wouldn't hurt.

Verdict (merge reference)

PASS. Every deterministically observable claim holds: bounded head/tail retention with honest markers, small output untouched, model-facing results untouched, no functional or memory regressions, cancel/resize robust. The one thing I could not demonstrate is an RSS-level improvement in a short session — by the math above, no short black-box session can, and the PR's own unit suites are the right instrument for the in-memory retention points. Nothing here blocks merging.

🇨🇳 中文版(点击展开)

🧪 本地运行时验证(构建后 CLI + 真实模型,tmux,含最新 main 对照构建)— ✅ 通过(零回归;压缩在确定性表面得到证实;短会话 RSS 为诚实的零结果)

构建了 PR head(db646b8,7 个 commit)以及最新 main(c491f33)的对照版本,在 tmux 中用真实模型对两个 dist/cli.js 构建执行完全相同的交互工作负载,在固定检查点测量进程 RSS,并检查 PR 所针对的保留产物。临时目录环境;两个 worker 进程基线几乎一致(202–204 MB),对照条件干净。

工作负载(两个构建完全相同,经真实 TUI 由模型驱动):

  • Shell 重载: 3 × seq 1 800000(每次 ≈6.2 MB 输出)+ printf 'alpha\nbeta\n' 对照
  • Edit 重载(全新会话): 生成 1.29 MB 的 big.txt,然后 3 次 Edit 工具单行编辑(每次 FileDiff 携带 ~1.29 MB 的 originalContent/newContent)
  • 探针:模型保真检查、38 MB 输出中途 Esc、流式期间调整窗口大小

确定性表面的结果(落盘的聊天记录 JSONL)

相同工作负载下,每个工具调用保留的 resultDisplay:

产物 main 对照 PR 构建
大型 shell 输出(字符串展示) 70,343 字符,无标记 精确 32,000 字符 + [... truncated from 70343 characters for CLI history display ...]
printf(10 字符) 原样 原样、无标记——普通大小输出不受影响
Edit 工具 FileDiff(1.29 MB 内容) 16,000 字符 + truncatedForSession: true 16,000 字符 + truncatedForSession: true,并带真实长度元数据(origContentLength: 1288895 等)

由此得出两个诚实的观察:

  1. PR 的压缩在可确定性观察的地方完全按设计工作:超大通用字符串展示从保留 70K 变为有界的 32K head/tail 并带诚实标记;小输出逐字节一致。
  2. FileDiff 在记录层的压缩在 main 上已经存在(对照构建返回了相同的 16K + truncatedForSession)。PR 对 FileDiff/agent 展示的新增覆盖在内存内保留点(scheduler state、实时 UI 历史、子 agent 摘要)——黑盒运行无法直接检视这些;其正确性由本 PR 的单测套件保证,而那正是单测覆盖的内容。

RSS 测量(核心声明,诚实测量)

worker 进程在相同检查点的 RSS:

shell 重载:  main 202→405→668→832→869 MB   |   PR 202→398→597→864→871 MB
edit 重载:   main 202→353→356→413→568 MB   |   PR 204→359→362→426→575 MB

**在此会话规模下,两个方向都没有可测量的 RSS 差异。**这是零结果而非反驳:本 PR 消除的每次调用保留展示增量(大 shell 调用约 38 KB;超大 diff 编辑约几 MB)远低于支配短会话 RSS 的 V8/xterm 瞬态扰动(相同检查点间 ±50 MB)。PR 声称的收益是长会话累积型的(如 100 次大 diff 编辑在 main 上 ≈ 数百 MB 展示副本 vs 压缩后 ≈ 数十 KB)——3 次编辑的评审会话无法通过 RSS 呈现它,我宁可如实报告,也不把 GC 噪声包装成收益。这些数字确实证明的是:压缩没有引入任何可观察的开销或回归。

功能检查(均在 PR 构建上)

  1. ✅ 超大 seq 输出 → TUI 照常渲染有界的实时尾部;既有的 "Output too long and was saved to: ~/.qwen/tmp/.../run_shell_command_*.output" 模型侧落盘路径完好;UI 保持响应。
  2. ✅ 模型保真: 运行 seq 1 9000 && echo MAGIC-LAST-LINE-XYZQ(展示 70,343 字符 → 压到 32K,标记证明压缩命中这一次调用),随后问模型输出的最后一行 → 准确回答 MAGIC-LAST-LINE-XYZQ。展示压缩未触碰模型侧结果。
  3. ✅ 普通大小对照:printf 的展示按 10 字符记录、无标记。
  4. 🔍 seq 1 5000000(≈38 MB)中途 Esc → 干净的 "Request cancelled.",会话随后健康;流式期间调整窗口 → 无渲染损坏。
  5. 🔍 8+ 次 shell 执行(含被取消的 38 MB 那次)→ 无 PTY 相关错误或挂起(自然退出 PTY 释放/200 行实时 scrollback 的改动在此规模的黑盒 RSS 中无法单独分辨;未观察到回归)。

备注

  • 进入保留环节的 shell 展示字符串在本 PR 之前就已被终端回放快照预先约束到 ~70K——因此纯 shell 输出的每次调用节省约 38 KB。MB 级收益在 FileDiff/agent 展示路径及长会话累积中。
  • 相同 edit-only 工作负载的记录文件总大小:main 155,084 字节 vs PR 154,312 字节——与"记录层 FileDiff 压缩先于本 PR 存在;PR 的磁盘可见增量是通用字符串上界"一致。
  • PR head 落后快速前进的 main 约 20 个 commit;对照为测试时的最新 main(c491f33)。行为上未见冲突,但合并前 rebase 一下无妨。

结论(合并参考)

**通过。**所有可确定性观察的声明全部成立:有界的 head/tail 保留 + 诚实标记、小输出不受影响、模型侧结果不受影响、无功能或内存回归、取消/调整窗口健壮。唯一未能演示的是短会话内 RSS 级别的改善——按上面的数学,任何短黑盒会话都无法做到,而 PR 自带的单测套件正是内存内保留点的正确检验工具。没有任何阻碍合并的问题。

DragonnZhang
DragonnZhang previously approved these changes Jun 15, 2026

@DragonnZhang DragonnZhang left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent memory optimization for interactive tool output. compactToolResultDisplayForHistory truncates large resultDisplay values (string and {ansiOutput}) to MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS for UI history while preserving full output in model history. Applied consistently across shellCommandProcessor, useReactToolScheduler, and mapToDisplay. The copyString helper correctly avoids shared memory references on truncated substrings. Surrogate code unit handling in truncation is correct. Thorough test coverage. CI green. LGTM ✅ — claude-opus-4-6 via Qwen Code /review

? (outputChunk: ToolResultDisplay) => {
const compactOutput =
this.compactResultDisplayForInteractiveHistory(outputChunk);
if (this.outputUpdateHandler) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Live-output compaction is applied up to three times on the same data. Here outputUpdateHandler receives the raw outputChunk, while tc.liveOutput stores the compacted version. React's useReactToolScheduler.ts:115 then compacts the raw chunk a second time before storing it, and mapToDisplay at line 364 compacts the already-compacted liveOutput a third time.

This works today because compactToolResultDisplayForHistory is idempotent, but the raw-vs-compacted boundary is unclear and fragile — any future change that breaks idempotency (lowering limits, changing marker format) would silently produce double-markered output.

Suggested approach: compact once at the source. Either (a) send compactOutput to outputUpdateHandler and remove redundant compaction in the React handler and mapToDisplay, or (b) skip compaction in the core live-output path and let only the React side compact at the display boundary.

— qwen3.7-max via Qwen Code /review

return {
...toolCallResult,
resultDisplay: sanitizedResultDisplay,
} as T;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The JSONL recording path now applies compactToolResultDisplayForHistory to all non-FileDiff displays, but this function was designed for interactive CLI history and embeds markers reading "truncated from N characters for CLI history display". The JSONL session file is a persistent saved-session artifact, not an interactive scrollback buffer.

Note that the FileDiff branch (just above) uses sanitizeFileDiffForRecording which produces recording-appropriate markers ("truncated for saved session preview"). Non-FileDiff types should use similar recording-specific markers for consistency.

Also, compactAnsiOutputDisplay always returns a new object (even when no truncation is needed), so the identity check sanitizedResultDisplay === resultDisplay on the next line never fires for ANSI outputs — every structured display triggers an unnecessary recording object copy.

Suggested approach: either create a compactToolResultDisplayForRecording variant with recording-appropriate markers, or parameterize the marker text in compactStringForHistory.

— qwen3.7-max via Qwen Code /review

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. I addressed both points in ab940eb:

  • Recording now uses a recording-specific compaction path, so saved session JSONL previews use saved-session wording instead of CLI history wording. I also kept unchanged ANSI output displays by reference so the recording sanitizer can avoid unnecessary object copies when nothing was compacted.
  • Executing live output is no longer compacted again in mapToDisplay. The raw outputUpdateHandler payload remains unchanged; React compacts raw update chunks when storing display state, and mapToDisplay now consumes that already-compacted display state.

Verified locally with focused core/cli tests, typecheck, and build.

@DragonnZhang DragonnZhang left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incremental review at ab940eb7: one new commit (fix(cli): refine tool output compaction boundaries) adds a clean CompactionPurpose abstraction (history vs recording) so the same compaction logic produces context-appropriate markers ("CLI history display" vs "saved session preview"). Also fixes a correctness issue where chatRecordingService was using compactToolResultDisplayForHistory instead of the new compactToolResultDisplayForRecording. Removes redundant double-compaction in mapToDisplay's executing case (live output is already compacted by outputUpdateHandler). New tests cover recording-specific wording and reference preservation. CI green (30/30 checks). LGTM ✅ — claude-opus-4-6 via Qwen Code /review

@wenshao

wenshao commented Jun 15, 2026

Copy link
Copy Markdown
Collaborator

✅ Verification report — real build + interactive E2E (merge reference)

I built the PR branch from source and verified it end-to-end on Linux (the platform marked ⚠️ untested in the PR description). Result: the change does what it claims and is safe to merge. Retained interactive display data is bounded, while model-facing tool results and the on-screen preview are unchanged. All touched unit suites, typecheck, and lint pass.

Environment: Linux x64 · Node v22.22.2 · npm 10.9.7 · clean npm install in a dedicated worktree at the PR head (ab940eb7c), diffed against base 6677ca1dd (16 files, +1670/−54).


1. Code audit — model fidelity is preserved

The compaction only ever rewrites display / history / recording copies; it never touches the model-facing payload.

  • coreToolScheduler.ts — compaction is gated behind isInteractive() and applied only to resultDisplay and the stored liveOutput. responseParts (the model-facing result) is passed through untouched, and the live outputUpdateHandler still receives the full chunk before the stored copy is compacted.
  • shellExecutionService.ts — the new scrollback: 200 bound is on the live headless terminal only (base was the xterm default of 1000). The final model-facing text output is rendered through replayTerminalOutput, which still uses scrollback: 10000 (unchanged). The 200-line path is reached only for binary output (isStreamingRawContent === false), which isn't rendered as text anyway. No model-facing text-output regression. PTY/terminal dispose() calls were added on natural exit, background-promote, and replay (try/finally, best-effort).
  • shellCommandProcessor.ts — model (geminiClient) history content is byte-identical; copyString() only forces a flat copy of the already-truncated substring(0, 10000) so it stops pinning the 300KB+ parent. UI history gets the compacted copy.
  • agent.ts — args / responseParts / result are dropped from nested sub-agent tool-call entries only in interactive mode (preserveProtocolPayloads = !isInteractive()); the headless JSON protocol keeps them. I confirmed via a code sweep that no UI (CLI Ink, WebUI, web-shell) ever reads those three fields for rendering — only callId/name/status/description/error/resultDisplay are rendered. So dropping them is display-safe.
  • chatRecordingService.ts — the existing FileDiff sanitization path is preserved; other displays now compact for recording without mutating the input object.

2. Unit tests — 549 passing

Suite Tests
core/toolResultDisplayCompaction.test.ts 11 ✅
core/shellExecutionService.test.ts 99 ✅
core/chatRecordingService.test.ts 34 ✅
core/agent/agent.test.ts 105 ✅
core/coreToolScheduler.test.ts 206 ✅
cli/useToolScheduler.test.ts 19 ✅
cli/shellCommandProcessor.test.ts 22 ✅
cli/nonInteractiveHelpers.test.ts 53 ✅

3. Independent reverse-audit probes (gaps the suites don't cover)

Importing the real exported functions, I probed claims the unit tests don't directly assert:

  • The core memory claim (untested in the suite) — confirmed. Slicing a 200 MB string and keeping a 32 KB head/tail the naive way (slice + concat) retains a 100 MB V8 SlicedString parent; compactStringForHistory (which routes through copyString = split('').join('')) retains 0 MB — the parent buffer is provably released. This is the mechanism the whole PR rests on.
  • Idempotent & strictly bounded: re-compacting is a no-op; output length is exactly the limit (32000), including the LIM and LIM+1 edges; an exactly-LIM input is returned unchanged.
  • No mutation: the original FileDiff object/strings are untouched after compaction.
  • FileDiff path (not covered by the compaction test file): fileDiff/originalContent/newContent bounded to 50K/16K/16K, truncatedForSession/fileDiffTruncated flags set, original lengths recorded, small diffs returned by reference.

4. Real interactive E2E (tmux) + A/B — the headline evidence

Built the real CLI, ran it in a tmux pane, and used !-shell mode to cat a 303,893-byte / 5,000-line file (exercises shellCommandProcessor with no model round-trip). I then toggled the compaction off in the built dist and re-ran the identical command:

"lines hidden" marker Retained display On-screen tail
With PR ... first 343 lines hidden ... ~533 lines (≈32 KB) LINE-04811 … LINE-05000
Compaction off (pre-PR equiv.) ... first 4810 lines hidden ... ~5000 lines (≈304 KB) LINE-04811 … LINE-05000

190 visible + 343 hidden = 533 lines ≈ 32,000 chars — exactly the 60/40 head/tail bound. The retained history structure shrank ~9.5× (5000 → 533 lines) for this input, while the user-visible output is byte-identical in both runs. That is precisely the PR's contract: bound the retained copy, preserve the rendered preview. The CLI stayed responsive and the prompt returned cleanly.

5. Build / typecheck / lint

  • npm install + workspace build (produces dist): OK
  • packages/core tsc --noEmit: clean (exit 0)
  • packages/cli tsc --noEmit: clean (exit 0)
  • eslint on all 16 touched files: clean (exit 0)

Minor observations (non-blocking)

  1. Live scrollback 1000 → 200 lines. While a long command is still running, interactive scroll-back is now capped at 200 lines (was 1000). The final result and the model-facing output are unaffected (10000-line replay). Reasonable trade-off; worth a one-line mention in the PR text.
  2. copyString is O(n) (split('').join('')) and runs per oversized chunk on canUpdateOutput tools. It only fires when a value exceeds the limit and is bounded by the output throttle, so impact is small — just noting it.
  3. Double compaction on the React path (coreToolScheduler then useReactToolScheduler) is idempotent; only a little redundant work.
  4. Scope: compaction is interactive-only by design, so headless/serve sessions don't get the bound — correct for protocol fidelity, but the memory win doesn't apply there.

Verdict

LGTM — recommend merge. The memory bound is real and measurable, model-facing results and the rendered preview are untouched, and the full touched-file test/typecheck/lint surface is green. Linux is now verified via a real interactive build in addition to the author's macOS testing.

🇨🇳 中文版验证报告(点击展开)

✅ 验证报告 — 真实构建 + 交互式 E2E(供合并参考)

我从源码构建了该 PR 分支,并在 Linux(PR 描述中标记为 ⚠️ 未测试的平台)上做了端到端验证。结论:改动确实达成了其声明的效果,可以安全合并。 被保留的交互式展示数据得到了限制,而面向模型的工具结果和屏幕上的预览保持不变。所有受影响的单测、typecheck 和 lint 均通过。

环境: Linux x64 · Node v22.22.2 · npm 10.9.7 · 在 PR head(ab940eb7c)的独立 worktree 中执行干净的 npm install,对比基线 6677ca1dd(16 个文件,+1670/−54)。

1. 代码审计 — 面向模型的保真度被保留

压缩只重写展示 / 历史 / 录制副本,从不触碰面向模型的 payload。

  • coreToolScheduler.ts — 压缩由 isInteractive() 把关,只作用于 resultDisplay 和存储的 liveOutput;responseParts(面向模型的结果)原样透传,实时 outputUpdateHandler 仍先收到完整 chunk,之后才压缩存储副本。
  • shellExecutionService.ts — 新增的 scrollback: 200 只限制实时 headless 终端(基线是 xterm 默认 1000)。最终面向模型的文本输出通过 replayTerminalOutput 渲染,仍使用未改动的 scrollback: 10000;200 行那条分支只在二进制输出(isStreamingRawContent === false)时走到,而二进制本就不会按文本渲染。面向模型的文本输出无回归。 在自然退出 / 后台提升 / replay 路径上新增了 PTY/终端 dispose()(try/finally,best-effort)。
  • shellCommandProcessor.ts — 写入模型(geminiClient)历史的内容逐字节一致;copyString() 只是把已经截断的 substring(0, 10000) 做一次扁平拷贝,从而不再 pin 住 300KB+ 的父字符串。UI 历史拿到的是压缩副本。
  • agent.ts — args / responseParts / result 仅在交互模式下从嵌套子 agent 的 tool-call 条目中丢弃(preserveProtocolPayloads = !isInteractive());headless JSON 协议会保留它们。我通过代码扫描确认:没有任何 UI(CLI Ink、WebUI、web-shell)在渲染时读取这三个字段——只读取 callId/name/status/description/error/resultDisplay。因此丢弃它们对展示是安全的。
  • chatRecordingService.ts — 保留了原有的 FileDiff 清洗路径;其它展示类型现在会为录制做压缩,且不修改输入对象。

2. 单元测试 — 549 个通过

测试套件 数量
core/toolResultDisplayCompaction.test.ts 11 ✅
core/shellExecutionService.test.ts 99 ✅
core/chatRecordingService.test.ts 34 ✅
core/agent/agent.test.ts 105 ✅
core/coreToolScheduler.test.ts 206 ✅
cli/useToolScheduler.test.ts 19 ✅
cli/shellCommandProcessor.test.ts 22 ✅
cli/nonInteractiveHelpers.test.ts 53 ✅

3. 独立的反向审计探针(覆盖测试套件未覆盖的点)

通过 import 真实导出的函数,我验证了单测没有直接断言的声明:

  • 核心内存声明(套件未测)— 已确认。 对一个 200MB 字符串切出 32KB head/tail:朴素写法(slice + concat)会保留 100MB 的 V8 SlicedString 父串;而 compactStringForHistory(经由 copyString = split('').join(''))保留 0MB——父缓冲区被切实释放。这正是整个 PR 依赖的机制。
  • 幂等且严格有界: 重复压缩为 no-op;输出长度恰好等于上限(32000),LIM 和 LIM+1 边界都成立;恰好 LIM 的输入原样返回。
  • 不修改原值: 压缩后原始 FileDiff 对象/字符串保持不变。
  • FileDiff 路径(压缩测试文件未覆盖):fileDiff/originalContent/newContent 被限制到 50K/16K/16K,truncatedForSession/fileDiffTruncated 标志置位,原始长度被记录,小 diff 按引用原样返回。

4. 真实交互式 E2E(tmux)+ A/B 对照 — 最有力的证据

构建真实 CLI,在 tmux pane 中运行,用 ! shell 模式 cat 一个 303,893 字节 / 5,000 行的文件(在不经过模型往返的情况下走 shellCommandProcessor)。随后在构建产物 dist 中关闭压缩并重跑同一条命令:

"lines hidden" 标记 保留的展示 屏幕上的尾部
启用 PR ... first 343 lines hidden ... ~533 行(≈32 KB) LINE-04811 … LINE-05000
关闭压缩(等价于 PR 前) ... first 4810 lines hidden ... ~5000 行(≈304 KB) LINE-04811 … LINE-05000

190 可见 + 343 隐藏 = 533 行 ≈ 32,000 字符——恰好是 60/40 head/tail 的界限。对该输入,保留的历史结构缩小了 ~9.5 倍(5000 → 533 行),而两次运行用户可见的输出逐字节一致。这正是 PR 的契约:限制保留副本,保留已渲染的预览。CLI 全程响应正常,prompt 干净返回。

5. 构建 / typecheck / lint

  • npm install + workspace 构建(生成 dist):OK
  • packages/core tsc --noEmit:干净(exit 0)
  • packages/cli tsc --noEmit:干净(exit 0)
  • 对全部 16 个改动文件跑 eslint:干净(exit 0)

次要观察(不阻塞合并)

  1. 实时 scrollback 由 1000 → 200 行。 命令仍在运行时,交互式回滚现在上限为 200 行(原 1000)。最终结果和面向模型的输出不受影响(10000 行 replay)。是合理的取舍;建议在 PR 文案里加一句说明。
  2. copyString 是 O(n)(split('').join('')),在 canUpdateOutput 工具上每个超限 chunk 都会跑。它只在值超限时触发且受输出节流限制,影响很小——仅作提示。
  3. React 路径上的双重压缩(先 coreToolScheduler 后 useReactToolScheduler)是幂等的,只是有一点冗余计算。
  4. 作用范围: 压缩按设计仅在交互模式生效,因此 headless/serve 会话不会得到该上限——从协议保真角度是正确的,但内存收益在那里不适用。

结论

LGTM — 建议合并。 内存上限是真实且可测量的,面向模型的结果与渲染预览均未被触碰,受影响文件的测试/typecheck/lint 全绿。除作者已测的 macOS 外,Linux 现也已通过真实交互式构建验证。

doudouOUC
doudouOUC previously approved these changes Jun 16, 2026
expect(compactedTask.tasks[0].owner).toContain('truncated from');
expect(compactedTeam.teamName).toContain('truncated from');
});
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] compactFileDiff is not tested through the compactToolResultDisplayForHistory path. The test file covers strings, agent results, ANSI output, todo/plan/MCP, task list, and team displays — but has zero FileDiff input for the history compaction function. The recording service uses a separate function (sanitizeFileDiffForRecording) with different limits, so existing recording tests don't cover this code.

The compactFileDiff function has three independent truncation branches (fileDiff, originalContent, newContent) plus a null-originalContent branch, all using different limit constants (50K for fileDiff, 16K for content fields). A bug in any of these (wrong limit constant, incorrect metadata fields like truncatedForSession or fileDiffLength) would silently corrupt the interactive UI history display for edit/write tools.

Consider adding a test that constructs a FileDiff with oversized fields and passes it through compactToolResultDisplayForHistory, verifying the output metadata. Also test the originalContent: null branch.

— qwen3.7-max via Qwen Code /review

);

expect(result.promoted).toBe(true);
expect(result.output).toContain('line-0');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The new finally { replayTerminal.dispose() } block in replayTerminalOutput ensures terminal cleanup even when serializeTerminalToText throws, but this test ("background-promote replay failure falls back") doesn't verify that dispose was called on the replay terminal. The natural-exit test at line 317 does verify Terminal.prototype.dispose — but that exercises the live PTY terminal, not the replay terminal instance.

If the finally block were accidentally removed, no test would catch the resource leak in the error path. Consider adding vi.spyOn(Terminal.prototype, 'dispose') before execution and expect(terminalDisposeSpy).toHaveBeenCalled() after, mirroring the pattern from the natural-exit test.

— qwen3.7-max via Qwen Code /review

this.activePtys.delete(ptyProcess.pid);

const finalize = async () => {
render(true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] render(true) is outside the try/finally block, so if renderFn() throws (e.g., terminal in unexpected state after rapid exit), disposeForegroundPtyResources() is never called. This causes a resource leak regression: the headlessTerminal is not disposed, dataDisposable/exitDisposable are not disposed, renderTimeout is not cleared, and the activePtys map entry is not deleted. Additionally, resolve() is never called, so the result Promise hangs indefinitely.

Before this PR, activePtys.delete(ptyProcess.pid) was called synchronously in the onExit handler before finalize was defined. Moving it into disposeForegroundPtyResources (inside the try/finally) means a render(true) throw now also leaks those resources.

Wrap the entire finalize body in try/finally:

const finalize = async () => {
  try {
    render(true);
    // ... decode output ...
    resolve({...});
  } finally {
    disposeForegroundPtyResources();
  }
};

— qwen3-235b-a22b via Qwen Code /review

}

const marker = buildStringCompactionMarker(value, purpose);
const contentBudget = Math.max(0, limit - marker.length);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] compactString uses String.prototype.slice() which operates on UTF-16 code units. When the cut point falls between the two code units of a supplementary-plane character (e.g., emoji like U+1F600 encoded as surrogate pair U+D83D U+DE00), the head ends with a dangling high surrogate and the tail starts with a dangling low surrogate. Both produce invalid Unicode that renders as replacement characters.

Adjust the cut point by one code unit when a high surrogate is detected at the boundary:

function safeSliceStart(str: string, index: number): number {
  if (index > 0 && index < str.length) {
    const code = str.charCodeAt(index - 1);
    if (code >= 0xD800 && code <= 0xDBFF) {
      return index - 1;
    }
  }
  return index;
}

Apply to both the head end-point and the tail start-point.

— qwen3-235b-a22b via Qwen Code /review

wenshao
wenshao previously approved these changes Jun 18, 2026
@kkhomej33-netizen
kkhomej33-netizen dismissed stale reviews from wenshao and doudouOUC via 6f698bb June 18, 2026 10:59
@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. I pushed 6f698bb4d to address the new feedback.

What changed:

  • finalize in the PTY exit path now wraps final result generation with a cleanup finally, and render(true) failures are handled as display-layer failures rather than preventing resolution. Added a regression test that forces final render to throw and verifies the result resolves and PTY resources are disposed.
  • compactString now avoids slicing through valid UTF-16 surrogate pairs at both head and tail boundaries while keeping the output within the configured limit and preserving intentionally unmatched surrogate code units. Added a focused emoji-boundary regression test.
  • Also picked up the earlier non-blocking coverage suggestions: FileDiff history compaction now has direct tests, and the background-promote replay-failure test verifies the replay terminal is disposed.

Verified locally:

  • packages/core: npx vitest run src/utils/toolResultDisplayCompaction.test.ts src/services/shellExecutionService.test.ts (114 tests passed)
  • packages/core: npm run typecheck --workspace=packages/core
  • touched-file npx eslint ...
  • git diff --check
  • root npm run typecheck
  • root npm run build (passed with existing VSCode companion warnings only)

@wenshao

wenshao commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

1 similar comment
@wenshao

wenshao commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@wenshao

wenshao commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator

✅ Real-build verification — the memory reduction is real (96.8%), and it holds up at the heap level

I built the actual core from this PR's head in an isolated worktree and drove the real compiled compactStringForHistory in a tmux pane, measuring retained heapUsed (with --expose-gc) for 40 distinct ~1 MB tool outputs — the thing this PR actually optimizes. Verdict: the fix works, and the subtle part (freeing the original strings, not just truncating the displayed copy) is genuinely correct.

1. Unit tests — 459/459 on PR head

vitest run over the 5 core suites — toolResultDisplayCompaction (14), coreToolScheduler (206), chatRecordingService (34), shellExecutionService (100, the PTY cleanup), agent (105) — all pass.

2. Heap-retention A/B — real dist, run in tmux

Retain 40 × distinct ~1 MB display strings the two ways (raw = pre-PR behavior; compacted = this PR), drop the originals, gc(), measure:

RAW retained (pre-PR) COMPACTED retained (this PR) reduction output ≤ 32 KB
FIXED 38.2 MB 1.23 MB 96.8 % ✓ (head + marker + tail preserved)

The headline isn't just that the output is bounded to MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS (32 000) — it's that the retained heap actually shrinks: the compacted copies hold ~1.2 MB and the 38 MB of originals get GC'd.

3. copyString is load-bearing — and the unit tests don't catch it

The non-obvious correctness hinge is copyString(value.slice(…)) = value.split('').join(''): a bare value.slice(…) returns a V8 SlicedString that retains the whole 1 MB parent, so the flatten-copy is what actually lets the original be freed. I confirmed this by neutering copyString to return value;, rebuilding, and re-running:

build COMPACTED retained reduction length ≤ 32 KB toolResultDisplayCompaction.test.ts
copyString flatten (PR) 1.23 MB 96.8 % ✓ 14/14 pass
copyString → return value 37.21 MB 2.5 % ✓ 14/14 still pass

So the memory win collapses (96.8 % → 2.5 %) when copyString is removed — yet every unit test still passes, because they assert output length, never retained bytes. The leak would silently come back on any future refactor that drops the flatten.

Suggestion (non-blocking): add one retention regression test that pins the actual property — e.g. compact N large distinct strings, drop the originals, global.gc(), and assert process.memoryUsage().heapUsed stays bounded (or assert the compacted slice is detached from its parent). It's the only test that would have failed in the nocopy column above.

Verdict: solid, real memory fix — 96.8 % retained-heap reduction, output bounded with head/tail preview, no behavioral regressions, all suites green. LGTM. Consider adding the retention test so the copyString flatten can't silently regress. 👍

中文说明(完整对应)

✅ 真实构建验证 —— 内存削减是真的(96.8%),且在堆层面站得住

我在隔离 worktree 里从本 PR head 构建了真实 core,并在 tmux 中驱动真实编译的 compactStringForHistory,用 --expose-gc 测量 40 个各约 1 MB 的不同工具输出的保留 heapUsed —— 也就是这个 PR 真正优化的对象。结论:修复有效,而且最微妙的部分(释放原始字符串,而不只是截断展示副本)确实正确。

1. 单元测试 —— PR head 459/459

vitest run 跑了 5 个 core 套件 —— toolResultDisplayCompaction(14)、coreToolScheduler(206)、chatRecordingService(34)、shellExecutionService(100,PTY 清理)、agent(105) —— 全过。

2. 堆保留 A/B —— 真实 dist,在 tmux 中运行

把 40 个各约 1 MB 的不同展示字符串按两种方式保留(raw = PR 前行为;compacted = 本 PR),丢掉原始引用、gc()、测量:

RAW 保留(PR 前) COMPACTED 保留(本 PR) 削减 输出 ≤ 32 KB
FIXED 38.2 MB 1.23 MB 96.8 % ✓(头 + 标记 + 尾保留)

重点不只是输出被限制在 MAX_RETAINED_TOOL_RESULT_DISPLAY_CHARS(32000)以内 —— 而是保留的堆真的变小了:压缩副本只占约 1.2 MB,38 MB 的原始串被 GC 回收。

3. copyString 是承重点 —— 而单元测试抓不到

不显眼的正确性关键是 copyString(value.slice(…)) = value.split('').join(''):裸 value.slice(…) 在 V8 里返回一个 SlicedString,会保留整个 1 MB 母串,所以这次 flatten 拷贝才是让原始串能被释放的真正原因。我把 copyString 改成 return value;、重建、重跑来验证:

构建 COMPACTED 保留 削减 长度 ≤ 32 KB toolResultDisplayCompaction.test.ts
copyString flatten(PR) 1.23 MB 96.8 % ✓ 14/14 通过
copyString → return value 37.21 MB 2.5 % ✓ 14/14 仍然通过

也就是说,去掉 copyString 后内存收益从 96.8% 崩到 2.5% —— 但每个单元测试照样通过,因为它们断言的是输出长度,从不断言保留的字节数。任何未来重构若丢掉这次 flatten,泄漏会悄悄回来。

建议(非阻塞): 加一个保留性回归测试钉住真正的属性 —— 例如压缩 N 个大的不同字符串、丢掉原始引用、global.gc(),断言 process.memoryUsage().heapUsed 保持有界(或断言压缩后的切片已与母串脱钩)。这是唯一会在上表 nocopy 那一列失败的测试。

结论:扎实、真实的内存修复 —— 保留堆削减 96.8%、输出按头/尾预览有界、无行为回归、所有套件全绿。LGTM。建议补上那个保留性测试,免得 copyString flatten 将来被悄悄改回去。 👍

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

@DragonnZhang Hi, the earlier blocking review on ab940eb7 should be addressed in the current head 6f698bb4.

Summary of the follow-up fix:

  • The PTY natural-exit finalize path now wraps final result generation in cleanup finally, so disposeForegroundPtyResources() still runs if final rendering fails.
  • render(true) failures are treated as display-layer failures and no longer leave the result promise unresolved.
  • Added regression coverage for final-render failure cleanup/resolve.
  • compactString now avoids splitting valid UTF-16 surrogate pairs at both head and tail boundaries, with a focused boundary test.
  • Also added the requested FileDiff/history and replay-terminal-dispose coverage.

Current status: CI is green, the PR is mergeable, and the latest automated review approved the current head. Could you please re-review or dismiss the stale changes-requested review when you have a chance? Thanks!

@kkhomej33-netizen

Copy link
Copy Markdown
Contributor Author

@wenshao Thanks for the real-build heap-retention verification — this is exactly the subtle property this PR depends on.

I agree that copyString is load-bearing: a length-only test would not catch a future regression that accidentally keeps V8 SlicedString parents alive. For this PR, I am leaning not to add a heap-retention unit test directly because it would need --expose-gc / process.memoryUsage().heapUsed and could become platform- or GC-timing-sensitive in normal CI.

I think the current best balance is to keep the implementation and existing deterministic tests as-is, with your A/B heap evidence documented here. If the project later adds a dedicated memory/perf regression harness, this would be a very good case to encode there.

@wenshao
wenshao merged commit cebc071 into QwenLM:main Jun 19, 2026
24 checks passed
@kkhomej33-netizen
kkhomej33-netizen deleted the zach/reduce-interactive-output-memory branch June 19, 2026 11:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants