@each1024/pi-mini-mode 2.0.18 → 2.0.20

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.
@@ -1,16 +1,18 @@
1
1
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { Text, truncateToWidth, visibleWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
3
  import { stripVTControlCharacters } from "node:util";
4
- import { agentCallDisplay, isAgentTool, liveAgentView, runningGlyph } from "./agent-view.ts";
5
- import { createAssistantImages, imagePlaceholders } from "./assistant-images.ts";
6
- import { linkToolFiles } from "./file-links.ts";
4
+ import { agentCallDisplay, agentChildren, childSessionData, isAgentTool, isPrintAgentCall, liveAgentView, printAgentStatuses, runningGlyph, type AgentCall } from "./agent-view.ts";
5
+ import { assistantImageSpans, clearAssistantImageCaches, createAssistantImages, imagePlaceholders } from "./assistant-images.ts";
6
+ import { clearFileLinkCaches, linkToolFiles } from "./file-links.ts";
7
7
  import { createLinkHover } from "./link-hover.ts";
8
8
  import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
9
9
  import { minimalSurface, paintExpandedHeading } from "./minimal-theme.ts";
10
10
  import { formatElapsed, formatThinkingElapsed, formatToolElapsed, piLoopSummary, type MinimalTurn } from "./minimal-turns.ts";
11
- import { DEFAULT_SETTINGS, uiLanguage, type UiLanguage } from "./settings.ts";
11
+ import { clearPrintAgentCaches } from "./print-agent.ts";
12
+ import { DEFAULT_SETTINGS, type UiLanguage } from "./settings.ts";
12
13
  import { thinkingPreview } from "./thinking-preview.ts";
13
14
  import type { NoticeRows, TurnNotices } from "./transcript-adapter.ts";
15
+ import { renderUpdateBanner } from "./update-banner.ts";
14
16
  import { addUsage, EMPTY_USAGE, formatTokens } from "./usage.ts";
15
17
 
16
18
  /** Shown when a thinking block has no displayable summary. */
@@ -19,12 +21,167 @@ const THINKING_FALLBACK: Record<UiLanguage, Record<"active" | "aborted" | "error
19
21
  en: { active: "Waiting for a displayable summary", aborted: "Interrupted, no displayable summary returned", error: "Failed, no displayable summary returned", ended: "Finished, no displayable summary returned" },
20
22
  };
21
23
 
