pi-render-btw 0.6.9 → 0.6.11

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,54 @@ 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
+
79
+ function findFdPath(): string | null {
80
+ const lookup = process.platform === "win32" ? "where" : "which";
81
+ for (const candidate of process.platform === "win32" ? ["fd.exe", "fd"] : ["fd", "fdfind"]) {
82
+ const result = spawnSync(lookup, [candidate], { encoding: "utf8" });
83
+ if (result.status === 0) {
84
+ const resolved = String(result.stdout ?? "").split(/\r?\n/).find(Boolean)?.trim();
85
+ if (resolved) return resolved;
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+
60
91
  const BTW_SYSTEM_PROMPT = [
61
92
  "You are having an aside conversation with the user, separate from their main working session.",
62
93
  "If main session messages are provided, they are for context only — that work is being handled by another agent.",
@@ -81,6 +112,8 @@ type SessionModel = NonNullable<ExtensionCommandContext["model"]>;
81
112
  type BtwModelRef = Pick<SessionModel, "provider" | "id" | "api">;
82
113
 
83
114
  type BtwDetails = {
115
+ /** Versioned so old btw-thread-entry details remain readable on restore. */
116
+ schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
84
117
  question: string;
85
118
  thinking: string;
86
119
  answer: string;
@@ -104,6 +137,20 @@ type BtwResetDetails = {
104
137
  mode?: BtwThreadMode;
105
138
  };
106
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
+
107
154
  type BtwModelOverrideDetails =
108
155
  | ({ timestamp: number; action: "set" } & Pick<SessionModel, "provider" | "id" | "api">)
109
156
  | { timestamp: number; action: "clear" };
@@ -140,7 +187,10 @@ type BtwTranscriptEntry =
140
187
  type: "tool-result";
141
188
  toolCallId: string;
142
189
  toolName: string;
190
+ /** Compact text used by the normal transcript row. */
143
191
  content: string;
192
+ /** Full result retained for the read-only Peek preview. */
193
+ fullContent?: string;
144
194
  truncated: boolean;
145
195
  isError: boolean;
146
196
  streaming: boolean;
@@ -385,19 +435,15 @@ function formatToolPreview(value: unknown): string {
385
435
  return value;
386
436
  }
387
437
 
388
- if (value && typeof value === "object") {
389
- const path = (value as { path?: unknown }).path;
390
- if (typeof path === "string") {
391
- return path;
392
- }
393
- }
394
-
395
438
  try {
396
439
  const preview = JSON.stringify(value);
397
440
  if (!preview || preview === "{}") {
398
441
  return "";
399
442
  }
400
- 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;
401
447
  } catch {
402
448
  return "";
403
449
  }
@@ -559,7 +605,7 @@ function upsertTranscriptTextEntry(
559
605
  appendTranscriptEntry(state, { type, turnId, text, streaming } as Omit<Extract<BtwTranscriptEntry, { type: "thinking" | "assistant-text" }>, "id">);
560
606
  }
561
607
 
562
- function summarizeToolResult(value: unknown, maxLength = 400): { content: string; truncated: boolean } {
608
+ function summarizeToolResult(value: unknown, maxLength = 400): { content: string; fullContent: string; truncated: boolean } {
563
609
  let content = "";
564
610
 
565
611
  if (value && typeof value === "object") {
@@ -605,6 +651,7 @@ function summarizeToolResult(value: unknown, maxLength = 400): { content: string
605
651
  const truncated = content.length > maxLength;
606
652
  return {
607
653
  content: truncated ? `${content.slice(0, maxLength - 3)}...` : content,
654
+ fullContent: content,
608
655
  truncated,
609
656
  };
610
657
  }
@@ -639,6 +686,7 @@ function upsertToolResultEntry(
639
686
  toolCallId: string,
640
687
  toolName: string,
641
688
  content: string,
689
+ fullContent: string,
642
690
  truncated: boolean,
643
691
  isError: boolean,
644
692
  streaming: boolean,
@@ -651,6 +699,7 @@ function upsertToolResultEntry(
651
699
 
652
700
  if (existing && existing.type === "tool-result") {
653
701
  existing.content = content;
702
+ existing.fullContent = fullContent;
654
703
  existing.truncated = truncated;
655
704
  existing.isError = isError;
656
705
  existing.streaming = streaming;
@@ -663,6 +712,7 @@ function upsertToolResultEntry(
663
712
  toolCallId,
664
713
  toolName,
665
714
  content,
715
+ fullContent,
666
716
  truncated,
667
717
  isError,
668
718
  streaming,
@@ -744,6 +794,7 @@ function applyTranscriptEvent(state: BtwTranscriptState, event: AgentSessionEven
744
794
  event.toolCallId,
745
795
  event.toolName,
746
796
  result.content,
797
+ result.fullContent,
747
798
  result.truncated,
748
799
  false,
749
800
  true,
@@ -759,6 +810,7 @@ function applyTranscriptEvent(state: BtwTranscriptState, event: AgentSessionEven
759
810
  event.toolCallId,
760
811
  event.toolName,
761
812
  result.content,
813
+ result.fullContent,
762
814
  result.truncated,
763
815
  event.isError,
764
816
  false,
@@ -784,6 +836,40 @@ function appendPersistedTranscriptTurn(state: BtwTranscriptState, details: BtwDe
784
836
  finishTranscriptTurn(state, turnId);
785
837
  }
786
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
+
787
873
  function setTranscriptFailure(state: BtwTranscriptState, message: string): void {
788
874
  const turnId = state.currentTurnId ?? state.lastTurnId ?? ensureTranscriptTurn(state);
789
875
  upsertTranscriptTextEntry(state, turnId, "assistant-text", `❌ ${message}`, false);
@@ -1052,13 +1138,20 @@ export class BtwOverlayComponent extends Container implements Focusable {
1052
1138
  private readonly onDismissCallback: () => void;
1053
1139
  private readonly onUnfocusCallback: () => void;
1054
1140
  private readonly onExternalEditorCallback?: () => void;
1141
+ private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1055
1142
  private externalEditorActive = false;
1056
1143
  private readonly tui: TUI;
1057
1144
  private readonly theme: ExtensionContext["ui"]["theme"];
1058
1145
  private transcriptLines: string[] = [];
1146
+ /** Rendered transcript line -> source entry id; separators/padding are null. */
1147
+ private transcriptLineEntryIds: Array<number | null> = [];
1059
1148
  private transcriptScrollOffset = 0;
1060
1149
  private transcriptViewportHeight = 8;
1061
1150
  private followTranscript = true;
1151
+ private liveHoveredEntryId: number | null = null;
1152
+ private liveFocusedEntryId: number | null = null;
1153
+ private liveFocusedToolCallId: string | null = null;
1154
+ private liveExpandedToolCallId: string | null = null;
1062
1155
  private _focused = false;
1063
1156
  private modeTextValue = "";
1064
1157
  private summaryTextValue = "";
@@ -1070,8 +1163,24 @@ export class BtwOverlayComponent extends Container implements Focusable {
1070
1163
  private peekBlocks: PeekBlock[] = [];
1071
1164
  private peekRenderedLines: string[] = [];
1072
1165
  private peekBlockStarts: number[] = [];
1166
+ private peekBlockEnds: number[] = [];
1073
1167
  private peekHeaderLines: string[] = [];
1168
+ private peekStickyHeaderIndex: number | null = null;
1074
1169
  private peekSearchBuffer = "";
1170
+ private peekHoveredIndex: number | null = null;
1171
+ private peekToolPreviewIndex: number | null = null;
1172
+ private peekToolPreviewBlockId: number | null = null;
1173
+ private peekToolPreviewLines: string[] = [];
1174
+ private peekToolPreviewScrollOffset = 0;
1175
+ private expandedToolId: number | null = null;
1176
+ /** The same bounded preview is used by Peek and by the live BTW panel. */
1177
+ private toolPreviewParent: "peek" | "live" | null = null;
1178
+ private liveToolPreviewBlock: PeekBlock | null = null;
1179
+ private lastRenderWidth = 80;
1180
+ // SGR mouse coordinates are one-based. Peek content starts at row 4;
1181
+ // live transcript content starts at row 5 after its title/rules.
1182
+ private peekContentTop = 4;
1183
+ private transcriptContentTop = 5;
1075
1184
 
1076
1185
  get focused(): boolean {
1077
1186
  return this._focused;
@@ -1094,6 +1203,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1094
1203
  onUnfocus: () => void,
1095
1204
  onExternalEditor?: () => void,
1096
1205
  cwd?: string,
1206
+ readToolArtifact?: (toolCallId: string) => ToolArtifact | null,
1097
1207
  ) {
1098
1208
  super();
1099
1209
  this.tui = tui;
@@ -1105,6 +1215,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1105
1215
  this.onDismissCallback = onDismiss;
1106
1216
  this.onUnfocusCallback = onUnfocus;
1107
1217
  this.onExternalEditorCallback = onExternalEditor;
1218
+ this.readToolArtifact = readToolArtifact;
1108
1219
 
1109
1220
  this.modeText = new Text("", 1, 0);
1110
1221
  this.summaryText = new Text("", 1, 0);
@@ -1136,16 +1247,13 @@ export class BtwOverlayComponent extends Container implements Focusable {
1136
1247
 
1137
1248
  // Wire up autocomplete (file-path completion only, no commands)
1138
1249
  const cwdPath = cwd ?? process.cwd();
1139
- const autocompleteProvider = new CombinedAutocompleteProvider([], cwdPath);
1250
+ const autocompleteProvider = new CombinedAutocompleteProvider([], cwdPath, findFdPath());
1140
1251
  this.input.setAutocompleteProvider(autocompleteProvider);
1141
1252
 
1142
1253
  this.peekState = createPeekState();
1143
1254
  this.hintsText = new Text("", 1, 0);
1144
1255
  this.mdTheme = getMarkdownTheme();
1145
1256
 
1146
- // Enable SGR mouse reporting so wheel/touchpad events reach handleInput().
1147
- this.tui.terminal?.write?.("\x1b[?1000h\x1b[?1006h");
1148
-
1149
1257
  const originalHandleInput = this.input.handleInput.bind(this.input);
1150
1258
  this.input.handleInput = (data: string) => {
1151
1259
  if (keybindings.matches(data, "app.editor.external")) {
@@ -1223,6 +1331,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1223
1331
  return this.theme.fg("border", `${left}${"─".repeat(innerWidth)}${right}`);
1224
1332
  }
1225
1333
 
1334
+ private titleLine(title: string, innerWidth: number): string {
1335
+ const escapeHint = this.theme.fg("dim", "[Esc]");
1336
+ const gap = Math.max(1, innerWidth - visibleWidth(title) - visibleWidth(escapeHint));
1337
+ return this.frameLine(`${title}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1338
+ }
1339
+
1226
1340
  private wrapTranscript(innerWidth: number): string[] {
1227
1341
  const wrapped: string[] = [];
1228
1342
  for (const line of this.transcriptLines) {
@@ -1238,17 +1352,26 @@ export class BtwOverlayComponent extends Container implements Focusable {
1238
1352
  private buildTranscriptLines(innerWidth: number): string[] {
1239
1353
  const entries = this.readTranscriptEntries();
1240
1354
  if (entries.length === 0) {
1355
+ this.transcriptLineEntryIds = [null];
1241
1356
  return [this.theme.fg("dim", "No BTW thread yet. Ask a side question to start one.")];
1242
1357
  }
1243
1358
 
1244
1359
  const allLines: string[] = [];
1245
- const userBadge = buildTranscriptBadge(this.theme, "You", "userMessageBg", "accent");
1246
- const thinkingBadge = buildTranscriptBadge(this.theme, "Thinking", "toolPendingBg", "warning");
1247
- const toolBadge = buildTranscriptBadge(this.theme, "Tool", "toolPendingBg", "warning");
1248
- const assistantBadge = buildTranscriptBadge(this.theme, "Assistant", "customMessageBg", "success");
1360
+ const lineEntryIds: Array<number | null> = [];
1361
+ const markBlock = (entryId: number, start: number): void => {
1362
+ const plain = (line: string) => line.replace(/\x1b\[[0-9;?]*[ -\/]*[@-~]/g, "");
1363
+ for (let index = start; index < allLines.length; index++) {
1364
+ const value = plain(allLines[index]);
1365
+ lineEntryIds[index] = value.trim() && !/^─+$/.test(value.trim()) ? entryId : null;
1366
+ }
1367
+ };
1368
+ const focusRail = (entryId: number): string =>
1369
+ this.liveFocusedEntryId === entryId ? "▎ " : this.liveHoveredEntryId === entryId ? "│ " : "";
1370
+ const userBadge = buildTranscriptBadge(this.theme, "USER", "userMessageBg", "accent");
1371
+ const thinkingBadge = buildTranscriptBadge(this.theme, "THINKING", "toolPendingBg", "warning");
1372
+ const assistantBadge = buildTranscriptBadge(this.theme, "ASSISTANT", "customMessageBg", "success");
1249
1373
  const separator = this.theme.fg("borderMuted", "─".repeat(40));
1250
1374
  const blockIndent = " ";
1251
- const resultIndent = blockIndent;
1252
1375
  const mdContentWidth = Math.max(1, innerWidth - visibleWidth(blockIndent));
1253
1376
 
1254
1377
  const pushBlank = (): void => {
@@ -1258,6 +1381,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1258
1381
  };
1259
1382
 
1260
1383
  for (const entry of entries) {
1384
+ const blockStart = allLines.length;
1261
1385
  if (entry.type === "turn-boundary") {
1262
1386
  if (entry.phase === "start" && allLines.length > 0) {
1263
1387
  pushBlank();
@@ -1268,67 +1392,81 @@ export class BtwOverlayComponent extends Container implements Focusable {
1268
1392
 
1269
1393
  if (entry.type === "user-message") {
1270
1394
  pushBlank();
1271
- allLines.push(userBadge);
1272
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1273
- for (const line of styledLines) {
1274
- allLines.push(`${blockIndent}${line}`);
1395
+ allLines.push(`${focusRail(entry.id)}${userBadge}`);
1396
+ const boundedText = entry.text.length > 16_000 ? `${entry.text.slice(0, 15_970)}\n… [truncated]` : entry.text;
1397
+ const mdLines = new Markdown(boundedText || "∅", 0, 0, this.mdTheme).render(mdContentWidth);
1398
+ for (const line of mdLines) {
1399
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1275
1400
  }
1401
+ markBlock(entry.id, blockStart);
1276
1402
  continue;
1277
1403
  }
1278
1404
 
1279
1405
  if (entry.type === "thinking") {
1280
1406
  const thinkingHeader = entry.streaming ? `${thinkingBadge} ${this.theme.fg("warning", "▍")}` : thinkingBadge;
1281
1407
  pushBlank();
1282
- allLines.push(thinkingHeader);
1408
+ allLines.push(`${focusRail(entry.id)}${thinkingHeader}`);
1283
1409
  const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1284
1410
  for (const line of styledLines) {
1285
1411
  allLines.push(`${blockIndent}${this.theme.fg("warning", this.theme.italic(line))}`);
1286
1412
  }
1413
+ markBlock(entry.id, blockStart);
1287
1414
  continue;
1288
1415
  }
1289
1416
 
1290
1417
  if (entry.type === "tool-call") {
1291
- const toolLabel = this.theme.fg("warning", this.theme.bold(entry.toolName));
1292
- const argsLabel = entry.args ? this.theme.fg("dim", ` · ${entry.args}`) : "";
1418
+ const toolLabel = this.theme.fg("toolTitle", this.theme.bold(`· TOOL ${entry.toolName}`));
1419
+ const argsLabel = entry.args ? this.theme.fg("dim", ` → ${entry.args}`) : "";
1420
+ const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1421
+ const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1293
1422
  pushBlank();
1294
- allLines.push(`${toolBadge} ${toolLabel}${argsLabel}`);
1423
+ allLines.push(`${focusRail(entry.id)}${toolLabel}${argsLabel}${moreLabel}`);
1424
+ if (isExpanded && entry.args) {
1425
+ for (const line of wrapTextWithAnsi(entry.args, mdContentWidth)) {
1426
+ allLines.push(`${blockIndent}${this.theme.fg("dim", line)}`);
1427
+ }
1428
+ }
1429
+ markBlock(entry.id, blockStart);
1295
1430
  continue;
1296
1431
  }
1297
1432
 
1298
1433
  if (entry.type === "tool-result") {
1299
- const resultHeader = entry.isError
1300
- ? this.theme.fg("error", "↳ error")
1301
- : entry.streaming
1302
- ? this.theme.fg("warning", "↳ streaming result")
1303
- : this.theme.fg("dim", "↳ result");
1304
- const truncLabel = entry.truncated ? this.theme.fg("dim", " (truncated)") : "";
1434
+ const resultIcon = entry.isError ? "✗" : "✓";
1435
+ const resultColor = entry.isError ? "error" : entry.streaming ? "warning" : "dim";
1436
+ const resultLabel = this.theme.fg(resultColor, ` ↳ ${resultIcon} ${entry.toolName}`);
1437
+ const summary = this.theme.fg(resultColor, ` · ${getToolResultSummary(entry.content)}`);
1438
+ const truncLabel = entry.truncated ? this.theme.fg("dim", " · truncated") : "";
1439
+ const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1440
+ const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1305
1441
  pushBlank();
1306
- allLines.push(`${resultHeader}${truncLabel}`);
1307
- const styledLines = wrapTextWithAnsi(entry.content, mdContentWidth);
1308
- for (const line of styledLines) {
1309
- allLines.push(`${resultIndent}${entry.isError ? this.theme.fg("error", line) : this.theme.fg("dim", line)}`);
1442
+ allLines.push(`${focusRail(entry.id)}${resultLabel}${summary}${truncLabel}${moreLabel}`);
1443
+ if (isExpanded) {
1444
+ for (const line of wrapTextWithAnsi(entry.fullContent ?? entry.content, mdContentWidth)) {
1445
+ allLines.push(`${blockIndent}${this.theme.fg(entry.isError ? "error" : "dim", line)}`);
1446
+ }
1310
1447
  }
1448
+ markBlock(entry.id, blockStart);
1311
1449
  continue;
1312
1450
  }
1313
1451
 
1314
1452
  if (entry.type === "assistant-text") {
1315
1453
  pushBlank();
1316
1454
  const header = entry.streaming ? `${assistantBadge} ${this.theme.fg("warning", "▍")}` : assistantBadge;
1317
- allLines.push(header);
1455
+ allLines.push(`${focusRail(entry.id)}${header}`);
1318
1456
 
1319
1457
  if (!entry.streaming) {
1320
1458
  // Render markdown for completed text — use cached result when available
1321
1459
  const cached = this.mdLineCache.get(entry.id);
1322
1460
  if (cached && cached.renderedAtWidth === mdContentWidth) {
1323
1461
  for (const line of cached.lines) {
1324
- allLines.push(`${blockIndent}${line}`);
1462
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1325
1463
  }
1326
1464
  } else {
1327
1465
  const md = new Markdown(entry.text, 0, 0, this.mdTheme);
1328
1466
  const mdLines = md.render(mdContentWidth);
1329
1467
  this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1330
1468
  for (const line of mdLines) {
1331
- allLines.push(`${blockIndent}${line}`);
1469
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1332
1470
  }
1333
1471
  }
1334
1472
  } else {
@@ -1338,44 +1476,229 @@ export class BtwOverlayComponent extends Container implements Focusable {
1338
1476
  allLines.push(`${blockIndent}${line}`);
1339
1477
  }
1340
1478
  }
1479
+ markBlock(entry.id, blockStart);
1341
1480
  continue;
1342
1481
  }
1343
1482
  }
1344
1483
 
1484
+ this.transcriptLineEntryIds = lineEntryIds;
1345
1485
  return allLines;
1346
1486
  }
1347
1487
 
1348
1488
  private getDialogHeight(inputLines: number): number {
1349
- const terminalRows = process.stdout.rows ?? 30;
1350
- const minHeight = Math.max(14, 8 + inputLines + 6); // chrome + input + min transcript
1351
- const maxHeight = Math.min(40, Math.floor(terminalRows * 0.82));
1352
- return Math.max(minHeight, Math.min(maxHeight, Math.floor(terminalRows * 0.78)));
1489
+ // Prefer the host TUI's measured viewport. Falling back to stdout keeps
1490
+ // this component usable in lightweight tests and non-interactive hosts.
1491
+ const terminalRows = Math.max(
1492
+ 1,
1493
+ this.tui.terminal?.rows ?? process.stdout.rows ?? 30,
1494
+ );
1495
+ const preferred = Math.floor(terminalRows * 0.78);
1496
+ const maxHeight = Math.max(1, Math.min(40, terminalRows));
1497
+ const minHeight = Math.min(maxHeight, Math.max(8, 8 + inputLines + 3));
1498
+ return Math.min(maxHeight, Math.max(minHeight, preferred));
1353
1499
  }
1354
1500
 
1355
1501
  private scrollTranscript(delta: number): void {
1502
+ // Wheel input can arrive before the first overlay render. Build the same
1503
+ // line cache used by rendering so the first wheel tick is not lost.
1504
+ if (this.transcriptLines.length === 0 && this.readTranscriptEntries().length > 0) {
1505
+ this.render(this.lastRenderWidth);
1506
+ }
1356
1507
  if (delta < 0) {
1357
1508
  this.followTranscript = false;
1358
1509
  }
1359
- this.transcriptScrollOffset = Math.max(0, this.transcriptScrollOffset + delta);
1510
+ const maxScroll = Math.max(0, this.transcriptLines.length - this.transcriptViewportHeight);
1511
+ this.transcriptScrollOffset = Math.max(
1512
+ 0,
1513
+ Math.min(maxScroll, this.transcriptScrollOffset + delta),
1514
+ );
1515
+ if (this.transcriptScrollOffset >= maxScroll) {
1516
+ this.followTranscript = true;
1517
+ }
1360
1518
  this.tui.requestRender();
1361
1519
  }
1362
1520
 
1363
1521
  dispose(): void {
1364
- this.tui.terminal?.write?.("\x1b[?1000l\x1b[?1006l");
1522
+ // Mouse reporting is owned by the host TUI. This component only handles
1523
+ // normalized events (or passively parses an event already delivered to it).
1365
1524
  }
1366
1525
 
1367
1526
  private getMouseScrollDelta(data: string): number | null {
1368
- const match = data.match(/^\x1b\[<(\d+);\d+;\d+[Mm]$/);
1369
- if (!match) {
1370
- return null;
1527
+ const event = parsePeekMouseInput(data);
1528
+ if (!event || event.action !== "wheel") return null;
1529
+ // Match the normalized TUI path and the subagent viewer: one logical
1530
+ // wheel unit means one rendered line. Do not apply a second multiplier.
1531
+ return Math.trunc(event.delta ?? 0);
1532
+ }
1533
+
1534
+ private transcriptEntryAtLine(y: number): number | null {
1535
+ const localLine = y - this.transcriptContentTop;
1536
+ if (localLine < 0 || localLine >= this.transcriptViewportHeight) return null;
1537
+ const line = this.transcriptScrollOffset + localLine;
1538
+ return this.transcriptLineEntryIds[line] ?? null;
1539
+ }
1540
+
1541
+ private focusLiveTranscriptEntry(entryId: number): boolean {
1542
+ const entry = this.readTranscriptEntries().find((candidate) => candidate.id === entryId);
1543
+ if (!entry || entry.type === "turn-boundary") return false;
1544
+ this.liveFocusedEntryId = entryId;
1545
+ this.liveHoveredEntryId = entryId;
1546
+ this.liveFocusedToolCallId = entry.type === "tool-call" || entry.type === "tool-result"
1547
+ ? entry.toolCallId ?? null
1548
+ : null;
1549
+ this.tui.requestRender();
1550
+ return true;
1551
+ }
1552
+
1553
+ private peekIndexAtLine(y: number): number | null {
1554
+ if (this.peekBlockStarts.length !== this.peekBlocks.length) return null;
1555
+ const localLine = y - this.peekContentTop;
1556
+ if (localLine < 0 || localLine >= this.peekState.viewportHeight) return null;
1557
+ if (localLine === 0 && this.peekStickyHeaderIndex !== null) {
1558
+ return this.peekStickyHeaderIndex;
1559
+ }
1560
+
1561
+ const line = this.peekState.scrollOffset + localLine;
1562
+ for (let index = 0; index < this.peekBlocks.length; index++) {
1563
+ const start = this.peekBlockStarts[index];
1564
+ const end = this.peekBlockEnds[index] ?? start;
1565
+ if (line >= start && line < end) return index;
1566
+ }
1567
+ return null;
1568
+ }
1569
+
1570
+ /**
1571
+ * Viewer-local mouse seam. Newer Pi TUI hosts call `handleMouse` with
1572
+ * zero-based `{ type, button, x, y, wheelDelta }` events; older hosts and
1573
+ * tests can pass the one-based normalized SGR shape from `peek.ts`.
1574
+ *
1575
+ * Only an explicit left click is actionable. Press/release are consumed
1576
+ * without changing selection, focus, expansion, or the composer draft.
1577
+ */
1578
+ handleMouse(event: PeekMouseEvent | {
1579
+ type: "press" | "release" | "move" | "drag" | "click" | "wheel";
1580
+ button: "left" | "middle" | "right" | "none" | number;
1581
+ x: number;
1582
+ y: number;
1583
+ clickCount?: number;
1584
+ wheelDelta?: number;
1585
+ }): any {
1586
+ const normalized: PeekMouseEvent = "action" in event
1587
+ ? event
1588
+ : {
1589
+ action: event.type === "wheel"
1590
+ ? "wheel"
1591
+ : event.type === "click"
1592
+ ? "click"
1593
+ : event.type === "release"
1594
+ ? "release"
1595
+ : event.type,
1596
+ button: typeof event.button === "number"
1597
+ ? event.button
1598
+ : event.button === "left"
1599
+ ? 0
1600
+ : event.button === "middle"
1601
+ ? 1
1602
+ : event.button === "right"
1603
+ ? 2
1604
+ : -1,
1605
+ // Pi TUI coordinates are zero-based local cells; the SGR adapter
1606
+ // and rendered spans below intentionally use one-based rows.
1607
+ x: event.x + 1,
1608
+ y: event.y + 1,
1609
+ clickCount: event.clickCount,
1610
+ delta: event.wheelDelta,
1611
+ };
1612
+
1613
+ if (normalized.action === "wheel") {
1614
+ const delta = Math.trunc(normalized.delta ?? 0);
1615
+ if (this.toolPreviewParent !== null) {
1616
+ this.scrollToolPreview(delta);
1617
+ } else if (this.peekState.active) {
1618
+ this.scrollPeek(delta);
1619
+ } else {
1620
+ this.scrollTranscript(delta);
1621
+ }
1622
+ return { handled: true, render: true };
1623
+ }
1624
+ if (this.toolPreviewParent !== null) {
1625
+ return { handled: true, render: false };
1371
1626
  }
1372
1627
 
1373
- const button = Number(match[1]);
1374
- if ((button & 64) !== 64) {
1375
- return null;
1628
+ if (!this.peekState.active) {
1629
+ if (this.transcriptLineEntryIds.length === 0 && this.readTranscriptEntries().length > 0) {
1630
+ this.render(this.lastRenderWidth);
1631
+ }
1632
+ if (normalized.action === "move" || normalized.action === "drag") {
1633
+ const hoveredEntryId = this.transcriptEntryAtLine(normalized.y);
1634
+ if (hoveredEntryId === this.liveHoveredEntryId) return { handled: true, render: false };
1635
+ this.liveHoveredEntryId = hoveredEntryId;
1636
+ this.tui.requestRender();
1637
+ return { handled: true, render: true };
1638
+ }
1639
+ if (normalized.action === "press" || normalized.action === "release") {
1640
+ return { handled: true, render: false };
1641
+ }
1642
+ if (normalized.action !== "click" || normalized.button !== 0) {
1643
+ return { handled: true, render: false };
1644
+ }
1645
+ if (normalized.x < 1 || normalized.x > this.lastRenderWidth) {
1646
+ return { handled: true, render: false };
1647
+ }
1648
+ const entryId = this.transcriptEntryAtLine(normalized.y);
1649
+ if (entryId === null) return { handled: true, render: false };
1650
+ const entry = this.readTranscriptEntries().find((candidate) => candidate.id === entryId);
1651
+ const focused = this.focusLiveTranscriptEntry(entryId);
1652
+ if (focused && (entry?.type === "tool-call" || entry?.type === "tool-result") && entry.toolCallId) {
1653
+ // A single click both focuses the tool row and toggles its compact
1654
+ // details. A second click collapses it, matching the Peek surface.
1655
+ if ((normalized.clickCount ?? 1) >= 2) {
1656
+ this.liveExpandedToolCallId = null;
1657
+ } else {
1658
+ this.liveExpandedToolCallId = this.liveExpandedToolCallId === entry.toolCallId
1659
+ ? null
1660
+ : entry.toolCallId;
1661
+ }
1662
+ this.tui.requestRender();
1663
+ }
1664
+ return { handled: true, focus: focused, render: focused };
1376
1665
  }
1377
1666
 
1378
- return (button & 1) === 0 ? -3 : 3;
1667
+ if (normalized.action === "move" || normalized.action === "drag") {
1668
+ const hoveredIndex = this.peekIndexAtLine(normalized.y);
1669
+ if (hoveredIndex === this.peekHoveredIndex) {
1670
+ return { handled: true, render: false };
1671
+ }
1672
+ this.peekHoveredIndex = hoveredIndex;
1673
+ this.tui.requestRender();
1674
+ return { handled: true, render: true };
1675
+ }
1676
+ if (normalized.action === "press" || normalized.action === "release") {
1677
+ return { handled: true, render: false };
1678
+ }
1679
+ if (normalized.action !== "click" || normalized.button !== 0) return;
1680
+ if (normalized.x < 1 || normalized.x > this.lastRenderWidth || this.peekBlockStarts.length !== this.peekBlocks.length) {
1681
+ return { handled: true, render: false };
1682
+ }
1683
+
1684
+ const targetIndex = this.peekIndexAtLine(normalized.y);
1685
+ if (targetIndex === null) return { handled: true, render: false };
1686
+ this.peekHoveredIndex = targetIndex;
1687
+ this.peekState.selectedIndex = targetIndex;
1688
+ const target = this.peekBlocks[targetIndex];
1689
+ const clickCount = normalized.clickCount ?? 1;
1690
+ const shouldCollapse = clickCount >= 2 &&
1691
+ (target?.type === "tool-call" || target?.type === "tool-result") &&
1692
+ this.expandedToolId === target.id;
1693
+ if (shouldCollapse) {
1694
+ this.expandedToolId = null;
1695
+ this.peekState.scrollOffset = Math.max(0, Math.min(
1696
+ this.peekState.scrollOffset,
1697
+ Math.max(0, this.peekRenderedLines.length - Math.max(1, this.peekState.viewportHeight)),
1698
+ ));
1699
+ }
1700
+ this.tui.requestRender();
1701
+ return { handled: true, focus: true, render: true };
1379
1702
  }
1380
1703
 
1381
1704
  handleInput(data: string): void {
@@ -1384,15 +1707,40 @@ export class BtwOverlayComponent extends Container implements Focusable {
1384
1707
  return;
1385
1708
  }
1386
1709
 
1710
+ // Older hosts may deliver raw SGR/X10 wheel bytes through handleInput
1711
+ // instead of dispatching a normalized mouse event.
1712
+ const earlyMouseScrollDelta = this.getMouseScrollDelta(data);
1713
+ if (earlyMouseScrollDelta !== null && this.toolPreviewParent !== null) {
1714
+ this.scrollToolPreview(earlyMouseScrollDelta);
1715
+ return;
1716
+ }
1717
+
1718
+ if (this.toolPreviewParent !== null && this.handleToolPreviewInput(data)) {
1719
+ return;
1720
+ }
1721
+
1722
+ // Ctrl+O is live-only: it opens the complete immutable input/output of
1723
+ // the focused tool without interfering with the composer.
1724
+ if (matchesKey(data, BTW_TOOL_OUTPUT_SHORTCUT)) {
1725
+ this.enterLiveToolPreview();
1726
+ if (this.toolPreviewParent === "live") return;
1727
+ }
1728
+
1729
+ const mouseEvent = parsePeekMouseInput(data);
1387
1730
  const mouseScrollDelta = this.getMouseScrollDelta(data);
1388
1731
  if (mouseScrollDelta !== null) {
1389
- if (this.peekState.active) {
1732
+ if (this.toolPreviewParent !== null) {
1733
+ this.scrollToolPreview(mouseScrollDelta);
1734
+ } else if (this.peekState.active) {
1390
1735
  this.scrollPeek(mouseScrollDelta);
1391
1736
  } else {
1392
1737
  this.scrollTranscript(mouseScrollDelta);
1393
1738
  }
1394
1739
  return;
1395
1740
  }
1741
+ // Consume bounded SGR button events locally. Without an explicit host
1742
+ // click dispatch, press/release are deliberately no-ops rather than input.
1743
+ if (mouseEvent) return;
1396
1744
 
1397
1745
  // Peek mode active → route all input to peek handler
1398
1746
  if (this.peekState.active) {
@@ -1409,8 +1757,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1409
1757
  this.input.handleInput(data);
1410
1758
  }
1411
1759
 
1412
- private inputFrameLines(innerWidth: number): string[] {
1413
- const lines = this.input.render(innerWidth);
1760
+ private inputFrameLines(innerWidth: number, maxLines = 6): string[] {
1761
+ const rendered = this.input.render(innerWidth);
1762
+ // CustomEditor owns cursor/history state; only clip its visual viewport,
1763
+ // keeping the newest lines visible instead of allowing the overlay to grow.
1764
+ const lines = rendered.slice(Math.max(0, rendered.length - maxLines));
1765
+ if (lines.length === 0) lines.push("");
1414
1766
  return lines.map((l) => {
1415
1767
  const pad = Math.max(0, innerWidth - visibleWidth(l));
1416
1768
  return `${this.theme.fg("border", "│")}${l}${" ".repeat(pad)}${this.theme.fg("border", "│")}`;
@@ -1424,20 +1776,33 @@ export class BtwOverlayComponent extends Container implements Focusable {
1424
1776
  override render(width: number): string[] {
1425
1777
  const dialogWidth = Math.max(24, width);
1426
1778
  const innerWidth = Math.max(22, dialogWidth - 2);
1779
+ this.lastRenderWidth = dialogWidth;
1780
+
1781
+ // Tool Output is a read-only view over the currently focused live tool.
1782
+ if (this.toolPreviewParent === "live") {
1783
+ return this.renderLiveToolPreview(innerWidth, width);
1784
+ }
1427
1785
 
1428
1786
  // Peek mode has its own full-content render
1429
1787
  if (this.peekState.active) {
1430
1788
  return this.renderPeekMode(innerWidth, width);
1431
1789
  }
1432
1790
 
1433
- // Compute input lines (cap at 6 for layout stability)
1791
+ // Compute input lines (cap at 6 for layout stability). On very short
1792
+ // terminals, reserve the composer a single visible row rather than letting
1793
+ // CustomEditor output push the bottom border out of the viewport.
1434
1794
  const rawInputLines = this.input.render(innerWidth);
1435
- const inputLineCount = Math.max(1, Math.min(rawInputLines.length, 6));
1795
+ const terminalRows = Math.max(1, this.tui.terminal?.rows ?? process.stdout.rows ?? 30);
1796
+ const inputBudget = Math.max(1, terminalRows - BTW_OVERLAY_CHROME_BASE - 1);
1797
+ const inputLineCount = Math.max(1, Math.min(rawInputLines.length, 6, inputBudget));
1436
1798
 
1437
1799
  const transcriptLines = this.buildTranscriptLines(innerWidth);
1800
+ this.transcriptLines = transcriptLines;
1438
1801
  const chromeHeight = BTW_OVERLAY_CHROME_BASE + inputLineCount;
1439
1802
  const dialogHeight = this.getDialogHeight(inputLineCount);
1440
- const transcriptHeight = Math.max(6, dialogHeight - chromeHeight);
1803
+ // On short terminals the viewport yields before the composer/chrome. Do
1804
+ // not force a six-line transcript that pushes the bottom border away.
1805
+ const transcriptHeight = Math.max(1, dialogHeight - chromeHeight);
1441
1806
  this.transcriptViewportHeight = transcriptHeight;
1442
1807
 
1443
1808
  const maxScroll = Math.max(0, transcriptLines.length - transcriptHeight);
@@ -1464,7 +1829,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1464
1829
 
1465
1830
  const lines = [this.borderLine(innerWidth, "top")];
1466
1831
 
1467
- lines.push(this.frameLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1832
+ lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1468
1833
  lines.push(this.frameLine(this.theme.fg("dim", summary), innerWidth));
1469
1834
  lines.push(this.ruleLine(innerWidth));
1470
1835
 
@@ -1477,7 +1842,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1477
1842
 
1478
1843
  lines.push(this.ruleLine(innerWidth));
1479
1844
  lines.push(this.frameLine(this.theme.fg("warning", this.statusTextValue.trim()), innerWidth));
1480
- lines.push(...this.inputFrameLines(innerWidth));
1845
+ lines.push(...this.inputFrameLines(innerWidth, inputLineCount));
1481
1846
  lines.push(this.frameLine(this.theme.fg("dim", this.hintsTextValue.trim()), innerWidth));
1482
1847
  lines.push(this.borderLine(innerWidth, "bottom"));
1483
1848
 
@@ -1528,13 +1893,277 @@ export class BtwOverlayComponent extends Container implements Focusable {
1528
1893
 
1529
1894
  // ── Peek Mode ──────────────────────────────────────────────────────
1530
1895
 
1896
+ private getSelectedPeekBlock(): PeekBlock | undefined {
1897
+ if (this.peekBlocks.length === 0) return undefined;
1898
+ this.peekState.selectedIndex = Math.max(
1899
+ 0,
1900
+ Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1),
1901
+ );
1902
+ return this.peekBlocks[this.peekState.selectedIndex];
1903
+ }
1904
+
1905
+ private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1906
+ // Keep the preview read-only and complete. The viewport, not the data,
1907
+ // supplies the bound: only the visible slice is emitted below.
1908
+ const text = getToolPreviewText(block);
1909
+ const lines: string[] = [];
1910
+ for (const line of text.split("\n")) {
1911
+ lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
1912
+ }
1913
+ return lines.length > 0 ? lines : ["(no tool data)"];
1914
+ }
1915
+
1916
+ private hydrateToolBlock(block: PeekBlock): PeekBlock {
1917
+ if (!block.toolCallId || !this.readToolArtifact) return block;
1918
+ const artifact = this.readToolArtifact(block.toolCallId);
1919
+ if (!artifact) return block;
1920
+
1921
+ const hydrated = { ...block };
1922
+ const input = formatToolPreview(artifact.input);
1923
+ const output = formatToolPreview(artifact.output);
1924
+ const details = formatToolPreview(artifact.details);
1925
+ if (input) hydrated.toolInput = input;
1926
+ if (output) hydrated.toolOutput = output;
1927
+ if (details) {
1928
+ hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDetails:\n${details}`;
1929
+ }
1930
+ if (artifact.diff) {
1931
+ hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDiff:\n${artifact.diff}`;
1932
+ }
1933
+ hydrated.toolName = artifact.toolName || hydrated.toolName;
1934
+ hydrated.isError = hydrated.isError || artifact.isError;
1935
+ return hydrated;
1936
+ }
1937
+
1938
+ private hydrateToolBlocks(blocks: PeekBlock[]): PeekBlock[] {
1939
+ return blocks.map((block) =>
1940
+ block.type === "tool-call" || block.type === "tool-result"
1941
+ ? this.hydrateToolBlock(block)
1942
+ : block,
1943
+ );
1944
+ }
1945
+
1946
+ private findLiveToolPreviewBlock(): PeekBlock | null {
1947
+ const selected = this.liveToolPreviewBlock;
1948
+ if (!selected) return null;
1949
+ const blocks = this.hydrateToolBlocks(buildPeekBlocks(
1950
+ this.readTranscriptEntries() as unknown as PeekEntry[],
1951
+ true,
1952
+ ));
1953
+ return blocks.find((block) => block.entryId === selected.entryId) ??
1954
+ blocks.find((block) => block.toolCallId === selected.toolCallId &&
1955
+ (block.type === "tool-call" || block.type === "tool-result")) ?? null;
1956
+ }
1957
+
1958
+ private scrollToolPreview(delta: number): void {
1959
+ // Opening a preview schedules the next render. A fast wheel event can
1960
+ // arrive first, so initialize its wrapped lines before calculating bounds.
1961
+ if (this.toolPreviewParent !== null && this.peekToolPreviewLines.length === 0) {
1962
+ this.render(this.lastRenderWidth);
1963
+ }
1964
+ if (this.toolPreviewParent === null) return;
1965
+ const viewportHeight = Math.max(1, this.peekState.viewportHeight);
1966
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
1967
+ this.peekToolPreviewScrollOffset = Math.max(
1968
+ 0,
1969
+ Math.min(maxScroll, this.peekToolPreviewScrollOffset + delta),
1970
+ );
1971
+ this.tui.requestRender();
1972
+ }
1973
+
1974
+ private renderLiveToolPreview(innerWidth: number, fullWidth: number): string[] {
1975
+ const block = this.findLiveToolPreviewBlock();
1976
+ if (!block) {
1977
+ this.toolPreviewParent = null;
1978
+ this.liveToolPreviewBlock = null;
1979
+ this.peekToolPreviewLines = [];
1980
+ this.peekToolPreviewScrollOffset = 0;
1981
+ return this.render(fullWidth);
1982
+ }
1983
+
1984
+ const dialogHeight = this.getDialogHeight(1);
1985
+ const viewportHeight = Math.max(1, dialogHeight - 6);
1986
+ this.peekState.viewportHeight = viewportHeight;
1987
+ this.peekToolPreviewLines = this.buildToolPreviewLines(block, innerWidth);
1988
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
1989
+ this.peekToolPreviewScrollOffset = Math.max(
1990
+ 0,
1991
+ Math.min(this.peekToolPreviewScrollOffset, maxScroll),
1992
+ );
1993
+
1994
+ const title = `BTW Tool Output · ${getSemanticBlockLabel(block)} · read-only`;
1995
+ const lines = [
1996
+ this.borderLine(innerWidth, "top"),
1997
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
1998
+ this.ruleLine(innerWidth),
1999
+ ];
2000
+ const visible = this.peekToolPreviewLines.slice(
2001
+ this.peekToolPreviewScrollOffset,
2002
+ this.peekToolPreviewScrollOffset + viewportHeight,
2003
+ );
2004
+ for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2005
+ for (let i = visible.length; i < viewportHeight; i++) lines.push(this.frameLine("", innerWidth));
2006
+ const hiddenAbove = this.peekToolPreviewScrollOffset;
2007
+ const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2008
+ const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2009
+ lines.push(this.ruleLine(innerWidth));
2010
+ lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn Esc:back${counts}`), innerWidth));
2011
+ lines.push(this.borderLine(innerWidth, "bottom"));
2012
+ return lines.map((line) => this.fitRenderedLine(line, fullWidth));
2013
+ }
2014
+
2015
+ private renderToolPreview(innerWidth: number, fullWidth: number): string[] {
2016
+ if (this.peekToolPreviewBlockId !== null) {
2017
+ const refreshedIndex = this.peekBlocks.findIndex((candidate) => candidate.id === this.peekToolPreviewBlockId);
2018
+ this.peekToolPreviewIndex = refreshedIndex >= 0 ? refreshedIndex : null;
2019
+ }
2020
+ const block = this.peekToolPreviewIndex === null ? undefined : this.peekBlocks[this.peekToolPreviewIndex];
2021
+ if (!block || !hasToolPreview(block)) {
2022
+ this.peekToolPreviewIndex = null;
2023
+ this.peekToolPreviewBlockId = null;
2024
+ this.peekToolPreviewLines = [];
2025
+ this.peekToolPreviewScrollOffset = 0;
2026
+ this.toolPreviewParent = null;
2027
+ return this.renderPeekMode(innerWidth, fullWidth);
2028
+ }
2029
+
2030
+ const dialogHeight = this.getDialogHeight(1);
2031
+ const viewportHeight = Math.max(1, dialogHeight - 6);
2032
+ this.peekState.viewportHeight = viewportHeight;
2033
+ this.peekToolPreviewLines = this.buildToolPreviewLines(block, innerWidth);
2034
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
2035
+ this.peekToolPreviewScrollOffset = Math.max(
2036
+ 0,
2037
+ Math.min(this.peekToolPreviewScrollOffset, maxScroll),
2038
+ );
2039
+
2040
+ const title = `BTW Peek · ${getSemanticBlockLabel(block)} · read-only`;
2041
+ const lines = [
2042
+ this.borderLine(innerWidth, "top"),
2043
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2044
+ this.ruleLine(innerWidth),
2045
+ ];
2046
+ const visible = this.peekToolPreviewLines.slice(
2047
+ this.peekToolPreviewScrollOffset,
2048
+ this.peekToolPreviewScrollOffset + viewportHeight,
2049
+ );
2050
+ for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2051
+ while (visible.length < viewportHeight) {
2052
+ visible.push("");
2053
+ lines.push(this.frameLine("", innerWidth));
2054
+ }
2055
+ const hiddenAbove = this.peekToolPreviewScrollOffset;
2056
+ const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2057
+ const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2058
+ lines.push(this.ruleLine(innerWidth));
2059
+ lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn q/Esc:back${counts}`), innerWidth));
2060
+ lines.push(this.borderLine(innerWidth, "bottom"));
2061
+ return lines.map((line) => this.fitRenderedLine(line, fullWidth));
2062
+ }
2063
+
2064
+ private enterToolPreview(): void {
2065
+ const block = this.getSelectedPeekBlock();
2066
+ if (!hasToolPreview(block)) return;
2067
+ this.peekToolPreviewIndex = this.peekState.selectedIndex;
2068
+ this.peekToolPreviewBlockId = block?.id ?? null;
2069
+ this.toolPreviewParent = "peek";
2070
+ this.peekToolPreviewScrollOffset = 0;
2071
+ this.peekToolPreviewLines = [];
2072
+ this.tui.requestRender();
2073
+ }
2074
+
2075
+ private enterLiveToolPreview(): void {
2076
+ if (this.peekState.active || !this.liveFocusedToolCallId) return;
2077
+ const block = buildPeekBlocks(
2078
+ this.readTranscriptEntries() as unknown as PeekEntry[],
2079
+ true,
2080
+ ).find((candidate) => candidate.toolCallId === this.liveFocusedToolCallId);
2081
+ if (!block) return;
2082
+ this.liveToolPreviewBlock = block;
2083
+ this.toolPreviewParent = "live";
2084
+ this.peekToolPreviewScrollOffset = 0;
2085
+ this.peekToolPreviewLines = [];
2086
+ this.tui.requestRender();
2087
+ }
2088
+
2089
+ private exitToolPreview(): void {
2090
+ this.peekToolPreviewIndex = null;
2091
+ this.peekToolPreviewBlockId = null;
2092
+ this.peekToolPreviewLines = [];
2093
+ this.peekToolPreviewScrollOffset = 0;
2094
+ this.liveToolPreviewBlock = null;
2095
+ this.toolPreviewParent = null;
2096
+ this.tui.requestRender();
2097
+ }
2098
+
2099
+ private toggleExpandedTool(): boolean {
2100
+ const block = this.getSelectedPeekBlock();
2101
+ if (!hasToolPreview(block)) return false;
2102
+ this.expandedToolId = this.expandedToolId === block?.id ? null : block?.id ?? null;
2103
+ this.peekState.scrollOffset = 0;
2104
+ this.tui.requestRender();
2105
+ return true;
2106
+ }
2107
+
2108
+ private handleToolPreviewInput(data: string): boolean {
2109
+ if (this.toolPreviewParent === null) return false;
2110
+ if (data === "q" || data === "\x1b" || data === "\x03") {
2111
+ this.exitToolPreview();
2112
+ return true;
2113
+ }
2114
+ const viewportHeight = Math.max(1, this.peekState.viewportHeight);
2115
+ const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
2116
+ if (data === "j" || data === "\x1b[B" || data === "\x1b[OB") {
2117
+ this.peekToolPreviewScrollOffset = Math.min(maxScroll, this.peekToolPreviewScrollOffset + 1);
2118
+ this.tui.requestRender();
2119
+ return true;
2120
+ }
2121
+ if (data === "k" || data === "\x1b[A" || data === "\x1b[OA") {
2122
+ this.peekToolPreviewScrollOffset = Math.max(0, this.peekToolPreviewScrollOffset - 1);
2123
+ this.tui.requestRender();
2124
+ return true;
2125
+ }
2126
+ if (data === "g") {
2127
+ this.peekToolPreviewScrollOffset = 0;
2128
+ this.tui.requestRender();
2129
+ return true;
2130
+ }
2131
+ if (data === "G") {
2132
+ this.peekToolPreviewScrollOffset = maxScroll;
2133
+ this.tui.requestRender();
2134
+ return true;
2135
+ }
2136
+ if (matchesPageKey(data, 5)) {
2137
+ this.peekToolPreviewScrollOffset = Math.max(0, this.peekToolPreviewScrollOffset - Math.max(1, viewportHeight - 2));
2138
+ this.tui.requestRender();
2139
+ return true;
2140
+ }
2141
+ if (matchesPageKey(data, 6)) {
2142
+ this.peekToolPreviewScrollOffset = Math.min(maxScroll, this.peekToolPreviewScrollOffset + Math.max(1, viewportHeight - 2));
2143
+ this.tui.requestRender();
2144
+ return true;
2145
+ }
2146
+ return true;
2147
+ }
2148
+
1531
2149
  private renderPeekMode(innerWidth: number, fullWidth: number): string[] {
1532
- this.peekState.viewportHeight = Math.max(6, this.getDialogHeight(1) - 8);
2150
+ if (this.peekToolPreviewIndex !== null) {
2151
+ return this.renderToolPreview(innerWidth, fullWidth);
2152
+ }
2153
+ const dialogHeight = this.getDialogHeight(1);
2154
+ // Normal Peek chrome is six rows: top/title/rule + rule/status/bottom.
2155
+ this.peekState.viewportHeight = Math.max(1, dialogHeight - 6);
1533
2156
  const vh = this.peekState.viewportHeight;
1534
2157
  const lines: string[] = [];
1535
2158
 
1536
2159
  // ── Header ───────────────────────────────────────────────────────
1537
2160
  const blockCount = this.peekBlocks.length;
2161
+ this.peekState.selectedIndex = blockCount === 0
2162
+ ? 0
2163
+ : Math.max(0, Math.min(this.peekState.selectedIndex, blockCount - 1));
2164
+ if (this.expandedToolId !== null && !this.peekBlocks.some((block) => block.id === this.expandedToolId && hasToolPreview(block))) {
2165
+ this.expandedToolId = null;
2166
+ }
1538
2167
  const pct =
1539
2168
  blockCount > 0
1540
2169
  ? `${Math.round((this.peekState.selectedIndex / Math.max(1, blockCount - 1)) * 100)}%`
@@ -1545,16 +2174,17 @@ export class BtwOverlayComponent extends Container implements Focusable {
1545
2174
  ? ` search ${this.peekState.currentMatchIndex + 1}/${this.peekState.searchMatches.length}`
1546
2175
  : "");
1547
2176
  lines.push(this.borderLine(innerWidth, "top"));
1548
- lines.push(this.frameLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth));
2177
+ lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth));
1549
2178
  lines.push(this.ruleLine(innerWidth));
1550
2179
 
1551
2180
  // ── Search bar ───────────────────────────────────────────────────
1552
2181
  if (this.peekState.searchActive) {
1553
2182
  const searchLine = `/ ${this.peekSearchBuffer}${this.theme.fg("warning", "█")}`;
2183
+ const searchViewportHeight = Math.max(1, dialogHeight - 8);
1554
2184
  lines.push(this.frameLine(this.theme.fg("accent", searchLine), innerWidth));
1555
2185
  lines.push(this.ruleLine(innerWidth));
1556
- // Fill rest with blank lines
1557
- for (let i = 0; i < vh; i++) {
2186
+ // Fill rest with blank lines while keeping the footer and border visible.
2187
+ for (let i = 0; i < searchViewportHeight; i++) {
1558
2188
  lines.push(this.frameLine("", innerWidth));
1559
2189
  }
1560
2190
  lines.push(this.ruleLine(innerWidth));
@@ -1565,58 +2195,62 @@ export class BtwOverlayComponent extends Container implements Focusable {
1565
2195
 
1566
2196
  // ── Content ──────────────────────────────────────────────────────
1567
2197
  const mdContentWidth = Math.max(1, innerWidth - 6);
2198
+ this.peekContentTop = 4;
1568
2199
  // Build rendered lines and remember each block's starting line so j/k
1569
2200
  // can scroll by line while J/K still jump by message.
1570
2201
  const blockRenderLines: string[][] = [];
1571
2202
  this.peekBlockStarts = [];
2203
+ this.peekBlockEnds = [];
1572
2204
  this.peekHeaderLines = [];
1573
2205
  let renderedLineCount = 0;
1574
2206
 
1575
2207
  for (const block of this.peekBlocks) {
1576
2208
  const blockLines: string[] = [];
1577
2209
  this.peekBlockStarts.push(renderedLineCount);
1578
- const label = getBlockTypeLabel(block);
2210
+ const label = getSemanticBlockLabel(block);
1579
2211
  const isCurrent = block.id === this.peekBlocks[this.peekState.selectedIndex]?.id;
2212
+ const isHovered = block.id === this.peekBlocks[this.peekHoveredIndex ?? -1]?.id;
1580
2213
 
1581
- // Block header line
1582
- const prefix = isCurrent ? "▎ " : " ";
2214
+ // The rail is the sole selection indicator. Hover is a quieter cue and
2215
+ // never changes the selected target until an explicit click arrives.
2216
+ const prefix = isCurrent ? "▎ " : isHovered ? "│ " : " ";
1583
2217
  if (block.type === "thinking") {
1584
- blockLines.push(`${prefix}${this.theme.fg("warning", this.theme.bold(this.theme.italic(`── ${label} ──`)))}`);
1585
- } else if (block.type === "tool-call") {
1586
- blockLines.push(`${prefix}${this.theme.fg("toolTitle", this.theme.bold(`── ${label} ──`))}`);
1587
- } else if (block.type === "tool-result") {
1588
- const errPrefix = block.isError ? this.theme.fg("error", " ⚠") : "";
1589
- blockLines.push(`${prefix}${this.theme.fg("dim", this.theme.bold(`── ${label} ──`))}${errPrefix}`);
2218
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "warning", this.theme.bold(this.theme.italic(`── ${label} ──`)))}`);
2219
+ } else if (block.type === "tool-call" || block.type === "tool-result") {
2220
+ const resultIcon = block.type === "tool-result" ? (block.isError ? "✗" : "✓") : "→";
2221
+ const toolColor = block.isError ? "error" : isHovered ? "text" : "toolTitle";
2222
+ const detail = block.type === "tool-result"
2223
+ ? getToolResultSummary(block.text)
2224
+ : block.toolInput || "(no input)";
2225
+ const detailColor = block.isError ? "error" : isHovered ? "text" : "dim";
2226
+ blockLines.push(`${prefix}${this.theme.fg(toolColor, this.theme.bold(`· ${block.toolName ?? "?"} ${resultIcon}`))} ${this.theme.fg(detailColor, detail)}`);
1590
2227
  } else if (block.type === "user") {
1591
- blockLines.push(`${prefix}${this.theme.fg("accent", this.theme.bold(`── ${label} ──`))}`);
2228
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "accent", this.theme.bold(`── ${label} ──`))}`);
1592
2229
  } else {
1593
- blockLines.push(`${prefix}${this.theme.fg("success", this.theme.bold(`── ${label} ──`))}`);
2230
+ blockLines.push(`${prefix}${this.theme.fg(isHovered ? "text" : "success", this.theme.bold(`── ${label} ──`))}`);
1594
2231
  }
1595
2232
 
1596
- // Block content
1597
- if (block.text) {
1598
- if (block.type === "assistant-text") {
1599
- // Use Markdown for assistant text
2233
+ // Tool rows stay compact by default. Enter is an optional safe
2234
+ // expansion; the full read-only view is also available through `w`.
2235
+ if (block.type === "tool-call" || block.type === "tool-result") {
2236
+ if (this.expandedToolId === block.id && hasToolPreview(block)) {
2237
+ const toolLines = this.buildToolPreviewLines(block, innerWidth);
2238
+ for (const toolLine of toolLines) {
2239
+ blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg(block.isError ? "error" : "dim", toolLine)}`);
2240
+ }
2241
+ }
2242
+ } else if (block.text) {
2243
+ if (block.type === "assistant-text" || block.type === "user") {
1600
2244
  const md = new Markdown(block.text, 0, 0, this.mdTheme);
1601
2245
  const mdLines = md.render(mdContentWidth);
1602
2246
  for (const mdLine of mdLines) {
1603
- blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine}`);
1604
- }
1605
- } else if (block.type === "tool-result" && block.isError) {
1606
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1607
- for (const sl of styledLines) {
1608
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("error", sl)}`);
2247
+ blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine.replace(/[ \t]+$/u, "")}`);
1609
2248
  }
1610
2249
  } else if (block.type === "thinking") {
1611
2250
  const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1612
2251
  for (const sl of styledLines) {
1613
2252
  blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("warning", this.theme.italic(sl))}`);
1614
2253
  }
1615
- } else {
1616
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
1617
- for (const sl of styledLines) {
1618
- blockLines.push(`${isCurrent ? "▎ " : " "}${sl}`);
1619
- }
1620
2254
  }
1621
2255
  }
1622
2256
 
@@ -1626,6 +2260,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1626
2260
  blockRenderLines.push(blockLines);
1627
2261
  this.peekHeaderLines.push(blockLines[0] ?? "");
1628
2262
  renderedLineCount += blockLines.length;
2263
+ // The final blank is visual separation, not part of the block hitbox.
2264
+ // This keeps clicks on separators/padding from changing focus.
2265
+ this.peekBlockEnds.push(Math.max(this.peekBlockStarts[this.peekBlockStarts.length - 1] + 1, renderedLineCount - 1));
1629
2266
  }
1630
2267
 
1631
2268
  this.peekRenderedLines = blockRenderLines.flat();
@@ -1633,12 +2270,14 @@ export class BtwOverlayComponent extends Container implements Focusable {
1633
2270
  this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
1634
2271
 
1635
2272
  const visibleStart = this.peekState.scrollOffset;
2273
+ this.peekStickyHeaderIndex = null;
1636
2274
  const displayLines = this.peekRenderedLines.slice(visibleStart, visibleStart + vh);
1637
2275
  if (blockCount === 0) {
1638
2276
  displayLines.push(this.theme.fg("dim", "No BTW thread yet."));
1639
2277
  }
1640
2278
  const selectedStart = this.peekBlockStarts[this.peekState.selectedIndex];
1641
2279
  if (selectedStart !== undefined && selectedStart < visibleStart && displayLines.length > 0) {
2280
+ this.peekStickyHeaderIndex = this.peekState.selectedIndex;
1642
2281
  displayLines[0] = this.peekHeaderLines[this.peekState.selectedIndex] ?? displayLines[0];
1643
2282
  }
1644
2283
 
@@ -1656,7 +2295,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1656
2295
  ? ` ${this.peekState.currentMatchIndex + 1}/${this.peekState.searchMatches.length}`
1657
2296
  : "";
1658
2297
  const toolsHint = this.peekState.showTools ? "t:hide" : "t:show";
1659
- const statusText = `j/k ↑↓ g/G /search${searchHint} ${toolsHint} M:copy o:nvim q:exit`;
2298
+ const selected = this.getSelectedPeekBlock();
2299
+ const previewHint = hasToolPreview(selected) ? " w:preview" : "";
2300
+ const expandHint = hasToolPreview(selected) ? " Enter:expand" : "";
2301
+ const statusText = `j/k ↑↓ J/K msg g/G /search${searchHint} ${toolsHint}${previewHint} M:copy o:nvim${expandHint} q:exit`;
1660
2302
  lines.push(this.ruleLine(innerWidth));
1661
2303
  lines.push(this.frameLine(this.theme.fg("dim", statusText), innerWidth));
1662
2304
  lines.push(this.borderLine(innerWidth, "bottom"));
@@ -1669,32 +2311,72 @@ export class BtwOverlayComponent extends Container implements Focusable {
1669
2311
  this.peekState.active = true;
1670
2312
  const entries = this.readTranscriptEntries();
1671
2313
  this.peekState.showTools = true;
1672
- this.peekBlocks = buildPeekBlocks(
2314
+ this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
1673
2315
  entries as unknown as PeekEntry[],
1674
2316
  this.peekState.showTools,
1675
- );
2317
+ ));
2318
+ this.peekState.blocks = this.peekBlocks;
1676
2319
  this.peekState.selectedIndex = 0;
1677
2320
  this.peekState.scrollOffset = 0;
2321
+ this.peekHoveredIndex = null;
2322
+ this.peekToolPreviewIndex = null;
2323
+ this.peekToolPreviewBlockId = null;
2324
+ this.peekToolPreviewLines = [];
2325
+ this.peekToolPreviewScrollOffset = 0;
2326
+ this.expandedToolId = null;
2327
+ this.peekBlockStarts = [];
2328
+ this.peekBlockEnds = [];
1678
2329
  this.tui.requestRender();
1679
2330
  }
1680
2331
 
1681
2332
  exitPeekMode(): void {
1682
2333
  this.peekState.active = false;
1683
2334
  this.peekState.searchActive = false;
2335
+ this.peekHoveredIndex = null;
1684
2336
  this.peekSearchBuffer = "";
2337
+ this.peekToolPreviewIndex = null;
2338
+ this.peekToolPreviewBlockId = null;
2339
+ this.peekToolPreviewLines = [];
2340
+ this.peekToolPreviewScrollOffset = 0;
2341
+ this.liveToolPreviewBlock = null;
2342
+ this.toolPreviewParent = null;
2343
+ this.expandedToolId = null;
1685
2344
  this.tui.requestRender();
1686
2345
  }
1687
2346
 
1688
2347
  private rebuildPeekBlocks(): void {
1689
2348
  const entries = this.readTranscriptEntries();
1690
- this.peekBlocks = buildPeekBlocks(
2349
+ this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
1691
2350
  entries as unknown as PeekEntry[],
1692
2351
  this.peekState.showTools,
1693
- );
2352
+ ));
2353
+ this.peekState.blocks = this.peekBlocks;
1694
2354
 
1695
2355
  const maxIndex = Math.max(0, this.peekBlocks.length - 1);
1696
- this.peekState.selectedIndex = Math.min(this.peekState.selectedIndex, maxIndex);
2356
+ this.peekState.selectedIndex = this.peekBlocks.length === 0
2357
+ ? 0
2358
+ : Math.max(0, Math.min(this.peekState.selectedIndex, maxIndex));
1697
2359
  this.peekState.scrollOffset = Math.max(0, this.peekState.scrollOffset);
2360
+ this.peekHoveredIndex = null;
2361
+ // Existing line spans belong to the old transcript snapshot.
2362
+ this.peekBlockStarts = [];
2363
+ this.peekBlockEnds = [];
2364
+ this.peekRenderedLines = [];
2365
+ this.peekHeaderLines = [];
2366
+ if (this.expandedToolId !== null && !this.peekBlocks.some((block) => block.id === this.expandedToolId && hasToolPreview(block))) {
2367
+ this.expandedToolId = null;
2368
+ }
2369
+ if (this.peekToolPreviewBlockId !== null) {
2370
+ const previewIndex = this.peekBlocks.findIndex((block) => block.id === this.peekToolPreviewBlockId);
2371
+ if (previewIndex < 0 || !hasToolPreview(this.peekBlocks[previewIndex])) {
2372
+ this.peekToolPreviewIndex = null;
2373
+ this.peekToolPreviewBlockId = null;
2374
+ this.peekToolPreviewLines = [];
2375
+ this.peekToolPreviewScrollOffset = 0;
2376
+ } else {
2377
+ this.peekToolPreviewIndex = previewIndex;
2378
+ }
2379
+ }
1698
2380
  if (this.peekState.searchQuery) {
1699
2381
  this.peekState.searchMatches = findSearchMatches(
1700
2382
  this.peekBlocks,
@@ -1709,22 +2391,33 @@ export class BtwOverlayComponent extends Container implements Focusable {
1709
2391
  }
1710
2392
 
1711
2393
  private scrollPeek(delta: number): void {
2394
+ // A key can arrive before the first post-enter render. Build the line
2395
+ // spans once so scrolling and mouse selection use the same coordinates.
2396
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length !== this.peekBlocks.length) {
2397
+ this.render(this.lastRenderWidth);
2398
+ }
2399
+
1712
2400
  const maxScroll = Math.max(0, this.peekRenderedLines.length - this.peekState.viewportHeight);
1713
2401
  this.peekState.scrollOffset = Math.max(
1714
2402
  0,
1715
2403
  Math.min(maxScroll, this.peekState.scrollOffset + delta),
1716
2404
  );
1717
2405
 
1718
- // Keep the selected message aligned with the first message at or before
1719
- // the viewport, while preserving line-level scrolling within a block.
1720
- let selected = this.peekState.selectedIndex;
1721
- for (let i = 0; i < this.peekBlockStarts.length; i++) {
1722
- if (this.peekBlockStarts[i] > this.peekState.scrollOffset) break;
1723
- if (this.peekBlocks[i]?.type !== "tool-call" && this.peekBlocks[i]?.type !== "tool-result") {
2406
+ // The block containing the current top line is the one selected. Include
2407
+ // tool blocks: there is one target, not a second hidden tool focus.
2408
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length === this.peekBlocks.length) {
2409
+ let selected = 0;
2410
+ for (let i = 0; i < this.peekBlockStarts.length; i++) {
2411
+ if (this.peekBlockStarts[i] > this.peekState.scrollOffset) break;
1724
2412
  selected = i;
1725
2413
  }
2414
+ this.peekState.selectedIndex = selected;
2415
+ } else {
2416
+ this.peekState.selectedIndex = Math.max(
2417
+ 0,
2418
+ Math.min(this.peekState.selectedIndex, Math.max(0, this.peekBlocks.length - 1)),
2419
+ );
1726
2420
  }
1727
- this.peekState.selectedIndex = selected;
1728
2421
  this.tui.requestRender();
1729
2422
  }
1730
2423
 
@@ -1734,6 +2427,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1734
2427
  }
1735
2428
 
1736
2429
  private jumpPeekMessage(direction: 1 | -1): void {
2430
+ if (this.peekBlocks.length > 0 && this.peekBlockStarts.length !== this.peekBlocks.length) {
2431
+ this.render(this.lastRenderWidth);
2432
+ }
1737
2433
  const isMessage = (block: PeekBlock): boolean =>
1738
2434
  block.type !== "tool-call" && block.type !== "tool-result";
1739
2435
  let target = this.peekState.selectedIndex + direction;
@@ -1749,32 +2445,40 @@ export class BtwOverlayComponent extends Container implements Focusable {
1749
2445
  }
1750
2446
 
1751
2447
  private ensurePeekVisible(): void {
2448
+ if (this.peekBlocks.length === 0) {
2449
+ this.peekState.selectedIndex = 0;
2450
+ this.peekState.scrollOffset = 0;
2451
+ return;
2452
+ }
2453
+ this.peekState.selectedIndex = Math.max(
2454
+ 0,
2455
+ Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1),
2456
+ );
1752
2457
  const start = this.peekBlockStarts[this.peekState.selectedIndex];
1753
2458
  if (start === undefined) return;
1754
2459
 
1755
- const vh = this.peekState.viewportHeight;
2460
+ const vh = Math.max(1, this.peekState.viewportHeight);
2461
+ const maxScroll = Math.max(0, this.peekRenderedLines.length - vh);
1756
2462
  if (start < this.peekState.scrollOffset) {
1757
2463
  this.peekState.scrollOffset = start;
1758
2464
  } else if (start >= this.peekState.scrollOffset + vh) {
1759
2465
  this.peekState.scrollOffset = start - vh + 1;
1760
2466
  }
2467
+ this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
1761
2468
  }
1762
2469
 
1763
2470
  private peekGoToFirst(): void {
1764
- this.peekState.selectedIndex = 0;
2471
+ this.peekState.selectedIndex = this.peekBlocks.length === 0 ? 0 : 0;
1765
2472
  this.peekState.scrollOffset = 0;
1766
2473
  this.tui.requestRender();
1767
2474
  }
1768
2475
 
1769
2476
  private peekGoToLast(): void {
1770
- let last = Math.max(0, this.peekBlocks.length - 1);
1771
- while (last > 0 && (this.peekBlocks[last]?.type === "tool-call" || this.peekBlocks[last]?.type === "tool-result")) {
1772
- last--;
1773
- }
2477
+ const last = Math.max(0, this.peekBlocks.length - 1);
1774
2478
  this.peekState.selectedIndex = last;
1775
2479
  this.peekState.scrollOffset = Math.max(
1776
2480
  0,
1777
- this.peekRenderedLines.length - this.peekState.viewportHeight,
2481
+ this.peekRenderedLines.length - Math.max(1, this.peekState.viewportHeight),
1778
2482
  );
1779
2483
  this.tui.requestRender();
1780
2484
  }
@@ -1782,8 +2486,16 @@ export class BtwOverlayComponent extends Container implements Focusable {
1782
2486
  private peekToggleTools(): void {
1783
2487
  this.peekState.showTools = !this.peekState.showTools;
1784
2488
  this.rebuildPeekBlocks();
1785
- this.peekState.selectedIndex = Math.min(this.peekState.selectedIndex, Math.max(0, this.peekBlocks.length - 1));
2489
+ this.peekState.selectedIndex = this.peekBlocks.length === 0
2490
+ ? 0
2491
+ : Math.max(0, Math.min(this.peekState.selectedIndex, this.peekBlocks.length - 1));
1786
2492
  this.peekState.scrollOffset = 0;
2493
+ this.peekHoveredIndex = null;
2494
+ this.expandedToolId = null;
2495
+ this.peekToolPreviewIndex = null;
2496
+ this.peekToolPreviewBlockId = null;
2497
+ this.peekToolPreviewLines = [];
2498
+ this.peekToolPreviewScrollOffset = 0;
1787
2499
  this.peekState.searchMatches = [];
1788
2500
  this.peekState.currentMatchIndex = -1;
1789
2501
  this.tui.requestRender();
@@ -1899,6 +2611,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1899
2611
  }
1900
2612
 
1901
2613
  private handlePeekInput(data: string): void {
2614
+ if (this.peekToolPreviewIndex !== null && this.handleToolPreviewInput(data)) {
2615
+ return;
2616
+ }
2617
+
1902
2618
  // If in search mode, capture input for search query
1903
2619
  if (this.peekState.searchActive) {
1904
2620
  if (data === "\r" || data === "\n") {
@@ -1970,6 +2686,19 @@ export class BtwOverlayComponent extends Container implements Focusable {
1970
2686
  return;
1971
2687
  }
1972
2688
 
2689
+ // Full tool input/output preview. It is intentionally a no-op for text
2690
+ // blocks and tools whose BTW data model has no input/output.
2691
+ if (data === "w") {
2692
+ this.enterToolPreview();
2693
+ return;
2694
+ }
2695
+
2696
+ // Enter can expand a tool card, but must never submit while Peek owns input.
2697
+ if (data === "\r" || data === "\n") {
2698
+ this.toggleExpandedTool();
2699
+ return;
2700
+ }
2701
+
1973
2702
  // Copy current message
1974
2703
  if (data === "M") {
1975
2704
  void this.peekCopyCurrent();
@@ -1983,12 +2712,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1983
2712
  }
1984
2713
 
1985
2714
  // Page up/down
1986
- if (data === "\x1b[5~" || data === "\x1b[5;*~") {
2715
+ if (matchesPageKey(data, 5)) {
1987
2716
  // PageUp
1988
2717
  this.scrollPeekPage(-1);
1989
2718
  return;
1990
2719
  }
1991
- if (data === "\x1b[6~" || data === "\x1b[6;*~") {
2720
+ if (matchesPageKey(data, 6)) {
1992
2721
  // PageDown
1993
2722
  this.scrollPeekPage(1);
1994
2723
  return;
@@ -1996,7 +2725,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1996
2725
 
1997
2726
  // Leaving Peek always returns to the BTW composer. The composer itself
1998
2727
  // remains responsible for dismissing the BTW overlay.
1999
- if (data === "q" || data === "\x03" || data === "\r" || data === "\n" || data === "\x1b") {
2728
+ if (data === "q" || data === "\x03" || data === "\x1b") {
2000
2729
  this.exitPeekMode();
2001
2730
  return;
2002
2731
  }
@@ -2024,6 +2753,7 @@ export default function (pi: ExtensionAPI) {
2024
2753
  let overlayRuntime: OverlayRuntime | null = null;
2025
2754
  let lastUiContext: ExtensionContext | ExtensionCommandContext | null = null;
2026
2755
  let activeBtwSession: BtwSessionRuntime | null = null;
2756
+ let btwStore: BtwTranscriptStore | null = null;
2027
2757
 
2028
2758
  function syncUi(ctx?: ExtensionContext | ExtensionCommandContext): void {
2029
2759
  const activeCtx = ctx ?? lastUiContext;
@@ -2038,6 +2768,68 @@ export default function (pi: ExtensionAPI) {
2038
2768
  syncUi(ctx);
2039
2769
  }
2040
2770
 
2771
+ function ensureBtwStore(ctx: ExtensionContext | ExtensionCommandContext): BtwTranscriptStore {
2772
+ const sessionId = ctx.sessionManager.getSessionId();
2773
+ if (!btwStore || btwStore.threadId !== sessionId) {
2774
+ btwStore = new BtwTranscriptStore(ctx.cwd, sessionId);
2775
+ }
2776
+ return btwStore;
2777
+ }
2778
+
2779
+ function persistTranscriptState(): void {
2780
+ if (!btwStore) return;
2781
+ try {
2782
+ const snapshot = btwStore.appendSnapshot({
2783
+ mode: pendingMode,
2784
+ entries: transcriptState.entries as unknown as DurableTranscriptSnapshot["entries"],
2785
+ nextEntryId: transcriptState.nextEntryId,
2786
+ nextTurnId: transcriptState.nextTurnId,
2787
+ currentTurnId: transcriptState.currentTurnId,
2788
+ lastTurnId: transcriptState.lastTurnId,
2789
+ });
2790
+ // Keep only a small, immutable locator in the Pi session. Large tool
2791
+ // payloads remain in .pi-subagents/btw and never enter LLM context.
2792
+ pi.appendEntry(BTW_TRANSCRIPT_TYPE, makeTranscriptLocator(btwStore, snapshot));
2793
+ } catch {
2794
+ // Durable BTW storage is best effort. The in-memory transcript remains
2795
+ // authoritative for the current overlay when a filesystem is unavailable.
2796
+ }
2797
+ }
2798
+
2799
+ function persistToolArtifact(event: AgentSessionEvent): void {
2800
+ if (!btwStore) return;
2801
+ try {
2802
+ if (event.type === "tool_execution_start") {
2803
+ btwStore.writeToolArtifact({
2804
+ toolCallId: event.toolCallId,
2805
+ toolName: event.toolName,
2806
+ phase: "start",
2807
+ input: event.args,
2808
+ isError: false,
2809
+ });
2810
+ } else if (event.type === "tool_execution_update") {
2811
+ btwStore.writeToolArtifact({
2812
+ toolCallId: event.toolCallId,
2813
+ toolName: event.toolName,
2814
+ phase: "update",
2815
+ output: event.partialResult,
2816
+ isError: false,
2817
+ });
2818
+ } else if (event.type === "tool_execution_end") {
2819
+ btwStore.writeToolArtifact({
2820
+ toolCallId: event.toolCallId,
2821
+ toolName: event.toolName,
2822
+ phase: "end",
2823
+ output: event.result,
2824
+ isError: event.isError,
2825
+ });
2826
+ }
2827
+ } catch {
2828
+ // Tool artifacts are diagnostics; a failed artifact write must not abort
2829
+ // the side conversation or change its visible transcript.
2830
+ }
2831
+ }
2832
+
2041
2833
  function setOverlayDraft(value: string): void {
2042
2834
  overlayDraft = value;
2043
2835
  overlayRuntime?.setDraft?.(value);
@@ -2097,11 +2889,17 @@ export default function (pi: ExtensionAPI) {
2097
2889
  event: AgentSessionEvent,
2098
2890
  ctx?: ExtensionContext | ExtensionCommandContext,
2099
2891
  ): void {
2100
- if (activeBtwSession?.session !== sessionRuntime.session || !overlayRuntime) {
2892
+ if (activeBtwSession?.session !== sessionRuntime.session) {
2101
2893
  return;
2102
2894
  }
2103
2895
 
2896
+ persistToolArtifact(event);
2104
2897
  applyTranscriptEvent(transcriptState, event);
2898
+ persistTranscriptState();
2899
+
2900
+ if (!overlayRuntime) {
2901
+ return;
2902
+ }
2105
2903
 
2106
2904
  if (event.type === "tool_execution_start") {
2107
2905
  setOverlayStatus(`⏳ running tool: ${event.toolName}`, ctx);
@@ -2388,6 +3186,7 @@ export default function (pi: ExtensionAPI) {
2388
3186
  },
2389
3187
  undefined,
2390
3188
  ctx.cwd,
3189
+ (toolCallId) => btwStore?.readToolArtifact(toolCallId) ?? null,
2391
3190
  );
2392
3191
 
2393
3192
  overlay.focused = runtime.handle?.isFocused() ?? true;
@@ -2665,6 +3464,8 @@ export default function (pi: ExtensionAPI) {
2665
3464
  pendingThread = [];
2666
3465
  pendingMode = mode;
2667
3466
  transcriptState = createEmptyTranscriptState();
3467
+ ensureBtwStore(ctx);
3468
+ persistTranscriptState();
2668
3469
  setOverlayDraft("");
2669
3470
  setOverlayStatus(null, ctx);
2670
3471
  if (persist) {
@@ -2684,9 +3485,11 @@ export default function (pi: ExtensionAPI) {
2684
3485
  overlayDraft = "";
2685
3486
  lastUiContext = ctx;
2686
3487
  overlayStatus = null;
3488
+ btwStore = new BtwTranscriptStore(ctx.cwd, ctx.sessionManager.getSessionId());
2687
3489
 
2688
3490
  const branch = ctx.sessionManager.getBranch();
2689
3491
  let lastResetIndex = -1;
3492
+ let transcriptLocator: { schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION; threadId: string; recordId: string } | null = null;
2690
3493
 
2691
3494
  for (let i = 0; i < branch.length; i++) {
2692
3495
  if (isCustomEntry(branch[i], BTW_MODEL_OVERRIDE_TYPE)) {
@@ -2708,7 +3511,9 @@ export default function (pi: ExtensionAPI) {
2708
3511
  const details = (branch[i] as unknown as { data?: BtwThinkingOverrideDetails }).data;
2709
3512
  btwThinkingOverride =
2710
3513
  details?.action === "set"
2711
- ? details.thinkingLevel
3514
+ ? isSessionThinkingLevel(details.thinkingLevel)
3515
+ ? details.thinkingLevel
3516
+ : null
2712
3517
  : details?.action === "clear"
2713
3518
  ? null
2714
3519
  : btwThinkingOverride;
@@ -2716,9 +3521,41 @@ export default function (pi: ExtensionAPI) {
2716
3521
 
2717
3522
  if (isCustomEntry(branch[i], BTW_RESET_TYPE)) {
2718
3523
  lastResetIndex = i;
3524
+ transcriptLocator = null;
2719
3525
  const details = (branch[i] as unknown as { data?: BtwResetDetails }).data;
2720
3526
  pendingMode = details?.mode ?? "contextual";
2721
3527
  }
3528
+
3529
+ if (i > lastResetIndex && isCustomEntry(branch[i], BTW_TRANSCRIPT_TYPE)) {
3530
+ const details = (branch[i] as unknown as { data?: unknown }).data;
3531
+ if (isTranscriptLocator(details)) {
3532
+ transcriptLocator = details;
3533
+ }
3534
+ }
3535
+ }
3536
+
3537
+ // A branch must opt into a persisted snapshot through its locator. Never
3538
+ // fall back to the newest file record here: the same session can have
3539
+ // divergent branches and that would leak one branch's BTW transcript into
3540
+ // another branch.
3541
+ const restored = transcriptLocator && transcriptLocator.threadId === btwStore.threadId
3542
+ ? btwStore.readSnapshot(transcriptLocator.recordId)
3543
+ : null;
3544
+ if (restored) {
3545
+ transcriptState = {
3546
+ entries: restored.snapshot.entries as unknown as BtwTranscript,
3547
+ nextEntryId: restored.snapshot.nextEntryId,
3548
+ nextTurnId: restored.snapshot.nextTurnId,
3549
+ currentTurnId: restored.snapshot.currentTurnId,
3550
+ lastTurnId: restored.snapshot.lastTurnId,
3551
+ toolCalls: restored.toolCalls,
3552
+ };
3553
+ pendingMode = restored.snapshot.mode;
3554
+ if (closeRestoredStreamingTurns(transcriptState)) {
3555
+ // Make the recovery durable immediately so another reload observes the
3556
+ // same closed historical turn instead of reviving a dead stream.
3557
+ persistTranscriptState();
3558
+ }
2722
3559
  }
2723
3560
 
2724
3561
  for (const entry of branch.slice(lastResetIndex + 1)) {
@@ -2733,13 +3570,23 @@ export default function (pi: ExtensionAPI) {
2733
3570
 
2734
3571
  const normalizedDetails: BtwDetails = {
2735
3572
  ...details,
3573
+ schemaVersion: details.schemaVersion === BTW_TRANSCRIPT_SCHEMA_VERSION
3574
+ ? details.schemaVersion
3575
+ : BTW_TRANSCRIPT_SCHEMA_VERSION,
2736
3576
  api: details.api || ctx.model?.api || "openai-responses",
2737
3577
  };
2738
3578
 
2739
3579
  pendingThread.push(normalizedDetails);
2740
- appendPersistedTranscriptTurn(transcriptState, normalizedDetails);
3580
+ if (!restored) {
3581
+ appendPersistedTranscriptTurn(transcriptState, normalizedDetails);
3582
+ }
2741
3583
  }
2742
3584
 
3585
+ // Sessions created before durable BTW storage still get a first snapshot
3586
+ // after restore, while current sessions retain the exact persisted state.
3587
+ if (!restored && pendingThread.length > 0) {
3588
+ persistTranscriptState();
3589
+ }
2743
3590
  syncUi(ctx);
2744
3591
  }
2745
3592
 
@@ -2750,6 +3597,7 @@ export default function (pi: ExtensionAPI) {
2750
3597
  mode: BtwThreadMode,
2751
3598
  ): Promise<void> {
2752
3599
  lastUiContext = ctx;
3600
+ ensureBtwStore(ctx);
2753
3601
  const settings = await resolveBtwSettings(ctx);
2754
3602
  const model = settings.model;
2755
3603
  if (!model) {
@@ -2792,6 +3640,7 @@ export default function (pi: ExtensionAPI) {
2792
3640
  }
2793
3641
  if (response.stopReason === "aborted") {
2794
3642
  removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
3643
+ persistTranscriptState();
2795
3644
  setOverlayStatus("Request aborted.", ctx);
2796
3645
  return;
2797
3646
  }
@@ -2806,6 +3655,7 @@ export default function (pi: ExtensionAPI) {
2806
3655
  const thinking = extractThinking(response) || streamedThinking || "";
2807
3656
 
2808
3657
  const details: BtwDetails = {
3658
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
2809
3659
  question,
2810
3660
  thinking,
2811
3661
  answer,
@@ -2819,6 +3669,7 @@ export default function (pi: ExtensionAPI) {
2819
3669
 
2820
3670
  pendingThread.push(details);
2821
3671
  pi.appendEntry(BTW_ENTRY_TYPE, details);
3672
+ persistTranscriptState();
2822
3673
 
2823
3674
  const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
2824
3675
  if (saveState === "saved") {
@@ -2833,6 +3684,7 @@ export default function (pi: ExtensionAPI) {
2833
3684
  } catch (error) {
2834
3685
  const errorMessage = error instanceof Error ? error.message : String(error);
2835
3686
  setTranscriptFailure(transcriptState, errorMessage);
3687
+ persistTranscriptState();
2836
3688
  setOverlayStatus("Request failed. Thread preserved for retry or follow-up.", ctx);
2837
3689
  notify(ctx, errorMessage, "error");
2838
3690
  await disposeBtwSession();