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

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
 
@@ -105,8 +107,8 @@ The block reuses `pi-content-layout`'s submitted-prompt geometry — the same ra
105
107
 
106
108
  - **Shape-first recognition.** Any tool whose result carries an `answers` array of `{ question, answer | selected }` entries renders as a question block, so another author's question tool works without a change here. The tool name (`ask_user_question` and close variants) is the fallback for a call that failed before answering.
107
109
  - **Answers, not options.** Each question shows its answer: an option label, typed custom text, or multi-select labels joined with commas. A question left blank reads `User: (no answer)`, a decline reads `User declined to answer questions`, and a validation failure keeps Pi's native failure row.
108
- - **Quoted questions.** The question is the model's text read inside a user-input shell, so it renders italic under a `>` marker and the answer stays upright: the answer is the user's own words. A theme without italics renders the question plainly.
109
- - **Prompt-shell tones.** The rail uses `borderAccent` and the body paints on `userMessageBg`, with the question in `text`, the `User:` label in `muted`, the answer in `userMessageText`, and a live row's `awaiting your answer…` in `warning`.
110
+ - **Quoted questions.** The `>` marker and every line of the question use `muted` in italics. The `User:` label and reply use `userMessageText`. Only the actual reply is bold, not the label or the blank-answer placeholder.
111
+ - **Prompt-shell tones.** The rail uses `borderAccent` and the body uses `userMessageBg`. A live row's `awaiting your answer…` stays in `warning`.
110
112
  - **One blank row per question.** Questions are separated by a painted blank row so a multi-question ask stays scannable. A lone question keeps its outcome on the following line.
111
113
  - **No grouping.** Question blocks never join an adjacent tool group and carry no tool glyph. `Ctrl+O` still restores Pi's native expanded rendering.
112
114
 
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.26",
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", "○"],
@@ -51,6 +50,8 @@ const TOOL_CALL_GLYPHS: ReadonlyMap<string, string> = new Map([
51
50
  ["get_search_content", "↗"],
52
51
  ["codemode", "¢"],
53
52
  ]);
53
+ // Keep the historical slot so old, still-reachable delegates can be handed off.
54
+ const PRESENTATION_GENERATION = 4;
54
55
  const PRESENTATION_PATCHED = Symbol.for("kg.pi.toolPresentation.v3");
55
56
  const LEGACY_PRESENTATION_PATCHED = Symbol.for("kg.pi.toolPresentation.v2");
56
57
  const GROUPING_PATCHED = Symbol.for("kg.pi.toolGrouping.v1");
@@ -100,10 +101,11 @@ type ToolExecutionRow = {
100
101
  };
101
102
 
