@pi-kaush/pi-tool-call-markers 0.3.24 → 0.3.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,6 +83,8 @@ A recognized `subagent` call renders as an unboxed plan in the shared tool aesth
83
83
 
84
84
  Single calls stay on one `▏ [<emoji>] [<profile>][<agent>] <task preview>` row — no tool label. Chain calls get a heading with the kind, count, and scope followed by numbered steps (parallel tasks list without numbers), with each step ordered emoji, profile badge, name badge. Agent display names (emoji + name) are scraped from the native plan component — including the single-call heading — with an args fallback, and render in `accent`; everything else stays muted, and failed subagents go full red. Subagents never join ordinary tool groups.
85
85
 
86
+ Assigned agent emojis take priority. Without one, calls use 👾 for non-interactive runs or 🤖 for interactive launches and worker controls (`list`, `status`, `send`, `wait`, `stop`, and `resume`). Tasks using the `coder` profile default to 🧑‍💻 in either mode. An explicit model override disables that profile default, just as it hides the profile badge. These defaults also cover generic fallback rows such as `subagent 🤖 ... [user]`.
87
+
86
88
  While a subagent runs, the plan headline's tail shows live progress from the streamed result details — `→ 1 turn · provider/model` in the warning tone — and a settled call keeps the same `→ N turns · provider/model` summary in muted (turns aggregate across tasks; the model shows only when every task used the same one).
87
89
 
88
90
  Malformed, ambiguous, future, or too-narrow shapes fall back to the generic `▏ subagent …` collapsed row rather than dropping information, and `Ctrl+O` still exposes the native subagent renderer.
@@ -94,10 +96,10 @@ A call that asks the user something is a user-input moment, not an execution row
94
96
  ```text
95
97
  ▎
96
98
  ▎ > Which call-site shape should `notifications:` use?
97
- ▎ User: Nested within subagent (Recommended)
99
+ ▎ User: Nested within subagent (Recommended)
98
100
  ▎
99
101
  ▎ > Which tier should the flag read at runtime?
100
- ▎ User: Client only, Client and server
102
+ ▎ User: Client only, Client and server
101
103
  ▎
102
104
  ```
103
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-kaush/pi-tool-call-markers",
3
- "version": "0.3.24",
3
+ "version": "0.3.25",
4
4
  "description": "Compact and group Pi tool calls, with a bundled extension for adjacent thinking blocks.",
5
5
  "license": "MIT",
6
6
  "author": "Kaushik Gopal",
package/src/bash-block.ts CHANGED
@@ -59,20 +59,25 @@ function renderBashBlockLines(
59
59
  theme: ThemeLike,
60
60
  status: string | undefined,
61
61
  inset = promptBlockInset(width),
62
- ): string[] {
63
- const [spacer, ...rest] = lines;
64
- const topRule = isRuleLine(rest[0]) ? rest[0] : undefined;
65
- const inner = topRule !== undefined ? rest.slice(1) : rest.slice();
66
- if (isRuleLine(inner[inner.length - 1])) inner.pop();
67
- const railColor = bashBlockRailColor(status, topRule, theme);
68
- const block = renderRailedBlockLines(
69
- ["", ...inner, ""],
70
- width,
71
- theme,
72
- inset,
73
- railColor,
74
- );
75
- return [fitLine(spacer ?? "", width), ...block];
62
+ ): string[] | undefined {
63
+ try {
64
+ const [spacer, ...rest] = lines;
65
+ const topRule = isRuleLine(rest[0]) ? rest[0] : undefined;
66
+ const inner = topRule !== undefined ? rest.slice(1) : rest.slice();
67
+ if (isRuleLine(inner[inner.length - 1])) inner.pop();
68
+ const railColor = bashBlockRailColor(status, topRule, theme);
69
+ const block = renderRailedBlockLines(
70
+ ["", ...inner, ""],
71
+ width,
72
+ theme,
73
+ inset,
74
+ railColor,
75
+ );
76
+ return [fitLine(spacer ?? "", width), ...block];
77
+ } catch {
78
+ // Decoration is optional; the caller retries Pi's native full-width render.
79
+ return undefined;
80
+ }
76
81
  }
77
82
 
78
83
  type BashRow = { status?: unknown };
@@ -154,6 +159,7 @@ function installBashBlockPatch(): BashBlockPatchState | undefined {
154
159
  typeof status === "string" ? status : undefined,
155
160
  inset,
156
161
  );
162
+ if (!decorated) return state.originalRender.call(this, width);
157
163
  state.cache.set(this, { width, src: lines, lines: decorated, palette });
