pi-cc-extensions 0.8.53 → 0.8.54

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.
Files changed (39) hide show
  1. package/README.en.md +6 -8
  2. package/README.md +5 -6
  3. package/assets/readme/hero.en.svg +101 -0
  4. package/extensions/config/config.ts +1 -17
  5. package/extensions/config/panel.ts +5 -3
  6. package/extensions/{utils/agent-summary.ts → feature/agent-summary/core.ts} +37 -35
  7. package/extensions/feature/{agent-summary.ts → agent-summary/index.ts} +2 -6
  8. package/extensions/feature/{session-reference.ts → reference/index.ts} +1 -1
  9. package/extensions/feature/{pi-startup-header.ts → shell/startup-header.ts} +1 -1
  10. package/extensions/index.ts +22 -33
  11. package/extensions/renderer/compact-mode.ts +371 -84
  12. package/extensions/renderer/default-mode.ts +726 -0
  13. package/extensions/renderer/index.ts +57 -773
  14. package/extensions/renderer/{mouse-hover.ts → mouse/hover.ts} +5 -5
  15. package/extensions/renderer/{mouse-interaction.ts → mouse/interaction.ts} +37 -35
  16. package/extensions/renderer/{mouse-layout.ts → mouse/layout.ts} +5 -21
  17. package/extensions/renderer/{mouse-packets.ts → mouse/packets.ts} +1 -1
  18. package/extensions/renderer/{mouse-scroll.ts → mouse/scroll.ts} +46 -33
  19. package/extensions/renderer/{tool-diff → tool/diff}/diff-renderer.ts +2 -2
  20. package/extensions/renderer/{tool-diff → tool/diff}/line-width-safety.ts +1 -1
  21. package/extensions/renderer/tool/diff/write-display-utils.ts +12 -0
  22. package/extensions/renderer/{tool-grouping.ts → tool/grouping.ts} +18 -8
  23. package/extensions/renderer/{tool-result.ts → tool/result.ts} +4 -13
  24. package/extensions/utils/fullscreen-detect.ts +0 -27
  25. package/package.json +3 -2
  26. package/extensions/renderer/tool-diff/write-display-utils.ts +0 -29
  27. /package/extensions/feature/{session-reference-core.ts → reference/session.ts} +0 -0
  28. /package/extensions/feature/{agent-autocomplete.ts → reference/subagent.ts} +0 -0
  29. /package/extensions/feature/{pi-aliases.ts → shell/aliases.ts} +0 -0
  30. /package/extensions/feature/{working-message.ts → shell/working-message.ts} +0 -0
  31. /package/extensions/{feature → renderer}/markdown-enhance.ts +0 -0
  32. /package/extensions/renderer/{tool-diff → tool/diff}/ATTRIBUTION.md +0 -0
  33. /package/extensions/renderer/{tool-diff → tool/diff}/ansi-utils.ts +0 -0
  34. /package/extensions/renderer/{tool-diff → tool/diff}/diff-presentation.ts +0 -0
  35. /package/extensions/renderer/{tool-diff → tool/diff}/index.ts +0 -0
  36. /package/extensions/renderer/{tool-diff → tool/diff}/render-utils.ts +0 -0
  37. /package/extensions/renderer/{tool-diff → tool/diff}/shiki-highlight.ts +0 -0
  38. /package/extensions/renderer/{tool-diff → tool/diff}/types.ts +0 -0
  39. /package/extensions/renderer/{tool-diff → tool/diff}/write-execution.ts +0 -0
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * Compact mode:每条含 toolCall 的 assistant message 折叠为一条逐步累加的摘要行
3
- * (`Thought for 8s, bash×2, read×2`),edit/write 独立单行(`✓ write <path> (+25 -0)`),
3
+ * (`Ran for 8s, bash×2, read×2`),edit/write 独立单行(`✓ write <path> (+25 -0)`),
4
4
  * 普通工具折叠时不显示独立行;展开(Ctrl+O / fullscreen 点击)在单个工具卡中恢复
5
5
  * compact-thinking/Pi 原生或专用 renderer。edit/write 折叠时显示统计,展开时显示 rich diff。
6
+ * Agent/Task 族:调用只进摘要计数,tool 卡始终折叠(避免 pending→完成高度闪动)。
7
+ * 底部 Agents/Tasks 面板由 pi-subagents/pi-tasks 独立 widget 负责,不经 tool 卡外置。
6
8
  *
7
- * 统计口径与 utils/agent-summary.ts 对齐:read 按非空路径去重、bash 按调用计数、
8
- * 其他工具按首次出现顺序计数;edit/write 不进入摘要。思考时长复用
9
- * compact-thinking 的 completedDurations/activeThinking 与持久化 entry(只读查询),
10
- * 不建立第二套计时器。最终 agent summary 仍由 feature/agent-summary.ts 独占。
9
+ * 工具计数:read 按非空路径去重、其余按调用计数(首次出现顺序);edit/write 不进摘要。
10
+ * 时长 = 回合流逝挂钟;进行中 Running...,结束 Ran for。
11
+ * abort/error/length 状态行挂在摘要外层,避免被折叠吞掉。
12
+ * 最终 agent 回合摘要由 feature/agent-summary 独占(bash/read/edit/write/other)。
11
13
  *
