pi-render-btw 0.6.10 → 0.6.12

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/extensions/btw.ts CHANGED
@@ -40,23 +40,42 @@ import {
40
40
  findNextSearchMatch,
41
41
  findSearchMatches,
42
42
  getBlockText,
43
- getBlockTypeLabel,
43
+ getSemanticBlockLabel,
44
+ getToolPreviewText,
45
+ getToolResultSummary,
46
+ hasToolPreview,
47
+ parsePeekMouseInput,
44
48
  type PeekBlock,
49
+ type PeekMouseEvent,
45
50
  type PeekEntry,
46
51
  type PeekModeState,
47
52
  } from "./btw/peek.ts";
53
+ import {
54
+ BTW_TRANSCRIPT_SCHEMA_VERSION,
55
+ BtwTranscriptStore,
56
+ isTranscriptLocator,
57
+ makeTranscriptLocator,
58
+ type DurableTranscriptSnapshot,
59
+ type ToolArtifact,
60
+ } from "./btw/transcript-store.ts";
48
61
 
49
62
  const BTW_MESSAGE_TYPE = "btw-note";
50
63
  const BTW_ENTRY_TYPE = "btw-thread-entry";
51
64
  const BTW_RESET_TYPE = "btw-thread-reset";
65
+ const BTW_TRANSCRIPT_TYPE = "btw-transcript";
52
66
  const BTW_MODEL_OVERRIDE_TYPE = "btw-model-override";
53
67
  const BTW_THINKING_OVERRIDE_TYPE = "btw-thinking-override";
54
68
  const BTW_FOCUS_SHORTCUTS = [Key.alt("/"), Key.ctrlAlt("w")] as const;
69
+ const BTW_TOOL_OUTPUT_SHORTCUT = Key.ctrl("o");
55
70
 
56
71
  function matchesBtwFocusShortcut(data: string): boolean {
57
72
  return BTW_FOCUS_SHORTCUTS.some((shortcut) => matchesKey(data, shortcut));
58
73
  }
59
74
 