158
164
  return decorated;
159
165
  };
package/src/index.ts CHANGED
@@ -38,7 +38,6 @@ const SUBAGENT_LABEL_GAP = " ";
38
38
  // to `*`. A single space separates the glyph from the call content: the
39
39
  // anchor is punctuation enough without a joining colon.
40
40
  const TOOL_CALL_GLYPHS: ReadonlyMap<string, string> = new Map([
41
- ["read", "●"],
42
41
  ["write", "+"],
43
42
  ["edit", "±"],
44
43
  ["grep", "○"],
@@ -129,12 +128,16 @@ type GroupingPatchState = {
129
128
  disabled?: boolean;
130
129
  };
131
130
 
131
+ type GroupMemberSnapshot = {
132
+ readonly row: ToolExecutionRow;
133
+ readonly version: number;
134
+ };
135
+
132
136
  type GroupRenderCache = {
133
137
  lines: string[];
134
138
  // The first member absorbs the leading blank; each member owns its line.
135
139
  heights: Array<{ component: ToolExecutionRow; height: number }>;
136
- members: ToolExecutionRow[];
137
- memberVersions: number[];
140
+ memberSnapshots: readonly GroupMemberSnapshot[];
138
141
  themeSample: string;
139
142
  width: number;
140
143
  };
@@ -183,14 +186,6 @@ function rowSignatureOf(row: ToolExecutionRow): string {
183
186
  return `${row.isPartial}|${row.expanded}|${row.result ? 1 : 0}|${row.result?.isError ? 1 : 0}`;
184
187
  }
185
188
 
186
- // Render caches hold lines with resolved colors baked in, so they key on the
187
- // palette's values rather than the theme object: Pi swaps the colors behind a
188
- // stable Proxy, which made an identity key survive a theme switch. Probing is
189
- // a handful of map lookups per row per frame.
190
- function themeSampleFor(theme: ThemeLike): string {
191
- return paletteSample(theme);
192
- }
193
-
194
189
  type InsetLayout = {
195
190
  contentWidth: number;
196
191
  left: number;
@@ -508,36 +503,29 @@ function liveElapsedText(row: ToolExecutionRow): string | undefined {
508
503
  return formatDuration(Math.max(0, Date.now() - startedAt));
509
504
  }
510
505
 
511
- function isLiveRow(row: ToolExecutionRow): boolean {
512
- return (
513
- row.expanded === false &&
514
- (row.isPartial !== false || !row.result) &&
515
- !hasImageResult(row)
516
- );
506
+ function isPendingRow(row: ToolExecutionRow): boolean {
507
+ return row.isPartial !== false || !row.result;
517
508
  }
518
509
 
519
- function isCollapsibleSuccess(row: ToolExecutionRow): boolean {
520
- return (
521
- row.expanded === false &&
522
- row.isPartial === false &&
523
- !!row.result &&
524
- !rowHasFailed(row) &&
525
- !hasImageResult(row)
526
- );
510
+ function isLiveRow(row: ToolExecutionRow): boolean {
511
+ return row.expanded === false && isPendingRow(row) && !hasImageResult(row);
527
512
  }
528
513
 
529
514
  // Settled failures join groups like settled successes; the row's error
530
515
  // color carries the failure, so the group stays visually unbroken.
531
- function isCollapsibleFailure(row: ToolExecutionRow): boolean {
516
+ function isCollapsibleRow(row: ToolExecutionRow): boolean {
532
517
  return (
533
518
  row.expanded === false &&
534
519
  row.isPartial === false &&
535
520
  !!row.result &&
536
- rowHasFailed(row) &&
537
521
  !hasImageResult(row)
538
522
  );
539
523
  }
540
524
 
525
+ function isCollapsibleSuccess(row: ToolExecutionRow): boolean {
526
+ return isCollapsibleRow(row) && !rowHasFailed(row);
527
+ }
528
+
541
529
  function hasToolSiblingInAssistantBatch(
542
530
  children: unknown[],
543
531
  index: number,
@@ -578,12 +566,7 @@ function isGroupableToolRow(
578
566
  if (row.toolName === "subagent") return false;
579
567
  if (isQuestionToolCall(row)) return false;
580
568
  if (drawsNoRowLines(row, renderAt(index))) return false;
581
- if (
582
- !isLiveRow(row) &&
583
- !isCollapsibleSuccess(row) &&
584
- !isCollapsibleFailure(row)
585
- )
586
- return false;
569
+ if (!isLiveRow(row) && !isCollapsibleRow(row)) return false;
587
570
  return (
588
571
  state.collapseParallel ||
589
572
  !hasToolSiblingInAssistantBatch(children, index, renderAt)
@@ -1030,7 +1013,7 @@ function collapsedSeam(
1030
1013
  // labels still carry it; a subagent fallback keeps `subagent` as its own
1031
1014
  // heading, which the scrape dropped.
1032
1015
  const text = isSubagent
1033
- ? `subagent${plain ? ` ${plain}` : ""}`
1016
+ ? subagentFallbackLabel(row.args, plain)
1034
1017
  : selfRendered
1035
1018
  ? dropCallToken(plain, row.toolName ?? "tool")
1036
1019
  : plain;
@@ -1061,7 +1044,7 @@ function collapsedOutcome(
1061
1044
  theme,
1062
1045
  );
1063
1046
  }
1064
- if (isLiveRow(row)) {
1047
+ if (isPendingRow(row)) {
1065
1048
  const elapsed = liveElapsedText(row);
1066
1049
  return theme.fg("warning", elapsed ? `… · ${elapsed}` : "…");
1067
1050
  }
@@ -1103,6 +1086,35 @@ function isRecord(value: unknown): value is Record<string, unknown> {
1103
1086
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
1104
1087
  }
1105
1088
 
1089
+ function defaultSubagentEmoji(args: unknown): string {
1090
+ if (!isRecord(args)) return "👾";
1091
+ if (
1092
+ typeof args.profile === "string" &&
1093
+ args.profile.trim() === "coder" &&
1094
+ args.model === undefined
1095
+ )
1096
+ return "🧑‍💻";
1097
+ return typeof args.action === "string" &&
1098
+ [
1099
+ "interactive",
1100
+ "list",
1101
+ "status",
1102
+ "send",
1103
+ "wait",
1104
+ "stop",
1105
+ "resume",
1106
+ ].includes(args.action)
1107
+ ? "🤖"
1108
+ : "👾";
1109
+ }
1110
+
1111
+ function subagentFallbackLabel(args: unknown, summary: string): string {
1112
+ const { displayName, bareName } = parseStepContent(summary);
1113
+ const prefix =
1114
+ displayName === bareName ? `${defaultSubagentEmoji(args)} ` : "";
1115
+ return `subagent ${prefix}${summary}`.trimEnd();
1116
+ }
1117
+
1106
1118
  type SubagentStep = {
1107
1119
  agent: string;
1108
1120
  profile: string | undefined;
@@ -1112,7 +1124,7 @@ type SubagentStep = {
1112
1124
  type SubagentPlan = {
1113
1125
  kind: "single" | "parallel" | "chain";
1114
1126
  scope: string;
1115
- steps: SubagentStep[];
1127
+ steps: readonly [SubagentStep, ...SubagentStep[]];
1116
1128
  };
1117
1129
 
1118
1130
  function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
@@ -1148,30 +1160,40 @@ function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1148
1160
  };
1149
1161
  };
1150
1162
 
1151
- if (hasParallel) {
1152
- const steps = (args.tasks as unknown[]).map(parseStep);
1153
- if (steps.some((step) => step === undefined)) return undefined;
1154
- return { kind: "parallel", scope, steps: steps as SubagentStep[] };
1155
- }
1156
- if (hasChain) {
1157
- const steps = (args.chain as unknown[]).map(parseStep);
1158
- if (steps.some((step) => step === undefined)) return undefined;
1159
- return { kind: "chain", scope, steps: steps as SubagentStep[] };
1163
+ const multiStepMode = hasParallel
1164
+ ? { kind: "parallel" as const, input: args.tasks as unknown[] }
1165
+ : hasChain
1166
+ ? { kind: "chain" as const, input: args.chain as unknown[] }
1167
+ : undefined;
1168
+
1169
+ if (multiStepMode) {
1170
+ const parsedSteps = multiStepMode.input.map(parseStep);
1171
+ const steps: SubagentStep[] = [];
1172
+ for (const step of parsedSteps) {
1173
+ if (step === undefined) return undefined;
1174
+ steps.push(step);
1175
+ }
1176
+ const firstStep = steps[0];
1177
+ if (firstStep === undefined) return undefined;
1178
+ const nonEmptySteps: readonly [SubagentStep, ...SubagentStep[]] = [
1179
+ firstStep,
1180
+ ...steps.slice(1),
1181
+ ];
1182
+ return { kind: multiStepMode.kind, scope, steps: nonEmptySteps };
1160
1183
  }
1184
+
1161
1185
  const single = parseStep(args);
1162
1186
  if (!single) return undefined;
1163
1187
  return { kind: "single", scope, steps: [single] };
1164
1188
  }
1165
1189
 
1166
- // Splits a scraped plan line's content into the agent display name (which may
1167
- // carry a leading emoji) and the remaining badge/preview text.
1190
+ // Splits scraped plan content into the emoji-capable display name and its bare lookup name.
1168
1191
  function parseStepContent(content: string): {
1169
1192
  displayName: string;
1170
1193
  bareName: string;
1171
- rest: string;
1172
1194
  } {
1173
1195
  const tokens = content.trim().split(/\s+/).filter(Boolean);
1174
- if (tokens.length === 0) return { displayName: "", bareName: "", rest: "" };
1196
+ if (tokens.length === 0) return { displayName: "", bareName: "" };
1175
1197
  const first = tokens[0]!;
1176
1198
  const hasEmoji = [...first].some((char) => (char.codePointAt(0) ?? 0) > 0x7f);
1177
1199
  const nameTokens = hasEmoji && tokens.length > 1 ? 2 : 1;
@@ -1179,7 +1201,6 @@ function parseStepContent(content: string): {
1179
1201
  return {
1180
1202
  displayName,
1181
1203
  bareName: tokens[nameTokens - 1] ?? displayName,
1182
- rest: tokens.slice(nameTokens).join(" "),
1183
1204
  };
1184
1205
  }
1185
1206
 
@@ -1273,7 +1294,7 @@ function subagentPlanOutcome(
1273
1294
  theme: ThemeLike,
1274
1295
  ): string | undefined {
1275
1296
  if (failed) return collapsedOutcome(row, budget, theme);
1276
- if (isLiveRow(row))
1297
+ if (isPendingRow(row))
1277
1298
  return theme.fg("warning", progress ? `→ ${progress}` : "…");
1278
1299
  if (row.result)
1279
1300
  return fgCollapsed(
@@ -1308,7 +1329,11 @@ function renderSubagentPlan(
1308
1329
  displayNames.get(step.agent) ?? sanitizeInline(step.agent);
1309
1330
  const { emoji, name } = splitEmojiName(displayName, step.agent);
1310
1331
  const accentPart = (text: string) => fgCollapsed(theme, nameColor, text);
1311
- const emojiPart = emoji ? `${accentPart(emoji)} ` : "";
1332
+ const fallbackEmoji = defaultSubagentEmoji({
1333
+ action: isRecord(row.args) ? row.args.action : undefined,
1334
+ profile: step.profile,
1335
+ });
1336
+ const emojiPart = `${accentPart(emoji || fallbackEmoji)} `;
1312
1337
  const profilePart = step.profile
1313
1338
  ? accentPart(`[${sanitizeInline(step.profile)}]`)
1314
1339
  : "";
@@ -1329,7 +1354,7 @@ function renderSubagentPlan(
1329
1354
  : fitSummary(label, budget, suffix));
1330
1355
 
1331
1356
  if (plan.kind === "single") {
1332
- const step = plan.steps[0]!;
1357
+ const step = plan.steps[0];
1333
1358
  return [headline(identityOf(step) + previewOf(step))];
1334
1359
  }
1335
1360
 
@@ -1431,25 +1456,17 @@ function renderGroupedCallLines(
1431
1456
  return segments;
1432
1457
  }
1433
1458
 
1434
- function sameMembers(
1435
- left: ToolExecutionRow[],
1436
- right: ToolExecutionRow[],
1437
- ): boolean {
1438
- return (
1439
- left.length === right.length &&
1440
- left.every((member, index) => member === right[index])
1441
- );
1442
- }
1443
-
1444
- function sameMemberVersions(
1459
+ function sameMemberSnapshots(
1460
+ snapshots: readonly GroupMemberSnapshot[],
1445
1461
  rows: ToolExecutionRow[],
1446
- versions: number[],
1447
1462
  state: PresentationPatchState,
1448
1463
  ): boolean {
1449
1464
  return (
1450
- rows.length === versions.length &&
1451
- rows.every(
1452
- (row, index) => (state.rowVersions.get(row) ?? 0) === versions[index],
1465
+ snapshots.length === rows.length &&
1466
+ snapshots.every(
1467
+ (snapshot, index) =>
1468
+ snapshot.row === rows[index] &&
1469
+ snapshot.version === (state.rowVersions.get(snapshot.row) ?? 0),
1453
1470
  )
1454
1471
  );
1455
1472
  }
@@ -1472,7 +1489,7 @@ function renderGroupedToolRows(
1472
1489
  const lines = state.originalRender.call(row, width);
1473
1490
  return { lines, heights: [{ component: row, height: lines.length }] };
1474
1491
  }
1475
- const themeSample = themeSampleFor(theme);
1492
+ const themeSample = paletteSample(theme);
1476
1493
  const cached = state.groupCache.get(row);
1477
1494
  const hasLiveMembers = rows.some(isLiveRow);
1478
1495
  if (
@@ -1480,8 +1497,7 @@ function renderGroupedToolRows(
1480
1497
  cached &&
1481
1498
  cached.width === width &&
1482
1499
  cached.themeSample === themeSample &&
1483
- sameMembers(cached.members, rows) &&
1484
- sameMemberVersions(rows, cached.memberVersions, state)
1500
+ sameMemberSnapshots(cached.memberSnapshots, rows, state)
1485
1501
  ) {
1486
1502
  return { lines: cached.lines, heights: cached.heights };
1487
1503
  }
@@ -1511,8 +1527,10 @@ function renderGroupedToolRows(
1511
1527
  state.groupCache.set(row, {
1512
1528
  lines,
1513
1529
  heights,
1514
- members: [...rows],
1515
- memberVersions: rows.map((member) => state.rowVersions.get(member) ?? 0),
1530
+ memberSnapshots: rows.map((member) => ({
1531
+ row: member,
1532
+ version: state.rowVersions.get(member) ?? 0,
1533
+ })),
1516
1534
  themeSample,
1517
1535
  width,
1518
1536
  });
@@ -1831,7 +1849,7 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1831
1849
  if (!this.isPartial) {
1832
1850
  const signature = rowSignatureOf(this);
1833
1851
  const version = state.rowVersions.get(this) ?? 0;
1834
- const themeSample = themeSampleFor(theme);
1852
+ const themeSample = paletteSample(theme);
1835
1853
  const cached = state.collapsedCache.get(this);
1836
1854
  if (
1837
1855
  cached &&
@@ -51,7 +51,8 @@ const DECLINE_TEXT = "User declined to answer questions";
51
51
  const AWAITING_TEXT = "awaiting your answer…";
52
52
  const NO_ANSWER_TEXT = "(no answer)";
53
53
  const QUESTION_PREFIX = "> ";
54
- const ANSWER_PREFIX = "User: ";
54
+ // Start the answer label under the question text, not its quote marker.
55
+ const ANSWER_PREFIX = `${" ".repeat(visibleWidth(QUESTION_PREFIX))}User: `;
55
56
 
56
57
  // Question tools keep the ask-tool vocabulary in their name even when they
57
58
  // invent their own result shape. The result-shape check is the primary signal;
@@ -244,7 +245,11 @@ function italics(theme: QuestionTheme, text: string): string {
244
245
  // width math exact and lets the shell's own fit pass stay a no-op.
245
246
  function wrapPlain(text: string, width: number): string[] {
246
247
  const max = Math.max(1, width);
247
- const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
248
+ const words = sanitizeInline(text)
249
+ .replace(/\s+/g, " ")
250
+ .trim()
251
+ .split(" ")
252
+ .filter(Boolean);
248
253
  if (words.length === 0) return [""];
249
254
 
250
255
  const lines: string[] = [];
@@ -325,6 +330,7 @@ export function renderQuestionBlock(
325
330
  ): string[] | undefined {
326
331
  const details = row.result?.details;
327
332
  if (!isQuestionToolCall(row)) return undefined;
333
+ if (row.result?.isError) return undefined;
328
334
  if (isRecord(details) && typeof details.error === "string") return undefined;
329
335
 
330
336
  const lines = questionLines(row, details);
@@ -7,7 +7,8 @@ import {
7
7
  withFaintCollapsedRail,
8
8
  } from "./muted.ts";
9
9
 
10
- const THINKING_GROUPING_PATCHED = Symbol.for("kg.pi.thinkingGrouping.v2");
10
+ // v2 wrappers close over module-local providers and cannot adopt shared contexts.
11
+ const THINKING_GROUPING_PATCHED = Symbol.for("kg.pi.thinkingGrouping.v3");
11
12
  const PI_SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
12
13
  const SPINNER_INTERVAL_MS = 80;
13
14
 
@@ -49,10 +50,18 @@ type ThemeDetail = {
49
50
  getColorMode?(): "truecolor" | "256color" | string;
50
51
  };
51
52
 
52
- // Live reference into the UI context: reading .theme per check keeps label
53
- // styles current across mid-session theme switches, which fire no event.
54
- let themeProvider: (() => ThemeDetail | undefined) | undefined;
55
- let activeLevel: (() => string) | undefined;
53
+ type ThinkingStylingContext = {
54
+ theme(): ThemeDetail | undefined;
55
+ level(): string;
56
+ };
57
+
58
+ // Entrypoints load uncached. A buried wrapper and every new owner must read
59
+ // the same contexts; the last session to start supplies live theme/level getters.
60
+ let stylingContexts = new Map<object, ThinkingStylingContext>();
61
+
62
+ function currentStylingContext(): ThinkingStylingContext | undefined {
63
+ return [...stylingContexts.values()].at(-1);
64
+ }
56
65
  // Pi builds both thinking labels italic. The default treatment replaces that
57
66
  // with a plain row: italic-off always leads — the TUI diff renderer can skip
58
67
  // bytes shared with the previous italic frame, which would leave the terminal
@@ -65,7 +74,10 @@ type LabelStyle = { prefix: string; suffix: string };
65
74
  // The package styles labels only inside a session it can read the theme from.
66
75
  // `inherit` is the other native case: it keeps Pi's italic labels.
67
76
  function stylesThinkingLabels(): boolean {
68
- return themeProvider !== undefined && thoughtLabelColorChoice() !== "inherit";
77
+ return (
78
+ currentStylingContext() !== undefined &&
79
+ thoughtLabelColorChoice() !== "inherit"
80
+ );
69
81
  }
70
82
 
71
83
  function styledWith(
@@ -105,7 +117,8 @@ function labelStyle(
105
117
  const token =
106
118
  choice === "mdheading"
107
119
  ? "mdHeading"
108
- : (LEVEL_TOKEN[activeLevel?.() ?? "off"] ?? "thinkingOff");
120
+ : (LEVEL_TOKEN[currentStylingContext()?.level() ?? "off"] ??
121
+ "thinkingOff");
109
122
  return styledWith(token, theme);
110
123
  }
111
124
 
@@ -143,8 +156,8 @@ function styledAnchoredLabel(
143
156
 
144
157
  export function visibleThoughtLabel(label: string): string {
145
158
  if (!stylesThinkingLabels()) return label;
146
- const raw = label.replace(/\x1b\[[0-9;]*m/g, "");
147
- const theme = themeProvider?.();
159
+ const raw = plainText(label);
160
+ const theme = currentStylingContext()?.theme();
148
161
  const settled = isSettledThoughtLabel(raw);
149
162
  const style = theme ? labelStyle(settled, theme) : undefined;
150
163
  // A theme that cannot resolve a color still drops Pi's italics.
@@ -321,13 +334,20 @@ function restyleHiddenThinkingLabel(
321
334
  });
322
335
  }
323
336
 
324
- type ThinkingTiming = {
325
- finishedAt?: number;
326
- startedAt: number;
327
- };
337
+ type ThinkingTiming =
338
+ | { readonly kind: "untimed" }
339
+ | { readonly kind: "live"; readonly startedAt: number }
340
+ | {
341
+ readonly kind: "settled";
342
+ readonly startedAt: number;
343
+ readonly finishedAt: number;
344
+ };
345
+
346
+ const UNTIMED_THINKING_TIMING: ThinkingTiming = { kind: "untimed" };
328
347
 
329
348
  type ThinkingGroupingPatchState = {
330
349
  owners: number;
350
+ stylingContexts: Map<object, ThinkingStylingContext>;
331
351
  // Set at the final owner's shutdown. A wrapper another extension has buried
332
352
  // cannot be uninstalled, so it delegates instead of outliving its owner; a
333
353
  // later install re-enables it.
@@ -438,22 +458,6 @@ function thinkingSpinner(startedAt: number, now: number): string {
438
458
  return PI_SPINNER_FRAMES[frame % PI_SPINNER_FRAMES.length]!;
439
459
  }
440
460
 
441
- // A row is live while it streams, and stays live through un-flagged rebuilds
442
- // (resize, theme switch, /reload) until an explicit final update arrives.
443
- // Rows that never carry the flag — restored history, older runtimes — count
444
- // as settled.
445
- function thinkingStillLive(
446
- streaming: boolean | undefined,
447
- timing: ThinkingTiming | undefined,
448
- ): boolean {
449
- if (streaming === true) return true;
450
- return (
451
- streaming === undefined &&
452
- timing !== undefined &&
453
- timing.finishedAt === undefined
454
- );
455
- }
456
-
457
461
  // Thinking ends when the answer starts: visible text or a tool call after
458
462
  // the last thinking block. Settling there keeps the duration honest and
459
463
  // keeps a live label as the transcript's last line, so its spinner never
@@ -473,15 +477,41 @@ function answerStarted(message: AssistantMessageLike): boolean {
473
477
  });
474
478
  }
475
479
 
476
- function timingLive(
480
+ type ThinkingTimingUpdate =
481
+ | { readonly kind: "begin"; readonly now: number }
482
+ | { readonly kind: "rebuild" }
483
+ | { readonly kind: "finish"; readonly now: number };
484
+
485
+ function classifyThinkingUpdate(
477
486
  streaming: boolean | undefined,
478
- timing: ThinkingTiming | undefined,
479
- ): boolean {
480
- return (
481
- streaming !== false &&
482
- timing !== undefined &&
483
- timing.finishedAt === undefined
484
- );
487
+ answering: boolean,
488
+ now: number,
489
+ ): ThinkingTimingUpdate {
490
+ if (answering || streaming === false) return { kind: "finish", now };
491
+ if (streaming === true) return { kind: "begin", now };
492
+ return { kind: "rebuild" };
493
+ }
494
+
495
+ function transitionThinkingTiming(
496
+ previous: ThinkingTiming,
497
+ update: ThinkingTimingUpdate,
498
+ ): ThinkingTiming {
499
+ switch (update.kind) {
500
+ case "begin":
501
+ return previous.kind === "live"
502
+ ? previous
503
+ : { kind: "live", startedAt: update.now };
504
+ case "rebuild":
505
+ return previous;
506
+ case "finish":
507
+ return previous.kind === "live"
508
+ ? {
509
+ kind: "settled",
510
+ startedAt: previous.startedAt,
511
+ finishedAt: update.now,
512
+ }
513
+ : previous;
514
+ }
485
515
  }
486
516
 
487
517
  function lifecycleLabel(
@@ -489,32 +519,25 @@ function lifecycleLabel(
489
519
  message: AssistantMessageLike,
490
520
  streaming: boolean | undefined,
491
521
  timings: WeakMap<AssistantMessageRow, ThinkingTiming>,
492
- ): string {
522
+ ): { label: string; timing: ThinkingTiming } {
493
523
  const now = Date.now();
494
- const previous = timings.get(row);
495
- const answering = answerStarted(message);
496
- if (!answering && thinkingStillLive(streaming, previous)) {
497
- const current =
498
- previous && previous.finishedAt === undefined
499
- ? previous
500
- : { startedAt: now };
501
- timings.set(row, current);
502
- return liveThinkingLabel(current.startedAt, now);
503
- }
504
-
505
- if (
506
- (streaming === false || answering) &&
507
- previous &&
508
- previous.finishedAt === undefined
509
- ) {
510
- previous.finishedAt = now;
511
- }
512
-
513
- const settled = timings.get(row);
514
- if (settled?.finishedAt !== undefined) {
515
- return `${SETTLED_THOUGHT} · ${formatThoughtDuration(settled.startedAt, settled.finishedAt)}`;
524
+ const update = classifyThinkingUpdate(streaming, answerStarted(message), now);
525
+ const timing = transitionThinkingTiming(
526
+ timings.get(row) ?? UNTIMED_THINKING_TIMING,
527
+ update,
528
+ );
529
+ timings.set(row, timing);
530
+
531
+ let label = SETTLED_THOUGHT;
532
+ if (timing.kind === "live") {
533
+ label = liveThinkingLabel(timing.startedAt, now);
534
+ } else if (timing.kind === "settled") {
535
+ label = `${SETTLED_THOUGHT} · ${formatThoughtDuration(
536
+ timing.startedAt,
537
+ timing.finishedAt,
538
+ )}`;
516
539
  }
517
- return SETTLED_THOUGHT;
540
+ return { label, timing };
518
541
  }
519
542
 
520
543
  function stripThinkingBlocks(
@@ -556,20 +579,21 @@ function applyHiddenThinkingLabel(
556
579
  message: AssistantMessageLike,
557
580
  streaming: boolean | undefined,
558
581
  timings: WeakMap<AssistantMessageRow, ThinkingTiming>,
559
- ): void {
582
+ ): ThinkingTiming {
560
583
  // Record the component's first streaming update even when the provider has
561
584
  // not emitted a non-empty thinking block yet.
562
- const label = lifecycleLabel(row, message, streaming, timings);
563
- if (!hasThinkingContent(message)) return;
585
+ const lifecycle = lifecycleLabel(row, message, streaming, timings);
586
+ if (!hasThinkingContent(message)) return lifecycle.timing;
564
587
  if (
565
588
  row.hideThinkingBlock !== true ||
566
589
  typeof row.hiddenThinkingLabel !== "string"
567
590
  ) {
568
- return;
591
+ return lifecycle.timing;
569
592
  }
570
593
  // Assign the row-local field directly. The public UI setter relabels every
571
594
  // historical assistant row and would make earlier durations change.
572
- row.hiddenThinkingLabel = label;
595
+ row.hiddenThinkingLabel = lifecycle.label;
596
+ return lifecycle.timing;
573
597
  }
574
598
 
575
599
  // TODO: Replace prototype patching with a public assistant-message rendering API.
@@ -591,12 +615,14 @@ function installThinkingGroupingPatch():
591
615
  if (existing) {
592
616
  existing.owners++;
593
617
  existing.rows ??= new Map();
618
+ stylingContexts = existing.stylingContexts;
594
619
  existing.disabled = false;
595
620
  return existing;
596
621
  }
597
622
 
598
623
  const state: ThinkingGroupingPatchState = {
599
624
  owners: 1,
625
+ stylingContexts,
600
626
  originalUpdateContent: proto.updateContent,
601
627
  timings: new WeakMap(),
602
628
  rows: new Map(),
@@ -624,29 +650,31 @@ function installThinkingGroupingPatch():
624
650
  } catch {
625
651
  // Preserve the original message intact.
626
652
  }
653
+ let timing = state.timings.get(this) ?? UNTIMED_THINKING_TIMING;
627
654
  try {
628
- applyHiddenThinkingLabel(this, combined, streaming, state.timings);
655
+ // Visibility changes the display copy, not the thinking lifecycle.
656
+ timing = applyHiddenThinkingLabel(
657
+ this,
658
+ message,
659
+ streaming,
660
+ state.timings,
661
+ );
629
662
  } catch {
630
663
  // Preserve Pi's native label if its private row shape changes.
664
+ timing = state.timings.get(this) ?? timing;
631
665
  }
632
666
  Reflect.apply(state.originalUpdateContent, this, [combined, ...args]);
633
667
  try {
634
668
  if (hasThinkingContent(combined)) {
635
- const timing = state.timings.get(this);
636
669
  const liveSince =
637
- timing && timingLive(streaming, timing)
638
- ? timing.startedAt
639
- : undefined;
670
+ timing.kind === "live" ? timing.startedAt : undefined;
640
671
  restyleHiddenThinkingLabel(this, combined, liveSince);
641
672
  }
642
673
  } catch {
643
674
  // Keep Pi's native label styling if the row shape changes.
644
675
  }
645
676
  try {
646
- if (
647
- hasThinkingContent(combined) &&
648
- !timingLive(streaming, state.timings.get(this))
649
- ) {
677
+ if (hasThinkingContent(combined) && timing.kind !== "live") {
650
678
  unitalicizeSettledThinking(this);
651
679
  }
652
680
  } catch {
@@ -694,9 +722,10 @@ function uninstallThinkingGroupingPatch(
694
722
 
695
723
  export default function (pi: ExtensionAPI) {
696
724
  const patch = installThinkingGroupingPatch();
725
+ const owner = {};
697
726
  let released = false;
698
727
  pi.on("session_start", (_event, ctx) => {
699
- if (ctx.mode !== "tui") return;
728
+ if (released || ctx.mode !== "tui") return;
700
729
  try {
701
730
  const proto = AssistantMessageComponent?.prototype as unknown as {
702
731
  [THINKING_GROUPING_PATCHED]?: ThinkingGroupingPatchState;
@@ -706,20 +735,22 @@ export default function (pi: ExtensionAPI) {
706
735
  // Best effort; stale rows would only linger until the process exits.
707
736
  }
708
737
  const uiCtx = ctx;
709
- themeProvider = () => uiCtx.ui?.theme as unknown as ThemeDetail;
710
- activeLevel = () => {
711
- try {
712
- return pi.getThinkingLevel();
713
- } catch {
714
- return "off";
715
- }
716
- };
738
+ stylingContexts.delete(owner);
739
+ stylingContexts.set(owner, {
740
+ theme: () => uiCtx.ui?.theme as unknown as ThemeDetail,
741
+ level: () => {
742
+ try {
743
+ return pi.getThinkingLevel();
744
+ } catch {
745
+ return "off";
746
+ }
747
+ },
748
+ });
717
749
  });
718
750
  pi.on("session_shutdown", () => {
719
751
  if (released) return;
720
752
  released = true;
721
- if (patch && !uninstallThinkingGroupingPatch(patch)) return;
722
- themeProvider = undefined;
723
- activeLevel = undefined;
753
+ stylingContexts.delete(owner);
754
+ uninstallThinkingGroupingPatch(patch);
724
755
  });
725
756
  }