12
14
  * 补丁生命周期遵循仓库既有模式:Symbol 所有权、dispose 仅恢复仍由本安装持有的
13
15
  * 方法、重入守卫防止 /reload 后残留闭包递归。
@@ -17,8 +19,7 @@ import {
17
19
  ToolExecutionComponent,
18
20
  type Theme,
19
21
  } from "@earendil-works/pi-coding-agent";
20
- import * as PiTui from "@earendil-works/pi-tui";
21
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
22
+ import { truncateToWidth, visibleWidth, Box } from "@earendil-works/pi-tui";
22
23
  import { config, getToolDisplayConfig } from "../config/config.ts";
23
24
  import { toolLoadingIcon } from "../utils/tool-loading-icon.ts";
24
25
  import { sanitizeToolResultText } from "../utils/tool-result-sanitize.ts";
@@ -29,15 +30,16 @@ import {
29
30
  countEditDiffStats,
30
31
  countWriteDiffStats,
31
32
  isRichDiffComponent,
32
- } from "./tool-diff/diff-renderer.ts";
33
- import { renderRichToolResult } from "./tool-diff/index.ts";
34
- import type { WriteExecutionMetadataStore } from "./tool-diff/write-execution.ts";
33
+ } from "./tool/diff/diff-renderer.ts";
34
+ import { renderRichToolResult } from "./tool/diff/index.ts";
35
+ import type { WriteExecutionMetadataStore } from "./tool/diff/write-execution.ts";
35
36
  import {
36
37
  insetComponent,
37
38
  oneLine,
38
39
  renderExpandedToolResult,
39
40
  scheduleAnimation,
40
- } from "./tool-result.ts";
41
+ } from "./tool/result.ts";
42
+ import { paddedBackgroundRow, stripBackgroundAnsi } from "./tool/grouping.ts";
41
43
 
42
44
  /** compact 渲染层对 compact-thinking 的只读查询面(不建第二套计时器)。 */