75
+ function matchesPageKey(data: string, page: 5 | 6): boolean {
76
+ return new RegExp(`^\\x1b\\[${page}(?:;\\d+)?~$`).test(data);
77
+ }
78
+
60
79
  function findFdPath(): string | null {
61
80
  const lookup = process.platform === "win32" ? "where" : "which";
62
81
  for (const candidate of process.platform === "win32" ? ["fd.exe", "fd"] : ["fd", "fdfind"]) {
@@ -93,6 +112,8 @@ type SessionModel = NonNullable<ExtensionCommandContext["model"]>;
93
112
  type BtwModelRef = Pick<SessionModel, "provider" | "id" | "api">;
94
113
 
95
114
  type BtwDetails = {
115
+ /** Versioned so old btw-thread-entry details remain readable on restore. */
116
+ schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
96
117
  question: string;
97
118
  thinking: string;
98
119
  answer: string;
@@ -116,6 +137,20 @@ type BtwResetDetails = {
116
137
  mode?: BtwThreadMode;
117
138
  };
118
139
 
140
+ const VALID_THINKING_LEVELS: readonly SessionThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
141
+
142
+ function isBtwThreadMode(value: unknown): value is BtwThreadMode {
143
+ return value === "contextual" || value === "tangent";
144
+ }
145
+
146
+ function isSessionThinkingLevel(value: unknown): value is SessionThinkingLevel {
147
+ return typeof value === "string" && VALID_THINKING_LEVELS.includes(value as SessionThinkingLevel);
148
+ }
149
+
150
+ function isRecord(value: unknown): value is Record<string, unknown> {
151
+ return !!value && typeof value === "object" && !Array.isArray(value);
152
+ }
153
+
119
154
  type BtwModelOverrideDetails =
120
155
  | ({ timestamp: number; action: "set" } & Pick<SessionModel, "provider" | "id" | "api">)
121
156
  | { timestamp: number; action: "clear" };
@@ -152,7 +187,10 @@ type BtwTranscriptEntry =
152
187
  type: "tool-result";
153
188
  toolCallId: string;
154
189
  toolName: string;
190
+ /** Compact text used by the normal transcript row. */
155
191
  content: string;
192
+ /** Full result retained for the read-only Peek preview. */
193
+ fullContent?: string;
156
194
  truncated: boolean;
157
195
  isError: boolean;
158
196
  streaming: boolean;
@@ -397,19 +435,15 @@ function formatToolPreview(value: unknown): string {
397
435
  return value;
398
436
  }
399
437
 
400
- if (value && typeof value === "object") {
401
- const path = (value as { path?: unknown }).path;
402
- if (typeof path === "string") {
403
- return path;
404
- }
405
- }
406
-
407
438
  try {
408
439
  const preview = JSON.stringify(value);
409
440
  if (!preview || preview === "{}") {
410
441
  return "";
411
442
  }
412
- return preview.length > 120 ? `${preview.slice(0, 117)}...` : preview;
443
+ // Keep the immutable input for `w`; normal rendering clips it to the row
444
+ // width, so storing a pre-truncated preview would make the read-only view
445
+ // incomplete.
446
+ return preview;
413
447
  } catch {
414
448
  return "";
415
449
  }
@@ -571,7 +605,7 @@ function upsertTranscriptTextEntry(
571
605
  appendTranscriptEntry(state, { type, turnId, text, streaming } as Omit<Extract<BtwTranscriptEntry, { type: "thinking" | "assistant-text" }>, "id">);
572
606
  }
573
607
 
574
- function summarizeToolResult(value: unknown, maxLength = 400): { content: string; truncated: boolean } {
608
+ function summarizeToolResult(value: unknown, maxLength = 400): { content: string; fullContent: string; truncated: boolean } {
575
609
  let content = "";
576
610
 
577
611
  if (value && typeof value === "object") {
@@ -617,6 +651,7 @@ function summarizeToolResult(value: unknown, maxLength = 400): { content: string
617
651
  const truncated = content.length > maxLength;
618
652
  return {
619
653
  content: truncated ? `${content.slice(0, maxLength - 3)}...` : content,
654
+ fullContent: content,
620
655
  truncated,
621
656
  };
622
657
  }
@@ -651,6 +686,7 @@ function upsertToolResultEntry(
651
686
  toolCallId: string,
652
687
  toolName: string,
653
688
  content: string,
689
+ fullContent: string,
654
690
  truncated: boolean,
655
691
  isError: boolean,
656
692
  streaming: boolean,
@@ -663,6 +699,7 @@ function upsertToolResultEntry(
663
699
 
664
700
  if (existing && existing.type === "tool-result") {
665
701
  existing.content = content;
702
+ existing.fullContent = fullContent;
666
703
  existing.truncated = truncated;
667
704
  existing.isError = isError;
668
705
  existing.streaming = streaming;
@@ -675,6 +712,7 @@ function upsertToolResultEntry(
675
712
  toolCallId,
676
713
  toolName,
677
714
  content,
715
+ fullContent,
678
716
  truncated,
679
717
  isError,
680
718
  streaming,
@@ -756,6 +794,7 @@ function applyTranscriptEvent(state: BtwTranscriptState, event: AgentSessionEven
756
794
  event.toolCallId,
757
795
  event.toolName,
758
796
  result.content,
797
+ result.fullContent,
759
798
  result.truncated,
760
799
  false,
761
800
  true,
@@ -771,6 +810,7 @@ function applyTranscriptEvent(state: BtwTranscriptState, event: AgentSessionEven
771
810
  event.toolCallId,
772
811
  event.toolName,
773
812
  result.content,
813
+ result.fullContent,
774
814
  result.truncated,
775
815
  event.isError,
776
816
  false,
@@ -796,6 +836,40 @@ function appendPersistedTranscriptTurn(state: BtwTranscriptState, details: BtwDe
796
836
  finishTranscriptTurn(state, turnId);
797
837
  }
798
838
 
839
+ /**
840
+ * A process can terminate while a BTW sub-session is streaming. There is no
841
+ * live producer after reload, so those entries must become a closed historical
842
+ * turn before the next composer submission is accepted.
843
+ */
844
+ function closeRestoredStreamingTurns(state: BtwTranscriptState): boolean {
845
+ const staleTurns = new Set<number>();
846
+ for (const entry of state.entries) {
847
+ if ((entry.type === "thinking" || entry.type === "assistant-text" || entry.type === "tool-result") && entry.streaming) {
848
+ staleTurns.add(entry.turnId);
849
+ }
850
+ }
851
+ if (staleTurns.size === 0) return false;
852
+
853
+ for (const turnId of staleTurns) {
854
+ for (const entry of state.entries) {
855
+ if (entry.turnId === turnId &&
856
+ (entry.type === "thinking" || entry.type === "assistant-text" || entry.type === "tool-result")) {
857
+ entry.streaming = false;
858
+ }
859
+ }
860
+ const hasEndBoundary = state.entries.some(
861
+ (entry) => entry.turnId === turnId && entry.type === "turn-boundary" && entry.phase === "end",
862
+ );
863
+ if (!hasEndBoundary) {
864
+ appendTranscriptEntry(state, { type: "turn-boundary", turnId, phase: "end" } as Omit<Extract<BtwTranscriptEntry, { type: "turn-boundary" }>, "id">);
865
+ }
866
+ }
867
+
868
+ state.currentTurnId = null;
869
+ state.lastTurnId = Math.max(state.lastTurnId ?? 0, ...staleTurns);
870
+ return true;
871
+ }
872
+
799
873
  function setTranscriptFailure(state: BtwTranscriptState, message: string): void {
800
874
  const turnId = state.currentTurnId ?? state.lastTurnId ?? ensureTranscriptTurn(state);
801
875
  upsertTranscriptTextEntry(state, turnId, "assistant-text", `❌ ${message}`, false);
@@ -1036,6 +1110,8 @@ function notify(ctx: ExtensionContext | ExtensionCommandContext, message: string
1036
1110
  /** Minimum rows for fixed overlay chrome outside the transcript viewport (without input lines).
1037
1111
  * render() computes the actual value dynamically: chrome = 8 + inputLines. */
1038
1112
  const BTW_OVERLAY_CHROME_BASE = 8;
1113
+ /** Coalesce provider/tool deltas into one render per frame-ish interval. */
1114
+ const BTW_UI_REFRESH_DEBOUNCE_MS = 16;
1039
1115
 
1040
1116
  function getOverlayTitle(mode: BtwThreadMode): string {
1041
1117
  return mode === "tangent" ? "BTW tangent" : "BTW";
@@ -1064,13 +1140,20 @@ export class BtwOverlayComponent extends Container implements Focusable {
1064
1140
  private readonly onDismissCallback: () => void;
1065
1141
  private readonly onUnfocusCallback: () => void;
1066
1142
  private readonly onExternalEditorCallback?: () => void;
1143
+ private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1067
1144
  private externalEditorActive = false;
1068
1145
  private readonly tui: TUI;
1069
1146
  private readonly theme: ExtensionContext["ui"]["theme"];
1070
1147
  private transcriptLines: string[] = [];
1148
+ /** Rendered transcript line -> source entry id; separators/padding are null. */
1149
+ private transcriptLineEntryIds: Array<number | null> = [];
1071
1150
  private transcriptScrollOffset = 0;
1072
1151
  private transcriptViewportHeight = 8;
1073
1152
  private followTranscript = true;
1153
+ private liveHoveredEntryId: number | null = null;
1154
+ private liveFocusedEntryId: number | null = null;
1155
+ private liveFocusedToolCallId: string | null = null;
1156
+ private liveExpandedToolCallId: string | null = null;
1074
1157
  private _focused = false;
1075
1158
  private modeTextValue = "";
1076
1159
  private summaryTextValue = "";
@@ -1082,8 +1165,24 @@ export class BtwOverlayComponent extends Container implements Focusable {
1082
1165
  private peekBlocks: PeekBlock[] = [];
1083
1166
  private peekRenderedLines: string[] = [];
1084
1167
  private peekBlockStarts: number[] = [];
1168
+ private peekBlockEnds: number[] = [];
1085
1169
  private peekHeaderLines: string[] = [];
1170
+ private peekStickyHeaderIndex: number | null = null;
1086
1171
  private peekSearchBuffer = "";
1172
+ private peekHoveredIndex: number | null = null;
1173
+ private peekToolPreviewIndex: number | null = null;
1174
+ private peekToolPreviewBlockId: number | null = null;
1175
+ private peekToolPreviewLines: string[] = [];
1176
+ private peekToolPreviewScrollOffset = 0;
1177
+ private expandedToolId: number | null = null;
1178
+ /** The same bounded preview is used by Peek and by the live BTW panel. */
1179
+ private toolPreviewParent: "peek" | "live" | null = null;
1180
+ private liveToolPreviewBlock: PeekBlock | null = null;
1181
+ private lastRenderWidth = 80;
1182
+ // SGR mouse coordinates are one-based. Peek content starts at row 4;
1183
+ // live transcript content starts at row 5 after its title/rules.
1184
+ private peekContentTop = 4;
1185
+ private transcriptContentTop = 5;
1087
1186
 
1088
1187
  get focused(): boolean {
1089
1188
  return this._focused;
@@ -1106,6 +1205,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1106
1205
  onUnfocus: () => void,
1107
1206
  onExternalEditor?: () => void,
1108
1207
  cwd?: string,
1208
+ readToolArtifact?: (toolCallId: string) => ToolArtifact | null,
1109
1209
  ) {
1110
1210
  super();
1111
1211
  this.tui = tui;
@@ -1117,6 +1217,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1117
1217
  this.onDismissCallback = onDismiss;
1118
1218
  this.onUnfocusCallback = onUnfocus;
1119
1219
  this.onExternalEditorCallback = onExternalEditor;
1220
+ this.readToolArtifact = readToolArtifact;
1120
1221
 
1121
1222
  this.modeText = new Text("", 1, 0);
1122
1223
  this.summaryText = new Text("", 1, 0);
@@ -1155,9 +1256,6 @@ export class BtwOverlayComponent extends Container implements Focusable {
1155
1256
  this.hintsText = new Text("", 1, 0);
1156
1257
  this.mdTheme = getMarkdownTheme();
1157
1258
 
1158
- // Enable SGR mouse reporting so wheel/touchpad events reach handleInput().
1159
- this.tui.terminal?.write?.("\x1b[?1000h\x1b[?1006h");
1160
-
1161
1259
  const originalHandleInput = this.input.handleInput.bind(this.input);
1162
1260
  this.input.handleInput = (data: string) => {
1163
1261
  if (keybindings.matches(data, "app.editor.external")) {
@@ -1235,6 +1333,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1235
1333
  return this.theme.fg("border", `${left}${"─".repeat(innerWidth)}${right}`);
1236
1334
  }
1237
1335
 
1336
+ private titleLine(title: string, innerWidth: number): string {
1337
+ const escapeHint = this.theme.fg("dim", "[Esc]");
1338
+ const gap = Math.max(1, innerWidth - visibleWidth(title) - visibleWidth(escapeHint));
1339
+ return this.frameLine(`${title}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1340
+ }
1341
+
1238
1342
  private wrapTranscript(innerWidth: number): string[] {
1239
1343
  const wrapped: string[] = [];
1240
1344
  for (const line of this.transcriptLines) {
@@ -1250,17 +1354,26 @@ export class BtwOverlayComponent extends Container implements Focusable {
1250
1354
  private buildTranscriptLines(innerWidth: number): string[] {
1251
1355
  const entries = this.readTranscriptEntries();
1252
1356
  if (entries.length === 0) {
1357
+ this.transcriptLineEntryIds = [null];
1253
1358
  return [this.theme.fg("dim", "No BTW thread yet. Ask a side question to start one.")];
1254
1359
  }
1255
1360
 
1256
1361
  const allLines: string[] = [];
1257
- const userBadge = buildTranscriptBadge(this.theme, "You", "userMessageBg", "accent");
1258
- const thinkingBadge = buildTranscriptBadge(this.theme, "Thinking", "toolPendingBg", "warning");
1259
- const toolBadge = buildTranscriptBadge(this.theme, "Tool", "toolPendingBg", "warning");
1260
- const assistantBadge = buildTranscriptBadge(this.theme, "Assistant", "customMessageBg", "success");
1362
+ const lineEntryIds: Array<number | null> = [];
1363
+ const markBlock = (entryId: number, start: number): void => {
1364
+ const plain = (line: string) => line.replace(/\x1b\[[0-9;?]*[ -\/]*[@-~]/g, "");
1365
+ for (let index = start; index < allLines.length; index++) {
1366
+ const value = plain(allLines[index]);
1367
+ lineEntryIds[index] = value.trim() && !/^─+$/.test(value.trim()) ? entryId : null;
1368
+ }
1369
+ };
1370
+ const focusRail = (entryId: number): string =>
1371
+ this.liveFocusedEntryId === entryId ? "▎ " : this.liveHoveredEntryId === entryId ? "│ " : "";
1372
+ const userBadge = buildTranscriptBadge(this.theme, "USER", "userMessageBg", "accent");
1373
+ const thinkingBadge = buildTranscriptBadge(this.theme, "THINKING", "toolPendingBg", "warning");
1374
+ const assistantBadge = buildTranscriptBadge(this.theme, "ASSISTANT", "customMessageBg", "success");
1261
1375
  const separator = this.theme.fg("borderMuted", "─".repeat(40));
1262
1376
  const blockIndent = " ";
1263
- const resultIndent = blockIndent;
1264
1377
  const mdContentWidth = Math.max(1, innerWidth - visibleWidth(blockIndent));
1265
1378
 
1266
1379
  const pushBlank = (): void => {
@@ -1270,6 +1383,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1270
1383
  };
1271
1384
 
1272
1385
  for (const entry of entries) {
1386
+ const blockStart = allLines.length;
1273
1387
  if (entry.type === "turn-boundary") {
1274
1388
  if (entry.phase === "start" && allLines.length > 0) {
1275
1389
  pushBlank();
@@ -1280,67 +1394,81 @@ export class BtwOverlayComponent extends Container implements Focusable {
1280
1394
 
1281
1395
  if (entry.type === "user-message") {
1282
1396
  pushBlank();
1283
- allLines.push(userBadge);
1284
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1285
- for (const line of styledLines) {
1286
- allLines.push(`${blockIndent}${line}`);
1397
+ allLines.push(`${focusRail(entry.id)}${userBadge}`);
1398
+ const boundedText = entry.text.length > 16_000 ? `${entry.text.slice(0, 15_970)}\n… [truncated]` : entry.text;
1399
+ const mdLines = new Markdown(boundedText || "∅", 0, 0, this.mdTheme).render(mdContentWidth);
1400
+ for (const line of mdLines) {
1401
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1287
1402
  }
1403
+ markBlock(entry.id, blockStart);
1288
1404
  continue;
1289
1405
  }
1290
1406
 
1291
1407
  if (entry.type === "thinking") {
1292
1408
  const thinkingHeader = entry.streaming ? `${thinkingBadge} ${this.theme.fg("warning", "▍")}` : thinkingBadge;
1293
1409
  pushBlank();
1294
- allLines.push(thinkingHeader);
1410
+ allLines.push(`${focusRail(entry.id)}${thinkingHeader}`);
1295
1411
  const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1296
1412
  for (const line of styledLines) {
1297
1413
  allLines.push(`${blockIndent}${this.theme.fg("warning", this.theme.italic(line))}`);
1298
1414
  }
1415
+ markBlock(entry.id, blockStart);
1299
1416
  continue;
1300
1417
  }
1301
1418
 
1302
1419
  if (entry.type === "tool-call") {
1303
- const toolLabel = this.theme.fg("warning", this.theme.bold(entry.toolName));
1304
- const argsLabel = entry.args ? this.theme.fg("dim", ` · ${entry.args}`) : "";
1420
+ const toolLabel = this.theme.fg("toolTitle", this.theme.bold(`· TOOL ${entry.toolName}`));
1421
+ const argsLabel = entry.args ? this.theme.fg("dim", ` → ${entry.args}`) : "";
1422
+ const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1423
+ const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1305
1424
  pushBlank();
1306
- allLines.push(`${toolBadge} ${toolLabel}${argsLabel}`);
1425
+ allLines.push(`${focusRail(entry.id)}${toolLabel}${argsLabel}${moreLabel}`);
1426
+ if (isExpanded && entry.args) {
1427
+ for (const line of wrapTextWithAnsi(entry.args, mdContentWidth)) {
1428
+ allLines.push(`${blockIndent}${this.theme.fg("dim", line)}`);
1429
+ }
1430
+ }
1431
+ markBlock(entry.id, blockStart);
1307
1432
  continue;
1308
1433
  }
1309
1434
 
1310
1435
  if (entry.type === "tool-result") {
1311
- const resultHeader = entry.isError
1312
- ? this.theme.fg("error", "↳ error")
1313
- : entry.streaming
1314
- ? this.theme.fg("warning", "↳ streaming result")
1315
- : this.theme.fg("dim", "↳ result");
1316
- const truncLabel = entry.truncated ? this.theme.fg("dim", " (truncated)") : "";
1436
+ const resultIcon = entry.isError ? "✗" : "✓";
1437
+ const resultColor = entry.isError ? "error" : entry.streaming ? "warning" : "dim";
1438
+ const resultLabel = this.theme.fg(resultColor, ` ↳ ${resultIcon} ${entry.toolName}`);
1439
+ const summary = this.theme.fg(resultColor, ` · ${getToolResultSummary(entry.content)}`);
1440
+ const truncLabel = entry.truncated ? this.theme.fg("dim", " · truncated") : "";
1441
+ const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1442
+ const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1317
1443
  pushBlank();
1318
- allLines.push(`${resultHeader}${truncLabel}`);
1319
- const styledLines = wrapTextWithAnsi(entry.content, mdContentWidth);
1320
- for (const line of styledLines) {
1321
- allLines.push(`${resultIndent}${entry.isError ? this.theme.fg("error", line) : this.theme.fg("dim", line)}`);
1444
+ allLines.push(`${focusRail(entry.id)}${resultLabel}${summary}${truncLabel}${moreLabel}`);
1445
+ if (isExpanded) {
1446
+ for (const line of wrapTextWithAnsi(entry.fullContent ?? entry.content, mdContentWidth)) {
1447
+ allLines.push(`${blockIndent}${this.theme.fg(entry.isError ? "error" : "dim", line)}`);
1448
+ }
1322
1449
  }
1450
+ markBlock(entry.id, blockStart);
1323
1451
  continue;
1324
1452
  }
1325
1453
 
1326
1454
  if (entry.type === "assistant-text") {
1327
1455
  pushBlank();
1328
1456
  const header = entry.streaming ? `${assistantBadge} ${this.theme.fg("warning", "▍")}` : assistantBadge;
1329
- allLines.push(header);
1457
+ allLines.push(`${focusRail(entry.id)}${header}`);
1330
1458
 
1331
1459
  if (!entry.streaming) {
1332
1460
  // Render markdown for completed text — use cached result when available
1333
1461
  const cached = this.mdLineCache.get(entry.id);
1334
1462
  if (cached && cached.renderedAtWidth === mdContentWidth) {
1335
1463
  for (const line of cached.lines) {
1336
- allLines.push(`${blockIndent}${line}`);
1464
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1337
1465
  }
1338
1466
  } else {
1339
1467
  const md = new Markdown(entry.text, 0, 0, this.mdTheme);
1340
1468
  const mdLines = md.render(mdContentWidth);
1341
1469
  this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1342
1470
  for (const line of mdLines) {
1343
- allLines.push(`${blockIndent}${line}`);
1471
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1344
1472
  }
1345
1473
  }
1346
1474
  } else {
@@ -1350,44 +1478,229 @@ export class BtwOverlayComponent extends Container implements Focusable {
1350
1478
  allLines.push(`${blockIndent}${line}`);
1351
1479
  }
1352
1480
  }
1481
+ markBlock(entry.id, blockStart);
1353
1482
  continue;
1354
1483
  }
1355
1484
  }
1356
1485
 
1486
+ this.transcriptLineEntryIds = lineEntryIds;
1357
1487
  return allLines;
1358
1488
  }
1359
1489
 
1360
1490
  private getDialogHeight(inputLines: number): number {
1361
- const terminalRows = process.stdout.rows ?? 30;
1362
- const minHeight = Math.max(14, 8 + inputLines + 6); // chrome + input + min transcript
1363
- const maxHeight = Math.min(40, Math.floor(terminalRows * 0.82));
1364
- return Math.max(minHeight, Math.min(maxHeight, Math.floor(terminalRows * 0.78)));
1491
+ // Prefer the host TUI's measured viewport. Falling back to stdout keeps
1492
+ // this component usable in lightweight tests and non-interactive hosts.
1493
+ const terminalRows = Math.max(
1494
+ 1,
1495
+ this.tui.terminal?.rows ?? process.stdout.rows ?? 30,
1496
+ );
1497
+ const preferred = Math.floor(terminalRows * 0.78);
1498
+ const maxHeight = Math.max(1, Math.min(40, terminalRows));
1499
+ const minHeight = Math.min(maxHeight, Math.max(8, 8 + inputLines + 3));
1500
+ return Math.min(maxHeight, Math.max(minHeight, preferred));
1365
1501
  }
1366
1502
 
1367
1503
  private scrollTranscript(delta: number): void {
1504
+ // Wheel input can arrive before the first overlay render. Build the same
1505
+ // line cache used by rendering so the first wheel tick is not lost.
1506
+ if (this.transcriptLines.length === 0 && this.readTranscriptEntries().length > 0) {
1507
+ this.render(this.lastRenderWidth);
1508
+ }
1368
1509
  if (delta < 0) {
1369
1510
  this.followTranscript = false;
1370
1511
  }
1371
- this.transcriptScrollOffset = Math.max(0, this.transcriptScrollOffset + delta);
1512
+ const maxScroll = Math.max(0, this.transcriptLines.length - this.transcriptViewportHeight);
1513
+ this.transcriptScrollOffset = Math.max(
1514
+ 0,
1515
+ Math.min(maxScroll, this.transcriptScrollOffset + delta),
1516
+ );
1517
+ if (this.transcriptScrollOffset >= maxScroll) {
1518
+ this.followTranscript = true;
1519
+ }
1372
1520
  this.tui.requestRender();
1373
1521
  }
1374
1522
 
1375
1523
  dispose(): void {
1376
- this.tui.terminal?.write?.("\x1b[?1000l\x1b[?1006l");
1524
+ // Mouse reporting is owned by the host TUI. This component only handles
1525
+ // normalized events (or passively parses an event already delivered to it).
1377
1526
  }
1378
1527
 
1379
1528
  private getMouseScrollDelta(data: string): number | null {
1380
- const match = data.match(/^\x1b\[<(\d+);\d+;\d+[Mm]$/);
1381
- if (!match) {
1382
- return null;
1529
+ const event = parsePeekMouseInput(data);
1530
+ if (!event || event.action !== "wheel") return null;
1531
+ // Match the normalized TUI path and the subagent viewer: one logical
1532
+ // wheel unit means one rendered line. Do not apply a second multiplier.
1533
+ return Math.trunc(event.delta ?? 0);
1534
+ }
1535
+
1536
+ private transcriptEntryAtLine(y: number): number | null {
1537
+ const localLine = y - this.transcriptContentTop;
1538
+ if (localLine < 0 || localLine >= this.transcriptViewportHeight) return null;
1539
+ const line = this.transcriptScrollOffset + localLine;
1540
+ return this.transcriptLineEntryIds[line] ?? null;
1541
+ }
1542
+
1543
+ private focusLiveTranscriptEntry(entryId: number): boolean {
1544
+ const entry = this.readTranscriptEntries().find((candidate) => candidate.id === entryId);
1545
+ if (!entry || entry.type === "turn-boundary") return false;
1546
+ this.liveFocusedEntryId = entryId;
1547
+ this.liveHoveredEntryId = entryId;
1548
+ this.liveFocusedToolCallId = entry.type === "tool-call" || entry.type === "tool-result"
1549
+ ? entry.toolCallId ?? null
1550
+ : null;
1551
+ this.tui.requestRender();
1552
+ return true;
1553
+ }
1554
+
1555
+ private peekIndexAtLine(y: number): number | null {
1556
+ if (this.peekBlockStarts.length !== this.peekBlocks.length) return null;
1557
+ const localLine = y - this.peekContentTop;
1558
+ if (localLine < 0 || localLine >= this.peekState.viewportHeight) return null;
1559
+ if (localLine === 0 && this.peekStickyHeaderIndex !== null) {
1560
+ return this.peekStickyHeaderIndex;
1561
+ }
1562
+
1563
+ const line = this.peekState.scrollOffset + localLine;
1564
+ for (let index = 0; index < this.peekBlocks.length; index++) {
1565
+ const start = this.peekBlockStarts[index];
1566
+ const end = this.peekBlockEnds[index] ?? start;
1567
+ if (line >= start && line < end) return index;
1568
+ }
1569
+ return null;
1570
+ }
1571
+
1572
+ /**
1573
+ * Viewer-local mouse seam. Newer Pi TUI hosts call `handleMouse` with
1574
+ * zero-based `{ type, button, x, y, wheelDelta }` events; older hosts and
1575
+ * tests can pass the one-based normalized SGR shape from `peek.ts`.
1576
+ *
1577
+ * Only an explicit left click is actionable. Press/release are consumed
1578
+ * without changing selection, focus, expansion, or the composer draft.
1579
+ */
1580
+ handleMouse(event: PeekMouseEvent | {
1581
+ type: "press" | "release" | "move" | "drag" | "click" | "wheel";
1582
+ button: "left" | "middle" | "right" | "none" | number;
1583
+ x: number;
1584
+ y: number;
1585
+ clickCount?: number;
1586
+ wheelDelta?: number;
1587
+ }): any {
1588
+ const normalized: PeekMouseEvent = "action" in event
1589
+ ? event
1590
+ : {
1591
+ action: event.type === "wheel"
1592
+ ? "wheel"
1593
+ : event.type === "click"
1594
+ ? "click"
1595
+ : event.type === "release"
1596
+ ? "release"
1597
+ : event.type,
1598
+ button: typeof event.button === "number"
1599
+ ? event.button
1600
+ : event.button === "left"
1601
+ ? 0
1602
+ : event.button === "middle"
1603
+ ? 1
1604
+ : event.button === "right"
1605
+ ? 2
1606
+ : -1,
1607
+ // Pi TUI coordinates are zero-based local cells; the SGR adapter
1608
+ // and rendered spans below intentionally use one-based rows.
1609
+ x: event.x + 1,
1610
+ y: event.y + 1,
1611
+ clickCount: event.clickCount,
1612
+ delta: event.wheelDelta,
1613
+ };
1614
+
1615
+ if (normalized.action === "wheel") {
1616
+ const delta = Math.trunc(normalized.delta ?? 0);
1617
+ if (this.toolPreviewParent !== null) {
1618
+ this.scrollToolPreview(delta);
1619
+ } else if (this.peekState.active) {
1620
+ this.scrollPeek(delta);
1621
+ } else {
1622
+ this.scrollTranscript(delta);
1623
+ }
1624
+ return { handled: true, render: true };
1625
+ }
1626
+ if (this.toolPreviewParent !== null) {
1627
+ return { handled: true, render: false };
1383
1628
  }
1384
1629
 
1385
- const button = Number(match[1]);
1386
- if ((button & 64) !== 64) {
1387
- return null;
1630
+ if (!this.peekState.active) {
1631
+ if (this.transcriptLineEntryIds.length === 0 && this.readTranscriptEntries().length > 0) {
1632
+ this.render(this.lastRenderWidth);
1633
+ }
1634
+ if (normalized.action === "move" || normalized.action === "drag") {
1635
+ const hoveredEntryId = this.transcriptEntryAtLine(normalized.y);
1636
+ if (hoveredEntryId === this.liveHoveredEntryId) return { handled: true, render: false };
1637
+ this.liveHoveredEntryId = hoveredEntryId;
1638
+ this.tui.requestRender();
1639
+ return { handled: true, render: true };
1640
+ }
1641
+ if (normalized.action === "press" || normalized.action === "release") {
1642
+ return { handled: true, render: false };
1643
+ }
1644
+ if (normalized.action !== "click" || normalized.button !== 0) {
1645
+ return { handled: true, render: false };
1646
+ }
1647
+ if (normalized.x < 1 || normalized.x > this.lastRenderWidth) {
1648
+ return { handled: true, render: false };
1649
+ }
1650
+ const entryId = this.transcriptEntryAtLine(normalized.y);
1651
+ if (entryId === null) return { handled: true, render: false };
1652
+ const entry = this.readTranscriptEntries().find((candidate) => candidate.id === entryId);
1653
+ const focused = this.focusLiveTranscriptEntry(entryId);
1654
+ if (focused && (entry?.type === "tool-call" || entry?.type === "tool-result") && entry.toolCallId) {
1655
+ // A single click both focuses the tool row and toggles its compact
1656
+ // details. A second click collapses it, matching the Peek surface.
1657
+ if ((normalized.clickCount ?? 1) >= 2) {
1658
+ this.liveExpandedToolCallId = null;
1659
+ } else {
1660
+ this.liveExpandedToolCallId = this.liveExpandedToolCallId === entry.toolCallId
1661
+ ? null
1662
+ : entry.toolCallId;
1663
+ }
1664
+ this.tui.requestRender();
1665
+ }
1666
+ return { handled: true, focus: focused, render: focused };
1388
1667
  }
1389
1668
 
1390
- return (button & 1) === 0 ? -3 : 3;
1669
+ if (normalized.action === "move" || normalized.action === "drag") {
1670
+ const hoveredIndex = this.peekIndexAtLine(normalized.y);
1671
+ if (hoveredIndex === this.peekHoveredIndex) {
1672
+ return { handled: true, render: false };
1673
+ }
1674
+ this.peekHoveredIndex = hoveredIndex;
1675
+ this.tui.requestRender();
1676
+ return { handled: true, render: true };
1677
+ }
1678
+ if (normalized.action === "press" || normalized.action === "release") {
1679
+ return { handled: true, render: false };
1680
+ }
1681
+ if (normalized.action !== "click" || normalized.button !== 0) return;
1682
+ if (normalized.x < 1 || normalized.x > this.lastRenderWidth || this.peekBlockStarts.length !== this.peekBlocks.length) {
1683
+ return { handled: true, render: false };
1684
+ }
1685
+
1686
+ const targetIndex = this.peekIndexAtLine(normalized.y);
1687
+ if (targetIndex === null) return { handled: true, render: false };
1688
+ this.peekHoveredIndex = targetIndex;
1689
+ this.peekState.selectedIndex = targetIndex;
1690
+ const target = this.peekBlocks[targetIndex];
1691
+ const clickCount = normalized.clickCount ?? 1;
1692
+ const shouldCollapse = clickCount >= 2 &&
1693
+ (target?.type === "tool-call" || target?.type === "tool-result") &&
1694
+ this.expandedToolId === target.id;
1695
+ if (shouldCollapse) {
1696
+ this.expandedToolId = null;
1697
+ this.peekState.scrollOffset = Math.max(0, Math.min(
1698
+ this.peekState.scrollOffset,
1699
+ Math.max(0, this.peekRenderedLines.length - Math.max(1, this.peekState.viewportHeight)),
1700
+ ));
1701
+ }
1702
+ this.tui.requestRender();
1703
+ return { handled: true, focus: true, render: true };
1391
1704
  }
1392
1705
 
1393
1706
  handleInput(data: string): void {
@@ -1396,15 +1709,41 @@ export class BtwOverlayComponent extends Container implements Focusable {
1396
1709
  return;
1397
1710
  }
1398
1711
 
1712
+ // Older hosts may deliver raw SGR/X10 wheel bytes through handleInput
1713
+ // instead of dispatching a normalized mouse event.
1714
+ const earlyMouseScrollDelta = this.getMouseScrollDelta(data);
1715
+ if (earlyMouseScrollDelta !== null && this.toolPreviewParent !== null) {
1716
+ this.scrollToolPreview(earlyMouseScrollDelta);
1717
+ return;
1718
+ }
1719
+
1720
+ if (this.toolPreviewParent !== null && this.handleToolPreviewInput(data)) {
1721
+ return;
1722
+ }
1723
+
1724
+ // Ctrl+O is live-only: it opens the read-only input/output snapshot of
1725
+ // the focused tool. It is always consumed here, including when no tool is
1726
+ // focused, so the control character can never reach the composer.
1727
+ if (matchesKey(data, BTW_TOOL_OUTPUT_SHORTCUT)) {
1728
+ if (!this.peekState.active) this.enterLiveToolPreview();
1729
+ return;
1730
+ }
1731
+
1732
+ const mouseEvent = parsePeekMouseInput(data);
1399
1733
  const mouseScrollDelta = this.getMouseScrollDelta(data);
1400
1734
  if (mouseScrollDelta !== null) {
1401
- if (this.peekState.active) {
1735
+ if (this.toolPreviewParent !== null) {
1736
+ this.scrollToolPreview(mouseScrollDelta);
1737
+ } else if (this.peekState.active) {
1402
1738
  this.scrollPeek(mouseScrollDelta);
1403
1739
  } else {
1404
1740
  this.scrollTranscript(mouseScrollDelta);
1405
1741
  }
1406
1742
  return;
1407
1743
  }
1744
+ // Consume bounded SGR button events locally. Without an explicit host
1745
+ // click dispatch, press/release are deliberately no-ops rather than input.
1746
+ if (mouseEvent) return;
1408
1747
 
1409
1748
  // Peek mode active → route all input to peek handler
1410
1749
  if (this.peekState.active) {
@@ -1421,8 +1760,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1421
1760
  this.input.handleInput(data);
1422
1761
  }
1423
1762
 
1424
- private inputFrameLines(innerWidth: number): string[] {
1425
- const lines = this.input.render(innerWidth);
1763
+ private inputFrameLines(innerWidth: number, maxLines = 6): string[] {
1764
+ const rendered = this.input.render(innerWidth);
1765
+ // CustomEditor owns cursor/history state; only clip its visual viewport,
1766
+ // keeping the newest lines visible instead of allowing the overlay to grow.
1767
+ const lines = rendered.slice(Math.max(0, rendered.length - maxLines));
1768
+ if (lines.length === 0) lines.push("");
1426
1769
  return lines.map((l) => {
1427
1770
  const pad = Math.max(0, innerWidth - visibleWidth(l));
1428
1771
  return `${this.theme.fg("border", "│")}${l}${" ".repeat(pad)}${this.theme.fg("border", "│")}`;
@@ -1436,20 +1779,33 @@ export class BtwOverlayComponent extends Container implements Focusable {
1436
1779
  override render(width: number): string[] {
1437
1780
  const dialogWidth = Math.max(24, width);
1438
1781
  const innerWidth = Math.max(22, dialogWidth - 2);
1782
+ this.lastRenderWidth = dialogWidth;
1783
+
1784
+ // Tool Output is a read-only view over the currently focused live tool.
1785
+ if (this.toolPreviewParent === "live") {
1786
+ return this.renderLiveToolPreview(innerWidth, width);
1787
+ }
1439
1788
 
1440
1789
  // Peek mode has its own full-content render
1441
1790
  if (this.peekState.active) {
1442
1791
  return this.renderPeekMode(innerWidth, width);
1443
1792
  }
1444
1793
 
1445
- // Compute input lines (cap at 6 for layout stability)
1794
+ // Compute input lines (cap at 6 for layout stability). On very short
1795
+ // terminals, reserve the composer a single visible row rather than letting
1796
+ // CustomEditor output push the bottom border out of the viewport.
1446
1797
  const rawInputLines = this.input.render(innerWidth);
1447
- const inputLineCount = Math.max(1, Math.min(rawInputLines.length, 6));
1798
+ const terminalRows = Math.max(1, this.tui.terminal?.rows ?? process.stdout.rows ?? 30);
1799
+ const inputBudget = Math.max(1, terminalRows - BTW_OVERLAY_CHROME_BASE - 1);
1800
+ const inputLineCount = Math.max(1, Math.min(rawInputLines.length, 6, inputBudget));
1448
1801
 
1449
1802
  const transcriptLines = this.buildTranscriptLines(innerWidth);
1803
+ this.transcriptLines = transcriptLines;
1450
1804
  const chromeHeight = BTW_OVERLAY_CHROME_BASE + inputLineCount;
1451
1805
  const dialogHeight = this.getDialogHeight(inputLineCount);
1452
- const transcriptHeight = Math.max(6, dialogHeight - chromeHeight);
1806
+ // On short terminals the viewport yields before the composer/chrome. Do
1807
+ // not force a six-line transcript that pushes the bottom border away.
1808
+ const transcriptHeight = Math.max(1, dialogHeight - chromeHeight);
1453
1809
  this.transcriptViewportHeight = transcriptHeight;
1454
1810
 
1455
1811
  const maxScroll = Math.max(0, transcriptLines.length - transcriptHeight);
@@ -1476,7 +1832,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1476
1832
 
1477
1833
  const lines = [this.borderLine(innerWidth, "top")];
1478
1834
 
1479
- lines.push(this.frameLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1835
+ lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1480
1836
  lines.push(this.frameLine(this.theme.fg("dim", summary), innerWidth));
1481
1837
  lines.push(this.ruleLine(innerWidth));
1482
1838
 
@@ -1489,7 +1845,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1489
1845
 
1490
1846
  lines.push(this.ruleLine(innerWidth));
1491
1847
  lines.push(this.frameLine(this.theme.fg("warning", this.statusTextValue.trim()), innerWidth));
1492
- lines.push(...this.inputFrameLines(innerWidth));
1848
+ lines.push(...this.inputFrameLines(innerWidth, inputLineCount));
1493
1849
  lines.push(this.frameLine(this.theme.fg("dim", this.hintsTextValue.trim()), innerWidth));
1494
1850
  lines.push(this.borderLine(innerWidth, "bottom"));
1495
1851
 
@@ -1540,13 +1896,280 @@ export class BtwOverlayComponent extends Container implements Focusable {
1540
1896
 
1541
1897
  // ── Peek Mode ──────────────────────────────────────────────────────
1542
1898
 
1899
+ private getSelectedPeekBlock(): PeekBlock | undefined {
1900
+ if (this.peekBlocks.length === 0) return undefined;
1901
+ this.peekState.selectedIndex = Math.max(
1902
+ 0,
1903
+ Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1),
1904
+ );
1905
+ return this.peekBlocks[this.peekState.selectedIndex];
1906
+ }
1907
+
1908
+ private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1909
+ // Keep the preview read-only and complete. The viewport, not the data,
1910
+ // supplies the bound: only the visible slice is emitted below.
1911
+ const status = block.streaming ? "Status: STREAMING\n\n" : "";
1912
+ const text = `${status}${getToolPreviewText(block)}`;
1913
+ const lines: string[] = [];
1914
+ for (const line of text.split("\n")) {
1915
+ lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
1916
+ }
1917
+ return lines.length > 0 ? lines : ["(no tool data)"];
1918
+ }
1919
+
1920
+ private hydrateToolBlock(block: PeekBlock): PeekBlock {
1921
+ if (!block.toolCallId || !this.readToolArtifact) return block;
1922
+ const artifact = this.readToolArtifact(block.toolCallId);
1923
+ if (!artifact) return block;
1924
+
1925
+ const hydrated = { ...block };
1926
+ const input = formatToolPreview(artifact.input);
1927
+ const output = formatToolPreview(artifact.output);
1928
+ const details = formatToolPreview(artifact.details);
1929
+ if (input) hydrated.toolInput = input;
1930
+ if (output) hydrated.toolOutput = output;
1931
+ if (details) {
1932
+ hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDetails:\n${details}`;
1933
+ }
1934
+ if (artifact.diff) {
1935
+ hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDiff:\n${artifact.diff}`;
1936
+ }
1937
+ hydrated.toolName = artifact.toolName || hydrated.toolName;
1938
+ hydrated.streaming = artifact.phase !== "end" && !artifact.isError;
1939
+ hydrated.isError = hydrated.isError || artifact.isError;
1940
+ return hydrated;
1941
+ }
1942
+
1943
+ private hydrateToolBlocks(blocks: PeekBlock[]): PeekBlock[] {
1944
+ return blocks.map((block) =>
1945
+ block.type === "tool-call" || block.type === "tool-result"
1946
+ ? this.hydrateToolBlock(block)
1947
+ : block,
1948
+ );
1949
+ }
1950
+
1951
+ private findLiveToolPreviewBlock(): PeekBlock | null {
1952
+ const selected = this.liveToolPreviewBlock;
1953
+ if (!selected) return null;
1954
+ const blocks = this.hydrateToolBlocks(buildPeekBlocks(
1955
+ this.readTranscriptEntries() as unknown as PeekEntry[],
1956
+ true,
1957
+ ));
1958
+ return blocks.find((block) => block.entryId === selected.entryId) ??
1959
+ blocks.find((block) => block.toolCallId === selected.toolCallId &&
1960
+ (block.type === "tool-call" || block.type === "tool-result")) ?? null;
1961
+ }
1962
+
1963
+ private scrollToolPreview(delta: number): void {
1964
+ // Opening a preview schedules the next render. A fast wheel event can
1965
+ // arrive first, so initialize its wrapped lines before calculating bounds.
1966
+ if (this.toolPreviewParent !== null && this.peekToolPreviewLines.length === 0) {
1967
+ this.render(this.lastRenderWidth);
1968
+ }
1969
+ if (this.toolPreviewParent === null) return;
1970
+ const viewportHeight = Math.max(1, this.peekState.viewportHeight);
1971
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
1972
+ this.peekToolPreviewScrollOffset = Math.max(
1973
+ 0,
1974
+ Math.min(maxScroll, this.peekToolPreviewScrollOffset + delta),
1975
+ );
1976
+ this.tui.requestRender();
1977
+ }
1978
+
1979
+ private renderLiveToolPreview(innerWidth: number, fullWidth: number): string[] {
1980
+ const block = this.findLiveToolPreviewBlock();
1981
+ if (!block) {
1982
+ this.toolPreviewParent = null;
1983
+ this.liveToolPreviewBlock = null;
1984
+ this.peekToolPreviewLines = [];
1985
+ this.peekToolPreviewScrollOffset = 0;
1986
+ return this.render(fullWidth);
1987
+ }
1988
+
1989
+ const dialogHeight = this.getDialogHeight(1);
1990
+ const viewportHeight = Math.max(1, dialogHeight - 6);
1991
+ this.peekState.viewportHeight = viewportHeight;
1992
+ this.peekToolPreviewLines = this.buildToolPreviewLines(block, innerWidth);
1993
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
1994
+ this.peekToolPreviewScrollOffset = Math.max(
1995
+ 0,
1996
+ Math.min(this.peekToolPreviewScrollOffset, maxScroll),
1997
+ );
1998
+
1999
+ const streamingLabel = block.streaming ? " · STREAMING" : "";
2000
+ const title = `BTW Tool Output · ${getSemanticBlockLabel(block)}${streamingLabel} · read-only`;
2001
+ const lines = [
2002
+ this.borderLine(innerWidth, "top"),
2003
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2004
+ this.ruleLine(innerWidth),
2005
+ ];
2006
+ const visible = this.peekToolPreviewLines.slice(
2007
+ this.peekToolPreviewScrollOffset,
2008
+ this.peekToolPreviewScrollOffset + viewportHeight,
2009
+ );
2010
+ for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2011
+ for (let i = visible.length; i < viewportHeight; i++) lines.push(this.frameLine("", innerWidth));
2012
+ const hiddenAbove = this.peekToolPreviewScrollOffset;
2013
+ const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2014
+ const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2015
+ lines.push(this.ruleLine(innerWidth));
2016
+ lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn Esc:back${counts}`), innerWidth));
2017
+ lines.push(this.borderLine(innerWidth, "bottom"));
2018
+ return lines.map((line) => this.fitRenderedLine(line, fullWidth));
2019
+ }
2020
+
2021
+ private renderToolPreview(innerWidth: number, fullWidth: number): string[] {
2022
+ if (this.peekToolPreviewBlockId !== null) {
2023
+ const refreshedIndex = this.peekBlocks.findIndex((candidate) => candidate.id === this.peekToolPreviewBlockId);
2024
+ this.peekToolPreviewIndex = refreshedIndex >= 0 ? refreshedIndex : null;
2025
+ }
2026
+ const block = this.peekToolPreviewIndex === null ? undefined : this.peekBlocks[this.peekToolPreviewIndex];
2027
+ if (!block || !hasToolPreview(block)) {
2028
+ this.peekToolPreviewIndex = null;
2029
+ this.peekToolPreviewBlockId = null;
2030
+ this.peekToolPreviewLines = [];
2031
+ this.peekToolPreviewScrollOffset = 0;
2032
+ this.toolPreviewParent = null;
2033
+ return this.renderPeekMode(innerWidth, fullWidth);
2034
+ }
2035
+
2036
+ const dialogHeight = this.getDialogHeight(1);
2037
+ const viewportHeight = Math.max(1, dialogHeight - 6);
2038
+ this.peekState.viewportHeight = viewportHeight;
2039
+ this.peekToolPreviewLines = this.buildToolPreviewLines(block, innerWidth);
2040
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
2041
+ this.peekToolPreviewScrollOffset = Math.max(
2042
+ 0,
2043
+ Math.min(this.peekToolPreviewScrollOffset, maxScroll),
2044
+ );
2045
+
2046
+ const title = `BTW Peek · ${getSemanticBlockLabel(block)} · read-only`;
2047
+ const lines = [
2048
+ this.borderLine(innerWidth, "top"),
2049
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2050
+ this.ruleLine(innerWidth),
2051
+ ];
2052
+ const visible = this.peekToolPreviewLines.slice(
2053
+ this.peekToolPreviewScrollOffset,
2054
+ this.peekToolPreviewScrollOffset + viewportHeight,
2055
+ );
2056
+ for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2057
+ while (visible.length < viewportHeight) {
2058
+ visible.push("");
2059
+ lines.push(this.frameLine("", innerWidth));
2060
+ }
2061
+ const hiddenAbove = this.peekToolPreviewScrollOffset;
2062
+ const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2063
+ const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2064
+ lines.push(this.ruleLine(innerWidth));
2065
+ lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn q/Esc:back${counts}`), innerWidth));
2066
+ lines.push(this.borderLine(innerWidth, "bottom"));
2067
+ return lines.map((line) => this.fitRenderedLine(line, fullWidth));
2068
+ }
2069
+
2070
+ private enterToolPreview(): void {
2071
+ const block = this.getSelectedPeekBlock();
2072
+ if (!hasToolPreview(block)) return;
2073
+ this.peekToolPreviewIndex = this.peekState.selectedIndex;
2074
+ this.peekToolPreviewBlockId = block?.id ?? null;
2075
+ this.toolPreviewParent = "peek";
2076
+ this.peekToolPreviewScrollOffset = 0;
2077
+ this.peekToolPreviewLines = [];
2078
+ this.tui.requestRender();
2079
+ }
2080
+
2081
+ private enterLiveToolPreview(): void {
2082
+ if (this.peekState.active || !this.liveFocusedToolCallId) return;
2083
+ const block = buildPeekBlocks(
2084
+ this.readTranscriptEntries() as unknown as PeekEntry[],
2085
+ true,
2086
+ ).find((candidate) => candidate.toolCallId === this.liveFocusedToolCallId);
2087
+ if (!block) return;
2088
+ this.liveToolPreviewBlock = block;
2089
+ this.toolPreviewParent = "live";
2090
+ this.peekToolPreviewScrollOffset = 0;
2091
+ this.peekToolPreviewLines = [];
2092
+ this.tui.requestRender();
2093
+ }
2094
+
2095
+ private exitToolPreview(): void {
2096
+ this.peekToolPreviewIndex = null;
2097
+ this.peekToolPreviewBlockId = null;
2098
+ this.peekToolPreviewLines = [];
2099
+ this.peekToolPreviewScrollOffset = 0;
2100
+ this.liveToolPreviewBlock = null;
2101
+ this.toolPreviewParent = null;
2102
+ this.tui.requestRender();
2103
+ }
2104
+
2105
+ private toggleExpandedTool(): boolean {
2106
+ const block = this.getSelectedPeekBlock();
2107
+ if (!hasToolPreview(block)) return false;
2108
+ this.expandedToolId = this.expandedToolId === block?.id ? null : block?.id ?? null;
2109
+ this.peekState.scrollOffset = 0;
2110
+ this.tui.requestRender();
2111
+ return true;
2112
+ }
2113
+
2114
+ private handleToolPreviewInput(data: string): boolean {
2115
+ if (this.toolPreviewParent === null) return false;
2116
+ if (data === "q" || data === "\x1b" || data === "\x03") {
2117
+ this.exitToolPreview();
2118
+ return true;
2119
+ }
2120
+ const viewportHeight = Math.max(1, this.peekState.viewportHeight);
2121
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
2122
+ if (data === "j" || data === "\x1b[B" || data === "\x1b[OB") {
2123
+ this.peekToolPreviewScrollOffset = Math.min(maxScroll, this.peekToolPreviewScrollOffset + 1);
2124
+ this.tui.requestRender();
2125
+ return true;
2126
+ }
2127
+ if (data === "k" || data === "\x1b[A" || data === "\x1b[OA") {
2128
+ this.peekToolPreviewScrollOffset = Math.max(0, this.peekToolPreviewScrollOffset - 1);
2129
+ this.tui.requestRender();
2130
+ return true;
2131
+ }
2132
+ if (data === "g") {
2133
+ this.peekToolPreviewScrollOffset = 0;
2134
+ this.tui.requestRender();
2135
+ return true;
2136
+ }
2137
+ if (data === "G") {
2138
+ this.peekToolPreviewScrollOffset = maxScroll;
2139
+ this.tui.requestRender();
2140
+ return true;
2141
+ }
2142
+ if (matchesPageKey(data, 5)) {
2143
+ this.peekToolPreviewScrollOffset = Math.max(0, this.peekToolPreviewScrollOffset - Math.max(1, viewportHeight - 2));
2144
+ this.tui.requestRender();
2145
+ return true;
2146
+ }
2147
+ if (matchesPageKey(data, 6)) {
2148
+ this.peekToolPreviewScrollOffset = Math.min(maxScroll, this.peekToolPreviewScrollOffset + Math.max(1, viewportHeight - 2));
2149
+ this.tui.requestRender();
2150
+ return true;
2151
+ }
2152
+ return true;
2153
+ }
2154
+
1543
2155
  private renderPeekMode(innerWidth: number, fullWidth: number): string[] {
1544
- this.peekState.viewportHeight = Math.max(6, this.getDialogHeight(1) - 8);
2156
+ if (this.peekToolPreviewIndex !== null) {
2157
+ return this.renderToolPreview(innerWidth, fullWidth);
2158
+ }
2159
+ const dialogHeight = this.getDialogHeight(1);
2160
+ // Normal Peek chrome is six rows: top/title/rule + rule/status/bottom.
2161
+ this.peekState.viewportHeight = Math.max(1, dialogHeight - 6);
1545
2162
  const vh = this.peekState.viewportHeight;
1546
2163
  const lines: string[] = [];
1547
2164
 
1548
2165
  // ── Header ───────────────────────────────────────────────────────
1549
2166
  const blockCount = this.peekBlocks.length;
2167
+ this.peekState.selectedIndex = blockCount === 0
2168
+ ? 0
2169
+ : Math.max(0, Math.min(this.peekState.selectedIndex, blockCount - 1));
2170
+ if (this.expandedToolId !== null && !this.peekBlocks.some((block) => block.id === this.expandedToolId && hasToolPreview(block))) {
2171
+ this.expandedToolId = null;
2172
+ }
1550
2173
  const pct =
1551
2174
  blockCount > 0
1552
2175
  ? `${Math.round((this.peekState.selectedIndex / Math.max(1, blockCount - 1)) * 100)}%`
@@ -1557,16 +2180,17 @@ export class BtwOverlayComponent extends Container implements Focusable {
1557
2180
  ? ` search ${this.peekState.currentMatchIndex + 1}/${this.peekState.searchMatches.length}`
1558
2181
  : "");
1559
2182
  lines.push(this.borderLine(innerWidth, "top"));
1560
- lines.push(this.frameLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth));
2183
+ lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth));
1561
2184
  lines.push(this.ruleLine(innerWidth));
1562
2185
 
1563
2186
  // ── Search bar ───────────────────────────────────────────────────
1564
2187
  if (this.peekState.searchActive) {
1565
2188
  const searchLine = `/ ${this.peekSearchBuffer}${this.theme.fg("warning", "█")}`;
2189
+ const searchViewportHeight = Math.max(1, dialogHeight - 8);
1566
2190
  lines.push(this.frameLine(this.theme.fg("accent", searchLine), innerWidth));
1567
2191
  lines.push(this.ruleLine(innerWidth));
1568
- // Fill rest with blank lines
1569
- for (let i = 0; i < vh; i++) {
2192
+ // Fill rest with blank lines while keeping the footer and border visible.
2193
+ for (let i = 0; i < searchViewportHeight; i++) {
1570
2194
  lines.push(this.frameLine("", innerWidth));
1571
2195
  }
1572
2196
  lines.push(this.ruleLine(innerWidth));
@@ -1577,58 +2201,62 @@ export class BtwOverlayComponent extends Container implements Focusable {
1577
2201
 
1578
2202
  // ── Content ──────────────────────────────────────────────────────
1579
2203
  const mdContentWidth = Math.max(1, innerWidth - 6);
2204
+ this.peekContentTop = 4;
1580
2205
  // Build rendered lines and remember each block's starting line so j/k
1581
2206
  // can scroll by line while J/K still jump by message.
1582
2207
  const blockRenderLines: string[][] = [];
1583
2208
  this.peekBlockStarts = [];
2209
+ this.peekBlockEnds = [];
1584
2210
  this.peekHeaderLines = [];
1585
2211
  let renderedLineCount = 0;
1586
2212
 
1587
2213
  for (const block of this.peekBlocks) {
1588
2214
  const blockLines: string[] = [];
1589
2215
  this.peekBlockStarts.push(renderedLineCount);
1590
- const label = getBlockTypeLabel(block);
2216
+ const label = getSemanticBlockLabel(block);
1591
2217
  const isCurrent = block.id === this.peekBlocks[this.peekState.selectedIndex]?.id;
2218
+ const isHovered = block.id === this.peekBlocks[this.peekHoveredIndex ?? -1]?.id;
1592
2219
 
1593
- // Block header line
1594
- const prefix = isCurrent ? "▎ " : " ";
2220
+ // The rail is the sole selection indicator. Hover is a quieter cue and
2221
+ // never changes the selected target until an explicit click arrives.
2222
+ const prefix = isCurrent ? "▎ " : isHovered ? "│ " : " ";
1595
2223
  if (block.type === "thinking") {
1596
- blockLines.push(`${prefix}${this.theme.fg("warning", this.theme.bold(this.theme.italic(`── ${label} ──`)))}`);
1597
- } else if (block.type === "tool-call") {
1598
- blockLines.push(`${prefix}${this.theme.fg("toolTitle", this.theme.bold(`── ${label} ──`))}`);
1599
- } else if (block.type === "tool-result") {
1600
- const errPrefix = block.isError ? this.theme.fg("error", " ⚠") : "";
1601
- blockLines.push(`${prefix}${this.theme.fg("dim", this.theme.bold(`── ${label} ──`))}${errPrefix}`);
2224
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "warning", this.theme.bold(this.theme.italic(`── ${label} ──`)))}`);
2225
+ } else if (block.type === "tool-call" || block.type === "tool-result") {
2226
+ const resultIcon = block.type === "tool-result" ? (block.isError ? "✗" : "✓") : "→";
2227
+ const toolColor = block.isError ? "error" : isHovered ? "text" : "toolTitle";
2228
+ const detail = block.type === "tool-result"
2229
+ ? getToolResultSummary(block.text)
2230
+ : block.toolInput || "(no input)";
2231
+ const detailColor = block.isError ? "error" : isHovered ? "text" : "dim";
2232
+ blockLines.push(`${prefix}${this.theme.fg(toolColor, this.theme.bold(`· ${block.toolName ?? "?"} ${resultIcon}`))} ${this.theme.fg(detailColor, detail)}`);
1602
2233
  } else if (block.type === "user") {
1603
- blockLines.push(`${prefix}${this.theme.fg("accent", this.theme.bold(`── ${label} ──`))}`);
2234
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "accent", this.theme.bold(`── ${label} ──`))}`);
1604
2235
  } else {
1605
- blockLines.push(`${prefix}${this.theme.fg("success", this.theme.bold(`── ${label} ──`))}`);
2236
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "success", this.theme.bold(`── ${label} ──`))}`);
1606
2237
  }
1607
2238
 
1608
- // Block content
1609
- if (block.text) {
1610
- if (block.type === "assistant-text") {
1611
- // Use Markdown for assistant text
2239
+ // Tool rows stay compact by default. Enter is an optional safe
2240
+ // expansion; the full read-only view is also available through `w`.
2241
+ if (block.type === "tool-call" || block.type === "tool-result") {
2242
+ if (this.expandedToolId === block.id && hasToolPreview(block)) {
2243
+ const toolLines = this.buildToolPreviewLines(block, innerWidth);
2244
+ for (const toolLine of toolLines) {
2245
+ blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg(block.isError ? "error" : "dim", toolLine)}`);
2246
+ }
2247
+ }
2248
+ } else if (block.text) {
2249
+ if (block.type === "assistant-text" || block.type === "user") {
1612
2250
  const md = new Markdown(block.text, 0, 0, this.mdTheme);
1613
2251
  const mdLines = md.render(mdContentWidth);
1614
2252
  for (const mdLine of mdLines) {
1615
- blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine}`);
1616
- }
1617
- } else if (block.type === "tool-result" && block.isError) {
1618
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1619
- for (const sl of styledLines) {
1620
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("error", sl)}`);
2253
+ blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine.replace(/[ \t]+$/u, "")}`);
1621
2254
  }
1622
2255
  } else if (block.type === "thinking") {
1623
2256
  const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1624
2257
  for (const sl of styledLines) {
1625
2258
  blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("warning", this.theme.italic(sl))}`);
1626
2259
  }
1627
- } else {
1628
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1629
- for (const sl of styledLines) {
1630
- blockLines.push(`${isCurrent ? "▎ " : " "}${sl}`);
1631
- }
1632
2260
  }
1633
2261
  }
1634
2262
 
@@ -1638,6 +2266,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1638
2266
  blockRenderLines.push(blockLines);
1639
2267
  this.peekHeaderLines.push(blockLines[0] ?? "");
1640
2268
  renderedLineCount += blockLines.length;
2269
+ // The final blank is visual separation, not part of the block hitbox.
2270
+ // This keeps clicks on separators/padding from changing focus.
2271
+ this.peekBlockEnds.push(Math.max(this.peekBlockStarts[this.peekBlockStarts.length - 1] + 1, renderedLineCount - 1));
1641
2272
  }
1642
2273
 
1643
2274
  this.peekRenderedLines = blockRenderLines.flat();
@@ -1645,12 +2276,14 @@ export class BtwOverlayComponent extends Container implements Focusable {
1645
2276
  this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
1646
2277
 
1647
2278
  const visibleStart = this.peekState.scrollOffset;
2279
+ this.peekStickyHeaderIndex = null;
1648
2280
  const displayLines = this.peekRenderedLines.slice(visibleStart, visibleStart + vh);
1649
2281
  if (blockCount === 0) {
1650
2282
  displayLines.push(this.theme.fg("dim", "No BTW thread yet."));
1651
2283
  }
1652
2284
  const selectedStart = this.peekBlockStarts[this.peekState.selectedIndex];
1653
2285
  if (selectedStart !== undefined && selectedStart < visibleStart && displayLines.length > 0) {
2286
+ this.peekStickyHeaderIndex = this.peekState.selectedIndex;
1654
2287
  displayLines[0] = this.peekHeaderLines[this.peekState.selectedIndex] ?? displayLines[0];
1655
2288
  }
1656
2289
 
@@ -1668,7 +2301,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1668
2301
  ? ` ${this.peekState.currentMatchIndex + 1}/${this.peekState.searchMatches.length}`
1669
2302
  : "";
1670
2303
  const toolsHint = this.peekState.showTools ? "t:hide" : "t:show";
1671
- const statusText = `j/k ↑↓ g/G /search${searchHint} ${toolsHint} M:copy o:nvim q:exit`;
2304
+ const selected = this.getSelectedPeekBlock();
2305
+ const previewHint = hasToolPreview(selected) ? " w:preview" : "";
2306
+ const expandHint = hasToolPreview(selected) ? " Enter:expand" : "";
2307
+ const statusText = `j/k ↑↓ J/K msg g/G /search${searchHint} ${toolsHint}${previewHint} M:copy o:nvim${expandHint} q:exit`;
1672
2308
  lines.push(this.ruleLine(innerWidth));
1673
2309
  lines.push(this.frameLine(this.theme.fg("dim", statusText), innerWidth));
1674
2310
  lines.push(this.borderLine(innerWidth, "bottom"));
@@ -1681,32 +2317,72 @@ export class BtwOverlayComponent extends Container implements Focusable {
1681
2317
  this.peekState.active = true;
1682
2318
  const entries = this.readTranscriptEntries();
1683
2319
  this.peekState.showTools = true;
1684
- this.peekBlocks = buildPeekBlocks(
2320
+ this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
1685
2321
  entries as unknown as PeekEntry[],
1686
2322
  this.peekState.showTools,
1687
- );
2323
+ ));
2324
+ this.peekState.blocks = this.peekBlocks;
1688
2325
  this.peekState.selectedIndex = 0;
1689
2326
  this.peekState.scrollOffset = 0;
2327
+ this.peekHoveredIndex = null;
2328
+ this.peekToolPreviewIndex = null;
2329
+ this.peekToolPreviewBlockId = null;
2330
+ this.peekToolPreviewLines = [];
2331
+ this.peekToolPreviewScrollOffset = 0;
2332
+ this.expandedToolId = null;
2333
+ this.peekBlockStarts = [];
2334
+ this.peekBlockEnds = [];
1690
2335
  this.tui.requestRender();
1691
2336
  }
1692
2337
 
1693
2338
  exitPeekMode(): void {
1694
2339
  this.peekState.active = false;
1695
2340
  this.peekState.searchActive = false;
2341
+ this.peekHoveredIndex = null;
1696
2342
  this.peekSearchBuffer = "";
2343
+ this.peekToolPreviewIndex = null;
2344
+ this.peekToolPreviewBlockId = null;
2345
+ this.peekToolPreviewLines = [];
2346
+ this.peekToolPreviewScrollOffset = 0;
2347
+ this.liveToolPreviewBlock = null;
2348
+ this.toolPreviewParent = null;
2349
+ this.expandedToolId = null;
1697
2350
  this.tui.requestRender();
1698
2351
  }
1699
2352
 
1700
2353
  private rebuildPeekBlocks(): void {
1701
2354
  const entries = this.readTranscriptEntries();
1702
- this.peekBlocks = buildPeekBlocks(
2355
+ this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
1703
2356
  entries as unknown as PeekEntry[],
1704
2357
  this.peekState.showTools,
1705
- );
2358
+ ));
2359
+ this.peekState.blocks = this.peekBlocks;
1706
2360
 
1707
2361
  const maxIndex = Math.max(0, this.peekBlocks.length - 1);
1708
- this.peekState.selectedIndex = Math.min(this.peekState.selectedIndex, maxIndex);
2362
+ this.peekState.selectedIndex = this.peekBlocks.length === 0
2363
+ ? 0
2364
+ : Math.max(0, Math.min(this.peekState.selectedIndex, maxIndex));
1709
2365
  this.peekState.scrollOffset = Math.max(0, this.peekState.scrollOffset);
2366
+ this.peekHoveredIndex = null;
2367
+ // Existing line spans belong to the old transcript snapshot.
2368
+ this.peekBlockStarts = [];
2369
+ this.peekBlockEnds = [];
2370
+ this.peekRenderedLines = [];
2371
+ this.peekHeaderLines = [];
2372
+ if (this.expandedToolId !== null && !this.peekBlocks.some((block) => block.id === this.expandedToolId && hasToolPreview(block))) {
2373
+ this.expandedToolId = null;
2374
+ }
2375
+ if (this.peekToolPreviewBlockId !== null) {
2376
+ const previewIndex = this.peekBlocks.findIndex((block) => block.id === this.peekToolPreviewBlockId);
2377
+ if (previewIndex < 0 || !hasToolPreview(this.peekBlocks[previewIndex])) {
2378
+ this.peekToolPreviewIndex = null;
2379
+ this.peekToolPreviewBlockId = null;
2380
+ this.peekToolPreviewLines = [];
2381
+ this.peekToolPreviewScrollOffset = 0;
2382
+ } else {
2383
+ this.peekToolPreviewIndex = previewIndex;
2384
+ }
2385
+ }
1710
2386
  if (this.peekState.searchQuery) {
1711
2387
  this.peekState.searchMatches = findSearchMatches(
1712
2388
  this.peekBlocks,
@@ -1721,22 +2397,33 @@ export class BtwOverlayComponent extends Container implements Focusable {
1721
2397
  }
1722
2398
 
1723
2399
  private scrollPeek(delta: number): void {
2400
+ // A key can arrive before the first post-enter render. Build the line
2401
+ // spans once so scrolling and mouse selection use the same coordinates.
2402
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length !== this.peekBlocks.length) {
2403
+ this.render(this.lastRenderWidth);
2404
+ }
2405
+
1724
2406
  const maxScroll = Math.max(0, this.peekRenderedLines.length - this.peekState.viewportHeight);
1725
2407
  this.peekState.scrollOffset = Math.max(
1726
2408
  0,
1727
2409
  Math.min(maxScroll, this.peekState.scrollOffset + delta),
1728
2410
  );
1729
2411
 
1730
- // Keep the selected message aligned with the first message at or before
1731
- // the viewport, while preserving line-level scrolling within a block.
1732
- let selected = this.peekState.selectedIndex;
1733
- for (let i = 0; i < this.peekBlockStarts.length; i++) {
1734
- if (this.peekBlockStarts[i] > this.peekState.scrollOffset) break;
1735
- if (this.peekBlocks[i]?.type !== "tool-call" && this.peekBlocks[i]?.type !== "tool-result") {
2412
+ // The block containing the current top line is the one selected. Include
2413
+ // tool blocks: there is one target, not a second hidden tool focus.
2414
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length === this.peekBlocks.length) {
2415
+ let selected = 0;
2416
+ for (let i = 0; i < this.peekBlockStarts.length; i++) {
2417
+ if (this.peekBlockStarts[i] > this.peekState.scrollOffset) break;
1736
2418
  selected = i;
1737
2419
  }
2420
+ this.peekState.selectedIndex = selected;
2421
+ } else {
2422
+ this.peekState.selectedIndex = Math.max(
2423
+ 0,
2424
+ Math.min(this.peekState.selectedIndex, Math.max(0, this.peekBlocks.length - 1)),
2425
+ );
1738
2426
  }
1739
- this.peekState.selectedIndex = selected;
1740
2427
  this.tui.requestRender();
1741
2428
  }
1742
2429
 
@@ -1746,6 +2433,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1746
2433
  }
1747
2434
 
1748
2435
  private jumpPeekMessage(direction: 1 | -1): void {
2436
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length !== this.peekBlocks.length) {
2437
+ this.render(this.lastRenderWidth);
2438
+ }
1749
2439
  const isMessage = (block: PeekBlock): boolean =>
1750
2440
  block.type !== "tool-call" && block.type !== "tool-result";
1751
2441
  let target = this.peekState.selectedIndex + direction;
@@ -1761,32 +2451,40 @@ export class BtwOverlayComponent extends Container implements Focusable {
1761
2451
  }
1762
2452
 
1763
2453
  private ensurePeekVisible(): void {
2454
+ if (this.peekBlocks.length === 0) {
2455
+ this.peekState.selectedIndex = 0;
2456
+ this.peekState.scrollOffset = 0;
2457
+ return;
2458
+ }
2459
+ this.peekState.selectedIndex = Math.max(
2460
+ 0,
2461
+ Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1),
2462
+ );
1764
2463
  const start = this.peekBlockStarts[this.peekState.selectedIndex];
1765
2464
  if (start === undefined) return;
1766
2465
 
1767
- const vh = this.peekState.viewportHeight;
2466
+ const vh = Math.max(1, this.peekState.viewportHeight);
2467
+ const maxScroll = Math.max(0, this.peekRenderedLines.length - vh);
1768
2468
  if (start < this.peekState.scrollOffset) {
1769
2469
  this.peekState.scrollOffset = start;
1770
2470
  } else if (start >= this.peekState.scrollOffset + vh) {
1771
2471
  this.peekState.scrollOffset = start - vh + 1;
1772
2472
  }
2473
+ this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
1773
2474
  }
1774
2475
 
1775
2476
  private peekGoToFirst(): void {
1776
- this.peekState.selectedIndex = 0;
2477
+ this.peekState.selectedIndex = this.peekBlocks.length === 0 ? 0 : 0;
1777
2478
  this.peekState.scrollOffset = 0;
1778
2479
  this.tui.requestRender();
1779
2480
  }
1780
2481
 
1781
2482
  private peekGoToLast(): void {
1782
- let last = Math.max(0, this.peekBlocks.length - 1);
1783
- while (last > 0 && (this.peekBlocks[last]?.type === "tool-call" || this.peekBlocks[last]?.type === "tool-result")) {
1784
- last--;
1785
- }
2483
+ const last = Math.max(0, this.peekBlocks.length - 1);
1786
2484
  this.peekState.selectedIndex = last;
1787
2485
  this.peekState.scrollOffset = Math.max(
1788
2486
  0,
1789
- this.peekRenderedLines.length - this.peekState.viewportHeight,
2487
+ this.peekRenderedLines.length - Math.max(1, this.peekState.viewportHeight),
1790
2488
  );
1791
2489
  this.tui.requestRender();
1792
2490
  }
@@ -1794,8 +2492,16 @@ export class BtwOverlayComponent extends Container implements Focusable {
1794
2492
  private peekToggleTools(): void {
1795
2493
  this.peekState.showTools = !this.peekState.showTools;
1796
2494
  this.rebuildPeekBlocks();
1797
- this.peekState.selectedIndex = Math.min(this.peekState.selectedIndex, Math.max(0, this.peekBlocks.length - 1));
2495
+ this.peekState.selectedIndex = this.peekBlocks.length === 0
2496
+ ? 0
2497
+ : Math.max(0, Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1));
1798
2498
  this.peekState.scrollOffset = 0;
2499
+ this.peekHoveredIndex = null;
2500
+ this.expandedToolId = null;
2501
+ this.peekToolPreviewIndex = null;
2502
+ this.peekToolPreviewBlockId = null;
2503
+ this.peekToolPreviewLines = [];
2504
+ this.peekToolPreviewScrollOffset = 0;
1799
2505
  this.peekState.searchMatches = [];
1800
2506
  this.peekState.currentMatchIndex = -1;
1801
2507
  this.tui.requestRender();
@@ -1911,6 +2617,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1911
2617
  }
1912
2618
 
1913
2619
  private handlePeekInput(data: string): void {
2620
+ if (this.peekToolPreviewIndex !== null && this.handleToolPreviewInput(data)) {
2621
+ return;
2622
+ }
2623
+
1914
2624
  // If in search mode, capture input for search query
1915
2625
  if (this.peekState.searchActive) {
1916
2626
  if (data === "\r" || data === "\n") {
@@ -1982,6 +2692,19 @@ export class BtwOverlayComponent extends Container implements Focusable {
1982
2692
  return;
1983
2693
  }
1984
2694
 
2695
+ // Full tool input/output preview. It is intentionally a no-op for text
2696
+ // blocks and tools whose BTW data model has no input/output.
2697
+ if (data === "w") {
2698
+ this.enterToolPreview();
2699
+ return;
2700
+ }
2701
+
2702
+ // Enter can expand a tool card, but must never submit while Peek owns input.
2703
+ if (data === "\r" || data === "\n") {
2704
+ this.toggleExpandedTool();
2705
+ return;
2706
+ }
2707
+
1985
2708
  // Copy current message
1986
2709
  if (data === "M") {
1987
2710
  void this.peekCopyCurrent();
@@ -1995,12 +2718,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1995
2718
  }
1996
2719
 
1997
2720
  // Page up/down
1998
- if (data === "\x1b[5~" || data === "\x1b[5;*~") {
2721
+ if (matchesPageKey(data, 5)) {
1999
2722
  // PageUp
2000
2723
  this.scrollPeekPage(-1);
2001
2724
  return;
2002
2725
  }
2003
- if (data === "\x1b[6~" || data === "\x1b[6;*~") {
2726
+ if (matchesPageKey(data, 6)) {
2004
2727
  // PageDown
2005
2728
  this.scrollPeekPage(1);
2006
2729
  return;
@@ -2008,7 +2731,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2008
2731
 
2009
2732
  // Leaving Peek always returns to the BTW composer. The composer itself
2010
2733
  // remains responsible for dismissing the BTW overlay.
2011
- if (data === "q" || data === "\x03" || data === "\r" || data === "\n" || data === "\x1b") {
2734
+ if (data === "q" || data === "\x03" || data === "\x1b") {
2012
2735
  this.exitPeekMode();
2013
2736
  return;
2014
2737
  }
@@ -2036,8 +2759,22 @@ export default function (pi: ExtensionAPI) {
2036
2759
  let overlayRuntime: OverlayRuntime | null = null;
2037
2760
  let lastUiContext: ExtensionContext | ExtensionCommandContext | null = null;
2038
2761
  let activeBtwSession: BtwSessionRuntime | null = null;
2762
+ let btwStore: BtwTranscriptStore | null = null;
2763
+ /** The locator is published only after its snapshot reaches the store. */
2764
+ let queuedTranscriptSnapshot: DurableTranscriptSnapshot | null = null;
2765
+ let uiRefreshTimer: ReturnType<typeof setTimeout> | null = null;
2766
+ let uiRefreshContext: ExtensionContext | ExtensionCommandContext | null = null;
2767
+
2768
+ function cancelScheduledUiRefresh(): void {
2769
+ if (uiRefreshTimer !== null) {
2770
+ clearTimeout(uiRefreshTimer);
2771
+ uiRefreshTimer = null;
2772
+ }
2773
+ uiRefreshContext = null;
2774
+ }
2039
2775
 
2040
2776
  function syncUi(ctx?: ExtensionContext | ExtensionCommandContext): void {
2777
+ cancelScheduledUiRefresh();
2041
2778
  const activeCtx = ctx ?? lastUiContext;
2042
2779
  if (activeCtx?.hasUI) {
2043
2780
  activeCtx.ui.setWidget("btw", undefined);
@@ -2045,17 +2782,132 @@ export default function (pi: ExtensionAPI) {
2045
2782
  }
2046
2783
  }
2047
2784
 
2785
+ /**
2786
+ * Stable seam for live partial UI: transcript state is updated immediately,
2787
+ * while rendering is debounced so message/tool deltas share one refresh.
2788
+ */
2789
+ function scheduleUiRefresh(ctx?: ExtensionContext | ExtensionCommandContext): void {
2790
+ if (ctx) {
2791
+ lastUiContext = ctx;
2792
+ uiRefreshContext = ctx;
2793
+ } else if (!uiRefreshContext) {
2794
+ uiRefreshContext = lastUiContext;
2795
+ }
2796
+ if (uiRefreshTimer !== null) return;
2797
+ uiRefreshTimer = setTimeout(() => {
2798
+ uiRefreshTimer = null;
2799
+ const refreshContext = uiRefreshContext;
2800
+ uiRefreshContext = null;
2801
+ syncUi(refreshContext ?? undefined);
2802
+ }, BTW_UI_REFRESH_DEBOUNCE_MS);
2803
+ uiRefreshTimer.unref?.();
2804
+ }
2805
+
2048
2806
  function setOverlayStatus(status: string | null, ctx?: ExtensionContext | ExtensionCommandContext): void {
2049
2807
  overlayStatus = status;
2050
2808
  syncUi(ctx);
2051
2809
  }
2052
2810
 
2811
+ function ensureBtwStore(ctx: ExtensionContext | ExtensionCommandContext): BtwTranscriptStore {
2812
+ const sessionId = ctx.sessionManager.getSessionId();
2813
+ if (!btwStore || btwStore.threadId !== sessionId) {
2814
+ btwStore = new BtwTranscriptStore(ctx.cwd, sessionId);
2815
+ }
2816
+ return btwStore;
2817
+ }
2818
+
2819
+ function persistTranscriptState(): void {
2820
+ if (!btwStore) return;
2821
+ try {
2822
+ // Event callbacks only enqueue. The synchronous filesystem work happens
2823
+ // in the store's debounced drain, and only the newest state needs a
2824
+ // locator because snapshots are immutable and restore follows the last
2825
+ // locator on this branch.
2826
+ queuedTranscriptSnapshot = btwStore.enqueueSnapshot({
2827
+ mode: pendingMode,
2828
+ entries: transcriptState.entries as unknown as DurableTranscriptSnapshot["entries"],
2829
+ nextEntryId: transcriptState.nextEntryId,
2830
+ nextTurnId: transcriptState.nextTurnId,
2831
+ currentTurnId: transcriptState.currentTurnId,
2832
+ lastTurnId: transcriptState.lastTurnId,
2833
+ });
2834
+ } catch {
2835
+ // Durable BTW storage is best effort. The in-memory transcript remains
2836
+ // authoritative for the current overlay when a filesystem is unavailable.
2837
+ }
2838
+ }
2839
+
2840
+ /**
2841
+ * Publish the latest locator only after queued writes are durable. This is
2842
+ * used at request completion, abort/error handling, reset, and shutdown.
2843
+ */
2844
+ async function flushTranscriptState(): Promise<void> {
2845
+ const store = btwStore;
2846
+ if (!store) return;
2847
+ try {
2848
+ await store.flush();
2849
+ } catch {
2850
+ // Keep the in-memory transcript authoritative and leave failed writes in
2851
+ // the store queue for a later boundary/retry.
2852
+ return;
2853
+ }
2854
+
2855
+ const snapshot = queuedTranscriptSnapshot;
2856
+ if (!snapshot || store !== btwStore) return;
2857
+ try {
2858
+ // Keep only a small, immutable locator in the Pi session. Large tool
2859
+ // payloads remain in .pi-subagents/btw and never enter LLM context.
2860
+ pi.appendEntry(BTW_TRANSCRIPT_TYPE, makeTranscriptLocator(store, snapshot));
2861
+ if (queuedTranscriptSnapshot === snapshot) {
2862
+ queuedTranscriptSnapshot = null;
2863
+ }
2864
+ } catch {
2865
+ // The snapshot remains durable even if the host rejects the locator;
2866
+ // retrying at the next boundary keeps branch restoration best effort.
2867
+ }
2868
+ }
2869
+
2870
+ function persistToolArtifact(event: AgentSessionEvent): void {
2871
+ if (!btwStore) return;
2872
+ try {
2873
+ if (event.type === "tool_execution_start") {
2874
+ btwStore.enqueueToolArtifact({
2875
+ toolCallId: event.toolCallId,
2876
+ toolName: event.toolName,
2877
+ phase: "start",
2878
+ input: event.args,
2879
+ isError: false,
2880
+ });
2881
+ } else if (event.type === "tool_execution_update") {
2882
+ btwStore.enqueueToolArtifact({
2883
+ toolCallId: event.toolCallId,
2884
+ toolName: event.toolName,
2885
+ phase: "update",
2886
+ output: event.partialResult,
2887
+ isError: false,
2888
+ });
2889
+ } else if (event.type === "tool_execution_end") {
2890
+ btwStore.enqueueToolArtifact({
2891
+ toolCallId: event.toolCallId,
2892
+ toolName: event.toolName,
2893
+ phase: "end",
2894
+ output: event.result,
2895
+ isError: event.isError,
2896
+ });
2897
+ }
2898
+ } catch {
2899
+ // Tool artifacts are diagnostics; a failed artifact write must not abort
2900
+ // the side conversation or change its visible transcript.
2901
+ }
2902
+ }
2903
+
2053
2904
  function setOverlayDraft(value: string): void {
2054
2905
  overlayDraft = value;
2055
2906
  overlayRuntime?.setDraft?.(value);
2056
2907
  }
2057
2908
 
2058
2909
  function dismissOverlay(): void {
2910
+ cancelScheduledUiRefresh();
2059
2911
  overlayRuntime?.close?.();
2060
2912
  overlayRuntime = null;
2061
2913
  }
@@ -2109,11 +2961,17 @@ export default function (pi: ExtensionAPI) {
2109
2961
  event: AgentSessionEvent,
2110
2962
  ctx?: ExtensionContext | ExtensionCommandContext,
2111
2963
  ): void {
2112
- if (activeBtwSession?.session !== sessionRuntime.session || !overlayRuntime) {
2964
+ if (activeBtwSession?.session !== sessionRuntime.session) {
2113
2965
  return;
2114
2966
  }
2115
2967
 
2968
+ persistToolArtifact(event);
2116
2969
  applyTranscriptEvent(transcriptState, event);
2970
+ persistTranscriptState();
2971
+
2972
+ if (!overlayRuntime) {
2973
+ return;
2974
+ }
2117
2975
 
2118
2976
  if (event.type === "tool_execution_start") {
2119
2977
  setOverlayStatus(`⏳ running tool: ${event.toolName}`, ctx);
@@ -2134,9 +2992,12 @@ export default function (pi: ExtensionAPI) {
2134
2992
  event.type === "message_start" ||
2135
2993
  event.type === "message_update" ||
2136
2994
  event.type === "message_end" ||
2995
+ event.type === "tool_execution_update" ||
2137
2996
  event.type === "turn_start"
2138
2997
  ) {
2139
- syncUi(ctx);
2998
+ // Partial assistant/tool events can arrive at token cadence. State is
2999
+ // already current; only the presentation is coalesced.
3000
+ scheduleUiRefresh(ctx);
2140
3001
  }
2141
3002
  }
2142
3003
 
@@ -2156,6 +3017,7 @@ export default function (pi: ExtensionAPI) {
2156
3017
  const current = activeBtwSession;
2157
3018
  activeBtwSession = null;
2158
3019
  if (!current) {
3020
+ await flushTranscriptState();
2159
3021
  return;
2160
3022
  }
2161
3023
 
@@ -2168,6 +3030,10 @@ export default function (pi: ExtensionAPI) {
2168
3030
  }
2169
3031
 
2170
3032
  current.session.dispose();
3033
+ // Subscription removal intentionally prevents abort-generated events from
3034
+ // mutating a replacement session. The already queued state still needs an
3035
+ // explicit durable boundary.
3036
+ await flushTranscriptState();
2171
3037
  }
2172
3038
 
2173
3039
  async function dismissOverlaySession(): Promise<void> {
@@ -2400,6 +3266,7 @@ export default function (pi: ExtensionAPI) {
2400
3266
  },
2401
3267
  undefined,
2402
3268
  ctx.cwd,
3269
+ (toolCallId) => btwStore?.readToolArtifact(toolCallId) ?? null,
2403
3270
  );
2404
3271
 
2405
3272
  overlay.focused = runtime.handle?.isFocused() ?? true;
@@ -2677,6 +3544,9 @@ export default function (pi: ExtensionAPI) {
2677
3544
  pendingThread = [];
2678
3545
  pendingMode = mode;
2679
3546
  transcriptState = createEmptyTranscriptState();
3547
+ ensureBtwStore(ctx);
3548
+ persistTranscriptState();
3549
+ await flushTranscriptState();
2680
3550
  setOverlayDraft("");
2681
3551
  setOverlayStatus(null, ctx);
2682
3552
  if (persist) {
@@ -2696,9 +3566,12 @@ export default function (pi: ExtensionAPI) {
2696
3566
  overlayDraft = "";
2697
3567
  lastUiContext = ctx;
2698
3568
  overlayStatus = null;
3569
+ btwStore = new BtwTranscriptStore(ctx.cwd, ctx.sessionManager.getSessionId());
3570
+ queuedTranscriptSnapshot = null;
2699
3571
 
2700
3572
  const branch = ctx.sessionManager.getBranch();
2701
3573
  let lastResetIndex = -1;
3574
+ let transcriptLocator: { schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION; threadId: string; recordId: string } | null = null;
2702
3575
 
2703
3576
  for (let i = 0; i < branch.length; i++) {
2704
3577
  if (isCustomEntry(branch[i], BTW_MODEL_OVERRIDE_TYPE)) {
@@ -2720,7 +3593,9 @@ export default function (pi: ExtensionAPI) {
2720
3593
  const details = (branch[i] as unknown as { data?: BtwThinkingOverrideDetails }).data;
2721
3594
  btwThinkingOverride =
2722
3595
  details?.action === "set"
2723
- ? details.thinkingLevel
3596
+ ? isSessionThinkingLevel(details.thinkingLevel)
3597
+ ? details.thinkingLevel
3598
+ : null
2724
3599
  : details?.action === "clear"
2725
3600
  ? null
2726
3601
  : btwThinkingOverride;
@@ -2728,9 +3603,42 @@ export default function (pi: ExtensionAPI) {
2728
3603
 
2729
3604
  if (isCustomEntry(branch[i], BTW_RESET_TYPE)) {
2730
3605
  lastResetIndex = i;
3606
+ transcriptLocator = null;
2731
3607
  const details = (branch[i] as unknown as { data?: BtwResetDetails }).data;
2732
3608
  pendingMode = details?.mode ?? "contextual";
2733
3609
  }
3610
+
3611
+ if (i > lastResetIndex && isCustomEntry(branch[i], BTW_TRANSCRIPT_TYPE)) {
3612
+ const details = (branch[i] as unknown as { data?: unknown }).data;
3613
+ if (isTranscriptLocator(details)) {
3614
+ transcriptLocator = details;
3615
+ }
3616
+ }
3617
+ }
3618
+
3619
+ // A branch must opt into a persisted snapshot through its locator. Never
3620
+ // fall back to the newest file record here: the same session can have
3621
+ // divergent branches and that would leak one branch's BTW transcript into
3622
+ // another branch.
3623
+ const restored = transcriptLocator && transcriptLocator.threadId === btwStore.threadId
3624
+ ? btwStore.readSnapshot(transcriptLocator.recordId)
3625
+ : null;
3626
+ if (restored) {
3627
+ transcriptState = {
3628
+ entries: restored.snapshot.entries as unknown as BtwTranscript,
3629
+ nextEntryId: restored.snapshot.nextEntryId,
3630
+ nextTurnId: restored.snapshot.nextTurnId,
3631
+ currentTurnId: restored.snapshot.currentTurnId,
3632
+ lastTurnId: restored.snapshot.lastTurnId,
3633
+ toolCalls: restored.toolCalls,
3634
+ };
3635
+ pendingMode = restored.snapshot.mode;
3636
+ if (closeRestoredStreamingTurns(transcriptState)) {
3637
+ // Make the recovery durable immediately so another reload observes the
3638
+ // same closed historical turn instead of reviving a dead stream.
3639
+ persistTranscriptState();
3640
+ await flushTranscriptState();
3641
+ }
2734
3642
  }
2735
3643
 
2736
3644
  for (const entry of branch.slice(lastResetIndex + 1)) {
@@ -2745,13 +3653,27 @@ export default function (pi: ExtensionAPI) {
2745
3653
 
2746
3654
  const normalizedDetails: BtwDetails = {
2747
3655
  ...details,
3656
+ schemaVersion: details.schemaVersion === BTW_TRANSCRIPT_SCHEMA_VERSION
3657
+ ? details.schemaVersion
3658
+ : BTW_TRANSCRIPT_SCHEMA_VERSION,
2748
3659
  api: details.api || ctx.model?.api || "openai-responses",
2749
3660
  };
2750
3661
 
2751
3662
  pendingThread.push(normalizedDetails);
2752
- appendPersistedTranscriptTurn(transcriptState, normalizedDetails);
3663
+ if (!restored) {
3664
+ appendPersistedTranscriptTurn(transcriptState, normalizedDetails);
3665
+ }
2753
3666
  }
2754
3667
 
3668
+ // Sessions created before durable BTW storage still get a first snapshot
3669
+ // after restore, while current sessions retain the exact persisted state.
3670
+ if (!restored && pendingThread.length > 0) {
3671
+ persistTranscriptState();
3672
+ await flushTranscriptState();
3673
+ }
3674
+ // Also drain a recovery snapshot if the branch had one but no legacy
3675
+ // entries; restore must never return with a locator still only in memory.
3676
+ await flushTranscriptState();
2755
3677
  syncUi(ctx);
2756
3678
  }
2757
3679
 
@@ -2762,6 +3684,7 @@ export default function (pi: ExtensionAPI) {
2762
3684
  mode: BtwThreadMode,
2763
3685
  ): Promise<void> {
2764
3686
  lastUiContext = ctx;
3687
+ ensureBtwStore(ctx);
2765
3688
  const settings = await resolveBtwSettings(ctx);
2766
3689
  const model = settings.model;
2767
3690
  if (!model) {
@@ -2804,6 +3727,8 @@ export default function (pi: ExtensionAPI) {
2804
3727
  }
2805
3728
  if (response.stopReason === "aborted") {
2806
3729
  removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
3730
+ persistTranscriptState();
3731
+ await flushTranscriptState();
2807
3732
  setOverlayStatus("Request aborted.", ctx);
2808
3733
  return;
2809
3734
  }
@@ -2818,6 +3743,7 @@ export default function (pi: ExtensionAPI) {
2818
3743
  const thinking = extractThinking(response) || streamedThinking || "";
2819
3744
 
2820
3745
  const details: BtwDetails = {
3746
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
2821
3747
  question,
2822
3748
  thinking,
2823
3749
  answer,
@@ -2831,6 +3757,8 @@ export default function (pi: ExtensionAPI) {
2831
3757
 
2832
3758
  pendingThread.push(details);
2833
3759
  pi.appendEntry(BTW_ENTRY_TYPE, details);
3760
+ persistTranscriptState();
3761
+ await flushTranscriptState();
2834
3762
 
2835
3763
  const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
2836
3764
  if (saveState === "saved") {
@@ -2845,6 +3773,8 @@ export default function (pi: ExtensionAPI) {
2845
3773
  } catch (error) {
2846
3774
  const errorMessage = error instanceof Error ? error.message : String(error);
2847
3775
  setTranscriptFailure(transcriptState, errorMessage);
3776
+ persistTranscriptState();
3777
+ await flushTranscriptState();
2848
3778
  setOverlayStatus("Request failed. Thread preserved for retry or follow-up.", ctx);
2849
3779
  notify(ctx, errorMessage, "error");
2850
3780
  await disposeBtwSession();
@@ -2968,7 +3898,9 @@ export default function (pi: ExtensionAPI) {
2968
3898
  });
2969
3899
 
2970
3900
  pi.on("session_shutdown", async () => {
3901
+ cancelScheduledUiRefresh();
2971
3902
  await disposeBtwSession();
3903
+ await flushTranscriptState();
2972
3904
  dismissOverlay();
2973
3905
  });
2974
3906