pi-render-btw 0.6.12 → 0.6.14

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.14 — 2026-09-18
4
+
5
+ - Keep BTW, Peek, and read-only Tool Output rendering aligned with Pi Markdown/tool colors and syntax highlighting, including safe terminal-text sanitization.
6
+ - Add a native-style right-hand scrollbar with `↑ N more` / `↓ N more` viewport affordances to the BTW transcript, Peek, and Tool Output surfaces.
7
+ - Add local BTW draft recall for `Alt+Up`, `a-up`, and `alt+up`; busy-session saved notes and handoffs continue through Pi follow-up delivery without mutating the read-only viewers.
8
+
9
+ ## 0.6.13 — 2026-09-14
10
+
11
+ - Keep the BTW/Peek/Tool Output title-row `[Esc]` affordance visible beside long titles.
12
+ - Highlight `[Esc]` on hover and close the current surface on a normalized or legacy SGR mouse click.
13
+
3
14
  ## 0.6.12 — 2026-09-13
4
15
 
5
16
  - Recover interrupted streaming turns as closed history after reload.
package/README.md CHANGED
@@ -22,6 +22,7 @@ with **full markdown rendering** (syntax highlighting, bold, code blocks, lists,
22
22
  - lets you inject the full thread, or a summary of it, back into the main agent
23
23
  - optionally saves an individual BTW exchange as a visible session note with `--save`
24
24
  - includes an internal Peek mode for browsing the current BTW side thread
25
+ - keeps a native-style right-hand scrollbar in the BTW transcript, Peek, and read-only Tool Output views, with `↑ N more` / `↓ N more` affordances at the viewport edges
25
26
 
26
27
  ## ✨ Markdown rendering
27
28
 
@@ -94,7 +95,7 @@ pi install /path/to/pi-render-btw
94
95
  - `Alt+/` toggles focus between BTW and the main editor without closing the overlay
95
96
  - `Ctrl+Alt+W` is a fallback focus toggle for terminals that do not deliver `Alt+/` as a usable shortcut
96
97
  - `Ctrl+G` opens the current BTW draft in `$VISUAL`/`$EDITOR` (falling back to `nano`) and reads it back when the editor exits successfully
97
- - the composer uses Pi's native editor behavior for undo, paste, prompt history, and Tab file-path completion (including `@` prefixes) relative to the BTW working directory
98
+ - the composer uses Pi's native editor behavior for undo, paste, prompt history, and Tab file-path completion (including `@` prefixes) relative to the BTW working directory; `Alt+Up` (`a-up`/`alt+up`) recalls a submitted draft
98
99
  - `Esc` still dismisses BTW immediately while the overlay is focused
99
100
  - hovering and left-clicking a transcript row focuses one shared USER/ASSISTANT/Tool target; clicking a Tool row toggles its compact details and double-clicking collapses it
100
101
  - with a focused Tool row, `Ctrl+O` opens a read-only Input/Output viewer; while the runtime emits partial tool updates it shows the latest provided data with a `STREAMING` marker, and after tool completion it switches to the final result
@@ -128,7 +129,8 @@ pi install /path/to/pi-render-btw
128
129
  - normalized mouse hover highlights a block and a left click selects it; press/release events do not change selection
129
130
  - `M` copies the selected message; `o` opens it read-only in nvim
130
131
  - `Esc`, `q`, or `Ctrl+C` returns to the BTW composer; press `Esc` again in the composer to dismiss BTW
131
- - the Peek and Tool Output headers show `[Esc]`; wheel input is handled locally without changing the main viewport
132
+ - the Peek and Tool Output headers show a hoverable `[Esc]` close/back affordance; wheel input is handled locally without changing the main viewport
133
+ - the BTW transcript, Peek, and Tool Output keep their scroll thumb in the rightmost cell, show hidden-line counts above/below the viewport, and support line/page/top/bottom navigation without entering the composer
132
134
 
133
135
  ### `/btw:clear`
134
136
 
@@ -0,0 +1,175 @@
1
+ import { getLanguageFromPath, getMarkdownTheme, highlightCode } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Markdown,
4
+ truncateToWidth,
5
+ visibleWidth,
6
+ wrapTextWithAnsi,
7
+ type MarkdownTheme,
8
+ } from "@earendil-works/pi-tui";
9
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+
11
+ export type BtwTheme = Pick<ExtensionContext["ui"]["theme"], "fg" | "bold" | "italic">;
12
+ export type BtwMarkdownRole = "user" | "assistant" | "thinking";
13
+
14
+ const UNSAFE_TERMINAL_ESCAPE = new RegExp(
15
+ "(?:\\u001B\\]|\\u009D)[\\s\\S]*?(?:\\u0007|\\u001B\\x5C|\\u009C)" +
16
+ "|(?:\\u001B[PX^_]|\\u0090)[\\s\\S]*?(?:\\u001B\\x5C|\\u009C)" +
17
+ "|(?:\\u001B\\[|\\u009B)[0-?]*[ -/]*[@-~]" +
18
+ "|\\u001B[@-_]",
19
+ "g",
20
+ );
21
+
22
+ /** Strip terminal control sequences before captured tool text is rendered again. */
23
+ export function sanitizeBtwText(value: string): string {
24
+ return value
25
+ .replace(UNSAFE_TERMINAL_ESCAPE, "")
26
+ .replace(/\x1B/g, "")
27
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "")
28
+ .replace(/\r\n?/g, "\n");
29
+ }
30
+
31
+ function fitLine(line: string, width: number): string {
32
+ const safeWidth = Math.max(1, Math.floor(Number.isFinite(width) ? width : 1));
33
+ return truncateToWidth(line, safeWidth, "");
34
+ }
35
+
36
+ function fitLines(lines: readonly string[], width: number): string[] {
37
+ return lines.length > 0 ? lines.map((line) => fitLine(line, width)) : [""];
38
+ }
39
+
40
+ /**
41
+ * Render BTW text with the same Markdown component/theme contract as Pi's
42
+ * native user and assistant message components. The role color is only a
43
+ * default style; Markdown code spans and blocks retain the native token colors.
44
+ */
45
+ export function renderBtwMarkdown(
46
+ text: string,
47
+ width: number,
48
+ theme: BtwTheme,
49
+ role: BtwMarkdownRole,
50
+ markdownTheme: MarkdownTheme = getMarkdownTheme(),
51
+ ): string[] {
52
+ const color = role === "user" ? "userMessageText" : role === "thinking" ? "thinkingText" : "text";
53
+ const source = sanitizeBtwText(text);
54
+ try {
55
+ const markdown = new Markdown(
56
+ source || "∅",
57
+ 0,
58
+ 0,
59
+ markdownTheme,
60
+ { color: (value) => theme.fg(color, value) },
61
+ role === "user"
62
+ ? { preserveOrderedListMarkers: true, preserveBackslashEscapes: true }
63
+ : undefined,
64
+ );
65
+ return fitLines(markdown.render(Math.max(1, Math.floor(width))), width);
66
+ } catch {
67
+ return fitLines(wrapTextWithAnsi(source || "∅", Math.max(1, Math.floor(width))), width);
68
+ }
69
+ }
70
+
71
+ function parseToolArgs(args: string | undefined): Record<string, unknown> | undefined {
72
+ if (!args?.trim()) return undefined;
73
+ try {
74
+ const parsed: unknown = JSON.parse(args);
75
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
76
+ return parsed as Record<string, unknown>;
77
+ }
78
+ } catch {
79
+ // A compact transcript may retain only the path as its tool input.
80
+ }
81
+ return { path: args.trim() };
82
+ }
83
+
84
+ function languageFromArgs(args: string | undefined): string | undefined {
85
+ const parsed = parseToolArgs(args);
86
+ const candidate = parsed?.file_path ?? parsed?.filePath ?? parsed?.path;
87
+ if (typeof candidate !== "string" || !candidate.trim()) return undefined;
88
+ try {
89
+ return getLanguageFromPath(candidate.replace(/^@/, "").trim());
90
+ } catch {
91
+ return undefined;
92
+ }
93
+ }
94
+
95
+ function languageFromFence(text: string): string | undefined {
96
+ const match = text.match(/^\s*(`{3,}|~{3,})\s*([A-Za-z][\w+.-]*)\b[^\n]*$/m);
97
+ return match?.[2];
98
+ }
99
+
100
+ /**
101
+ * Render tool output using Pi's synchronous native syntax highlighter when a
102
+ * tool path or explicit fenced language identifies the output. Plain output
103
+ * keeps the tool-output semantic color and is always terminal-safe.
104
+ */
105
+ export function renderBtwToolText(
106
+ text: string,
107
+ width: number,
108
+ theme: BtwTheme,
109
+ args?: string,
110
+ isError = false,
111
+ ): string[] {
112
+ const source = sanitizeBtwText(text);
113
+ const language = languageFromArgs(args) ?? languageFromFence(source);
114
+ let highlighted: string[] | undefined;
115
+ if (language && source.trim() && source.length <= 200_000) {
116
+ try {
117
+ // highlightCode is Pi's own renderer and returns only terminal SGR
118
+ // styling; preserve those token colors while the source itself remains
119
+ // sanitized before entering the highlighter.
120
+ highlighted = highlightCode(source, language);
121
+ } catch {
122
+ highlighted = undefined;
123
+ }
124
+ }
125
+
126
+ const output = highlighted ?? source.split("\n");
127
+ const color = isError ? "error" : "toolOutput";
128
+ const safeWidth = Math.max(1, Math.floor(Number.isFinite(width) ? width : 1));
129
+ const rendered: string[] = [];
130
+ for (const line of output.length > 0 ? output : [""]) {
131
+ const styled = highlighted ? line : theme.fg(color, line);
132
+ rendered.push(...fitLines(wrapTextWithAnsi(styled, safeWidth), safeWidth));
133
+ }
134
+ return rendered.length > 0 ? rendered : [""];
135
+ }
136
+
137
+ export function renderBtwScrollRail(
138
+ theme: BtwTheme,
139
+ totalLines: number,
140
+ viewportHeight: number,
141
+ scrollOffset: number,
142
+ lineIndex: number,
143
+ scrollbarActive = false,
144
+ ): string {
145
+ const total = Math.max(0, Math.floor(totalLines));
146
+ const viewport = Math.max(1, Math.floor(viewportHeight));
147
+ const offset = Math.max(0, Math.min(Math.max(0, total - viewport), Math.floor(scrollOffset)));
148
+ if (total <= viewport) return theme.fg("scrollbarTrack", " ");
149
+
150
+ const thumbHeight = Math.max(1, Math.round((viewport * viewport) / total));
151
+ const thumbStart = Math.round(((viewport - thumbHeight) * offset) / (total - viewport));
152
+ const inThumb = lineIndex >= thumbStart && lineIndex < thumbStart + thumbHeight;
153
+ return theme.fg(
154
+ inThumb ? "scrollbarThumb" : "scrollbarTrack",
155
+ inThumb ? (scrollbarActive ? "█" : "┃") : "│",
156
+ );
157
+ }
158
+
159
+ export function renderBtwScrollRule(
160
+ theme: BtwTheme,
161
+ innerWidth: number,
162
+ direction: "top" | "bottom",
163
+ hiddenLines: number,
164
+ ): string | undefined {
165
+ if (hiddenLines <= 0) return undefined;
166
+ const safeWidth = Math.max(1, Math.floor(innerWidth));
167
+ const label = `${direction === "top" ? "↑" : "↓"} ${hiddenLines} more`;
168
+ const labelWidth = visibleWidth(label);
169
+ if (labelWidth + 2 > safeWidth) {
170
+ return theme.fg("border", `├${"─".repeat(Math.max(0, safeWidth - 1))}┤`);
171
+ }
172
+ const left = Math.floor((safeWidth - labelWidth) / 2);
173
+ const right = Math.max(0, safeWidth - left - labelWidth);
174
+ return `${theme.fg("border", `├${"─".repeat(left)}`)}${theme.fg("dim", label)}${theme.fg("border", `${"─".repeat(right)}┤`)}`;
175
+ }
@@ -144,6 +144,32 @@ describe("BTW transcript message layout", () => {
144
144
  expect(component.getDraft()).toBe(testValue);
145
145
  });
146
146
 
147
+ it("recalls the newest submitted draft through Alt+Up aliases", () => {
148
+ const submitted: string[] = [];
149
+ const component = new BtwOverlayComponent(
150
+ tui,
151
+ theme,
152
+ keybindings,
153
+ () => [],
154
+ () => null,
155
+ () => "contextual",
156
+ (value) => submitted.push(value),
157
+ () => {},
158
+ () => {},
159
+ );
160
+
161
+ component.setDraft("first side question");
162
+ component.handleInput("\r");
163
+ expect(submitted).toEqual(["first side question"]);
164
+
165
+ component.setDraft("new draft");
166
+ component.handleInput("alt+up");
167
+ expect(component.getDraft()).toBe("first side question");
168
+ component.setDraft("new draft");
169
+ component.handleInput("a-up");
170
+ expect(component.getDraft()).toBe("first side question");
171
+ });
172
+
147
173
  it("routes Ctrl+G to the external-editor callback", () => {
148
174
  let opened = 0;
149
175
  const externalKeybindings = {
@@ -676,6 +702,75 @@ describe("BTW transcript message layout", () => {
676
702
  expect(dismissed).toBe(1);
677
703
  });
678
704
 
705
+ it("keeps the title [Esc] affordance visible, highlights it on hover, and closes on click", () => {
706
+ let dismissed = 0;
707
+ const component = new BtwOverlayComponent(
708
+ tui,
709
+ theme,
710
+ keybindings,
711
+ () => [],
712
+ () => null,
713
+ () => "contextual",
714
+ () => {},
715
+ () => { dismissed++; },
716
+ () => {},
717
+ );
718
+
719
+ const lines = component.render(24);
720
+ expect(lines[1]).toMatch(/\[Esc\]│$/);
721
+
722
+ const hover = component.handleMouse({ type: "move", button: "none", x: 20, y: 1 } as any);
723
+ expect((component as any).hoveredEscapeHint).toBe(true);
724
+ expect(hover).toEqual({ handled: true, render: true });
725
+
726
+ const click = component.handleMouse({ type: "click", button: "left", x: 20, y: 1 } as any);
727
+ expect(click).toEqual({ handled: true, render: false });
728
+ expect(dismissed).toBe(1);
729
+ });
730
+
731
+ it("uses the title [Esc] button in Peek as back, not overlay dismissal", () => {
732
+ let dismissed = 0;
733
+ const component = new BtwOverlayComponent(
734
+ tui,
735
+ theme,
736
+ keybindings,
737
+ () => [],
738
+ () => null,
739
+ () => "contextual",
740
+ () => {},
741
+ () => { dismissed++; },
742
+ () => {},
743
+ );
744
+
745
+ component.handleInput("\x10");
746
+ component.render(80);
747
+ component.handleMouse({ type: "click", button: "left", x: 76, y: 1 } as any);
748
+
749
+ expect((component as any).peekState.active).toBe(false);
750
+ expect(dismissed).toBe(0);
751
+ });
752
+
753
+ it("closes from the title [Esc] button through the raw SGR fallback", () => {
754
+ let dismissed = 0;
755
+ const component = new BtwOverlayComponent(
756
+ tui,
757
+ theme,
758
+ keybindings,
759
+ () => [],
760
+ () => null,
761
+ () => "contextual",
762
+ () => {},
763
+ () => { dismissed++; },
764
+ () => {},
765
+ );
766
+
767
+ component.render(80);
768
+ component.handleInput("\x1b[<0;77;2M");
769
+ component.handleInput("\x1b[<0;77;2m");
770
+
771
+ expect(dismissed).toBe(1);
772
+ });
773
+
679
774
  it("configures fd-backed completion for @ path suggestions", () => {
680
775
  const component = new BtwOverlayComponent(
681
776
  tui,
package/extensions/btw.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  type ExtensionAPI,
15
15
  type ExtensionCommandContext,
16
16
  type ExtensionContext,
17
+ type ModelRuntime,
17
18
  type ResourceLoader,
18
19
  } from "@earendil-works/pi-coding-agent";
19
20
  import { type AssistantMessage, type Message, type ThinkingLevel as AiThinkingLevel, type UserMessage } from "@earendil-works/pi-ai";
@@ -21,7 +22,6 @@ import {
21
22
  Box,
22
23
  Container,
23
24
  Key,
24
- Markdown,
25
25
  Text,
26
26
  matchesKey,
27
27
  truncateToWidth,
@@ -50,6 +50,12 @@ import {
50
50
  type PeekEntry,
51
51
  type PeekModeState,
52
52
  } from "./btw/peek.ts";
53
+ import {
54
+ renderBtwMarkdown,
55
+ renderBtwScrollRail,
56
+ renderBtwScrollRule,
57
+ renderBtwToolText,
58
+ } from "./btw/render-utils.ts";
53
59
  import {
54
60
  BTW_TRANSCRIPT_SCHEMA_VERSION,
55
61
  BtwTranscriptStore,
@@ -253,7 +259,9 @@ function createBtwResourceLoader(
253
259
  getThemes: () => ({ themes: [], diagnostics: [] }),
254
260
  getAgentsFiles: () => ({ agentsFiles: [] }),
255
261
  getSystemPrompt: () => systemPrompt,
262
+ getSystemPromptSource: () => undefined,
256
263
  getAppendSystemPrompt: () => appendSystemPrompt,
264
+ getAppendSystemPromptSources: () => [],
257
265
  extendResources: () => {},
258
266
  reload: async () => {},
259
267
  };
@@ -1141,6 +1149,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1141
1149
  private readonly onUnfocusCallback: () => void;
1142
1150
  private readonly onExternalEditorCallback?: () => void;
1143
1151
  private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1152
+ /** BTW keeps its own recall cursor so Alt+Up works even when host history bindings are unset. */
1153
+ private draftHistory: string[] = [];
1154
+ private draftHistoryIndex = -1;
1155
+ private draftHistoryDraft = "";
1144
1156
  private externalEditorActive = false;
1145
1157
  private readonly tui: TUI;
1146
1158
  private readonly theme: ExtensionContext["ui"]["theme"];
@@ -1150,6 +1162,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1150
1162
  private transcriptScrollOffset = 0;
1151
1163
  private transcriptViewportHeight = 8;
1152
1164
  private followTranscript = true;
1165
+ private scrollbarActive = false;
1153
1166
  private liveHoveredEntryId: number | null = null;
1154
1167
  private liveFocusedEntryId: number | null = null;
1155
1168
  private liveFocusedToolCallId: string | null = null;
@@ -1175,6 +1188,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1175
1188
  private peekToolPreviewLines: string[] = [];
1176
1189
  private peekToolPreviewScrollOffset = 0;
1177
1190
  private expandedToolId: number | null = null;
1191
+ private hoveredEscapeHint = false;
1192
+ private rawEscapePress = false;
1178
1193
  /** The same bounded preview is used by Peek and by the live BTW panel. */
1179
1194
  private toolPreviewParent: "peek" | "live" | null = null;
1180
1195
  private liveToolPreviewBlock: PeekBlock | null = null;
@@ -1240,6 +1255,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1240
1255
  this.input = new CustomEditor(tui, editorTheme, editorKeybindings);
1241
1256
  this.input.onSubmit = (value) => {
1242
1257
  this.input.addToHistory(value);
1258
+ this.rememberDraft(value);
1243
1259
  this.followTranscript = true;
1244
1260
  this.onSubmitCallback(value);
1245
1261
  };
@@ -1258,6 +1274,15 @@ export class BtwOverlayComponent extends Container implements Focusable {
1258
1274
 
1259
1275
  const originalHandleInput = this.input.handleInput.bind(this.input);
1260
1276
  this.input.handleInput = (data: string) => {
1277
+ // Some hosts expose Alt+Up as the symbolic `a-up` token rather than a
1278
+ // terminal escape sequence. Keep draft recall local to BTW so this does
1279
+ // not depend on the host having configured an editor history binding.
1280
+ if (matchesKey(data, Key.alt("up")) || data === "a-up" || data === "alt+up") {
1281
+ this.recallDraft(-1);
1282
+ this.tui.requestRender();
1283
+ return;
1284
+ }
1285
+
1261
1286
  if (keybindings.matches(data, "app.editor.external")) {
1262
1287
  if (this.onExternalEditorCallback) {
1263
1288
  this.onExternalEditorCallback();
@@ -1270,6 +1295,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1270
1295
  // app.clear with non-empty input → clear input
1271
1296
  if (keybindings.matches(data, "app.clear") && this.input.getText().length > 0) {
1272
1297
  this.input.setText("");
1298
+ this.resetDraftRecall();
1273
1299
  this.tui.requestRender();
1274
1300
  return;
1275
1301
  }
@@ -1277,7 +1303,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
1277
1303
  // Everything else (including Escape → dismiss, Enter → submit,
1278
1304
  // Ctrl+Enter → newline) goes to CustomEditor's own handler
1279
1305
  // (CustomEditor delegates app keybindings, then Editor).
1306
+ const before = this.input.getText();
1280
1307
  originalHandleInput(data);
1308
+ if (before !== this.input.getText()) {
1309
+ this.resetDraftRecall();
1310
+ }
1281
1311
  };
1282
1312
 
1283
1313
  this.refresh();
@@ -1323,6 +1353,40 @@ export class BtwOverlayComponent extends Container implements Focusable {
1323
1353
  return `${this.theme.fg("border", "│")}${truncated}${" ".repeat(padding)}${this.theme.fg("border", "│")}`;
1324
1354
  }
1325
1355
 
1356
+ /**
1357
+ * Frame one row of a bounded ScrollView-like viewport. The rail occupies
1358
+ * the last cell inside the box, so content never gets painted over it.
1359
+ */
1360
+ private frameScrollableLine(
1361
+ content: string,
1362
+ innerWidth: number,
1363
+ totalLines: number,
1364
+ viewportHeight: number,
1365
+ scrollOffset: number,
1366
+ lineIndex: number,
1367
+ ): string {
1368
+ const contentWidth = Math.max(1, innerWidth - 1);
1369
+ const truncated = truncateToWidth(content, contentWidth, "");
1370
+ const padding = Math.max(0, contentWidth - visibleWidth(truncated));
1371
+ const rail = renderBtwScrollRail(
1372
+ this.theme,
1373
+ totalLines,
1374
+ viewportHeight,
1375
+ scrollOffset,
1376
+ lineIndex,
1377
+ this.scrollbarActive,
1378
+ );
1379
+ return `${this.theme.fg("border", "│")}${truncated}${" ".repeat(padding)}${rail}${this.theme.fg("border", "│")}`;
1380
+ }
1381
+
1382
+ private scrollRule(
1383
+ innerWidth: number,
1384
+ direction: "top" | "bottom",
1385
+ hiddenLines: number,
1386
+ ): string {
1387
+ return renderBtwScrollRule(this.theme, innerWidth, direction, hiddenLines) ?? this.ruleLine(innerWidth);
1388
+ }
1389
+
1326
1390
  private ruleLine(innerWidth: number): string {
1327
1391
  return this.theme.fg("border", `├${"─".repeat(innerWidth)}┤`);
1328
1392
  }
@@ -1334,9 +1398,57 @@ export class BtwOverlayComponent extends Container implements Focusable {
1334
1398
  }
1335
1399
 
1336
1400
  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);
1401
+ const escapeLabel = "[Esc]";
1402
+ const escapeHint = this.hoveredEscapeHint
1403
+ ? this.theme.fg("text", this.theme.bold(escapeLabel))
1404
+ : this.theme.fg("dim", escapeLabel);
1405
+ const escapeWidth = visibleWidth(escapeLabel);
1406
+ // Reserve the close label before truncating the title so a long tool name
1407
+ // can never hide the only visible mouse/keyboard dismissal affordance.
1408
+ const titleWidth = Math.max(0, innerWidth - escapeWidth - 1);
1409
+ const clippedTitle = truncateToWidth(title, titleWidth, "");
1410
+ const gap = Math.max(1, innerWidth - visibleWidth(clippedTitle) - escapeWidth);
1411
+ return this.frameLine(`${clippedTitle}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1412
+ }
1413
+
1414
+ private resetDraftRecall(): void {
1415
+ this.draftHistoryIndex = -1;
1416
+ this.draftHistoryDraft = "";
1417
+ }
1418
+
1419
+ private rememberDraft(value: string): void {
1420
+ const draft = value.trim();
1421
+ if (!draft) {
1422
+ this.resetDraftRecall();
1423
+ return;
1424
+ }
1425
+ // Match the native editor's useful behavior without creating an endless
1426
+ // run of identical entries when a prompt is submitted repeatedly.
1427
+ if (this.draftHistory[this.draftHistory.length - 1] !== value) {
1428
+ this.draftHistory.push(value);
1429
+ }
1430
+ this.resetDraftRecall();
1431
+ }
1432
+
1433
+ private recallDraft(direction: -1 | 1): void {
1434
+ if (this.draftHistory.length === 0) return;
1435
+
1436
+ if (this.draftHistoryIndex === -1) {
1437
+ this.draftHistoryDraft = this.input.getText();
1438
+ this.draftHistoryIndex = direction < 0 ? this.draftHistory.length - 1 : 0;
1439
+ } else {
1440
+ const next = this.draftHistoryIndex + direction;
1441
+ if (next < 0 || next >= this.draftHistory.length) {
1442
+ if (direction > 0 && this.draftHistoryIndex === this.draftHistory.length - 1) {
1443
+ this.draftHistoryIndex = -1;
1444
+ this.input.setText(this.draftHistoryDraft);
1445
+ }
1446
+ return;
1447
+ }
1448
+ this.draftHistoryIndex = next;
1449
+ }
1450
+
1451
+ this.input.setText(this.draftHistory[this.draftHistoryIndex]);
1340
1452
  }
1341
1453
 
1342
1454
  private wrapTranscript(innerWidth: number): string[] {
@@ -1374,7 +1486,13 @@ export class BtwOverlayComponent extends Container implements Focusable {
1374
1486
  const assistantBadge = buildTranscriptBadge(this.theme, "ASSISTANT", "customMessageBg", "success");
1375
1487
  const separator = this.theme.fg("borderMuted", "─".repeat(40));
1376
1488
  const blockIndent = " ";
1377
- const mdContentWidth = Math.max(1, innerWidth - visibleWidth(blockIndent));
1489
+ const toolArgsByCall = new Map<string, string>();
1490
+ for (const entry of entries) {
1491
+ if (entry.type === "tool-call") toolArgsByCall.set(entry.toolCallId, entry.args);
1492
+ }
1493
+ // Reserve the final inner cell for the right-hand ScrollView rail.
1494
+ const scrollContentWidth = Math.max(1, innerWidth - 1);
1495
+ const mdContentWidth = Math.max(1, scrollContentWidth - visibleWidth(blockIndent));
1378
1496
 
1379
1497
  const pushBlank = (): void => {
1380
1498
  if (allLines.length > 0 && allLines[allLines.length - 1] !== "") {
@@ -1396,7 +1514,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1396
1514
  pushBlank();
1397
1515
  allLines.push(`${focusRail(entry.id)}${userBadge}`);
1398
1516
  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);
1517
+ const mdLines = renderBtwMarkdown(boundedText, mdContentWidth, this.theme, "user", this.mdTheme);
1400
1518
  for (const line of mdLines) {
1401
1519
  allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1402
1520
  }
@@ -1408,9 +1526,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1408
1526
  const thinkingHeader = entry.streaming ? `${thinkingBadge} ${this.theme.fg("warning", "▍")}` : thinkingBadge;
1409
1527
  pushBlank();
1410
1528
  allLines.push(`${focusRail(entry.id)}${thinkingHeader}`);
1411
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1412
- for (const line of styledLines) {
1413
- allLines.push(`${blockIndent}${this.theme.fg("warning", this.theme.italic(line))}`);
1529
+ const markdownLines = renderBtwMarkdown(entry.text, mdContentWidth, this.theme, "thinking", this.mdTheme);
1530
+ for (const line of markdownLines) {
1531
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1414
1532
  }
1415
1533
  markBlock(entry.id, blockStart);
1416
1534
  continue;
@@ -1424,8 +1542,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1424
1542
  pushBlank();
1425
1543
  allLines.push(`${focusRail(entry.id)}${toolLabel}${argsLabel}${moreLabel}`);
1426
1544
  if (isExpanded && entry.args) {
1427
- for (const line of wrapTextWithAnsi(entry.args, mdContentWidth)) {
1428
- allLines.push(`${blockIndent}${this.theme.fg("dim", line)}`);
1545
+ const toolLines = renderBtwToolText(entry.args, mdContentWidth, this.theme);
1546
+ for (const line of toolLines) {
1547
+ allLines.push(`${blockIndent}${line}`);
1429
1548
  }
1430
1549
  }
1431
1550
  markBlock(entry.id, blockStart);
@@ -1443,8 +1562,15 @@ export class BtwOverlayComponent extends Container implements Focusable {
1443
1562
  pushBlank();
1444
1563
  allLines.push(`${focusRail(entry.id)}${resultLabel}${summary}${truncLabel}${moreLabel}`);
1445
1564
  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)}`);
1565
+ const toolLines = renderBtwToolText(
1566
+ entry.fullContent ?? entry.content,
1567
+ mdContentWidth,
1568
+ this.theme,
1569
+ entry.toolCallId ? toolArgsByCall.get(entry.toolCallId) : entry.toolName,
1570
+ entry.isError,
1571
+ );
1572
+ for (const line of toolLines) {
1573
+ allLines.push(`${blockIndent}${line}`);
1448
1574
  }
1449
1575
  }
1450
1576
  markBlock(entry.id, blockStart);
@@ -1456,27 +1582,17 @@ export class BtwOverlayComponent extends Container implements Focusable {
1456
1582
  const header = entry.streaming ? `${assistantBadge} ${this.theme.fg("warning", "▍")}` : assistantBadge;
1457
1583
  allLines.push(`${focusRail(entry.id)}${header}`);
1458
1584
 
1459
- if (!entry.streaming) {
1460
- // Render markdown for completed text — use cached result when available
1461
- const cached = this.mdLineCache.get(entry.id);
1462
- if (cached && cached.renderedAtWidth === mdContentWidth) {
1463
- for (const line of cached.lines) {
1464
- allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1465
- }
1466
- } else {
1467
- const md = new Markdown(entry.text, 0, 0, this.mdTheme);
1468
- const mdLines = md.render(mdContentWidth);
1469
- this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1470
- for (const line of mdLines) {
1471
- allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1472
- }
1473
- }
1474
- } else {
1475
- // While streaming, use plain text for speed and stability
1476
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1477
- for (const line of styledLines) {
1478
- allLines.push(`${blockIndent}${line}`);
1479
- }
1585
+ // Use the same Pi Markdown renderer for completed and streaming text.
1586
+ // Markdown is intentionally cheap here because the overlay already
1587
+ // coalesces streaming refreshes, and it avoids a visual mode switch at
1588
+ // the end of a response.
1589
+ const cached = this.mdLineCache.get(entry.id);
1590
+ const mdLines = cached && cached.renderedAtWidth === mdContentWidth
1591
+ ? cached.lines
1592
+ : renderBtwMarkdown(entry.text, mdContentWidth, this.theme, "assistant", this.mdTheme);
1593
+ this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1594
+ for (const line of mdLines) {
1595
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1480
1596
  }
1481
1597
  markBlock(entry.id, blockStart);
1482
1598
  continue;
@@ -1510,10 +1626,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1510
1626
  this.followTranscript = false;
1511
1627
  }
1512
1628
  const maxScroll = Math.max(0, this.transcriptLines.length - this.transcriptViewportHeight);
1513
- this.transcriptScrollOffset = Math.max(
1629
+ const nextOffset = Math.max(
1514
1630
  0,
1515
1631
  Math.min(maxScroll, this.transcriptScrollOffset + delta),
1516
1632
  );
1633
+ if (nextOffset !== this.transcriptScrollOffset) this.scrollbarActive = true;
1634
+ this.transcriptScrollOffset = nextOffset;
1517
1635
  if (this.transcriptScrollOffset >= maxScroll) {
1518
1636
  this.followTranscript = true;
1519
1637
  }
@@ -1569,6 +1687,23 @@ export class BtwOverlayComponent extends Container implements Focusable {
1569
1687
  return null;
1570
1688
  }
1571
1689
 
1690
+ /** The title row is line 2 in one-based local coordinates. */
1691
+ private isEscapeHintHit(x: number, y: number): boolean {
1692
+ const labelWidth = visibleWidth("[Esc]");
1693
+ const labelStart = this.lastRenderWidth - labelWidth;
1694
+ return y === 2 && x >= labelStart && x < this.lastRenderWidth;
1695
+ }
1696
+
1697
+ private closeEscapeTarget(): void {
1698
+ if (this.toolPreviewParent !== null) {
1699
+ this.exitToolPreview();
1700
+ } else if (this.peekState.active) {
1701
+ this.exitPeekMode();
1702
+ } else {
1703
+ this.onDismissCallback();
1704
+ }
1705
+ }
1706
+
1572
1707
  /**
1573
1708
  * Viewer-local mouse seam. Newer Pi TUI hosts call `handleMouse` with
1574
1709
  * zero-based `{ type, button, x, y, wheelDelta }` events; older hosts and
@@ -1612,6 +1747,32 @@ export class BtwOverlayComponent extends Container implements Focusable {
1612
1747
  delta: event.wheelDelta,
1613
1748
  };
1614
1749
 
1750
+ const overEscapeHint = this.isEscapeHintHit(normalized.x, normalized.y);
1751
+ if (normalized.action === "move" || normalized.action === "drag") {
1752
+ const hoverChanged = overEscapeHint !== this.hoveredEscapeHint;
1753
+ this.hoveredEscapeHint = overEscapeHint;
1754
+ if (overEscapeHint) {
1755
+ return { handled: true, render: hoverChanged };
1756
+ }
1757
+ // Continue routing a move outside the title to update transcript/block
1758
+ // hover state. In preview mode there is no other hover target.
1759
+ if (hoverChanged && this.toolPreviewParent !== null) {
1760
+ return { handled: true, render: true };
1761
+ }
1762
+ }
1763
+ if (overEscapeHint && normalized.button === 0) {
1764
+ if (normalized.action === "press") {
1765
+ return { handled: true, capture: true, render: false };
1766
+ }
1767
+ if (normalized.action === "click") {
1768
+ this.closeEscapeTarget();
1769
+ return { handled: true, render: false };
1770
+ }
1771
+ if (normalized.action === "release") {
1772
+ return { handled: true, render: false };
1773
+ }
1774
+ }
1775
+
1615
1776
  if (normalized.action === "wheel") {
1616
1777
  const delta = Math.trunc(normalized.delta ?? 0);
1617
1778
  if (this.toolPreviewParent !== null) {
@@ -1741,9 +1902,22 @@ export class BtwOverlayComponent extends Container implements Focusable {
1741
1902
  }
1742
1903
  return;
1743
1904
  }
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;
1905
+ // Consume bounded SGR button events locally. Older hosts do not expose
1906
+ // normalized click dispatch, so retain the close-button press/release
1907
+ // pair as the one actionable fallback; transcript clicks remain read-only.
1908
+ if (mouseEvent) {
1909
+ const overEscapeHint = this.isEscapeHintHit(mouseEvent.x, mouseEvent.y);
1910
+ this.handleMouse(mouseEvent);
1911
+ if (mouseEvent.button === 0 && mouseEvent.action === "press") {
1912
+ this.rawEscapePress = overEscapeHint;
1913
+ } else if (mouseEvent.button === 0 && mouseEvent.action === "release") {
1914
+ const close = this.rawEscapePress && overEscapeHint;
1915
+ this.rawEscapePress = false;
1916
+ if (close) this.closeEscapeTarget();
1917
+ }
1918
+ return;
1919
+ }
1920
+ this.rawEscapePress = false;
1747
1921
 
1748
1922
  // Peek mode active → route all input to peek handler
1749
1923
  if (this.peekState.active) {
@@ -1822,7 +1996,6 @@ export class BtwOverlayComponent extends Container implements Focusable {
1822
1996
  this.transcriptScrollOffset,
1823
1997
  this.transcriptScrollOffset + transcriptHeight,
1824
1998
  );
1825
- const transcriptPadCount = Math.max(0, transcriptHeight - visibleTranscript.length);
1826
1999
  const hiddenAbove = this.transcriptScrollOffset;
1827
2000
  const hiddenBelow = Math.max(0, maxScroll - this.transcriptScrollOffset);
1828
2001
  const summary =
@@ -1834,16 +2007,20 @@ export class BtwOverlayComponent extends Container implements Focusable {
1834
2007
 
1835
2008
  lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1836
2009
  lines.push(this.frameLine(this.theme.fg("dim", summary), innerWidth));
1837
- lines.push(this.ruleLine(innerWidth));
1838
-
1839
- for (const line of visibleTranscript) {
1840
- lines.push(this.frameLine(line, innerWidth));
1841
- }
1842
- for (let i = 0; i < transcriptPadCount; i++) {
1843
- lines.push(this.frameLine("", innerWidth));
2010
+ lines.push(this.scrollRule(innerWidth, "top", hiddenAbove));
2011
+
2012
+ for (let i = 0; i < transcriptHeight; i++) {
2013
+ lines.push(this.frameScrollableLine(
2014
+ visibleTranscript[i] ?? "",
2015
+ innerWidth,
2016
+ transcriptLines.length,
2017
+ transcriptHeight,
2018
+ this.transcriptScrollOffset,
2019
+ i,
2020
+ ));
1844
2021
  }
1845
2022
 
1846
- lines.push(this.ruleLine(innerWidth));
2023
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
1847
2024
  lines.push(this.frameLine(this.theme.fg("warning", this.statusTextValue.trim()), innerWidth));
1848
2025
  lines.push(...this.inputFrameLines(innerWidth, inputLineCount));
1849
2026
  lines.push(this.frameLine(this.theme.fg("dim", this.hintsTextValue.trim()), innerWidth));
@@ -1854,6 +2031,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1854
2031
 
1855
2032
  setDraft(value: string): void {
1856
2033
  this.input.setText(value);
2034
+ this.resetDraftRecall();
1857
2035
  this.tui.requestRender();
1858
2036
  }
1859
2037
 
@@ -1907,13 +2085,21 @@ export class BtwOverlayComponent extends Container implements Focusable {
1907
2085
 
1908
2086
  private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1909
2087
  // 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)}`;
2088
+ // supplies the bound: only the visible slice is emitted below. Inputs and
2089
+ // outputs use the same Pi tool highlighter as expanded transcript rows.
2090
+ const bodyWidth = Math.max(1, innerWidth - 1 - 2);
2091
+ const input = block.toolInput || (block.type === "tool-call" ? block.text : "") || "(no input)";
2092
+ const output = block.toolOutput || (block.type === "tool-result" ? block.text : "") || "(no output)";
1913
2093
  const lines: string[] = [];
1914
- for (const line of text.split("\n")) {
1915
- lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
2094
+ if (block.streaming) {
2095
+ lines.push(this.theme.fg("warning", "Status: STREAMING"));
2096
+ lines.push("");
1916
2097
  }
2098
+ lines.push(this.theme.fg("toolTitle", this.theme.bold("Input:")));
2099
+ lines.push(...renderBtwToolText(input, bodyWidth, this.theme).map((line) => ` ${line}`));
2100
+ lines.push("");
2101
+ lines.push(this.theme.fg(block.isError ? "error" : "toolTitle", this.theme.bold(`Output${block.isError ? " (error)" : ""}:`)));
2102
+ lines.push(...renderBtwToolText(output, bodyWidth, this.theme, block.toolInput, block.isError).map((line) => ` ${line}`));
1917
2103
  return lines.length > 0 ? lines : ["(no tool data)"];
1918
2104
  }
1919
2105
 
@@ -1969,10 +2155,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1969
2155
  if (this.toolPreviewParent === null) return;
1970
2156
  const viewportHeight = Math.max(1, this.peekState.viewportHeight);
1971
2157
  const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
1972
- this.peekToolPreviewScrollOffset = Math.max(
2158
+ const nextOffset = Math.max(
1973
2159
  0,
1974
2160
  Math.min(maxScroll, this.peekToolPreviewScrollOffset + delta),
1975
2161
  );
2162
+ if (nextOffset !== this.peekToolPreviewScrollOffset) this.scrollbarActive = true;
2163
+ this.peekToolPreviewScrollOffset = nextOffset;
1976
2164
  this.tui.requestRender();
1977
2165
  }
1978
2166
 
@@ -1998,21 +2186,29 @@ export class BtwOverlayComponent extends Container implements Focusable {
1998
2186
 
1999
2187
  const streamingLabel = block.streaming ? " · STREAMING" : "";
2000
2188
  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
2189
  const visible = this.peekToolPreviewLines.slice(
2007
2190
  this.peekToolPreviewScrollOffset,
2008
2191
  this.peekToolPreviewScrollOffset + viewportHeight,
2009
2192
  );
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
2193
  const hiddenAbove = this.peekToolPreviewScrollOffset;
2013
2194
  const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2195
+ const lines = [
2196
+ this.borderLine(innerWidth, "top"),
2197
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2198
+ this.scrollRule(innerWidth, "top", hiddenAbove),
2199
+ ];
2200
+ for (let i = 0; i < viewportHeight; i++) {
2201
+ lines.push(this.frameScrollableLine(
2202
+ visible[i] ?? "",
2203
+ innerWidth,
2204
+ this.peekToolPreviewLines.length,
2205
+ viewportHeight,
2206
+ this.peekToolPreviewScrollOffset,
2207
+ i,
2208
+ ));
2209
+ }
2210
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2014
2211
  const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2015
- lines.push(this.ruleLine(innerWidth));
2016
2212
  lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn Esc:back${counts}`), innerWidth));
2017
2213
  lines.push(this.borderLine(innerWidth, "bottom"));
2018
2214
  return lines.map((line) => this.fitRenderedLine(line, fullWidth));
@@ -2044,24 +2240,29 @@ export class BtwOverlayComponent extends Container implements Focusable {
2044
2240
  );
2045
2241
 
2046
2242
  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
2243
  const visible = this.peekToolPreviewLines.slice(
2053
2244
  this.peekToolPreviewScrollOffset,
2054
2245
  this.peekToolPreviewScrollOffset + viewportHeight,
2055
2246
  );
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
2247
  const hiddenAbove = this.peekToolPreviewScrollOffset;
2062
2248
  const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2249
+ const lines = [
2250
+ this.borderLine(innerWidth, "top"),
2251
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2252
+ this.scrollRule(innerWidth, "top", hiddenAbove),
2253
+ ];
2254
+ for (let i = 0; i < viewportHeight; i++) {
2255
+ lines.push(this.frameScrollableLine(
2256
+ visible[i] ?? "",
2257
+ innerWidth,
2258
+ this.peekToolPreviewLines.length,
2259
+ viewportHeight,
2260
+ this.peekToolPreviewScrollOffset,
2261
+ i,
2262
+ ));
2263
+ }
2264
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2063
2265
  const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2064
- lines.push(this.ruleLine(innerWidth));
2065
2266
  lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn q/Esc:back${counts}`), innerWidth));
2066
2267
  lines.push(this.borderLine(innerWidth, "bottom"));
2067
2268
  return lines.map((line) => this.fitRenderedLine(line, fullWidth));
@@ -2089,6 +2290,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2089
2290
  this.toolPreviewParent = "live";
2090
2291
  this.peekToolPreviewScrollOffset = 0;
2091
2292
  this.peekToolPreviewLines = [];
2293
+ this.scrollbarActive = false;
2092
2294
  this.tui.requestRender();
2093
2295
  }
2094
2296
 
@@ -2200,7 +2402,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
2200
2402
  }
2201
2403
 
2202
2404
  // ── Content ──────────────────────────────────────────────────────
2203
- const mdContentWidth = Math.max(1, innerWidth - 6);
2405
+ // Keep one inner cell free for the right-hand ScrollView rail.
2406
+ const mdContentWidth = Math.max(1, innerWidth - 7);
2204
2407
  this.peekContentTop = 4;
2205
2408
  // Build rendered lines and remember each block's starting line so j/k
2206
2409
  // can scroll by line while J/K still jump by message.
@@ -2242,21 +2445,14 @@ export class BtwOverlayComponent extends Container implements Focusable {
2242
2445
  if (this.expandedToolId === block.id && hasToolPreview(block)) {
2243
2446
  const toolLines = this.buildToolPreviewLines(block, innerWidth);
2244
2447
  for (const toolLine of toolLines) {
2245
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg(block.isError ? "error" : "dim", toolLine)}`);
2448
+ blockLines.push(`${isCurrent ? "▎ " : " "}${toolLine}`);
2246
2449
  }
2247
2450
  }
2248
2451
  } else if (block.text) {
2249
- if (block.type === "assistant-text" || block.type === "user") {
2250
- const md = new Markdown(block.text, 0, 0, this.mdTheme);
2251
- const mdLines = md.render(mdContentWidth);
2252
- for (const mdLine of mdLines) {
2253
- blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine.replace(/[ \t]+$/u, "")}`);
2254
- }
2255
- } else if (block.type === "thinking") {
2256
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
2257
- for (const sl of styledLines) {
2258
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("warning", this.theme.italic(sl))}`);
2259
- }
2452
+ const role = block.type === "user" ? "user" : block.type === "thinking" ? "thinking" : "assistant";
2453
+ const markdownLines = renderBtwMarkdown(block.text, mdContentWidth, this.theme, role, this.mdTheme);
2454
+ for (const markdownLine of markdownLines) {
2455
+ blockLines.push(`${isCurrent ? "▎ " : " "}${markdownLine.replace(/[ \t]+$/u, "")}`);
2260
2456
  }
2261
2457
  }
2262
2458
 
@@ -2276,6 +2472,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
2276
2472
  this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
2277
2473
 
2278
2474
  const visibleStart = this.peekState.scrollOffset;
2475
+ const hiddenAbove = visibleStart;
2476
+ const hiddenBelow = Math.max(0, maxScroll - visibleStart);
2477
+ // The header rule is the top ScrollView more indicator. It is emitted
2478
+ // before content so the hit-test coordinates remain stable.
2479
+ lines[2] = this.scrollRule(innerWidth, "top", hiddenAbove);
2279
2480
  this.peekStickyHeaderIndex = null;
2280
2481
  const displayLines = this.peekRenderedLines.slice(visibleStart, visibleStart + vh);
2281
2482
  if (blockCount === 0) {
@@ -2291,9 +2492,16 @@ export class BtwOverlayComponent extends Container implements Focusable {
2291
2492
  displayLines.push("");
2292
2493
  }
2293
2494
 
2294
- // Frame each line
2295
- for (const line of displayLines) {
2296
- lines.push(this.frameLine(line, innerWidth));
2495
+ // Frame each line and reserve the final inner cell for the scrollbar.
2496
+ for (let i = 0; i < vh; i++) {
2497
+ lines.push(this.frameScrollableLine(
2498
+ displayLines[i] ?? "",
2499
+ innerWidth,
2500
+ this.peekRenderedLines.length,
2501
+ vh,
2502
+ this.peekState.scrollOffset,
2503
+ i,
2504
+ ));
2297
2505
  }
2298
2506
 
2299
2507
  // ── Status bar ───────────────────────────────────────────────────
@@ -2305,7 +2513,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2305
2513
  const previewHint = hasToolPreview(selected) ? " w:preview" : "";
2306
2514
  const expandHint = hasToolPreview(selected) ? " Enter:expand" : "";
2307
2515
  const statusText = `j/k ↑↓ J/K msg g/G /search${searchHint} ${toolsHint}${previewHint} M:copy o:nvim${expandHint} q:exit`;
2308
- lines.push(this.ruleLine(innerWidth));
2516
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2309
2517
  lines.push(this.frameLine(this.theme.fg("dim", statusText), innerWidth));
2310
2518
  lines.push(this.borderLine(innerWidth, "bottom"));
2311
2519
 
@@ -2315,6 +2523,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2315
2523
  enterPeekMode(): void {
2316
2524
  this.peekState = createPeekState();
2317
2525
  this.peekState.active = true;
2526
+ this.scrollbarActive = false;
2318
2527
  const entries = this.readTranscriptEntries();
2319
2528
  this.peekState.showTools = true;
2320
2529
  this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
@@ -3176,15 +3385,22 @@ export default function (pi: ExtensionAPI) {
3176
3385
  throw new Error(settings.fallbackReason || "No active model selected.");
3177
3386
  }
3178
3387
 
3179
- const { session } = await createAgentSession({
3388
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime | null }).runtime ?? undefined;
3389
+ const sessionOptions: Parameters<typeof createAgentSession>[0] & {
3390
+ modelRegistry?: ExtensionContext["modelRegistry"];
3391
+ modelRuntime?: ModelRuntime;
3392
+ } = {
3180
3393
  sessionManager: SessionManager.inMemory(),
3181
3394
  model: settings.model,
3182
- modelRegistry: ctx.modelRegistry as AgentSession["modelRegistry"],
3395
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
3183
3396
  thinkingLevel: settings.thinkingLevel,
3184
3397
  // Match pi's default coding-agent toolset (read/bash/edit/write).
3185
3398
  tools: ["read", "bash", "edit", "write"],
3186
3399
  resourceLoader: createBtwResourceLoader(ctx),
3187
- });
3400
+ // Keep the pre-ModelRuntime facade available for older Pi hosts.
3401
+ modelRegistry: ctx.modelRegistry,
3402
+ };
3403
+ const { session } = await createAgentSession(sessionOptions);
3188
3404
 
3189
3405
  const { messages: seedMessages, sideThreadStartIndex } = buildBtwSeedState(ctx, pendingThread, mode, settings.model);
3190
3406
  if (seedMessages.length > 0) {
@@ -3813,14 +4029,21 @@ export default function (pi: ExtensionAPI) {
3813
4029
  throw new Error(auth.ok ? `No credentials available for ${model.provider}/${model.id}.` : auth.error);
3814
4030
  }
3815
4031
 
3816
- const { session } = await createAgentSession({
4032
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime | null }).runtime ?? undefined;
4033
+ const sessionOptions: Parameters<typeof createAgentSession>[0] & {
4034
+ modelRegistry?: ExtensionContext["modelRegistry"];
4035
+ modelRuntime?: ModelRuntime;
4036
+ } = {
3817
4037
  sessionManager: SessionManager.inMemory(),
3818
4038
  model,
3819
- modelRegistry: ctx.modelRegistry as AgentSession["modelRegistry"],
4039
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
3820
4040
  thinkingLevel: "off",
3821
4041
  tools: [],
3822
4042
  resourceLoader: createBtwResourceLoader(ctx, [BTW_SUMMARIZE_SYSTEM_PROMPT]),
3823
- });
4043
+ // Keep the pre-ModelRuntime facade available for older Pi hosts.
4044
+ modelRegistry: ctx.modelRegistry,
4045
+ };
4046
+ const { session } = await createAgentSession(sessionOptions);
3824
4047
 
3825
4048
  try {
3826
4049
  await session.prompt(formatThread(thread), { source: "extension" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-render-btw",
3
- "version": "0.6.12",
3
+ "version": "0.6.14",
4
4
  "description": "A pi extension for parallel side conversations with /btw — with markdown rendering in the floating window",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,9 +47,9 @@
47
47
  "image": "https://raw.githubusercontent.com/ESSO0428/pi-render-btw/main/docs/btw-overlay.png"
48
48
  },
49
49
  "peerDependencies": {
50
- "@earendil-works/pi-ai": ">=0.74.0 <1",
51
- "@earendil-works/pi-coding-agent": ">=0.74.0 <1",
52
- "@earendil-works/pi-tui": ">=0.74.0 <1"
50
+ "@earendil-works/pi-ai": ">=0.80.8 <1",
51
+ "@earendil-works/pi-coding-agent": ">=0.80.8 <1",
52
+ "@earendil-works/pi-tui": ">=0.80.8 <1"
53
53
  },
54
54
  "devDependencies": {
55
55
  "typescript": "^6.0.2",