Repository navigation
Conversation
| responseParts: event.responseParts, | ||
| ...(typeof event.resultDisplay === 'string' | ||
| ? { resultDisplay: event.resultDisplay } | ||
| : {}), |
There was a problem hiding this comment.
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:
buildRequestusestoolCall.args || {}— withargsremoved on line 881, all subagent tool_use events now carryinput: {}.buildResponseusestoolCall.responseParts || []— withresponsePartsremoved here, all subagent tool_result events now carry emptyresponseParts.hasResultContentreturnsfalsewhenresultDisplayis not a string andresponsePartsis absent and status issuccess. For subagent tool calls whoseresultDisplayis aFileDiff(edit tool) orAnsiOutputDisplay(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.
|
Thanks, this was a good catch. I pushed What changed:
Verification:
|
|
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 ( After 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:
|
|
Correction to my previous follow-up: I pushed Updated RSS-only comparison for the same interactive shell repro (120 rounds x 1MB output):
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:
|
|
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, Focused red/green memory bench, using the real
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:
|
15037c4 to
00368f9
Compare
| ]; | ||
| } | ||
|
|
||
| function compactAnsiLine(line: AnsiLine): AnsiLine { |
There was a problem hiding this comment.
[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, | ||
| ), |
There was a problem hiding this comment.
[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; | ||
| } | ||
|
|
There was a problem hiding this comment.
[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, |
There was a problem hiding this comment.
[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 { |
There was a problem hiding this comment.
[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
🧪 Local runtime verification (built CLI + real model, tmux, with a latest-
|
| 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:
- 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.
FileDiffcompaction at the recording layer already existed onmain(same 16 K +truncatedForSessioncame 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)
- ✅ Huge
seqoutput → 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. - ✅ 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 answeredMAGIC-LAST-LINE-XYZQ. Display compaction did not touch the model-facing result. - ✅ Normal-size control:
printfdisplay recorded at 10 chars, no marker. - 🔍 Esc mid-
seq 1 5000000(≈38 MB) → clean "Request cancelled.", session healthy afterwards; pane resize mid-stream → no corruption. - 🔍 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:
main155,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 latestmainat 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 等) |
由此得出两个诚实的观察:
- PR 的压缩在可确定性观察的地方完全按设计工作:超大通用字符串展示从保留 70K 变为有界的 32K head/tail 并带诚实标记;小输出逐字节一致。
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 构建上)
- ✅ 超大
seq输出 → TUI 照常渲染有界的实时尾部;既有的 "Output too long and was saved to: ~/.qwen/tmp/.../run_shell_command_*.output" 模型侧落盘路径完好;UI 保持响应。 - ✅ 模型保真: 运行
seq 1 9000 && echo MAGIC-LAST-LINE-XYZQ(展示 70,343 字符 → 压到 32K,标记证明压缩命中这一次调用),随后问模型输出的最后一行 → 准确回答MAGIC-LAST-LINE-XYZQ。展示压缩未触碰模型侧结果。 - ✅ 普通大小对照:
printf的展示按 10 字符记录、无标记。 - 🔍
seq 1 5000000(≈38 MB)中途 Esc → 干净的 "Request cancelled.",会话随后健康;流式期间调整窗口 → 无渲染损坏。 - 🔍 8+ 次 shell 执行(含被取消的 38 MB 那次)→ 无 PTY 相关错误或挂起(自然退出 PTY 释放/200 行实时 scrollback 的改动在此规模的黑盒 RSS 中无法单独分辨;未观察到回归)。
备注
- 进入保留环节的 shell 展示字符串在本 PR 之前就已被终端回放快照预先约束到 ~70K——因此纯 shell 输出的每次调用节省约 38 KB。MB 级收益在 FileDiff/agent 展示路径及长会话累积中。
- 相同 edit-only 工作负载的记录文件总大小:
main155,084 字节 vs PR 154,312 字节——与"记录层 FileDiff 压缩先于本 PR 存在;PR 的磁盘可见增量是通用字符串上界"一致。 - PR head 落后快速前进的
main约 20 个 commit;对照为测试时的最新main(c491f33)。行为上未见冲突,但合并前 rebase 一下无妨。
结论(合并参考)
**通过。**所有可确定性观察的声明全部成立:有界的 head/tail 保留 + 诚实标记、小输出不受影响、模型侧结果不受影响、无功能或内存回归、取消/调整窗口健壮。唯一未能演示的是短会话内 RSS 级别的改善——按上面的数学,任何短黑盒会话都无法做到,而 PR 自带的单测套件正是内存内保留点的正确检验工具。没有任何阻碍合并的问题。
db646b8 to
bcfa1d2
Compare
DragonnZhang
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
[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; |
There was a problem hiding this comment.
[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
|
Thanks for the detailed review. I addressed both points in ab940eb:
Verified locally with focused core/cli tests, typecheck, and build. |
DragonnZhang
left a comment
There was a problem hiding this comment.
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
✅ 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 Environment: Linux x64 · Node v22.22.2 · npm 10.9.7 · clean 1. Code audit — model fidelity is preservedThe compaction only ever rewrites display / history / recording copies; it never touches the model-facing payload.
2. Unit tests — 549 passing
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:
4. Real interactive E2E (tmux) + A/B — the headline evidenceBuilt the real CLI, ran it in a tmux pane, and used
5. Build / typecheck / lint
Minor observations (non-blocking)
VerdictLGTM — 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 描述中标记为 环境: Linux x64 · Node v22.22.2 · npm 10.9.7 · 在 PR head( 1. 代码审计 — 面向模型的保真度被保留压缩只重写展示 / 历史 / 录制副本,从不触碰面向模型的 payload。
2. 单元测试 — 549 个通过
3. 独立的反向审计探针(覆盖测试套件未覆盖的点)通过 import 真实导出的函数,我验证了单测没有直接断言的声明:
4. 真实交互式 E2E(tmux)+ A/B 对照 — 最有力的证据构建真实 CLI,在 tmux pane 中运行,用
5. 构建 / typecheck / lint
次要观察(不阻塞合并)
结论LGTM — 建议合并。 内存上限是真实且可测量的,面向模型的结果与渲染预览均未被触碰,受影响文件的测试/typecheck/lint 全绿。除作者已测的 macOS 外,Linux 现也已通过真实交互式构建验证。 |
| expect(compactedTask.tasks[0].owner).toContain('truncated from'); | ||
| expect(compactedTeam.teamName).toContain('truncated from'); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
[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'); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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
6f698bb
|
Thanks for the careful review. I pushed What changed:
Verified locally:
|
|
@qwen-code /triage |
1 similar comment
|
@qwen-code /triage |
✅ Real-build verification — the memory reduction is real (96.8%), and it holds up at the heap levelI built the actual core from this PR's head in an isolated worktree and drove the real compiled 1. Unit tests — 459/459 on PR head
2. Heap-retention A/B — real
|
| 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 将来被悄悄改回去。 👍
|
@DragonnZhang Hi, the earlier blocking review on Summary of the follow-up fix:
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! |
|
@wenshao Thanks for the real-build heap-retention verification — this is exactly the subtle property this PR depends on. I agree that 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. |
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, andcd 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 withnpx eslintfor 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
resultDisplaystrings, 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-renderedargs,responseParts, andresultpayloads, 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
Environment (optional)
macOS with Node.js v22.22.2 and npm 10.9.7.
npm run buildcompleted locally.packages/coreandpackages/clitypecheck passed after the workspace build generated local package declarations. Fullnpm run preflightwas 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
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和resultpayload,保存的聊天元数据会在不修改原始输入的情况下压缩大型展示数据,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 并通过。风险与范围
关联 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