102
103
  type PresentationPatchState = {
104
+ generation?: number;
103
105
  owners: number;
104
106
  // Set at the final owner's shutdown. A wrapper that another extension has
105
107
  // buried cannot be uninstalled, so it delegates instead of outliving its
106
- // owner; a later install re-enables it.
108
+ // owner; a later compatible install re-enables it.
107
109
  disabled?: boolean;
108
110
  theme?: ThemeLike;
109
111
  cwd: string;
@@ -129,12 +131,16 @@ type GroupingPatchState = {
129
131
  disabled?: boolean;
130
132
  };
131
133
 
134
+ type GroupMemberSnapshot = {
135
+ readonly row: ToolExecutionRow;
136
+ readonly version: number;
137
+ };
138
+
132
139
  type GroupRenderCache = {
133
140
  lines: string[];
134
141
  // The first member absorbs the leading blank; each member owns its line.
135
142
  heights: Array<{ component: ToolExecutionRow; height: number }>;
136
- members: ToolExecutionRow[];
137
- memberVersions: number[];
143
+ memberSnapshots: readonly GroupMemberSnapshot[];
138
144
  themeSample: string;
139
145
  width: number;
140
146
  };
@@ -183,14 +189,6 @@ function rowSignatureOf(row: ToolExecutionRow): string {
183
189
  return `${row.isPartial}|${row.expanded}|${row.result ? 1 : 0}|${row.result?.isError ? 1 : 0}`;
184
190
  }
185
191
 
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
192
  type InsetLayout = {
195
193
  contentWidth: number;
196
194
  left: number;
@@ -508,36 +506,29 @@ function liveElapsedText(row: ToolExecutionRow): string | undefined {
508
506
  return formatDuration(Math.max(0, Date.now() - startedAt));
509
507
  }
510
508
 
511
- function isLiveRow(row: ToolExecutionRow): boolean {
512
- return (
513
- row.expanded === false &&
514
- (row.isPartial !== false || !row.result) &&
515
- !hasImageResult(row)
516
- );
509
+ function isPendingRow(row: ToolExecutionRow): boolean {
510
+ return row.isPartial !== false || !row.result;
517
511
  }
518
512
 
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
- );
513
+ function isLiveRow(row: ToolExecutionRow): boolean {
514
+ return row.expanded === false && isPendingRow(row) && !hasImageResult(row);
527
515
  }
528
516
 
529
517
  // Settled failures join groups like settled successes; the row's error
530
518
  // color carries the failure, so the group stays visually unbroken.
531
- function isCollapsibleFailure(row: ToolExecutionRow): boolean {
519
+ function isCollapsibleRow(row: ToolExecutionRow): boolean {
532
520
  return (
533
521
  row.expanded === false &&
534
522
  row.isPartial === false &&
535
523
  !!row.result &&
536
- rowHasFailed(row) &&
537
524
  !hasImageResult(row)
538
525
  );
539
526
  }
540
527
 
528
+ function isCollapsibleSuccess(row: ToolExecutionRow): boolean {
529
+ return isCollapsibleRow(row) && !rowHasFailed(row);
530
+ }
531
+
541
532
  function hasToolSiblingInAssistantBatch(
542
533
  children: unknown[],
543
534
  index: number,
@@ -578,12 +569,7 @@ function isGroupableToolRow(
578
569
  if (row.toolName === "subagent") return false;
579
570
  if (isQuestionToolCall(row)) return false;
580
571
  if (drawsNoRowLines(row, renderAt(index))) return false;
581
- if (
582
- !isLiveRow(row) &&
583
- !isCollapsibleSuccess(row) &&
584
- !isCollapsibleFailure(row)
585
- )
586
- return false;
572
+ if (!isLiveRow(row) && !isCollapsibleRow(row)) return false;
587
573
  return (
588
574
  state.collapseParallel ||
589
575
  !hasToolSiblingInAssistantBatch(children, index, renderAt)
@@ -1030,7 +1016,7 @@ function collapsedSeam(
1030
1016
  // labels still carry it; a subagent fallback keeps `subagent` as its own
1031
1017
  // heading, which the scrape dropped.
1032
1018
  const text = isSubagent
1033
- ? `subagent${plain ? ` ${plain}` : ""}`
1019
+ ? subagentFallbackLabel(row.args, plain)
1034
1020
  : selfRendered
1035
1021
  ? dropCallToken(plain, row.toolName ?? "tool")
1036
1022
  : plain;
@@ -1061,7 +1047,7 @@ function collapsedOutcome(
1061
1047
  theme,
1062
1048
  );
1063
1049
  }
1064
- if (isLiveRow(row)) {
1050
+ if (isPendingRow(row)) {
1065
1051
  const elapsed = liveElapsedText(row);
1066
1052
  return theme.fg("warning", elapsed ? `… · ${elapsed}` : "…");
1067
1053
  }
@@ -1103,6 +1089,69 @@ function isRecord(value: unknown): value is Record<string, unknown> {
1103
1089
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
1104
1090
  }
1105
1091
 
1092
+ function subagentDisplayProfile(
1093
+ args: Record<string, unknown>,
1094
+ action: unknown,
1095
+ ): string | undefined {
1096
+ const { profile, model } = args;
1097
+ if (typeof profile !== "string") return undefined;
1098
+ // Blank model strings do not override launch profiles. Keep the existing
1099
+ // rendering of controls, unknown actions, and malformed model values.
1100
+ const launch =
1101
+ action === undefined || action === "run" || action === "interactive";
1102
+ if (
1103
+ model !== undefined &&
1104
+ (!launch || typeof model !== "string" || model.trim() !== "")
1105
+ )
1106
+ return undefined;
1107
+ return profile.trim() || undefined;
1108
+ }
1109
+
1110
+ function defaultSubagentEmoji(
1111
+ action: unknown,
1112
+ profile: string | undefined,
1113
+ ): string {
1114
+ if (profile === "coder") return "🧑‍💻";
1115
+ return typeof action === "string" &&
1116
+ [
1117
+ "interactive",
1118
+ "list",
1119
+ "status",
1120
+ "send",
1121
+ "wait",
1122
+ "stop",
1123
+ "resume",
1124
+ ].includes(action)
1125
+ ? "🤖"
1126
+ : "👾";
1127
+ }
1128
+
1129
+ // Match a whole icon token, including joined emoji, flags, and keycaps.
1130
+ // ASCII digits, #, and * count only in keycap sequences.
1131
+ const SUBAGENT_EMOJI_TOKEN =
1132
+ /^(?:[#*0-9]\uFE0F?\u20E3|(?![#*0-9])\p{Emoji}[\uFE0E\uFE0F\u{E0020}-\u{E007F}]*\u200D?)+$/u;
1133
+
1134
+ function subagentFallbackLabel(args: unknown, summary: string): string {
1135
+ const input = isRecord(args) ? args : undefined;
1136
+ const match = /^(\S+)\s+(?=\S)/u.exec(summary);
1137
+ const icon = match?.[1] ?? "";
1138
+ const heading = match ? summary.slice(match[0].length) : "";
1139
+ const agent =
1140
+ typeof input?.agent === "string" ? sanitizeInline(input.agent).trim() : "";
1141
+ const startsWithAgent = (text: string) =>
1142
+ agent !== "" && (text === agent || text.startsWith(`${agent} `));
1143
+ // Subagents also accept configured Unicode symbols as icons. A token
1144
+ // directly before the known name can still be one of those assignments.
1145
+ const assigned = startsWithAgent(heading)
1146
+ ? /[^\x00-\x7f]/u.test(icon)
1147
+ : !startsWithAgent(summary) && SUBAGENT_EMOJI_TOKEN.test(icon);
1148
+ const action = input?.action;
1149
+ const prefix = assigned
1150
+ ? ""
1151
+ : `${defaultSubagentEmoji(action, input && subagentDisplayProfile(input, action))} `;
1152
+ return `subagent ${prefix}${summary}`.trimEnd();
1153
+ }
1154
+
1106
1155
  type SubagentStep = {
1107
1156
  agent: string;
1108
1157
  profile: string | undefined;
@@ -1112,11 +1161,12 @@ type SubagentStep = {
1112
1161
  type SubagentPlan = {
1113
1162
  kind: "single" | "parallel" | "chain";
1114
1163
  scope: string;
1115
- steps: SubagentStep[];
1164
+ steps: readonly [SubagentStep, ...SubagentStep[]];
1116
1165
  };
1117
1166
 
1118
- function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1119
- if (!isRecord(args)) return undefined;
1167
+ function parseSubagentArgs(
1168
+ args: Record<string, unknown>,
1169
+ ): SubagentPlan | undefined {
1120
1170
  const scope =
1121
1171
  args.agentScope === "project" || args.agentScope === "both"
1122
1172
  ? args.agentScope
@@ -1136,70 +1186,53 @@ function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1136
1186
  typeof item.agent === "string" && item.agent.trim()
1137
1187
  ? item.agent.trim()
1138
1188
  : "...",
1139
- // The subagent extension suppresses the profile badge when a model
1140
- // override is present; mirror that here.
1141
- profile:
1142
- typeof item.profile === "string" &&
1143
- item.profile.trim() &&
1144
- item.model === undefined
1145
- ? item.profile.trim()
1146
- : undefined,
1189
+ profile: subagentDisplayProfile(item, args.action),
1147
1190
  task: item.task,
1148
1191
  };
1149
1192
  };
1150
1193
 
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[] };
1194
+ const multiStepMode = hasParallel
1195
+ ? { kind: "parallel" as const, input: args.tasks as unknown[] }
1196
+ : hasChain
1197
+ ? { kind: "chain" as const, input: args.chain as unknown[] }
1198
+ : undefined;
1199
+
1200
+ if (multiStepMode) {
1201
+ const parsedSteps = multiStepMode.input.map(parseStep);
1202
+ const steps: SubagentStep[] = [];
1203
+ for (const step of parsedSteps) {
1204
+ if (step === undefined) return undefined;
1205
+ steps.push(step);
1206
+ }
1207
+ const firstStep = steps[0];
1208
+ if (firstStep === undefined) return undefined;
1209
+ const nonEmptySteps: readonly [SubagentStep, ...SubagentStep[]] = [
1210
+ firstStep,
1211
+ ...steps.slice(1),
1212
+ ];
1213
+ return { kind: multiStepMode.kind, scope, steps: nonEmptySteps };
1160
1214
  }
1215
+
1161
1216
  const single = parseStep(args);
1162
1217
  if (!single) return undefined;
1163
1218
  return { kind: "single", scope, steps: [single] };
1164
1219
  }
1165
1220
 
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.
1168
- function parseStepContent(content: string): {
1169
- displayName: string;
1170
- bareName: string;
1171
- rest: string;
1172
- } {
1173
- const tokens = content.trim().split(/\s+/).filter(Boolean);
1174
- if (tokens.length === 0) return { displayName: "", bareName: "", rest: "" };
1175
- const first = tokens[0]!;
1221
+ // Extract the existing emoji-capable prefix and its bare lookup name.
1222
+ function parseStepContent(
1223
+ content: string,
1224
+ ): { emoji: string; bareName: string } | undefined {
1225
+ const [first, bareName] = content.trim().split(/\s+/).filter(Boolean);
1226
+ if (!first || !bareName) return undefined;
1176
1227
  const hasEmoji = [...first].some((char) => (char.codePointAt(0) ?? 0) > 0x7f);
1177
- const nameTokens = hasEmoji && tokens.length > 1 ? 2 : 1;
1178
- const displayName = tokens.slice(0, nameTokens).join(" ");
1179
- return {
1180
- displayName,
1181
- bareName: tokens[nameTokens - 1] ?? displayName,
1182
- rest: tokens.slice(nameTokens).join(" "),
1183
- };
1228
+ return hasEmoji ? { emoji: first, bareName } : undefined;
1184
1229
  }
1185
1230
 
1186
- // Splits a scraped "emoji name" display into its emoji prefix and bare name;
1187
- // plain names pass through with no emoji.
1188
- function splitEmojiName(
1189
- displayName: string,
1190
- bareName: string,
1191
- ): { emoji: string; name: string } {
1192
- const tokens = displayName.trim().split(/\s+/).filter(Boolean);
1193
- if (tokens.length > 1 && tokens[tokens.length - 1] === bareName) {
1194
- return { emoji: tokens.slice(0, -1).join(" "), name: bareName };
1195
- }
1196
- return { emoji: "", name: bareName };
1197
- }
1198
-
1199
- // Agent display names (emoji + name) come from the subagent extension's own
1200
- // call component when available; args only carry the bare agent name.
1201
- function scrapeSubagentDisplayNames(
1231
+ // Assigned emojis come from the subagent extension's call component when
1232
+ // available; args only carry the bare agent name.
1233
+ function scrapeSubagentEmojis(
1202
1234
  row: ToolExecutionRow,
1235
+ kind: SubagentPlan["kind"],
1203
1236
  ): Map<string, string> {
1204
1237
  const names = new Map<string, string>();
1205
1238
  let component = row.callRendererComponent;
@@ -1209,20 +1242,21 @@ function scrapeSubagentDisplayNames(
1209
1242
  if (!component || typeof component.render !== "function") return names;
1210
1243
  try {
1211
1244
  for (const raw of component.render(120)) {
1212
- const line = sanitizeInline(stripAnsi(raw)).trim();
1245
+ const text = sanitizeInline(stripAnsi(raw));
1246
+ // Native single-call headings can wrap. The first indented line starts
1247
+ // the task preview; neither it nor its continuations carry identity.
1248
+ if (kind === "single" && text.startsWith(" ")) break;
1249
+ const line = text.trim();
1213
1250
  if (!line) continue;
1214
1251
  // Single calls carry the agent name on their "subagent <name>" heading
1215
1252
  // line; stripping the heading word (and step numbers) lets both shapes
1216
1253
  // flow through the same parse. Heading remainders without an emoji
1217
- // (e.g. "chain (2 steps)") degrade to displayName === bareName and are
1218
- // skipped by the guard below.
1254
+ // (e.g. "chain (2 steps)") are skipped.
1219
1255
  const content = line
1220
1256
  .replace(/^subagent\b\s*/, "")
1221
1257
  .replace(/^\d+\.\s*/, "");
1222
- const { displayName, bareName } = parseStepContent(content);
1223
- if (displayName && bareName && displayName !== bareName) {
1224
- names.set(bareName, displayName);
1225
- }
1258
+ const identity = parseStepContent(content);
1259
+ if (identity) names.set(identity.bareName, identity.emoji);
1226
1260
  }
1227
1261
  } catch {
1228
1262
  // Display-name scraping is cosmetic; args still carry the bare name.
@@ -1273,7 +1307,7 @@ function subagentPlanOutcome(
1273
1307
  theme: ThemeLike,
1274
1308
  ): string | undefined {
1275
1309
  if (failed) return collapsedOutcome(row, budget, theme);
1276
- if (isLiveRow(row))
1310
+ if (isPendingRow(row))
1277
1311
  return theme.fg("warning", progress ? `→ ${progress}` : "…");
1278
1312
  if (row.result)
1279
1313
  return fgCollapsed(
@@ -1292,6 +1326,8 @@ function renderSubagentPlan(
1292
1326
  width: number,
1293
1327
  theme: ThemeLike,
1294
1328
  ): string[] | undefined {
1329
+ if (!isRecord(row.args)) return undefined;
1330
+ const { action } = row.args;
1295
1331
  const plan = parseSubagentArgs(row.args);
1296
1332
  if (!plan || width < 12) return undefined;
1297
1333
 
@@ -1299,20 +1335,19 @@ function renderSubagentPlan(
1299
1335
  const color = failed ? "error" : "muted";
1300
1336
  const nameColor = failed ? "error" : "accent";
1301
1337
  const suffix = fgCollapsed(theme, color, "…");
1302
- const displayNames = scrapeSubagentDisplayNames(row);
1338
+ const displayEmojis = scrapeSubagentEmojis(row, plan.kind);
1303
1339
  // Agent/profile/task values are model-supplied; sanitize them like every
1304
1340
  // other collapsed-row text so control bytes cannot reach the terminal.
1305
1341
  // Identity order: emoji, then the profile and agent-name badges.
1306
1342
  const identityOf = (step: SubagentStep) => {
1307
- const displayName =
1308
- displayNames.get(step.agent) ?? sanitizeInline(step.agent);
1309
- const { emoji, name } = splitEmojiName(displayName, step.agent);
1343
+ const emoji = displayEmojis.get(step.agent);
1310
1344
  const accentPart = (text: string) => fgCollapsed(theme, nameColor, text);
1311
- const emojiPart = emoji ? `${accentPart(emoji)} ` : "";
1345
+ const fallbackEmoji = defaultSubagentEmoji(action, step.profile);
1346
+ const emojiPart = `${accentPart(emoji || fallbackEmoji)} `;
1312
1347
  const profilePart = step.profile
1313
1348
  ? accentPart(`[${sanitizeInline(step.profile)}]`)
1314
1349
  : "";
1315
- return `${emojiPart}${profilePart}${accentPart(`[${sanitizeInline(name)}]`)}`;
1350
+ return `${emojiPart}${profilePart}${accentPart(`[${sanitizeInline(step.agent)}]`)}`;
1316
1351
  };
1317
1352
  const detailColor = failed ? "error" : "toolOutput";
1318
1353
  const previewOf = (step: SubagentStep) =>
@@ -1329,7 +1364,7 @@ function renderSubagentPlan(
1329
1364
  : fitSummary(label, budget, suffix));
1330
1365
 
1331
1366
  if (plan.kind === "single") {
1332
- const step = plan.steps[0]!;
1367
+ const step = plan.steps[0];
1333
1368
  return [headline(identityOf(step) + previewOf(step))];
1334
1369
  }
1335
1370
 
@@ -1431,25 +1466,17 @@ function renderGroupedCallLines(
1431
1466
  return segments;
1432
1467
  }
1433
1468
 
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(
1469
+ function sameMemberSnapshots(
1470
+ snapshots: readonly GroupMemberSnapshot[],
1445
1471
  rows: ToolExecutionRow[],
1446
- versions: number[],
1447
1472
  state: PresentationPatchState,
1448
1473
  ): boolean {
1449
1474
  return (
1450
- rows.length === versions.length &&
1451
- rows.every(
1452
- (row, index) => (state.rowVersions.get(row) ?? 0) === versions[index],
1475
+ snapshots.length === rows.length &&
1476
+ snapshots.every(
1477
+ (snapshot, index) =>
1478
+ snapshot.row === rows[index] &&
1479
+ snapshot.version === (state.rowVersions.get(snapshot.row) ?? 0),
1453
1480
  )
1454
1481
  );
1455
1482
  }
@@ -1472,7 +1499,7 @@ function renderGroupedToolRows(
1472
1499
  const lines = state.originalRender.call(row, width);
1473
1500
  return { lines, heights: [{ component: row, height: lines.length }] };
1474
1501
  }
1475
- const themeSample = themeSampleFor(theme);
1502
+ const themeSample = paletteSample(theme);
1476
1503
  const cached = state.groupCache.get(row);
1477
1504
  const hasLiveMembers = rows.some(isLiveRow);
1478
1505
  if (
@@ -1480,8 +1507,7 @@ function renderGroupedToolRows(
1480
1507
  cached &&
1481
1508
  cached.width === width &&
1482
1509
  cached.themeSample === themeSample &&
1483
- sameMembers(cached.members, rows) &&
1484
- sameMemberVersions(rows, cached.memberVersions, state)
1510
+ sameMemberSnapshots(cached.memberSnapshots, rows, state)
1485
1511
  ) {
1486
1512
  return { lines: cached.lines, heights: cached.heights };
1487
1513
  }
@@ -1511,8 +1537,10 @@ function renderGroupedToolRows(
1511
1537
  state.groupCache.set(row, {
1512
1538
  lines,
1513
1539
  heights,
1514
- members: [...rows],
1515
- memberVersions: rows.map((member) => state.rowVersions.get(member) ?? 0),
1540
+ memberSnapshots: rows.map((member) => ({
1541
+ row: member,
1542
+ version: state.rowVersions.get(member) ?? 0,
1543
+ })),
1516
1544
  themeSample,
1517
1545
  width,
1518
1546
  });
@@ -1714,12 +1742,16 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1714
1742
  if (!proto) return undefined;
1715
1743
 
1716
1744
  const existing = proto[PRESENTATION_PATCHED];
1717
- if (existing) {
1745
+ const retired =
1746
+ existing?.disabled && existing.generation !== PRESENTATION_GENERATION
1747
+ ? existing
1748
+ : undefined;
1749
+ if (existing && !retired) {
1718
1750
  existing.owners++;
1719
1751
  existing.disabled = false;
1720
1752
  return existing;
1721
1753
  }
1722
- const legacy = proto[LEGACY_PRESENTATION_PATCHED];
1754
+ const legacy = !existing && proto[LEGACY_PRESENTATION_PATCHED];
1723
1755
  if (legacy) {
1724
1756
  proto.render = legacy.originalRender;
1725
1757
  proto.updateDisplay = legacy.originalUpdateDisplay;
@@ -1730,17 +1762,25 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1730
1762
  )
1731
1763
  return undefined;
1732
1764
 
1765
+ const { render, updateDisplay } = proto;
1766
+ const buriedRender = retired && render !== retired.patchedRender;
1767
+ const buriedUpdate =
1768
+ retired && updateDisplay !== retired.patchedUpdateDisplay;
1769
+ const retiredMouse = retired?.originalHandleMouse;
1770
+
1733
1771
  const state: PresentationPatchState = {
1772
+ generation: PRESENTATION_GENERATION,
1734
1773
  owners: 1,
1735
1774
  cwd: process.cwd(),
1736
1775
  promptPaths: new Set(),
1737
- collapseParallel: envEnabled(COLLAPSE_PARALLEL_ENV, true),
1738
- expandedTools: envToolNames(EXPANDED_TOOLS_ENV),
1776
+ collapseParallel:
1777
+ retired?.collapseParallel ?? envEnabled(COLLAPSE_PARALLEL_ENV, true),
1778
+ expandedTools: retired?.expandedTools ?? envToolNames(EXPANDED_TOOLS_ENV),
1739
1779
  groupCache: new WeakMap(),
1740
1780
  collapsedCache: new WeakMap(),
1741
1781
  rowVersions: new WeakMap(),
1742
- originalRender: proto.render,
1743
- originalUpdateDisplay: proto.updateDisplay,
1782
+ originalRender: retired?.originalRender ?? render,
1783
+ originalUpdateDisplay: retired?.originalUpdateDisplay ?? updateDisplay,
1744
1784
  };
1745
1785
  const patchedUpdateDisplay = function updateDisplayWithToolPresentation(
1746
1786
  this: ToolExecutionRow,
@@ -1774,8 +1814,9 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1774
1814
  let patchedHandleMouse:
1775
1815
  | ((this: ToolExecutionRow, event: unknown) => unknown)
1776
1816
  | undefined;
1777
- if (typeof proto.handleMouse === "function") {
1778
- state.originalHandleMouse = proto.handleMouse;
1817
+ const originalHandleMouse = retiredMouse ?? proto.handleMouse;
1818
+ if (typeof originalHandleMouse === "function") {
1819
+ state.originalHandleMouse = originalHandleMouse;
1779
1820
  patchedHandleMouse = function handleMouseWithCollapsedToggle(
1780
1821
  this: ToolExecutionRow,
1781
1822
  event: unknown,
@@ -1797,7 +1838,7 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1797
1838
  }
1798
1839
  return state.originalHandleMouse?.call(this, event);
1799
1840
  };
1800
- proto.handleMouse = patchedHandleMouse;
1841
+ if (!retiredMouse) proto.handleMouse = patchedHandleMouse;
1801
1842
  }
1802
1843
  const patchedRender = function renderWithToolPresentation(
1803
1844
  this: ToolExecutionRow,
@@ -1831,7 +1872,7 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1831
1872
  if (!this.isPartial) {
1832
1873
  const signature = rowSignatureOf(this);
1833
1874
  const version = state.rowVersions.get(this) ?? 0;
1834
- const themeSample = themeSampleFor(theme);
1875
+ const themeSample = paletteSample(theme);
1835
1876
  const cached = state.collapsedCache.get(this);
1836
1877
  if (
1837
1878
  cached &&
@@ -1877,15 +1918,24 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1877
1918
  try {
1878
1919
  state.patchedUpdateDisplay = patchedUpdateDisplay;
1879
1920
  state.patchedRender = patchedRender;
1880
- proto.updateDisplay = patchedUpdateDisplay;
1881
- proto.render = patchedRender;
1921
+ if (!buriedUpdate) proto.updateDisplay = patchedUpdateDisplay;
1922
+ if (!buriedRender) proto.render = patchedRender;
1882
1923
  Object.defineProperty(proto, PRESENTATION_PATCHED, {
1883
1924
  configurable: true,
1884
1925
  value: state,
1885
1926
  });
1927
+ if (retired) {
1928
+ // Keep foreign wrappers on the outside, including on cached renders.
1929
+ // The retired closures stay disabled and only forward to these delegates.
1930
+ if (buriedRender) retired.originalRender = patchedRender;
1931
+ if (buriedUpdate) retired.originalUpdateDisplay = patchedUpdateDisplay;
1932
+ if (retiredMouse && patchedHandleMouse) {
1933
+ retired.originalHandleMouse = patchedHandleMouse;
1934
+ }
1935
+ }
1886
1936
  } catch {
1887
- proto.updateDisplay = state.originalUpdateDisplay;
1888
- proto.render = state.originalRender;
1937
+ if (!buriedUpdate) proto.updateDisplay = updateDisplay;
1938
+ if (!buriedRender) proto.render = render;
1889
1939
  return undefined;
1890
1940
  }
1891
1941
  return state;
@@ -158,7 +158,7 @@ export function renderRailedBlockLines(
158
158
  const margin = " ".repeat(inset);
159
159
  const leftPad = " ".repeat(padding.left);
160
160
  const rightPad = " ".repeat(padding.right);
161
- const contentWidth = Math.max(1, bodyWidth - padding.left - padding.right);
161
+ const contentWidth = promptBlockContentWidth(width, inset, padding);
162
162
  const surfaceBg = promptSurfaceBg(theme);
163
163
  return lines.map((line) => {
164
164
  const { controls, content } = splitLeadingSemanticControls(line);
@@ -16,7 +16,7 @@ import { sanitizeInline } from "./sanitize.ts";
16
16
  // any particular question-tool implementation is needed.
17
17
 
18
18
  type QuestionTheme = PromptShellTheme & {
19
- fg(color: string, text: string): string;
19
+ bold?(text: string): string;
20
20
  italic?(text: string): string;
21
21
  };
22
22
 
@@ -40,7 +40,7 @@ type AnswerEntry = {
40
40
 
41
41
  type QuestionLine =
42
42
  | { kind: "question"; text: string }
43
- | { kind: "answer"; text: string }
43
+ | { kind: "answer"; text: string | undefined }
44
44
  | { kind: "status"; text: string; tone: "muted" | "warning" }
45
45
  // A painted blank body row; the shell gives it the prompt surface.
46
46
  | { kind: "spacer" };
@@ -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;
@@ -195,7 +196,7 @@ function questionLines(
195
196
  const groups: QuestionLine[][] = pairs.map((pair) => {
196
197
  const group: QuestionLine[] = [{ kind: "question", text: pair.question }];
197
198
  if (!pending && !declined) {
198
- group.push({ kind: "answer", text: pair.answer ?? NO_ANSWER_TEXT });
199
+ group.push({ kind: "answer", text: pair.answer });
199
200
  }
200
201
  return group;
201
202
  });
@@ -227,24 +228,31 @@ function fg(theme: QuestionTheme, token: string, text: string): string {
227
228
  }
228
229
  }
229
230
 
230
- // The question is the model's text read inside a user-input shell, so it takes
231
- // the quotation's italics; the answer is the user's own words and stays upright.
232
- // A theme without italics simply renders the question plainly.
233
- function italics(theme: QuestionTheme, text: string): string {
234
- if (text === "" || typeof theme.italic !== "function") return text;
231
+ function emphasize(
232
+ theme: QuestionTheme,
233
+ style: "bold" | "italic",
234
+ text: string,
235
+ ): string {
236
+ if (text === "" || typeof theme[style] !== "function") return text;
235
237
  try {
236
- return theme.italic(text);
238
+ return theme[style](text);
237
239
  } catch {
238
240
  return text;
239
241
  }
240
242
  }
241
243
 
244
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
245
+
242
246
  // Plain-text word wrap with a hanging indent, so a wrapped question stays
243
247
  // visually attached to its `> ` prefix. Wrapping before styling keeps the
244
248
  // width math exact and lets the shell's own fit pass stay a no-op.
245
249
  function wrapPlain(text: string, width: number): string[] {
246
250
  const max = Math.max(1, width);
247
- const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
251
+ const words = sanitizeInline(text)
252
+ .replace(/\s+/g, " ")
253
+ .trim()
254
+ .split(" ")
255
+ .filter(Boolean);
248
256
  if (words.length === 0) return [""];
249
257
 
250
258
  const lines: string[] = [];
@@ -256,15 +264,24 @@ function wrapPlain(text: string, width: number): string[] {
256
264
  return;
257
265
  }
258
266
  if (current !== "") lines.push(current);
259
- // A single token wider than the line is hard-split rather than truncated.
260
- let rest = word;
261
- while (visibleWidth(rest) > max) {
262
- let cut = rest.length;
263
- while (cut > 1 && visibleWidth(rest.slice(0, cut)) > max) cut--;
264
- lines.push(rest.slice(0, cut));
265
- rest = rest.slice(cut);
267
+ if (visibleWidth(word) <= max) {
268
+ current = word;
269
+ return;
270
+ }
271
+
272
+ current = "";
273
+ let columns = 0;
274
+ for (const { segment } of graphemes.segment(word)) {
275
+ const segmentWidth = visibleWidth(segment);
276
+ // Let the shell clip a grapheme wider than the whole line.
277
+ if (current !== "" && columns + segmentWidth > max) {
278
+ lines.push(current);
279
+ current = "";
280
+ columns = 0;
281
+ }
282
+ current += segment;
283
+ columns += segmentWidth;
266
284
  }
267
- current = rest;
268
285
  };
269
286
  for (const word of words) push(word);
270
287
  if (current !== "") lines.push(current);
@@ -283,22 +300,25 @@ function styleLine(
283
300
  : line.kind === "answer"
284
301
  ? ANSWER_PREFIX
285
302
  : "";
286
- const prefixToken = line.kind === "question" ? "borderAccent" : "muted";
287
- const textToken =
288
- line.kind === "question"
289
- ? "text"
290
- : line.kind === "answer"
291
- ? "userMessageText"
292
- : line.tone;
293
- const hang = " ".repeat(visibleWidth(prefix));
294
- const body = wrapPlain(line.text, Math.max(1, width - visibleWidth(prefix)));
295
- return body.map(
296
- (piece, index) =>
297
- fg(theme, prefixToken, index === 0 ? prefix : hang) +
298
- (line.kind === "question"
299
- ? italics(theme, fg(theme, textToken, piece))
300
- : fg(theme, textToken, piece)),
301
- );
303
+ const text =
304
+ line.kind === "answer" ? (line.text ?? NO_ANSWER_TEXT) : line.text;
305
+ const prefixWidth = visibleWidth(prefix);
306
+ const hang = " ".repeat(prefixWidth);
307
+ const body = wrapPlain(text, Math.max(1, width - prefixWidth));
308
+ return body.map((piece, index) => {
309
+ const leading = index === 0 ? prefix : hang;
310
+ switch (line.kind) {
311
+ case "question":
312
+ return fg(theme, "muted", emphasize(theme, "italic", leading + piece));
313
+ case "answer": {
314
+ const reply =
315
+ line.text === undefined ? piece : emphasize(theme, "bold", piece);
316
+ return fg(theme, "userMessageText", leading + reply);
317
+ }
318
+ case "status":
319
+ return fg(theme, line.tone, piece);
320
+ }
321
+ });
302
322
  }
303
323
 
304
324
  /**
@@ -325,6 +345,7 @@ export function renderQuestionBlock(
325
345
  ): string[] | undefined {
326
346
  const details = row.result?.details;
327
347
  if (!isQuestionToolCall(row)) return undefined;
348
+ if (row.result?.isError) return undefined;
328
349
  if (isRecord(details) && typeof details.error === "string") return undefined;
329
350
 
330
351
  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
  }