43
45
  export type CompactThinkingQuery = {
@@ -57,7 +59,6 @@ const ASSISTANT_SET_EXPANDED_KEY = Symbol.for(ASSISTANT_SET_EXPANDED_DESCRIPTION
57
59
  const ASSISTANT_TOGGLE_ROUND_KEY = Symbol.for(ASSISTANT_TOGGLE_ROUND_DESCRIPTION);
58
60
  const ASSISTANT_REENTRY_KEY = Symbol.for(ASSISTANT_REENTRY_DESCRIPTION);
59
61
 
60
- const Box = (PiTui as any).Box;
61
62
  const EDIT_WRITE_TOOLS = new Set(["edit", "write"]);
62
63
 
63
64
  type CompactThinkingTheme = Pick<Theme, "fg" | "italic" | "bold">;
@@ -124,26 +125,52 @@ function formatThoughtDuration(durationMs: number) {
124
125
 
125
126
  export { formatThoughtDuration };
126
127
 
128
+ /** assistant stopReason → 外层状态文案(与 Pi 原生口径对齐)。 */
129
+ export function messageStopStatus(message: any): string | undefined {
130
+ const reason = message?.stopReason;
131
+ if (reason === "aborted") {
132
+ return message.errorMessage && message.errorMessage !== "Request was aborted"
133
+ ? String(message.errorMessage)
134
+ : "Operation aborted";
135
+ }
136
+ if (reason === "error") {
137
+ return `Error: ${message.errorMessage || "Unknown error"}`;
138
+ }
139
+ if (reason === "length") {
140
+ return "Response was truncated before completion.";
141
+ }
142
+ return undefined;
143
+ }
144
+
145
+ function roundStopStatus(messages: Iterable<any>): string | undefined {
146
+ for (const message of messages) {
147
+ const status = messageStopStatus(message);
148
+ if (status) return status;
149
+ }
150
+ return undefined;
151
+ }
152
+
127
153
  /**
128
154
  * 逐条 assistant message 的摘要文本(无工具计数时可为空串):
129
- * 思考时长在前,工具按消息内首次出现顺序排列;read 按非空路径去重。
155
+ * 时长 = max(thinking query, durationFloorMs 挂钟);工具首次出现顺序;read 路径去重。
130
156
  */
131
157
  function buildMessagesSummary(
132
158
  messages: Iterable<any>,
133
159
  query?: CompactThinkingQuery,
134
- thinkingActiveOverride?: boolean,
160
+ runningActiveOverride?: boolean,
161
+ durationFloorMs?: number,
135
162
  ): string {
136
163
  const parts: string[] = [];
137
164
  const counts = new Map<string, number>();
138
165
  const readPaths = new Set<string>();
139
166
  const durationTimestamps = new Set<number>();
140
167
  let durationMs = 0;
141
- let thinkingActive = false;
168
+ let runningActive = false;
142
169
 
143
170
  for (const message of messages) {
144
171
  if (typeof message?.timestamp === "number" && !durationTimestamps.has(message.timestamp)) {
145
172
  durationTimestamps.add(message.timestamp);
146
- if (query?.isMessageThinkingActive?.(message.timestamp)) thinkingActive = true;
173
+ if (query?.isMessageThinkingActive?.(message.timestamp)) runningActive = true;
147
174
  const value = query?.getMessageThinkingDurationMs(message.timestamp);
148
175
  if (typeof value === "number" && Number.isFinite(value) && value > 0) durationMs += value;
149
176
  }
@@ -165,18 +192,28 @@ function buildMessagesSummary(
165
192
  }
166
193
  }
167
194
 
168
- thinkingActive = thinkingActiveOverride ?? thinkingActive;
169
- if (thinkingActive) {
170
- parts.push(
171
- durationMs > 0 ? `Thinking... · ${formatThoughtDuration(durationMs)}` : "Thinking...",
172
- );
173
- } else if (durationMs > 0) parts.push(`Thought for ${formatThoughtDuration(durationMs)}`);
195
+ if (
196
+ typeof durationFloorMs === "number" &&
197
+ Number.isFinite(durationFloorMs) &&
198
+ durationFloorMs > durationMs
199
+ ) {
200
+ durationMs = durationFloorMs;
201
+ }
202
+
203
+ runningActive = runningActiveOverride ?? runningActive;
204
+ if (runningActive) {
205
+ parts.push(durationMs > 0 ? `Running... · ${formatThoughtDuration(durationMs)}` : "Running...");
206
+ } else if (durationMs > 0) parts.push(`Ran for ${formatThoughtDuration(durationMs)}`);
174
207
  for (const [name, count] of counts) parts.push(`${name}×${count}`);
175
208
  return parts.join(", ");
176
209
  }
177
210
 
178
- export function buildMessageSummary(message: any, query?: CompactThinkingQuery): string {
179
- return buildMessagesSummary([message], query);
211
+ export function buildMessageSummary(
212
+ message: any,
213
+ query?: CompactThinkingQuery,
214
+ durationFloorMs?: number,
215
+ ): string {
216
+ return buildMessagesSummary([message], query, undefined, durationFloorMs);
180
217
  }
181
218
 
182
219
  function fallbackTheme(): any {
@@ -191,7 +228,101 @@ function themeOf(): any {
191
228
  return getMessageDisplayTheme() ?? fallbackTheme();
192
229
  }
193
230
 
194
- function expandedToolCard(theme: any): any {
231
+ /** RGB → HSL(h∈[0,1), l/s∈[0,1])。 */
232
+ function rgbToHsl(r: number, g: number, b: number): [number, number, number] {
233
+ r /= 255;
234
+ g /= 255;
235
+ b /= 255;
236
+ const max = Math.max(r, g, b);
237
+ const min = Math.min(r, g, b);
238
+ const l = (max + min) / 2;
239
+ if (max === min) return [0, 0, l];
240
+ const d = max - min;
241
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
242
+ let h: number;
243
+ switch (max) {
244
+ case r:
245
+ h = (g - b) / d + (g < b ? 6 : 0);
246
+ break;
247
+ case g:
248
+ h = (b - r) / d + 2;
249
+ break;
250
+ default:
251
+ h = (r - g) / d + 4;
252
+ }
253
+ return [h / 6, l, s];
254
+ }
255
+
256
+ /** HSL → RGB(h∈[0,1),l/s∈[0,1])。 */
257
+ function hslToRgb(h: number, l: number, s: number): [number, number, number] {
258
+ if (s === 0) {
259
+ const v = Math.round(l * 255);
260
+ return [v, v, v];
261
+ }
262
+ const hue2rgb = (p: number, q: number, t: number): number => {
263
+ if (t < 0) t += 1;
264
+ if (t > 1) t -= 1;
265
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
266
+ if (t < 1 / 2) return q;
267
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
268
+ return p;
269
+ };
270
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
271
+ const p = 2 * l - q;
272
+ return [
273
+ Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
274
+ Math.round(hue2rgb(p, q, h) * 255),
275
+ Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
276
+ ];
277
+ }
278
+
279
+ /** 内部 tool call card 背景:在 userMessageBg 基础上按 HSL 变暗(l×0.7),
280
+ * 与外卡片形成嵌套层次;非 RGB 色或已足够暗时原样返回。 */
281
+ function darkenBgAnsi(theme: any, slot: string): string {
282
+ const prefix = typeof theme?.getBgAnsi === "function" ? String(theme.getBgAnsi(slot)) : "";
283
+ const m = prefix.match(/48;2;(\d+);(\d+);(\d+)/);
284
+ if (!m) return prefix;
285
+ const [h, l, s] = rgbToHsl(Number(m[1]), Number(m[2]), Number(m[3]));
286
+ if (l <= 0.05) return prefix; // 已足够暗,不再变暗
287
+ const [r, g, b] = hslToRgb(h, l * 0.7, s);
288
+ return `\x1b[48;2;${r};${g};${b}m`;
289
+ }
290
+
291
+ /** 去掉行内所有 CSI/OSC 序列后是否有可见文本(判断工具卡首尾内容行)。 */
292
+ function hasVisibleText(line: string): boolean {
293
+ return (
294
+ line
295
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
296
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
297
+ .trim().length > 0
298
+ );
299
+ }
300
+
301
+ /** 工具卡深色行:左右内缩(左 2 右 3 格,含工具卡自身 padding),背景只到内容区,
302
+ * 修复行尾 reset 截断。 */
303
+ function toolCardBgRow(
304
+ theme: any,
305
+ slot: string,
306
+ bgAnsi: string,
307
+ line: string,
308
+ width: number,
309
+ ): string {
310
+ const leftInset = 2;
311
+ const rightInset = 3;
312
+ const contentWidth = Math.max(0, width - leftInset - rightInset);
313
+ // 深色块内左右各 1 格内部 padding;去掉行首原有空格后重新对齐
314
+ const text = stripBackgroundAnsi(line).replace(/^ +/, "");
315
+ const innerPad = 2;
316
+ const clipped = truncateToWidth(text, Math.max(0, contentWidth - innerPad), "");
317
+ const pad = Math.max(0, contentWidth - innerPad - visibleWidth(clipped));
318
+ const body = ` ${clipped}${" ".repeat(pad)} `;
319
+ const stable = body.replace(/\x1b\[(?:0)?m/g, (reset) => reset + bgAnsi);
320
+ const outerBg = typeof theme?.getBgAnsi === "function" ? String(theme.getBgAnsi(slot)) : "";
321
+ const inset = (n) => (outerBg ? `${outerBg}${" ".repeat(n)}\x1b[49m` : " ".repeat(n));
322
+ return `${inset(leftInset)}${bgAnsi}${stable}\x1b[49m${inset(rightInset)}`;
323
+ }
324
+ /** edit/write 展开卡:保持原样式(userMessageBg Box),不应用工具卡深色/间距改动。 */
325
+ function editWriteExpandedCard(theme: any): any {
195
326
  return new Box(
196
327
  1,
197
328
  1,
@@ -199,6 +330,73 @@ function expandedToolCard(theme: any): any {
199
330
  );
200
331
  }
201
332
 
333
+ /** compact 展开卡:外卡片保持 userMessageBg 原色;内部 tool call card(addToolChild)
334
+ * 背景更深一层且只覆盖内容区(左右内缩、上下限首尾文本行),形成嵌套层次。
335
+ * 逐行重建背景同时修复嵌套 Box 的右侧截断。 */
336
+ function expandedToolCard(theme: any): any {
337
+ const slot = "userMessageBg";
338
+ const toolBgAnsi = darkenBgAnsi(theme, slot);
339
+ const children: any[] = [];
340
+ return {
341
+ children,
342
+ addChild(child: any) {
343
+ children.push(child);
344
+ },
345
+ addToolChild(child: any) {
346
+ child.__ccToolCard = true;
347
+ children.push(child);
348
+ },
349
+ render(width: number): string[] {
350
+ const innerWidth = Math.max(0, width - 2);
351
+ const lines: string[] = [];
352
+ lines.push(paddedBackgroundRow(theme, slot, "", width));
353
+ // 展开不再显示摘要行:跳过第一个 child 的首行空白,避免白占一行
354
+ let skipLeadingBlank = true;
355
+ for (const child of children) {
356
+ const childLines = child.render(innerWidth);
357
+ if (!child.__ccToolCard) {
358
+ let start = 0;
359
+ if (skipLeadingBlank) {
360
+ while (start < childLines.length && !hasVisibleText(childLines[start])) start++;
361
+ skipLeadingBlank = false;
362
+ }
363
+ for (let i = start; i < childLines.length; i++) {
364
+ lines.push(paddedBackgroundRow(theme, slot, childLines[i], width));
365
+ }
366
+ continue;
367
+ }
368
+ // 工具卡:前导 1 空行 + 首尾文本行之间的内容区(深色);不保留尾随,
369
+ // 相邻工具卡之间正好 1 空行,底部由卡片 padding 收尾。
370
+ skipLeadingBlank = false;
371
+ let first = -1;
372
+ let last = -1;
373
+ for (let i = 0; i < childLines.length; i++) {
374
+ if (hasVisibleText(childLines[i])) {
375
+ if (first < 0) first = i;
376
+ last = i;
377
+ }
378
+ }
379
+ if (first < 0) {
380
+ for (const line of childLines) {
381
+ lines.push(paddedBackgroundRow(theme, slot, line, width));
382
+ }
383
+ continue;
384
+ }
385
+ lines.push(paddedBackgroundRow(theme, slot, "", width));
386
+ // 子卡片内部上下各 1 行深色 padding
387
+ lines.push(toolCardBgRow(theme, slot, toolBgAnsi, "", width));
388
+ for (let i = first; i <= last; i++) {
389
+ lines.push(toolCardBgRow(theme, slot, toolBgAnsi, childLines[i], width));
390
+ }
391
+ lines.push(toolCardBgRow(theme, slot, toolBgAnsi, "", width));
392
+ }
393
+ lines.push(paddedBackgroundRow(theme, slot, "", width));
394
+ return lines;
395
+ },
396
+ invalidate() {},
397
+ };
398
+ }
399
+
202
400
  function isAssistantComponent(value: any): boolean {
203
401
  return value instanceof AssistantMessageComponent;
204
402
  }
@@ -249,7 +447,7 @@ export type CompactModeHooks = {
249
447
  refresh(): void;
250
448
  /** compact 模式下重新认领 assistant patch(位于 compact-thinking 之上)。 */
251
449
  assertOwnership(): void;
252
- /** 重新渲染包含指定 toolCallId 的 assistant 消息(思考收尾时刷新时长)。 */
450
+ /** 重新渲染包含指定 toolCallId 的 assistant 消息(思考收尾时刷新)。 */
253
451
  refreshToolCallMessage(toolCallId: string | undefined): void;
254
452
  shutdown(): void;
255
453
  };
@@ -383,7 +581,7 @@ function compactEditWriteExpandedLines(
383
581
  component.resultRendererComponent = detail;
384
582
  }
385
583
 
386
- const box = expandedToolCard(theme);
584
+ const box = editWriteExpandedCard(theme);
387
585
  box.addChild({
388
586
  render(innerWidth: number): string[] {
389
587
  return compactEditWriteLine(component, innerWidth, writeMetadata).slice(1);
@@ -396,7 +594,8 @@ function compactEditWriteExpandedLines(
396
594
 
397
595
  function compactAssistantLineComponent(
398
596
  component: any,
399
- summary: string,
597
+ /** 静态串或每次 render 重算(Running 时长需逐步跳动)。 */
598
+ summary: string | (() => string),
400
599
  query?: CompactThinkingQuery,
401
600
  options: { hint?: boolean; leadingBlank?: boolean; pad?: number } = {},
402
601
  ): any {
@@ -408,17 +607,15 @@ function compactAssistantLineComponent(
408
607
  const available = Math.max(0, width - pad);
409
608
  const hintText = options.hint === false ? "" : ` • ${showMoreHintText()}`;
410
609
  const summaryWidth = Math.max(0, available - visibleWidth(hintText));
411
- const thinkingActive = summary.startsWith("Thinking...");
412
- const displaySummary = thinkingActive
413
- ? `${self.hiddenThinkingLabel || "Thinking..."}${summary.slice("Thinking...".length)}`
414
- : summary;
415
- const plainText = truncateToWidth(displaySummary, summaryWidth, "…");
610
+ const resolved = typeof summary === "function" ? summary() : summary;
611
+ const runningActive = resolved.startsWith("Running...");
612
+ const plainText = truncateToWidth(resolved, summaryWidth, "…");
416
613
  let text = theme.fg("muted", plainText);
417
- if (thinkingActive || plainText.startsWith("Thought for ")) {
614
+ if (runningActive || plainText.startsWith("Ran for ")) {
418
615
  const separator = plainText.indexOf(", ");
419
616
  const heading = separator < 0 ? plainText : plainText.slice(0, separator);
420
617
  const tools = separator < 0 ? "" : plainText.slice(separator);
421
- if (thinkingActive) {
618
+ if (runningActive) {
422
619
  const durationSeparator = heading.indexOf(" · ");
423
620
  const label = durationSeparator < 0 ? heading : heading.slice(0, durationSeparator);
424
621
  const duration = durationSeparator < 0 ? "" : heading.slice(durationSeparator);
@@ -440,11 +637,35 @@ function compactAssistantLineComponent(
440
637
  };
441
638
  }
442
639
 
443
- function compactAssistantLine(component: any, summary: string, query?: CompactThinkingQuery): void {
444
- if (!summary) return;
640
+ function compactStopStatusLine(status: string, pad = 0): any {
641
+ return {
642
+ render(width: number): string[] {
643
+ const theme = themeOf();
644
+ const prefix = " ".repeat(Math.max(0, pad));
645
+ const line = `${prefix}${theme.fg("error", status)}`;
646
+ return ["", truncateToWidth(line, width, "")];
647
+ },
648
+ invalidate() {},
649
+ };
650
+ }
651
+
652
+ function compactAssistantLine(
653
+ component: any,
654
+ summary: string | (() => string),
655
+ query?: CompactThinkingQuery,
656
+ ): void {
657
+ // 空静态串跳过;getter 留给 render 判断(Running 可能稍后才有时长)。
658
+ if (typeof summary === "string" && !summary) return;
445
659
  component.contentContainer.addChild(compactAssistantLineComponent(component, summary, query));
446
660
  }
447
661
 
662
+ function appendStopStatus(component: any, status: string | undefined): void {
663
+ if (!status || !component?.contentContainer?.addChild) return;
664
+ component.contentContainer.addChild(
665
+ compactStopStatusLine(status, Number(component.outputPad) || 0),
666
+ );
667
+ }
668
+
448
669
  function ensureAssistantSetExpanded(component: any): void {
449
670
  if (
450
671
  typeof component[ASSISTANT_SET_EXPANDED_KEY] === "function" &&
@@ -508,10 +729,17 @@ function collectMountedComponents(root: any): void {
508
729
  }
509
730
  };
510
731
  visit(root);
511
- trackedAssistantComponents.clear();
512
- trackedToolComponents.clear();
513
- for (const component of assistants) trackedAssistantComponents.add(component);
514
- for (const component of tools) trackedToolComponents.add(component);
732
+ // 扫到组件才替换跟踪表。面板/custom UI 打开时 root 往往扫不到 transcript,
733
+ // 若此时清空会丢掉 live updateContent/updateDisplay 已登记的实例,
734
+ // /ccstyle 切换就只能靠 /reload 重建。
735
+ if (assistants.size > 0 || tools.size > 0) {
736
+ trackedAssistantComponents.clear();
737
+ trackedToolComponents.clear();
738
+ for (const component of assistants) trackedAssistantComponents.add(component);
739
+ for (const component of tools) trackedToolComponents.add(component);
740
+ } else if (config.mode === "compact") {
741
+ for (const component of trackedAssistantComponents) ensureAssistantSetExpanded(component);
742
+ }
515
743
  }
516
744
 
517
745
  export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHooks {
@@ -553,10 +781,62 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
553
781
  detachedMessages: any[];
554
782
  active: boolean;
555
783
  suppressedToolIds: Set<string>;
784
+ /** 回合挂钟起点,保证 Running 时长连续递增。 */
785
+ startedAt: number;
786
+ endedAt?: number;
556
787
  };
557
788
  let activeRound: CompactRound | undefined;
558
789
  let roundByComponent = new WeakMap<object, CompactRound>();
559
790
  const expandedRoundToolIds = new Set<string>();
791
+ let uiRef: { requestRender?: (force?: boolean) => void } | undefined;
792
+ let roundTickTimer: ReturnType<typeof setInterval> | undefined;
793
+
794
+ const roundWallMs = (round: CompactRound): number => {
795
+ const end = round.active ? Date.now() : (round.endedAt ?? Date.now());
796
+ return Math.max(1, end - round.startedAt);
797
+ };
798
+
799
+ const summarize = (messages: Iterable<any>, runningActive?: boolean, round?: CompactRound) =>
800
+ buildMessagesSummary(
801
+ messages,
802
+ deps.query,
803
+ runningActive,
804
+ round ? roundWallMs(round) : undefined,
805
+ );
806
+
807
+ const stopRoundTick = (): void => {
808
+ if (!roundTickTimer) return;
809
+ clearInterval(roundTickTimer);
810
+ roundTickTimer = undefined;
811
+ };
812
+
813
+ // 自备 tick:getter 在 render 重算挂钟;兼驱动 Running 扫光(setCompactSummaryActive)。
814
+ const ensureRoundTick = (): void => {
815
+ if (roundTickTimer) return;
816
+ roundTickTimer = setInterval(() => {
817
+ if (!patch.active || !activeRound?.active) {
818
+ stopRoundTick();
819
+ return;
820
+ }
821
+ try {
822
+ uiRef?.requestRender?.(true);
823
+ } catch {
824
+ /* 无 UI */
825
+ }
826
+ }, 250);
827
+ };
828
+
829
+ /** 结束回合活动态;可选立即重绘。 */
830
+ const endRound = (round: CompactRound, render = false): void => {
831
+ round.active = false;
832
+ if (round.endedAt === undefined) round.endedAt = Date.now();
833
+ if (activeRound === round) {
834
+ activeRound = undefined;
835
+ deps.query?.setCompactSummaryActive?.(false);
836
+ stopRoundTick();
837
+ }
838
+ if (render) renderRound(round);
839
+ };
560
840
 
561
841
  const renderAssistantWithoutThinking = (component: any, message: any): any => {
562
842
  const content = Array.isArray(message?.content) ? message.content : [];
@@ -584,7 +864,12 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
584
864
  };
585
865
 
586
866
  const renderRound = (round: CompactRound): void => {
587
- const summary = buildMessagesSummary(roundMessages(round), deps.query, round.active);
867
+ const messages = roundMessages(round);
868
+ const stopStatus = roundStopStatus(messages);
869
+ if (stopStatus) endRound(round);
870
+ // Running 时每次 render 重算时长(含挂钟下限);结束后固定。
871
+ const getSummary = () => summarize(roundMessages(round), round.active, round);
872
+ const summary = getSummary();
588
873
  for (const id of round.suppressedToolIds) expandedRoundToolIds.delete(id);
589
874
  round.suppressedToolIds.clear();
590
875
 
@@ -634,20 +919,13 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
634
919
  render(width: number): string[] {
635
920
  const theme = themeOf();
636
921
  const box = expandedToolCard(theme);
637
- box.addChild(
638
- compactAssistantLineComponent(round.anchor, summary, deps.query, {
639
- hint: false,
640
- leadingBlank: false,
641
- pad: 0,
642
- }),
643
- );
644
922
  for (const child of assistantChildren) box.addChild(child);
645
923
  const ids = roundToolCallIds(round);
646
924
  for (const tool of trackedToolComponents) {
647
925
  if (!ids.has(tool.toolCallId) || EDIT_WRITE_TOOLS.has(String(tool.toolName ?? ""))) {
648
926
  continue;
649
927
  }
650
- box.addChild({
928
+ box.addToolChild({
651
929
  render: (innerWidth: number) => patch.toolOriginalRender.call(tool, innerWidth),
652
930
  invalidate: () => tool.invalidate?.(),
653
931
  });
@@ -658,13 +936,18 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
658
936
  for (const child of assistantChildren) child.invalidate?.();
659
937
  },
660
938
  });
939
+ // 展开卡内工具会显示 error,外层仍挂 abort/length,避免只藏在折叠工具里。
940
+ appendStopStatus(round.anchor, stopStatus);
661
941
  return;
662
942
  }
663
943
 
664
944
  for (const [component, message] of round.messages) {
665
945
  if (component === round.anchor) {
666
946
  renderAssistantWithoutThinking(component, message);
667
- compactAssistantLine(component, summary, deps.query);
947
+ // 空摘要不挂行(getter 在 Running 启动瞬间也可能短暂为空)
948
+ if (summary || round.active) compactAssistantLine(component, getSummary, deps.query);
949
+ // 折叠时工具行被隐藏:abort/error/length 必须挂在摘要外层。
950
+ appendStopStatus(component, stopStatus);
668
951
  } else {
669
952
  component.contentContainer?.clear?.();
670
953
  }
@@ -673,24 +956,21 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
673
956
 
674
957
  const activateRound = (round: CompactRound): void => {
675
958
  round.active = true;
959
+ if (!round.startedAt) round.startedAt = Date.now();
960
+ delete round.endedAt;
676
961
  activeRound = round;
677
962
  deps.query?.setCompactSummaryActive?.(true);
963
+ ensureRoundTick();
678
964
  };
679
965
 
680
- const finishRound = (round: CompactRound): void => {
681
- round.active = false;
682
- renderRound(round);
683
- if (activeRound === round) {
684
- activeRound = undefined;
685
- deps.query?.setCompactSummaryActive?.(false);
686
- }
687
- };
966
+ const finishRound = (round: CompactRound): void => endRound(round, true);
688
967
 
689
968
  const resetRounds = (): void => {
690
969
  activeRound = undefined;
691
970
  roundByComponent = new WeakMap();
692
971
  expandedRoundToolIds.clear();
693
972
  deps.query?.setCompactSummaryActive?.(false);
973
+ stopRoundTick();
694
974
  };
695
975
 
696
976
  patch.assistantInstalled = function (this: any, message: any) {
@@ -725,6 +1005,7 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
725
1005
  detachedMessages: [],
726
1006
  active: true,
727
1007
  suppressedToolIds: new Set(),
1008
+ startedAt: Date.now(),
728
1009
  };
729
1010
  roundByComponent.set(this, round);
730
1011
  activateRound(round);
@@ -735,6 +1016,7 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
735
1016
  detachedMessages: [],
736
1017
  active: true,
737
1018
  suppressedToolIds: new Set(),
1019
+ startedAt: Date.now(),
738
1020
  };
739
1021
  roundByComponent.set(this, round);
740
1022
  if (!activeRound) activateRound(round);
@@ -757,12 +1039,8 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
757
1039
  return renderAssistantWithoutThinking(this, message);
758
1040
  }
759
1041
  if (round) {
760
- round.active = false;
1042
+ endRound(round);
761
1043
  roundByComponent.delete(this);
762
- if (activeRound === round) {
763
- activeRound = undefined;
764
- deps.query?.setCompactSummaryActive?.(false);
765
- }
766
1044
  return passThroughAssistant(this, message);
767
1045
  }
768
1046
  if (activeRound) finishRound(activeRound);
@@ -779,6 +1057,7 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
779
1057
  detachedMessages: [],
780
1058
  active: true,
781
1059
  suppressedToolIds: new Set(),
1060
+ startedAt: Date.now(),
782
1061
  };
783
1062
  roundByComponent.set(this, round);
784
1063
  if (!activeRound) activateRound(round);
@@ -788,6 +1067,15 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
788
1067
  return undefined;
789
1068
  }
790
1069
 
1070
+ // 无可见内容的 abort/error/length:直接外层状态行,并结束进行中的回合。
1071
+ const loneStatus = messageStopStatus(message);
1072
+ if (loneStatus) {
1073
+ if (activeRound) finishRound(activeRound);
1074
+ self.contentContainer.clear();
1075
+ appendStopStatus(this, loneStatus);
1076
+ return undefined;
1077
+ }
1078
+
791
1079
  self.contentContainer.clear();
792
1080
  return undefined;
793
1081
  };
@@ -803,6 +1091,7 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
803
1091
  if (this.expanded !== true) return lines;
804
1092
  return compactEditWriteExpandedLines(this, width, deps.writeMetadata);
805
1093
  }
1094
+ // Agent/Task 等同普通工具:折叠不外置(live 面板走独立 widget)。
806
1095
  if (expandedRoundToolIds.has(String(this.toolCallId ?? ""))) return [];
807
1096
  // 普通工具折叠时不显示独立行(摘要行已统计),独立展开走原 renderer。
808
1097
  if (this.expanded === true) {
@@ -826,12 +1115,18 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
826
1115
  };
827
1116
 
828
1117
  patch.assertAssistantOwnership = () => {
829
- // 仅从已标记的 compact-thinking 包装器重新认领。未知外部包装器必须保留所有权。
1118
+ // compact 必须在外层:从 compact-thinking 包装器认领,或收回 mode=on/off
1119
+ // 时主动释放给 original/native 的所有权。未知外部包装器不抢,避免递归。
830
1120
  if (!patch.active || assistantPrototype.updateContent === patch.assistantInstalled) return;
831
1121
  const current = assistantPrototype.updateContent;
832
- if ((current as any)[COMPACT_THINKING_PATCH_KEY] !== true) return;
833
- patch.assistantOriginal = current;
834
- assistantPrototype.updateContent = patch.assistantInstalled;
1122
+ if ((current as any)[COMPACT_THINKING_PATCH_KEY] === true) {
1123
+ patch.assistantOriginal = current;
1124
+ assistantPrototype.updateContent = patch.assistantInstalled;
1125
+ return;
1126
+ }
1127
+ if (current === patch.assistantOriginal || current === patch.assistantNative) {
1128
+ assistantPrototype.updateContent = patch.assistantInstalled;
1129
+ }
835
1130
  };
836
1131
 
837
1132
  (patch.assistantInstalled as any)[PROTOTYPE_ORIGINAL_KEY] = patch.assistantNative;
@@ -872,31 +1167,23 @@ export function installCompactMode(deps: CompactModeInstallDeps): CompactModeHoo
872
1167
  for (const component of trackedToolComponents) component.expanded = globalExpanded;
873
1168
  };
874
1169
 
875
- const releaseAssistantOwnership = (): void => {
876
- if (assistantPrototype.updateContent === patch.assistantInstalled) {
877
- assistantPrototype.updateContent = patch.assistantOriginal;
878
- }
879
- };
880
-
881
1170
  return {
882
1171
  sync(ctx: any) {
883
1172
  if (!patch.active) return;
1173
+ uiRef = ctx?.ui;
884
1174
  resetRounds();
885
- if (config.mode === "compact") {
886
- patch.assertAssistantOwnership();
887
- syncGlobalExpanded(ctx);
888
- } else {
889
- releaseAssistantOwnership();
890
- }
1175
+ // 始终保持补丁在链上:mode=on/off 走 passThrough,仍写入 lastMessage
1176
+ // 与 tracked 集合,这样 /ccstyle 切回 compact 时不必 /reload。
1177
+ patch.assertAssistantOwnership();
1178
+ if (config.mode === "compact") syncGlobalExpanded(ctx);
1179
+ else hoveredAssistantComponent = undefined;
891
1180
  refreshTrackedComponents();
892
1181
  },
893
1182
  refresh() {
894
1183
  if (!patch.active) return;
895
1184
  resetRounds();
896
- if (config.mode !== "compact") {
897
- releaseAssistantOwnership();
898
- hoveredAssistantComponent = undefined;
899
- }
1185
+ patch.assertAssistantOwnership();
1186
+ if (config.mode !== "compact") hoveredAssistantComponent = undefined;
900
1187
  refreshTrackedComponents();
901
1188
  },
902
1189
  assertOwnership() {