22
- export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: { cwd(): string; requestRender(): void; write?(data: string): void }, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"], getLanguage: () => UiLanguage = () => uiLanguage({})) {
24
+ const MINIMAL_COPY = {
25
+ zh: {
26
+ collapsePrompt: "▴ 收起",
27
+ expandPrompt: "▾ 展开",
28
+ expandPromptLines: (n: number) => `▾ 展开 (${n} 行)`,
29
+ session: "会话 ",
30
+ cache: " · 缓存 ",
31
+ inputLabel: "输入:",
32
+ outputLabel: "输出:",
33
+ waitingToolResult: "等待工具文本结果…",
34
+ emptyToolResult: "无文本结果",
35
+ waitingModel: "等待模型响应",
36
+ waitingNextStep: "等待下一步执行",
37
+ },
38
+ en: {
39
+ collapsePrompt: "▴ Collapse",
40
+ expandPrompt: "▾ Expand",
41
+ expandPromptLines: (n: number) => `▾ Expand (${n} lines)`,
42
+ session: "Session ",
43
+ cache: " · Cache ",
44
+ inputLabel: "Input:",
45
+ outputLabel: "Output:",
46
+ waitingToolResult: "Waiting for tool text result…",
47
+ emptyToolResult: "No text result",
48
+ waitingModel: "Waiting for model response",
49
+ waitingNextStep: "Waiting for next step",
50
+ },
51
+ } as const;
52
+
53
+ const LRU_MAX = 800;
54
+ function lruGet<K, V>(map: Map<K, V>, key: K): V | undefined {
55
+ return map.get(key);
56
+ }
57
+ function lruSet<K, V>(map: Map<K, V>, key: K, val: V, max = LRU_MAX): V {
58
+ if (map.has(key)) map.delete(key);
59
+ else if (map.size >= max) {
60
+ const first = map.keys().next().value;
61
+ if (first !== undefined) map.delete(first);
62
+ }
63
+ map.set(key, val);
64
+ return val;
65
+ }
66
+
67
+ function keysEqual(a: readonly unknown[], b: readonly unknown[]): boolean {
68
+ if (a.length !== b.length) return false;
69
+ for (let i = 0; i < a.length; i++) {
70
+ if (a[i] !== b[i]) return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ /** First row with this y. Each control list is one record per rendered line, so y is unique. */
76
+ function firstAtY<T extends { y: number }>(rows: readonly T[], y: number): T | undefined {
77
+ let lo = 0;
78
+ let hi = rows.length - 1;
79
+ while (lo <= hi) {
80
+ const mid = (lo + hi) >> 1;
81
+ const rowY = rows[mid].y;
82
+ if (rowY < y) lo = mid + 1;
83
+ else if (rowY > y) hi = mid - 1;
84
+ else {
85
+ let index = mid;
86
+ while (index > 0 && rows[index - 1].y === y) index--;
87
+ return rows[index];
88
+ }
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ function isSubAgentChildRunning(child: Record<string, unknown>): boolean {
94
+ const exit = typeof child.exitCode === "number" ? child.exitCode : undefined;
95
+ const raw = String(child.status ?? child.state ?? "");
96
+ const failed = (exit !== undefined && exit > 0) || /^(failed|error|aborted|cancelled|canceled|timed?_?out|killed)$/i.test(raw);
97
+ const done = !failed && /^(done|completed?|succeeded|success|failed|error|aborted|cancelled|canceled|stopped|timed?_?out|killed)$/i.test(raw);
98
+ return !failed && !done;
99
+ }
100
+
101
+ interface TurnRenderResult {
102
+ lines: string[];
103
+ promptControls: Array<{ index: number; question: string; y: number; x: number; width: number; label: string }>;
104
+ toolControls: Array<{ id: string; y: number; width: number; title: string }>;
105
+ processRows: Array<{ key: string; y: number }>;
106
+ agentControls: Array<{ index: number; y: number; width: number }>;
107
+ subagentControls: Array<{ runId: string; y: number; width: number; line: string }>;
108
+ pinnedTool?: { id: string; y: number; line: string };
109
+ pinnedAgent?: { index: number; y: number; line: string };
110
+ pinnedSubagent?: { id: string; y: number; line: string; autoScroll?: boolean };
111
+ claimedPrintFiles: string[];
112
+ }
113
+
114
+ export interface UpdateBannerState {
115
+ version: string;
116
+ previousVersion?: string;
117
+ collapsed: boolean;
118
+ toggle: () => void;
119
+ }
120
+
121
+ export interface MinimalOutputOptions {
122
+ cwd(): string;
123
+ requestRender(): void;
124
+ write?(data: string): void;
125
+ updateBanner?: () => UpdateBannerState | undefined;
126
+ }
127
+
128
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: MinimalOutputOptions, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"], getLanguage: () => UiLanguage = () => "zh", getUpdateBanner?: () => UpdateBannerState | undefined) {
129
+ const resolveUpdateBanner = getUpdateBanner ?? imageOptions?.updateBanner;
130
+ const markdownCache = new Map<string, string[]>();
131
+ const assistantMdCache = new Map<string, string[]>();
132
+ const callDisplayCache = new Map<string, { tool?: string; name: string; action?: string; state: string; task: string; output?: string; value: { summary: string; detail: string } }>();
133
+ const turnCache = new Map<number, { key: readonly unknown[]; value: TurnRenderResult }>();
23
134
  const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
24
- const markdown = (text: string, width: number, process = false) => renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
25
- { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
26
- const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, imageOptions.requestRender, imageOptions.write);
27
- const assistantMarkdown = (text: string, width: number, owner: string) => assistantImages ? assistantImages.render(text, width, markdown, owner) : markdown(text, width);
135
+ const markdown = (text: string, width: number, process = false): string[] => {
136
+ const key = `${process ? 1 : 0}|${width}|${text}`;
137
+ const hit = lruGet(markdownCache, key);
138
+ if (hit !== undefined) return [...hit];
139
+ const rows = renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
140
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
141
+ lruSet(markdownCache, key, rows);
142
+ return [...rows];
143
+ };
144
+ const thinkingMarkdown = (text: string, width: number, color: "error" | "accent" | "muted", previewRows: number): string[] => {
145
+ const key = `t:${color}|${width}|${previewRows}|${text}`;
146
+ const hit = lruGet(markdownCache, key);
147
+ if (hit !== undefined) return [...hit];
148
+ const rows = renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
149
+ { color: value => theme.fg(color, value) }, (source, avail) => transformText(placeholderText(diagramMarkdown(source, avail))))
150
+ .slice(0, previewRows);
151
+ lruSet(markdownCache, key, rows);
152
+ return [...rows];
153
+ };
154
+ const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, () => { turnCache.clear(); imageOptions.requestRender(); }, imageOptions.write);
155
+ const assistantMarkdown = (text: string, width: number, owner: string): string[] => {
156
+ if (!assistantImages) return markdown(text, width);
157
+ const key = `${width}|${text}`;
158
+ const hit = lruGet(assistantMdCache, key);
159
+ if (hit !== undefined) return [...hit];
160
+ if (!assistantImageSpans(text, imageOptions!.cwd()).length) {
161
+ const rows = markdown(text, width);
162
+ lruSet(assistantMdCache, key, rows);
163
+ return [...rows];
164
+ }
165
+ return assistantImages.render(text, width, markdown, owner);
166
+ };
167
+ const cachedCallDisplay = (call: AgentCall) => {
168
+ const hit = callDisplayCache.get(call.id);
169
+ if (hit && hit.state === call.state && hit.output === call.output && hit.task === call.task && hit.name === call.name && hit.tool === call.tool && hit.action === call.action) {
170
+ return hit.value;
171
+ }
172
+ const value = agentCallDisplay(call);
173
+ lruSet(callDisplayCache, call.id, { tool: call.tool, name: call.name, action: call.action, state: call.state, task: call.task, output: call.output, value });
174
+ return value;
175
+ };
176
+ const clearAllCaches = () => {
177
+ markdownCache.clear();
178
+ assistantMdCache.clear();
179
+ callDisplayCache.clear();
180
+ turnCache.clear();
181
+ clearAssistantImageCaches();
182
+ clearFileLinkCaches();
183
+ clearPrintAgentCaches();
184
+ };
28
185
  const surface = (rows: string[], width: number, user: boolean, selected = -1, expanded = false) => {
29
186
  const padding = Math.min(2, Math.floor((width - 1) / 2));
30
187
  return ["", ...rows, ""].map((row, index) => {
@@ -74,7 +231,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
74
231
  clearHover();
75
232
  return;
76
233
  }
77
- if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
234
+ if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name) && !isPrintAgentCall(call)))) return;
78
235
  if (expandedTools.has(id)) {
79
236
  expandedTools.delete(id);
80
237
  if (pinnedToolId === id) pinnedToolId = undefined;
@@ -99,6 +256,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
99
256
  let promptControls: Array<{ index: number; question: string; y: number; x: number; width: number; label: string }> = [];
100
257
  let subagentControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
101
258
  let noticeRegions: Array<{ y: number; rows: NoticeRows }> = [];
259
+ let bannerControl: { headerRows: number; totalRows: number; width: number; toggle: () => void } | undefined;
102
260
  const togglePrompt = (index: number, question: string) => {
103
261
  if (getTurns()[index]?.question !== question) return;
104
262
  if (expandedPrompts.get(index) === question) expandedPrompts.delete(index);
@@ -106,10 +264,11 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
106
264
  };
107
265
  return {
108
266
  dispose() { assistantImages?.dispose(); },
109
- invalidate() { clearHover(); },
267
+ invalidate() { clearHover(); clearAllCaches(); },
110
268
  resetProcessView() {
111
269
  agentModes.clear(); expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear();
112
270
  thinkingPreviews.clear();
271
+ clearAllCaches();
113
272
  pinnedToolId = undefined; pinnedAgentIndex = undefined; pinnedSubagentId = undefined;
114
273
  },
115
274
  clearHover,
@@ -126,11 +285,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
126
285
  promptChoices: () => promptControls.map(control => ({ ...control })),
127
286
  togglePrompt,
128
287
  handleMouse(event: TuiMouseEvent) {
129
- const tool = toolControls.find(control => event.y === control.y && event.x >= 2 && event.x < Math.min(5, control.width));
288
+ const toolAt = firstAtY(toolControls, event.y);
289
+ const tool = toolAt && event.x >= 2 && event.x < Math.min(5, toolAt.width) ? toolAt : undefined;
130
290
  if (event.type === "move") {
131
291
  const linkChanged = linkHover.handleMouse(event);
132
292
  const next = !event.shift && !event.ctrl && !event.alt ? tool : undefined;
133
- const record = processRows.find(row => row.y === event.y);
293
+ const record = firstAtY(processRows, event.y);
134
294
  if (hoveredTool?.id !== next?.id || hoveredProcess?.key !== record?.key || hoveredProcess?.y !== record?.y || linkChanged) {
135
295
  hoveredTool = next;
136
296
  hoveredProcess = record;
@@ -147,7 +307,20 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
147
307
  }
148
308
  }
149
309
  if (event.button !== "left" || event.shift || event.ctrl || event.alt) return;
150
- const agent = agentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
310
+ if (bannerControl && (event.clickCount ?? 1) === 1) {
311
+ const inHeader = event.y >= 0 && event.y < bannerControl.headerRows;
312
+ const inFooter = bannerControl.totalRows > bannerControl.headerRows
313
+ && event.y >= bannerControl.totalRows - 3 && event.y < bannerControl.totalRows;
314
+ if ((inHeader || inFooter) && event.x >= 0 && event.x < bannerControl.width) {
315
+ if (event.type === "press") return { handled: true };
316
+ if (event.type === "click") {
317
+ bannerControl.toggle();
318
+ return { handled: true, render: true };
319
+ }
320
+ }
321
+ }
322
+ const agentAt = firstAtY(agentControls, event.y);
323
+ const agent = agentAt && event.x >= 0 && event.x < agentAt.width ? agentAt : undefined;
151
324
  if (agent && (event.clickCount ?? 1) === 1) {
152
325
  if (event.type === "press") return { handled: true };
153
326
  if (event.type === "click") {
@@ -158,7 +331,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
158
331
  return { handled: true, render: true };
159
332
  }
160
333
  }
161
- const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
334
+ const promptAt = firstAtY(promptControls, event.y);
335
+ const control = promptAt && event.x >= promptAt.x && event.x < promptAt.x + promptAt.width ? promptAt : undefined;
162
336
  if (control && (event.clickCount ?? 1) === 1) {
163
337
  if (event.type === "press") return { handled: true };
164
338
  if (event.type === "click") {
@@ -166,7 +340,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
166
340
  return { handled: true, render: true };
167
341
  }
168
342
  }
169
- const sub = subagentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
343
+ const subAt = firstAtY(subagentControls, event.y);
344
+ const sub = subAt && event.x >= 0 && event.x < subAt.width ? subAt : undefined;
170
345
  if (sub) {
171
346
  if (event.type === "press") return { handled: true };
172
347
  if (event.type === "click") {
@@ -190,24 +365,166 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
190
365
  pinnedSubagent = undefined;
191
366
  subagentControls = [];
192
367
  noticeRegions = [];
368
+ bannerControl = undefined;
193
369
  agentExpiry = Infinity;
194
370
  if (width <= 0) { clearHover(); return linkHover.render([], width); }
195
371
  const turns = getTurns();
196
- const toolIds = new Set(turns.flatMap(turn => (turn.agentCalls ?? []).map(call => call.id)));
197
- for (const id of expandedTools) if (!toolIds.has(id)) expandedTools.delete(id);
198
- const thinkingIds = new Set(turns.flatMap((turn, turnIndex) => turn.process.flatMap((entry, processIndex) =>
199
- entry.startsWith("thinking") ? [`thinking:${turnIndex}:${processIndex}`] : [])));
200
- for (const id of expandedThinking) if (!thinkingIds.has(id)) expandedThinking.delete(id);
201
- for (const id of thinkingPreviews.keys()) if (!thinkingIds.has(id)) thinkingPreviews.delete(id);
372
+ if (turnCache.size > turns.length) {
373
+ for (const k of turnCache.keys()) if (k >= turns.length) turnCache.delete(k);
374
+ }
375
+ const renderCwd = imageOptions?.cwd() ?? process.cwd();
376
+ const claimedPrintSessions = new Set<string>();
377
+ const isCapturedCall = (call: AgentCall) => isAgentTool(call.tool ?? call.name) || isPrintAgentCall(call);
378
+ if (expandedTools.size > 0) {
379
+ const toolIds = new Set(turns.flatMap(turn => (turn.agentCalls ?? []).filter(call => !isCapturedCall(call)).map(call => call.id)));
380
+ for (const id of expandedTools) if (!toolIds.has(id)) expandedTools.delete(id);
381
+ }
382
+ if (expandedThinking.size > 0 || thinkingPreviews.size > 0) {
383
+ const hasThinkingId = (id: string) => {
384
+ const parts = id.split(":");
385
+ return Boolean(turns[Number(parts[1])]?.process[Number(parts[2])]?.startsWith("thinking"));
386
+ };
387
+ for (const id of expandedThinking) if (!hasThinkingId(id)) expandedThinking.delete(id);
388
+ for (const id of thinkingPreviews.keys()) if (!hasThinkingId(id)) thinkingPreviews.delete(id);
389
+ }
202
390
  const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
203
391
  const lines: string[] = [];
204
392
  // An open heading wears the same full-width selectedBg band as an expanded SubAgent row.
205
393
  const bandHeading = (row: string, open: boolean) => open
206
394
  ? paintExpandedHeading(theme, row + " ".repeat(Math.max(0, width - visibleWidth(row)))) : row;
207
- for (const [index, turn] of turns.entries()) {
208
- if (index > 0) lines.push("");
209
- if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
210
- const noticeRows = notices?.get(index) ?? [];
395
+ const now = Date.now();
396
+ let hasFutureDeadline = false;
397
+ for (const deadline of agentDeadlines.values()) {
398
+ if (deadline > now) {
399
+ hasFutureDeadline = true;
400
+ agentExpiry = Math.min(agentExpiry, deadline);
401
+ }
402
+ }
403
+ const exp = isExpanded();
404
+ const subExp = subAgentsExpanded();
405
+ const usageShown = showUsage();
406
+ const recLimit = getRecordLimit();
407
+ const lang = getLanguage();
408
+ const banner = resolveUpdateBanner?.();
409
+ if (banner) {
410
+ const renderedBanner = renderUpdateBanner(theme, width, {
411
+ version: banner.version,
412
+ previousVersion: banner.previousVersion,
413
+ language: lang,
414
+ collapsed: banner.collapsed,
415
+ });
416
+ if (renderedBanner.rows.length > 0) {
417
+ bannerControl = {
418
+ headerRows: renderedBanner.headerRows,
419
+ totalRows: renderedBanner.rows.length,
420
+ width,
421
+ toggle: banner.toggle,
422
+ };
423
+ lines.push(...renderedBanner.rows);
424
+ if (turns.length > 0) lines.push("");
425
+ }
426
+ }
427
+
428
+ const buildTurnKey = (index: number, turn: MinimalTurn, baseY: number, subChildren: Record<string, unknown>[]): readonly unknown[] => {
429
+ const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
430
+ const calls = turn.agentCalls ?? [];
431
+ const turnExpandedTools = expandedTools.size > 0
432
+ ? calls.filter(c => expandedTools.has(c.id)).map(c => c.id).join(",")
433
+ : "";
434
+ const thinkingPrefix = `thinking:${index}:`;
435
+ let turnExpandedThinking = "";
436
+ if (expandedThinking.size > 0) {
437
+ for (const id of expandedThinking) {
438
+ if (id.startsWith(thinkingPrefix)) turnExpandedThinking += (turnExpandedThinking ? "," : "") + id;
439
+ }
440
+ }
441
+ const turnExpandedSubagents = expandedSubagents.size > 0 && (subChildren.length > 0 || calls.some(isPrintAgentCall))
442
+ ? Array.from(expandedSubagents).join(",")
443
+ : "";
444
+ const hoveredId = hoveredTool && (hoveredTool.id.startsWith(thinkingPrefix) || calls.some(c => c.id === hoveredTool!.id))
445
+ ? `${hoveredTool.id}@${hoveredTool.y - baseY}@${hoveredTool.width}`
446
+ : "";
447
+ const turnPinnedTool = pinnedToolId && calls.some(c => c.id === pinnedToolId) ? pinnedToolId : "";
448
+ const turnPinnedAgent = pinnedAgentIndex === index ? index : -1;
449
+ const turnPinnedSubagent = pinnedSubagentId && (subChildren.length > 0 || calls.some(isPrintAgentCall)) ? pinnedSubagentId : "";
450
+ const elapsedSec = turn.startedAt != null && turn.endedAt == null
451
+ ? Math.floor((now - turn.startedAt) / 1000)
452
+ : (turn.endedAt ?? -1);
453
+ const key: unknown[] = [
454
+ width,
455
+ exp,
456
+ subExp,
457
+ usageShown,
458
+ recLimit,
459
+ lang,
460
+ agentModes.get(index),
461
+ expandedPrompts.get(index),
462
+ turnExpandedTools,
463
+ turnExpandedThinking,
464
+ turnExpandedSubagents,
465
+ hoveredId,
466
+ turnPinnedTool,
467
+ turnPinnedAgent,
468
+ turnPinnedSubagent,
469
+ turn.question,
470
+ turn.final ?? "",
471
+ turn.replies?.length ?? 0,
472
+ turn.replies?.at(-1) ?? "",
473
+ turn.process.length,
474
+ turn.process[0] ?? "",
475
+ turn.process.at(-1) ?? "",
476
+ turn.startedAt ?? -1,
477
+ elapsedSec,
478
+ turn.thinkingClocks?.length ?? 0,
479
+ turn.thinkingClocks?.at(-1)?.endedAt ?? -1,
480
+ turn.thinkingOutcomes?.length ?? 0,
481
+ usage.totalTokens,
482
+ usage.cacheRead,
483
+ calls.length,
484
+ subChildren.length,
485
+ ];
486
+ const replies = turn.replies;
487
+ if (replies) for (let i = 0; i < replies.length; i++) key.push(replies[i]);
488
+ for (let i = 0; i < turn.process.length; i++) key.push(turn.process[i]);
489
+ const clocks = turn.thinkingClocks;
490
+ if (clocks) {
491
+ for (let i = 0; i < clocks.length; i++) {
492
+ const clock = clocks[i];
493
+ key.push(clock?.startedAt, clock?.endedAt);
494
+ }
495
+ }
496
+ const outcomes = turn.thinkingOutcomes;
497
+ if (outcomes) for (let i = 0; i < outcomes.length; i++) key.push(outcomes[i]);
498
+ for (const c of calls) {
499
+ key.push(c.id, c.state, c.task, c.output?.length ?? -1, c.output, c.startedAt ?? -1, c.endedAt ?? -1, c.name, c.tool, c.action, c.command);
500
+ }
501
+ for (const sub of subChildren) {
502
+ key.push(
503
+ sub.runId ?? sub.displayId,
504
+ sub.status ?? sub.state,
505
+ sub.finalOutput,
506
+ sub.error,
507
+ (sub.notice as { summary?: unknown } | undefined)?.summary,
508
+ (sub.noticeMessages as unknown[] | undefined)?.length ?? 0,
509
+ childSessionData(sub.sessionFile)?.stamp ?? "",
510
+ );
511
+ }
512
+ return key;
513
+ };
514
+
515
+ const renderTurn = (index: number, turn: MinimalTurn, baseY: number): TurnRenderResult => {
516
+ const turnLines: string[] = [];
517
+ const turnPromptControls: TurnRenderResult["promptControls"] = [];
518
+ const turnToolControls: TurnRenderResult["toolControls"] = [];
519
+ const turnProcessRows: TurnRenderResult["processRows"] = [];
520
+ const turnAgentControls: TurnRenderResult["agentControls"] = [];
521
+ const turnSubagentControls: TurnRenderResult["subagentControls"] = [];
522
+ let turnPinnedTool: TurnRenderResult["pinnedTool"];
523
+ let turnPinnedAgent: TurnRenderResult["pinnedAgent"];
524
+ let turnPinnedSubagent: TurnRenderResult["pinnedSubagent"];
525
+ const beforeClaimedSize = claimedPrintSessions.size;
526
+ const copy = MINIMAL_COPY[lang] ?? MINIMAL_COPY.zh;
527
+
211
528
  const questionRows = markdown(turn.question, inner);
212
529
  const loopSummary = piLoopSummary(turn.question);
213
530
  const expanded = expandedPrompts.get(index) === turn.question;
@@ -218,20 +535,20 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
218
535
  const userRows = expanded || keepFence ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
219
536
  let controlIndex = -1;
220
537
  if (!keepFence && (loopSummary || questionRows.length > 4)) {
221
- const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
538
+ const label = expanded ? copy.collapsePrompt : loopSummary ? copy.expandPrompt : copy.expandPromptLines(questionRows.length);
222
539
  const control = truncateToWidth(label, inner, "");
223
- promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
540
+ turnPromptControls.push({ index, question: turn.question, y: turnLines.length + 1 + userRows.length,
224
541
  x: 0, width, label });
225
542
  userRows.push(theme.fg("accent", control));
226
543
  // The expanded control is this message's heading, so it keeps the band in place of the user surface.
227
544
  controlIndex = userRows.length;
228
545
  }
229
- lines.push(...surface(userRows, width, true, controlIndex, expanded));
546
+ turnLines.push(...surface(userRows, width, true, controlIndex, expanded));
230
547
  const entries = turn.process.flatMap((entry, processIndex) => {
231
548
  if (entry.startsWith("call ")) {
232
549
  const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
233
- if (call && isAgentTool(call.tool ?? call.name)) return [];
234
- const display = call && agentCallDisplay(call);
550
+ if (call && isCapturedCall(call)) return [];
551
+ const display = call && cachedCallDisplay(call);
235
552
  return call && display ? [{ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`.trim(), detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex, activeThinking: false }] : [];
236
553
  }
237
554
  const part = entry.match(/^(tool|output|thinking|skill)(?:\s+|$)([\s\S]*)/);
@@ -243,54 +560,49 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
243
560
  });
244
561
  // Older in-memory turns may predate call markers.
245
562
  for (const call of turn.agentCalls ?? []) {
246
- if (isAgentTool(call.tool ?? call.name)) continue;
247
- const display = agentCallDisplay(call);
563
+ if (isCapturedCall(call)) continue;
564
+ const display = cachedCallDisplay(call);
248
565
  if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`, detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex: -1, activeThinking: false });
249
566
  }
567
+ const printStatuses = (turn.agentCalls ?? []).flatMap(call => printAgentStatuses(call, renderCwd, claimedPrintSessions));
568
+ const claimedPrintFiles = claimedPrintSessions.size > beforeClaimedSize
569
+ ? Array.from(claimedPrintSessions).slice(beforeClaimedSize)
570
+ : [];
571
+ const combinedSubAgents = [...(turn.subAgents ?? []), ...printStatuses];
572
+ const hasTableSubAgents = printStatuses.length > 0 || agentChildren(turn.subAgents ?? []).some(child => Boolean(child.usage || childSessionData(child.sessionFile)?.sessionId));
250
573
  const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
251
- const agents = liveAgentView(turn.subAgents ?? [], theme, width, false, true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
574
+ const agents = liveAgentView(combinedSubAgents, theme, width, subExp && hasTableSubAgents, true, agentDeadlines, now, expandedSubagents, agentTurnControls, lang);
252
575
  const active = !!turn.running || agents.running > 0 || entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
253
- if (active) runningTurns.add(index);
254
- else if (runningTurns.delete(index)) {
255
- // Return to the configured preview once; a later click can expand everything again.
256
- if (agentModes.get(index) === "all") {
257
- agentModes.set(index, "preview");
258
- expandedThinking.clear();
259
- expandedTools.clear();
260
- expandedSubagents.clear();
261
- if (pinnedAgentIndex === index) pinnedAgentIndex = undefined;
262
- }
263
- }
264
576
  if (entries.length || active || turn.usage || agents.total) {
265
- const mode = agentModes.get(index) ?? (isExpanded() ? "all" : "preview");
577
+ const mode = agentModes.get(index) ?? (exp ? "all" : "preview");
266
578
  const expanded = mode === "all";
267
579
  const busy = entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
268
580
  const working = turn.running && !busy && !turn.final;
269
- const showAgentRows = (expanded || subAgentsExpanded()) && agents.total > 0;
581
+ const showAgentRows = (Boolean(agents.table) || expanded || subExp) && agents.total > 0;
270
582
  // Every child keeps its heading; process records share the remaining preview budget.
271
- const processLimit = Math.max(0, getRecordLimit() - (showAgentRows ? agents.total : 0));
583
+ const processLimit = Math.max(0, recLimit - (!agents.table && showAgentRows ? agents.total : 0));
272
584
  const shown = expanded ? entries : processLimit ? entries.slice(-processLimit) : [];
273
585
  const showWorking = working && (turn.awaitingResponse || expanded || (!shown.length && !agents.total));
274
- const sparkle = active ? Math.floor(Date.now() / 360) % 2 ? "✧" : "✦" : "✦";
586
+ const sparkle = active ? Math.floor(now / 360) % 2 ? "✧" : "✦" : "✦";
275
587
  const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
276
588
  const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
277
589
  const totals = hasUsage
278
- ? theme.fg("muted", "会话 ") + theme.bold(theme.fg("text", formatTokens(usage.totalTokens)))
279
- + theme.fg("muted", " · 缓存 ") + theme.bold(theme.fg("text", formatTokens(usage.cacheRead)))
590
+ ? theme.fg("muted", copy.session) + theme.bold(theme.fg("text", formatTokens(usage.totalTokens)))
591
+ + theme.fg("muted", copy.cache) + theme.bold(theme.fg("text", formatTokens(usage.cacheRead)))
280
592
  : "";
281
593
  const recordCount = entries.length + agents.total;
282
594
  const progressHeader = theme.fg(active ? "accent" : "muted", sparkle + " ") + theme.bold(theme.fg("text", "Agent")) + theme.fg("muted", recordCount ? ` · ${recordCount}` : "");
283
595
  const caret = theme.fg("muted", expanded ? " ▾" : " ▸");
284
- const elapsedHeader = turn.startedAt == null ? "" : theme.fg("muted", " · ") + theme.fg(active ? "success" : "muted", formatElapsed(turn.startedAt, turn.endedAt ?? Date.now()));
596
+ const elapsedHeader = turn.startedAt == null ? "" : theme.fg("muted", " · ") + theme.fg(active ? "success" : "muted", formatElapsed(turn.startedAt, turn.endedAt ?? now));
285
597
  const left = progressHeader + elapsedHeader + caret;
286
- const showTotals = hasUsage && showUsage() && visibleWidth(left) + 2 + visibleWidth(totals) <= width;
287
- agentControls.push({ index, y: lines.length + 1, width: Math.min(width, visibleWidth(left)) });
288
- if (expanded && pinnedAgentIndex === index) pinnedAgent = { index, y: lines.length + 1, line: truncateToWidth(left, width) };
289
- lines.push("", showTotals
598
+ const showTotals = hasUsage && usageShown && visibleWidth(left) + 2 + visibleWidth(totals) <= width;
599
+ turnAgentControls.push({ index, y: turnLines.length + 1, width: Math.min(width, visibleWidth(left)) });
600
+ if (expanded && pinnedAgentIndex === index) turnPinnedAgent = { index, y: turnLines.length + 1, line: truncateToWidth(left, width) };
601
+ turnLines.push("", showTotals
290
602
  ? left + " ".repeat(width - visibleWidth(left) - visibleWidth(totals)) + totals
291
603
  : truncateToWidth(left, width));
292
604
  shown.forEach((entry, row) => {
293
- processRows.push({ key: entry.id || `${index}:${entry.processIndex}`, y: lines.length });
605
+ turnProcessRows.push({ key: entry.id || `${index}:${entry.processIndex}`, y: turnLines.length });
294
606
  const title = entry.title;
295
607
  const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
296
608
  const split = text.indexOf(" ");
@@ -298,19 +610,19 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
298
610
  const label = split < 0 ? text : text.slice(0, split);
299
611
  const body = split < 0 ? "" : text.slice(split + 1);
300
612
  const activeThinking = !!entry.activeThinking;
301
- const elapsed = entry.thinking ? formatThinkingElapsed(turn, entry.processIndex, activeThinking) : "";
613
+ const elapsed = entry.thinking ? formatThinkingElapsed(turn, entry.processIndex, activeThinking, now) : "";
302
614
  const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
303
- const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
615
+ const call = turn.agentCalls?.find(call => call.id === entry.id && !isCapturedCall(call));
304
616
  const controlId = call?.id ?? (entry.thinking && !noThinkingBody || entry.id.startsWith("agents:") ? entry.id : "");
305
617
  const open = call ? expandedTools.has(call.id) : entry.thinking && !noThinkingBody && expandedThinking.has(entry.id);
306
618
  const identity = entry.state === "error" ? "error" : open || activeThinking ? "accent" : "text";
307
619
  const duration = call ? formatToolElapsed(call.startedAt,
308
- call.endedAt ?? (call.state === "running" ? Date.now() : undefined)) : "";
620
+ call.endedAt ?? (call.state === "running" ? now : undefined)) : "";
309
621
  const toolElapsed = duration ? theme.fg(entry.state === "error" ? "error" : call?.state === "running" ? "accent" : "muted", ` ${duration}`) : "";
310
622
  const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + toolElapsed + " ";
311
- if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
312
- if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
313
- const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
623
+ if (controlId && width >= 4) turnToolControls.push({ id: controlId, y: turnLines.length, width, title: text });
624
+ if (hoveredTool?.id === controlId && (hoveredTool.y !== baseY + turnLines.length || hoveredTool.width !== width)) clearHover();
625
+ const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph(now) : "●";
314
626
  const arrow = !!controlId && (open || hoveredTool?.id === controlId);
315
627
  const keepStatus = entry.state === "running" || (open && entry.state === "error");
316
628
  const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
@@ -323,8 +635,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
323
635
  const indent = visibleWidth(prefix);
324
636
  const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
325
637
  const wrapped = markdown(body, Math.max(1, width - indent), true);
326
- lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
327
- for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
638
+ turnLines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
639
+ for (const extra of wrapped.slice(1)) turnLines.push(truncateToWidth(rail + extra, width, ""));
328
640
  } else {
329
641
  const available = Math.max(0, width - visibleWidth(prefix));
330
642
  if (entry.thinking) {
@@ -334,29 +646,27 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
334
646
  const display = reuse ? cached.text : thinkingPreview(entry.detail, available, previewRows, activeThinking);
335
647
  if (!reuse) thinkingPreviews.set(entry.id, { text: display, source: entry.detail, width: available, rows: previewRows, live: activeThinking });
336
648
  const outcome = turn.thinkingOutcomes?.[entry.processIndex];
337
- const fallbackCopy = THINKING_FALLBACK[getLanguage()];
649
+ const fallbackCopy = THINKING_FALLBACK[lang];
338
650
  const fallback = activeThinking ? fallbackCopy.active
339
651
  : outcome === "aborted" ? fallbackCopy.aborted
340
652
  : outcome === "error" ? fallbackCopy.error : fallbackCopy.ended;
341
653
  const color = entry.state === "error" ? "error" : activeThinking ? "accent" : "muted";
342
654
  const rows = available > 0
343
- ? renderMinimalMarkdown(display || fallback, available, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
344
- { color: value => theme.fg(color, value) }, (source, avail) => transformText(placeholderText(diagramMarkdown(source, avail))))
345
- .slice(0, previewRows)
655
+ ? thinkingMarkdown(display || fallback, available, color, previewRows)
346
656
  : [];
347
- lines.push(bandHeading(truncateToWidth(prefix + (rows[0] ?? ""), width, ""), open));
657
+ turnLines.push(bandHeading(truncateToWidth(prefix + (rows[0] ?? ""), width, ""), open));
348
658
  const rail = theme.fg(last ? color : "dim", last ? " " : "│") + " ".repeat(Math.max(0, visibleWidth(prefix) - 1));
349
- for (const extra of rows.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
659
+ for (const extra of rows.slice(1)) turnLines.push(truncateToWidth(rail + extra, width, ""));
350
660
  } else {
351
661
  const displayBody = placeholderText(body);
352
- const compactBody = linkToolFiles(displayBody, imageOptions?.cwd() ?? process.cwd(), !open);
662
+ const compactBody = linkToolFiles(displayBody, renderCwd, !open);
353
663
  const fittedBody = truncateToWidth(compactBody, available, "…");
354
664
  // Always close a hyperlink before subsequent rows.
355
665
  const styledBody = theme.fg(entry.state === "error" ? "error" : open ? "accent" : "muted", fittedBody + "\x1b]8;;\x07");
356
- lines.push(bandHeading(truncateToWidth(prefix + styledBody, width, "…"), open));
666
+ turnLines.push(bandHeading(truncateToWidth(prefix + styledBody, width, "…"), open));
357
667
  }
358
668
  }
359
- if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
669
+ if (open && call && call.id === pinnedToolId) turnPinnedTool = { id: call.id, y: turnLines.length - 1, line: turnLines.at(-1)! };
360
670
  if (open && call) {
361
671
  // ponytail: saved text only; native view retains images, args and custom renderers.
362
672
  const output = stripVTControlCharacters(call.output ?? "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
@@ -364,43 +674,104 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
364
674
  const detailWidth = Math.max(1, width - visibleWidth(rail));
365
675
  if (call.task && (/\r|\n/.test(call.task) || visibleWidth(call.task) > width - visibleWidth(prefix))) {
366
676
  const input = stripVTControlCharacters(call.task).replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
367
- lines.push(...new Text(`输入:\n${input}`, 0, 0).render(detailWidth).map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
368
- lines.push(truncateToWidth(rail + theme.fg("muted", "输出:"), width, ""));
677
+ turnLines.push(...new Text(`${copy.inputLabel}\n${input}`, 0, 0).render(detailWidth).map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
678
+ turnLines.push(truncateToWidth(rail + theme.fg("muted", copy.outputLabel), width, ""));
369
679
  }
370
- const details = new Text(output || (entry.state === "running" ? "等待工具文本结果…" : "无文本结果"), 0, 0).render(detailWidth);
371
- lines.push(...details.map(line => truncateToWidth(rail + theme.fg(entry.state === "error" ? "error" : "muted", line), width, "")));
680
+ const details = new Text(output || (entry.state === "running" ? copy.waitingToolResult : copy.emptyToolResult), 0, 0).render(detailWidth);
681
+ turnLines.push(...details.map(line => truncateToWidth(rail + theme.fg(entry.state === "error" ? "error" : "muted", line), width, "")));
372
682
  } else if (open && entry.thinking) {
373
683
  const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
374
684
  const detailWidth = Math.max(1, width - visibleWidth(rail));
375
- lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
685
+ turnLines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
376
686
  }
377
687
  });
378
688
  if (showAgentRows) {
379
- const agentStartY = lines.length;
689
+ const agentStartY = turnLines.length;
380
690
  for (const c of agentTurnControls) {
381
691
  const control = { ...c, y: agentStartY + c.y };
382
- subagentControls.push(control);
383
- if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
692
+ turnSubagentControls.push(control);
693
+ if (c.runId === pinnedSubagentId) turnPinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
384
694
  }
385
- lines.push(...agents.rows);
695
+ turnLines.push(...agents.rows);
386
696
  }
387
697
  if (showWorking) {
388
698
  const label = turn.awaitingResponse ? "Waiting" : "Working";
389
- const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + " ";
390
- lines.push(truncateToWidth(prefix + theme.fg("muted", turn.awaitingResponse ? "等待模型响应" : "等待下一步执行"), width, ""));
699
+ const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph(now)} `) + theme.fg("text", theme.bold(label)) + " ";
700
+ turnLines.push(truncateToWidth(prefix + theme.fg("muted", turn.awaitingResponse ? copy.waitingModel : copy.waitingNextStep), width, ""));
701
+ }
702
+ }
703
+ for (const [replyIndex, reply] of (turn.replies ?? []).entries()) turnLines.push("", ...assistantMarkdown(reply, width, `reply:${index}:${replyIndex}`));
704
+ if (turn.final) turnLines.push("", ...assistantMarkdown(turn.final, width, `final:${index}`));
705
+ return {
706
+ lines: turnLines,
707
+ promptControls: turnPromptControls,
708
+ toolControls: turnToolControls,
709
+ processRows: turnProcessRows,
710
+ agentControls: turnAgentControls,
711
+ subagentControls: turnSubagentControls,
712
+ pinnedTool: turnPinnedTool,
713
+ pinnedAgent: turnPinnedAgent,
714
+ pinnedSubagent: turnPinnedSubagent,
715
+ claimedPrintFiles,
716
+ };
717
+ };
718
+
719
+ for (const [index, turn] of turns.entries()) {
720
+ if (index > 0) lines.push("");
721
+ const baseY = lines.length;
722
+ if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
723
+ const subChildren = turn.subAgents?.length ? agentChildren(turn.subAgents) : [];
724
+ const cheapActive = !!turn.running
725
+ || (turn.waitingTools?.length ?? 0) > 0
726
+ || (turn.agentCalls ?? []).some(call => !isAgentTool(call.tool ?? call.name) && call.state === "running")
727
+ || subChildren.some(isSubAgentChildRunning);
728
+ if (cheapActive) runningTurns.add(index);
729
+ else if (runningTurns.delete(index)) {
730
+ // Return to the configured preview once; a later click can expand everything again.
731
+ if (agentModes.get(index) === "all") {
732
+ agentModes.set(index, "preview");
733
+ expandedThinking.clear();
734
+ expandedTools.clear();
735
+ expandedSubagents.clear();
736
+ if (pinnedAgentIndex === index) pinnedAgentIndex = undefined;
737
+ }
738
+ }
739
+ const canCache = !cheapActive && !hasFutureDeadline;
740
+ let rendered: TurnRenderResult | undefined;
741
+ if (canCache) {
742
+ const key = buildTurnKey(index, turn, baseY, subChildren);
743
+ const cached = turnCache.get(index);
744
+ if (cached && keysEqual(cached.key, key)) {
745
+ rendered = cached.value;
746
+ } else {
747
+ rendered = renderTurn(index, turn, baseY);
748
+ turnCache.set(index, { key: buildTurnKey(index, turn, baseY, subChildren), value: rendered });
391
749
  }
750
+ } else {
751
+ turnCache.delete(index);
752
+ rendered = renderTurn(index, turn, baseY);
392
753
  }
393
- for (const [replyIndex, reply] of (turn.replies ?? []).entries()) lines.push("", ...assistantMarkdown(reply, width, `reply:${index}:${replyIndex}`));
394
- if (turn.final) lines.push("", ...assistantMarkdown(turn.final, width, `final:${index}`));
754
+ for (const f of rendered.claimedPrintFiles) claimedPrintSessions.add(f);
755
+ for (const c of rendered.promptControls) promptControls.push({ ...c, y: baseY + c.y });
756
+ for (const c of rendered.toolControls) toolControls.push({ ...c, y: baseY + c.y });
757
+ for (const r of rendered.processRows) processRows.push({ key: r.key, y: baseY + r.y });
758
+ for (const c of rendered.agentControls) agentControls.push({ ...c, y: baseY + c.y });
759
+ for (const c of rendered.subagentControls) subagentControls.push({ ...c, y: baseY + c.y });
760
+ if (rendered.pinnedTool) pinnedTool = { ...rendered.pinnedTool, y: baseY + rendered.pinnedTool.y };
761
+ if (rendered.pinnedAgent) pinnedAgent = { ...rendered.pinnedAgent, y: baseY + rendered.pinnedAgent.y };
762
+ if (rendered.pinnedSubagent) pinnedSubagent = { ...rendered.pinnedSubagent, y: baseY + rendered.pinnedSubagent.y };
763
+ for (const line of rendered.lines) lines.push(line);
764
+ const noticeRows = notices?.get(index) ?? [];
395
765
  noticeRegions.push({ y: lines.length, rows: noticeRows });
396
- lines.push(...noticeRows);
766
+ for (const line of noticeRows) lines.push(line);
397
767
  }
398
768
  if (hoveredTool && !toolControls.some(control => control.id === hoveredTool!.id)) clearHover();
399
769
  if (hoveredProcess && !processRows.some(row => row.key === hoveredProcess!.key && row.y === hoveredProcess!.y)) clearHover();
400
770
  for (const deadline of agentDeadlines.values()) if (deadline > Date.now()) agentExpiry = Math.min(agentExpiry, deadline);
401
771
  const linkedRows = linkHover.render(lines, width);
402
772
  const hovered = hoveredProcess;
403
- const hoveredRow = hovered && processRows.find(row => row.key === hovered.key && row.y === hovered.y);
773
+ const hoveredAt = hovered && firstAtY(processRows, hovered.y);
774
+ const hoveredRow = hoveredAt && hoveredAt.key === hovered.key ? hoveredAt : undefined;
404
775
  if (!hoveredRow) return linkedRows;
405
776
  const result = [...linkedRows];
406
777
  const line = result[hoveredRow.y];