pi-render-btw 0.6.13 → 0.6.15

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.15 — 2026-09-18
4
+
5
+ - Use one local Cc-style Input/Output card renderer for Peek and read-only Tool Output, including stable input key/value rows, rails, error styling, and width-safe synchronous highlighting.
6
+ - Keep complete tool output in the card and let the existing outer viewport/scrollbar provide scrolling and hidden-line affordances.
7
+
8
+ ## 0.6.14 — 2026-09-18
9
+
10
+ - Keep BTW, Peek, and read-only Tool Output rendering aligned with Pi Markdown/tool colors and syntax highlighting, including safe terminal-text sanitization.
11
+ - Add a native-style right-hand scrollbar with `↑ N more` / `↓ N more` viewport affordances to the BTW transcript, Peek, and Tool Output surfaces.
12
+ - 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.
13
+
3
14
  ## 0.6.13 — 2026-09-14
4
15
 
5
16
  - Keep the BTW/Peek/Tool Output title-row `[Esc]` affordance visible beside long titles.
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
+ - uses a consistent Cc-style Input/Output card renderer in Peek and read-only Tool Output, while keeping BTW's native-style right-hand scrollbar with `↑ N more` / `↓ N more` affordances at the viewport edges
25
26
 
26
27
  ## ✨ Markdown rendering
27
28
 
@@ -94,10 +95,10 @@ 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
- - 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
101
+ - with a focused Tool row, `Ctrl+O` opens a read-only Input/Output viewer using the same structured card style as Peek; 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
101
102
  - if the runtime has not provided tool output yet, the viewer shows an explicit no-output state rather than inventing content; its wheel, `j/k`, arrows, `g/G`, PageUp/PageDown, and `Esc` controls stay inside the viewer
102
103
  - BTW opens top-centered so the main session remains visible underneath it
103
104
 
@@ -129,6 +130,7 @@ pi install /path/to/pi-render-btw
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
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
+ }
@@ -0,0 +1,87 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { visibleWidth } from "@earendil-works/pi-tui";
3
+ import {
4
+ formatBtwToolInputArgs,
5
+ renderBtwToolOutput,
6
+ type BtwToolOutputTheme,
7
+ } from "./tool-output.ts";
8
+
9
+ const theme: BtwToolOutputTheme = {
10
+ fg: (_name, value) => value,
11
+ bold: (value) => value,
12
+ italic: (value) => value,
13
+ };
14
+
15
+ describe("BTW tool output renderer", () => {
16
+ it("renders the Cc-style input and output card", () => {
17
+ const result = renderBtwToolOutput({
18
+ input: { value: 1, name: "tool" },
19
+ output: "ok",
20
+ width: 60,
21
+ isError: false,
22
+ }, theme);
23
+
24
+ expect(result.lines).toEqual([
25
+ " ├ Input",
26
+ " │ name: tool",
27
+ " │ value: 1",
28
+ " │",
29
+ " └ Output",
30
+ " ok",
31
+ ]);
32
+ expect(result.lineSections).toEqual([null, "input", "input", null, null, "output"]);
33
+ });
34
+
35
+ it("formats preferred keys first and preserves multiline values", () => {
36
+ expect(formatBtwToolInputArgs({ z: "last", content: "a\nb", path: "a.ts" })).toBe(
37
+ "path: a.ts\ncontent:\n a\n b\nz: last",
38
+ );
39
+ expect(formatBtwToolInputArgs("compact input")).toBe("compact input");
40
+ });
41
+
42
+ it("sanitizes captured text and renders empty output as Done", () => {
43
+ const result = renderBtwToolOutput({
44
+ input: "\u001b]0;title\u0007",
45
+ output: "",
46
+ width: 40,
47
+ isError: false,
48
+ }, theme);
49
+
50
+ expect(result.lines.join("\n")).not.toContain("title");
51
+ expect(result.lines).toContain(" └ Output");
52
+ expect(result.lines).toContain(" Done");
53
+ });
54
+
55
+ it("supports bounded sections without affecting the full-output default", () => {
56
+ const output = ["one", "two", "three"].join("\n");
57
+ const full = renderBtwToolOutput({
58
+ input: {},
59
+ output,
60
+ width: 40,
61
+ isError: false,
62
+ }, theme);
63
+ const bounded = renderBtwToolOutput({
64
+ input: {},
65
+ output,
66
+ width: 40,
67
+ maxOutputLines: 1,
68
+ isError: false,
69
+ }, theme);
70
+
71
+ expect(full.lines).toContain(" three");
72
+ expect(full.showMoreRows).toEqual({});
73
+ expect(bounded.lines).toContain(" … +2 more lines");
74
+ expect(bounded.showMoreRows.output).toBeDefined();
75
+ });
76
+
77
+ it("keeps rendered rows within the requested visible width", () => {
78
+ const result = renderBtwToolOutput({
79
+ input: { command: "echo a very long command that must wrap safely" },
80
+ output: "a very long output line that must wrap safely",
81
+ width: 24,
82
+ isError: false,
83
+ }, theme);
84
+
85
+ expect(result.lines.every((line) => visibleWidth(line) <= 24)).toBe(true);
86
+ });
87
+ });
@@ -0,0 +1,182 @@
1
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import type { BtwTheme } from "./render-utils.ts";
4
+ import { renderBtwToolText, sanitizeBtwText } from "./render-utils.ts";
5
+
6
+ export type BtwToolIoSection = "input" | "output";
7
+ export type BtwToolOutputTheme = BtwTheme;
8
+
9
+ export interface BtwToolOutputOptions {
10
+ input: unknown;
11
+ output: string;
12
+ width: number;
13
+ isError: boolean;
14
+ maxInputLines?: number;
15
+ maxOutputLines?: number;
16
+ }
17
+
18
+ export interface BtwToolOutputRenderResult {
19
+ lines: string[];
20
+ lineSections: Array<BtwToolIoSection | null>;
21
+ showMoreRows: Partial<Record<BtwToolIoSection, number>>;
22
+ }
23
+
24
+ const PREFERRED_INPUT_KEYS = [
25
+ "path",
26
+ "file_path",
27
+ "command",
28
+ "query",
29
+ "pattern",
30
+ "url",
31
+ "name",
32
+ "message",
33
+ "content",
34
+ "old_string",
35
+ "new_string",
36
+ ];
37
+
38
+ function safeJson(value: unknown): string {
39
+ try {
40
+ return JSON.stringify(value, null, 2) ?? "";
41
+ } catch {
42
+ return String(value);
43
+ }
44
+ }
45
+
46
+ function parsedInput(value: unknown): unknown {
47
+ if (typeof value !== "string") return value;
48
+ const source = sanitizeBtwText(value).trim();
49
+ if (!source) return "";
50
+ try {
51
+ return JSON.parse(source);
52
+ } catch {
53
+ return source;
54
+ }
55
+ }
56
+
57
+ /** Format arguments as stable, readable key/value rows for the Input rail. */
58
+ export function formatBtwToolInputArgs(args: unknown, maxChars = 8_000): string {
59
+ const parsed = parsedInput(args);
60
+ if (parsed === undefined || parsed === null) return "";
61
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
62
+ const rendered = typeof parsed === "string" ? sanitizeBtwText(parsed) : safeJson(parsed);
63
+ return rendered.length > maxChars ? `${rendered.slice(0, maxChars)}…` : rendered;
64
+ }
65
+
66
+ const entries = Object.entries(parsed as Record<string, unknown>)
67
+ .filter(([, value]) => value !== undefined)
68
+ .sort(([left], [right]) => {
69
+ const leftIndex = PREFERRED_INPUT_KEYS.indexOf(left);
70
+ const rightIndex = PREFERRED_INPUT_KEYS.indexOf(right);
71
+ if (leftIndex < 0 && rightIndex < 0) return left.localeCompare(right);
72
+ if (leftIndex < 0) return 1;
73
+ if (rightIndex < 0) return -1;
74
+ return leftIndex - rightIndex;
75
+ });
76
+
77
+ const lines: string[] = [];
78
+ for (const [key, value] of entries) {
79
+ const safeKey = sanitizeBtwText(key);
80
+ const rendered = typeof value === "string" ? sanitizeBtwText(value) : safeJson(value);
81
+ if (rendered.includes("\n")) {
82
+ lines.push(`${safeKey}:`);
83
+ lines.push(...rendered.split("\n").map((line) => ` ${line}`));
84
+ } else {
85
+ lines.push(`${safeKey}: ${rendered}`);
86
+ }
87
+ }
88
+ const result = lines.join("\n");
89
+ return result.length > maxChars ? `${result.slice(0, Math.max(0, maxChars - 1))}…` : result;
90
+ }
91
+
92
+ function serializedInput(value: unknown): string {
93
+ const parsed = parsedInput(value);
94
+ return typeof parsed === "string" ? parsed : safeJson(parsed);
95
+ }
96
+
97
+ function toolViewportWidth(width: number): number {
98
+ return Math.max(1, Math.floor(Number.isFinite(width) ? width : 1));
99
+ }
100
+
101
+ function styledInputLine(line: string, theme: BtwToolOutputTheme): string {
102
+ const match = line.match(/^([A-Za-z_][\w.-]*)(:\s*)(.*)$/);
103
+ if (!match) return theme.fg("muted", line);
104
+ return theme.fg("dim", `${match[1]}${match[2]}`) + theme.fg("muted", match[3] ?? "");
105
+ }
106
+
107
+ /** Render the Pi Cc-style Input/Output card without owning viewport state. */
108
+ export function renderBtwToolOutput(
109
+ options: BtwToolOutputOptions,
110
+ theme: BtwToolOutputTheme,
111
+ ): BtwToolOutputRenderResult {
112
+ const width = toolViewportWidth(options.width);
113
+ const contentWidth = Math.max(1, width - visibleWidth(" │ "));
114
+ const lines: string[] = [];
115
+ const lineSections: Array<BtwToolIoSection | null> = [];
116
+ const showMoreRows: Partial<Record<BtwToolIoSection, number>> = {};
117
+ const maxInputLines = Math.max(1, Math.floor(options.maxInputLines ?? Number.MAX_SAFE_INTEGER));
118
+ const maxOutputLines = Math.max(1, Math.floor(options.maxOutputLines ?? Number.MAX_SAFE_INTEGER));
119
+ const color = (name: ThemeColor, value: string): string => theme.fg(name, value);
120
+ const push = (line: string, section: BtwToolIoSection | null): void => {
121
+ lines.push(truncateToWidth(line, width, ""));
122
+ lineSections.push(section);
123
+ };
124
+ const pushHeader = (corner: "├" | "└", title: string): void => {
125
+ push(color("dim", ` ${corner} `) + color("accent", theme.bold(title)), null);
126
+ };
127
+ const pushRail = (line: string, section: BtwToolIoSection, continued: boolean): void => {
128
+ push(color("dim", continued ? " │ " : " ") + line, section);
129
+ };
130
+ const pushBody = (
131
+ body: string,
132
+ section: BtwToolIoSection,
133
+ limit: number,
134
+ input: boolean,
135
+ ): void => {
136
+ const raw = sanitizeBtwText(body).replace(/\t/g, " ").replace(/\n+$/, "");
137
+ if (!raw.trim()) {
138
+ pushRail(color("dim", "(empty)"), section, input);
139
+ return;
140
+ }
141
+
142
+ const sourceLines = raw.split("\n");
143
+ const wrapped: string[] = [];
144
+ if (!input) {
145
+ // renderBtwToolText already performs ANSI-safe wrapping for every source
146
+ // line; keep all wrapped rows instead of indexing by source line.
147
+ wrapped.push(...renderBtwToolText(
148
+ raw,
149
+ contentWidth,
150
+ theme,
151
+ serializedInput(options.input),
152
+ options.isError,
153
+ ));
154
+ } else {
155
+ for (const sourceLine of sourceLines) {
156
+ const rendered = styledInputLine(sourceLine, theme);
157
+ const wrappedLines = wrapTextWithAnsi(rendered, contentWidth);
158
+ wrapped.push(...(wrappedLines.length > 0 ? wrappedLines : [rendered]));
159
+ }
160
+ }
161
+
162
+ const truncated = wrapped.length > limit;
163
+ const visible = truncated ? wrapped.slice(0, limit) : wrapped;
164
+ for (const line of visible) pushRail(line, section, input);
165
+ if (truncated) {
166
+ const hidden = wrapped.length - visible.length;
167
+ pushRail(color("dim", `… +${hidden} more lines`), section, input);
168
+ showMoreRows[section] = lines.length - 1;
169
+ }
170
+ };
171
+
172
+ const inputText = formatBtwToolInputArgs(options.input);
173
+ if (inputText.trim()) {
174
+ pushHeader("├", "Input");
175
+ pushBody(inputText, "input", maxInputLines, true);
176
+ push(color("dim", " │"), null);
177
+ }
178
+ pushHeader("└", "Output");
179
+ pushBody(options.output.trim() ? options.output : "Done", "output", maxOutputLines, false);
180
+
181
+ return { lines, lineSections, showMoreRows };
182
+ }
@@ -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 = {
@@ -344,7 +370,8 @@ describe("BTW transcript message layout", () => {
344
370
  expect((component as any).expandedToolId).toBeNull();
345
371
  component.handleInput("w");
346
372
  const preview = component.render(80).join("\n");
347
- expect(preview).toContain("Input:");
373
+ expect(preview).toContain("Input");
374
+ expect(preview).toContain("├ Input");
348
375
  expect(preview).toContain("Output");
349
376
  component.handleInput("g");
350
377
  const beforeWheel = (component as any).peekToolPreviewScrollOffset as number;
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,13 @@ 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";
59
+ import { renderBtwToolOutput } from "./btw/tool-output.ts";
53
60
  import {
54
61
  BTW_TRANSCRIPT_SCHEMA_VERSION,
55
62
  BtwTranscriptStore,
@@ -253,7 +260,9 @@ function createBtwResourceLoader(
253
260
  getThemes: () => ({ themes: [], diagnostics: [] }),
254
261
  getAgentsFiles: () => ({ agentsFiles: [] }),
255
262
  getSystemPrompt: () => systemPrompt,
263
+ getSystemPromptSource: () => undefined,
256
264
  getAppendSystemPrompt: () => appendSystemPrompt,
265
+ getAppendSystemPromptSources: () => [],
257
266
  extendResources: () => {},
258
267
  reload: async () => {},
259
268
  };
@@ -1141,6 +1150,10 @@ export class BtwOverlayComponent extends Container implements Focusable {
1141
1150
  private readonly onUnfocusCallback: () => void;
1142
1151
  private readonly onExternalEditorCallback?: () => void;
1143
1152
  private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1153
+ /** BTW keeps its own recall cursor so Alt+Up works even when host history bindings are unset. */
1154
+ private draftHistory: string[] = [];
1155
+ private draftHistoryIndex = -1;
1156
+ private draftHistoryDraft = "";
1144
1157
  private externalEditorActive = false;
1145
1158
  private readonly tui: TUI;
1146
1159
  private readonly theme: ExtensionContext["ui"]["theme"];
@@ -1150,6 +1163,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1150
1163
  private transcriptScrollOffset = 0;
1151
1164
  private transcriptViewportHeight = 8;
1152
1165
  private followTranscript = true;
1166
+ private scrollbarActive = false;
1153
1167
  private liveHoveredEntryId: number | null = null;
1154
1168
  private liveFocusedEntryId: number | null = null;
1155
1169
  private liveFocusedToolCallId: string | null = null;
@@ -1242,6 +1256,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1242
1256
  this.input = new CustomEditor(tui, editorTheme, editorKeybindings);
1243
1257
  this.input.onSubmit = (value) => {
1244
1258
  this.input.addToHistory(value);
1259
+ this.rememberDraft(value);
1245
1260
  this.followTranscript = true;
1246
1261
  this.onSubmitCallback(value);
1247
1262
  };
@@ -1260,6 +1275,15 @@ export class BtwOverlayComponent extends Container implements Focusable {
1260
1275
 
1261
1276
  const originalHandleInput = this.input.handleInput.bind(this.input);
1262
1277
  this.input.handleInput = (data: string) => {
1278
+ // Some hosts expose Alt+Up as the symbolic `a-up` token rather than a
1279
+ // terminal escape sequence. Keep draft recall local to BTW so this does
1280
+ // not depend on the host having configured an editor history binding.
1281
+ if (matchesKey(data, Key.alt("up")) || data === "a-up" || data === "alt+up") {
1282
+ this.recallDraft(-1);
1283
+ this.tui.requestRender();
1284
+ return;
1285
+ }
1286
+
1263
1287
  if (keybindings.matches(data, "app.editor.external")) {
1264
1288
  if (this.onExternalEditorCallback) {
1265
1289
  this.onExternalEditorCallback();
@@ -1272,6 +1296,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1272
1296
  // app.clear with non-empty input → clear input
1273
1297
  if (keybindings.matches(data, "app.clear") && this.input.getText().length > 0) {
1274
1298
  this.input.setText("");
1299
+ this.resetDraftRecall();
1275
1300
  this.tui.requestRender();
1276
1301
  return;
1277
1302
  }
@@ -1279,7 +1304,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
1279
1304
  // Everything else (including Escape → dismiss, Enter → submit,
1280
1305
  // Ctrl+Enter → newline) goes to CustomEditor's own handler
1281
1306
  // (CustomEditor delegates app keybindings, then Editor).
1307
+ const before = this.input.getText();
1282
1308
  originalHandleInput(data);
1309
+ if (before !== this.input.getText()) {
1310
+ this.resetDraftRecall();
1311
+ }
1283
1312
  };
1284
1313
 
1285
1314
  this.refresh();
@@ -1325,6 +1354,40 @@ export class BtwOverlayComponent extends Container implements Focusable {
1325
1354
  return `${this.theme.fg("border", "│")}${truncated}${" ".repeat(padding)}${this.theme.fg("border", "│")}`;
1326
1355
  }
1327
1356
 
1357
+ /**
1358
+ * Frame one row of a bounded ScrollView-like viewport. The rail occupies
1359
+ * the last cell inside the box, so content never gets painted over it.
1360
+ */
1361
+ private frameScrollableLine(
1362
+ content: string,
1363
+ innerWidth: number,
1364
+ totalLines: number,
1365
+ viewportHeight: number,
1366
+ scrollOffset: number,
1367
+ lineIndex: number,
1368
+ ): string {
1369
+ const contentWidth = Math.max(1, innerWidth - 1);
1370
+ const truncated = truncateToWidth(content, contentWidth, "");
1371
+ const padding = Math.max(0, contentWidth - visibleWidth(truncated));
1372
+ const rail = renderBtwScrollRail(
1373
+ this.theme,
1374
+ totalLines,
1375
+ viewportHeight,
1376
+ scrollOffset,
1377
+ lineIndex,
1378
+ this.scrollbarActive,
1379
+ );
1380
+ return `${this.theme.fg("border", "│")}${truncated}${" ".repeat(padding)}${rail}${this.theme.fg("border", "│")}`;
1381
+ }
1382
+
1383
+ private scrollRule(
1384
+ innerWidth: number,
1385
+ direction: "top" | "bottom",
1386
+ hiddenLines: number,
1387
+ ): string {
1388
+ return renderBtwScrollRule(this.theme, innerWidth, direction, hiddenLines) ?? this.ruleLine(innerWidth);
1389
+ }
1390
+
1328
1391
  private ruleLine(innerWidth: number): string {
1329
1392
  return this.theme.fg("border", `├${"─".repeat(innerWidth)}┤`);
1330
1393
  }
@@ -1349,6 +1412,46 @@ export class BtwOverlayComponent extends Container implements Focusable {
1349
1412
  return this.frameLine(`${clippedTitle}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1350
1413
  }
1351
1414
 
1415
+ private resetDraftRecall(): void {
1416
+ this.draftHistoryIndex = -1;
1417
+ this.draftHistoryDraft = "";
1418
+ }
1419
+
1420
+ private rememberDraft(value: string): void {
1421
+ const draft = value.trim();
1422
+ if (!draft) {
1423
+ this.resetDraftRecall();
1424
+ return;
1425
+ }
1426
+ // Match the native editor's useful behavior without creating an endless
1427
+ // run of identical entries when a prompt is submitted repeatedly.
1428
+ if (this.draftHistory[this.draftHistory.length - 1] !== value) {
1429
+ this.draftHistory.push(value);
1430
+ }
1431
+ this.resetDraftRecall();
1432
+ }
1433
+
1434
+ private recallDraft(direction: -1 | 1): void {
1435
+ if (this.draftHistory.length === 0) return;
1436
+
1437
+ if (this.draftHistoryIndex === -1) {
1438
+ this.draftHistoryDraft = this.input.getText();
1439
+ this.draftHistoryIndex = direction < 0 ? this.draftHistory.length - 1 : 0;
1440
+ } else {
1441
+ const next = this.draftHistoryIndex + direction;
1442
+ if (next < 0 || next >= this.draftHistory.length) {
1443
+ if (direction > 0 && this.draftHistoryIndex === this.draftHistory.length - 1) {
1444
+ this.draftHistoryIndex = -1;
1445
+ this.input.setText(this.draftHistoryDraft);
1446
+ }
1447
+ return;
1448
+ }
1449
+ this.draftHistoryIndex = next;
1450
+ }
1451
+
1452
+ this.input.setText(this.draftHistory[this.draftHistoryIndex]);
1453
+ }
1454
+
1352
1455
  private wrapTranscript(innerWidth: number): string[] {
1353
1456
  const wrapped: string[] = [];
1354
1457
  for (const line of this.transcriptLines) {
@@ -1384,7 +1487,13 @@ export class BtwOverlayComponent extends Container implements Focusable {
1384
1487
  const assistantBadge = buildTranscriptBadge(this.theme, "ASSISTANT", "customMessageBg", "success");
1385
1488
  const separator = this.theme.fg("borderMuted", "─".repeat(40));
1386
1489
  const blockIndent = " ";
1387
- const mdContentWidth = Math.max(1, innerWidth - visibleWidth(blockIndent));
1490
+ const toolArgsByCall = new Map<string, string>();
1491
+ for (const entry of entries) {
1492
+ if (entry.type === "tool-call") toolArgsByCall.set(entry.toolCallId, entry.args);
1493
+ }
1494
+ // Reserve the final inner cell for the right-hand ScrollView rail.
1495
+ const scrollContentWidth = Math.max(1, innerWidth - 1);
1496
+ const mdContentWidth = Math.max(1, scrollContentWidth - visibleWidth(blockIndent));
1388
1497
 
1389
1498
  const pushBlank = (): void => {
1390
1499
  if (allLines.length > 0 && allLines[allLines.length - 1] !== "") {
@@ -1406,7 +1515,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1406
1515
  pushBlank();
1407
1516
  allLines.push(`${focusRail(entry.id)}${userBadge}`);
1408
1517
  const boundedText = entry.text.length > 16_000 ? `${entry.text.slice(0, 15_970)}\n… [truncated]` : entry.text;
1409
- const mdLines = new Markdown(boundedText || "∅", 0, 0, this.mdTheme).render(mdContentWidth);
1518
+ const mdLines = renderBtwMarkdown(boundedText, mdContentWidth, this.theme, "user", this.mdTheme);
1410
1519
  for (const line of mdLines) {
1411
1520
  allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1412
1521
  }
@@ -1418,9 +1527,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1418
1527
  const thinkingHeader = entry.streaming ? `${thinkingBadge} ${this.theme.fg("warning", "▍")}` : thinkingBadge;
1419
1528
  pushBlank();
1420
1529
  allLines.push(`${focusRail(entry.id)}${thinkingHeader}`);
1421
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1422
- for (const line of styledLines) {
1423
- allLines.push(`${blockIndent}${this.theme.fg("warning", this.theme.italic(line))}`);
1530
+ const markdownLines = renderBtwMarkdown(entry.text, mdContentWidth, this.theme, "thinking", this.mdTheme);
1531
+ for (const line of markdownLines) {
1532
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1424
1533
  }
1425
1534
  markBlock(entry.id, blockStart);
1426
1535
  continue;
@@ -1434,8 +1543,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1434
1543
  pushBlank();
1435
1544
  allLines.push(`${focusRail(entry.id)}${toolLabel}${argsLabel}${moreLabel}`);
1436
1545
  if (isExpanded && entry.args) {
1437
- for (const line of wrapTextWithAnsi(entry.args, mdContentWidth)) {
1438
- allLines.push(`${blockIndent}${this.theme.fg("dim", line)}`);
1546
+ const toolLines = renderBtwToolText(entry.args, mdContentWidth, this.theme);
1547
+ for (const line of toolLines) {
1548
+ allLines.push(`${blockIndent}${line}`);
1439
1549
  }
1440
1550
  }
1441
1551
  markBlock(entry.id, blockStart);
@@ -1453,8 +1563,15 @@ export class BtwOverlayComponent extends Container implements Focusable {
1453
1563
  pushBlank();
1454
1564
  allLines.push(`${focusRail(entry.id)}${resultLabel}${summary}${truncLabel}${moreLabel}`);
1455
1565
  if (isExpanded) {
1456
- for (const line of wrapTextWithAnsi(entry.fullContent ?? entry.content, mdContentWidth)) {
1457
- allLines.push(`${blockIndent}${this.theme.fg(entry.isError ? "error" : "dim", line)}`);
1566
+ const toolLines = renderBtwToolText(
1567
+ entry.fullContent ?? entry.content,
1568
+ mdContentWidth,
1569
+ this.theme,
1570
+ entry.toolCallId ? toolArgsByCall.get(entry.toolCallId) : entry.toolName,
1571
+ entry.isError,
1572
+ );
1573
+ for (const line of toolLines) {
1574
+ allLines.push(`${blockIndent}${line}`);
1458
1575
  }
1459
1576
  }
1460
1577
  markBlock(entry.id, blockStart);
@@ -1466,27 +1583,17 @@ export class BtwOverlayComponent extends Container implements Focusable {
1466
1583
  const header = entry.streaming ? `${assistantBadge} ${this.theme.fg("warning", "▍")}` : assistantBadge;
1467
1584
  allLines.push(`${focusRail(entry.id)}${header}`);
1468
1585
 
1469
- if (!entry.streaming) {
1470
- // Render markdown for completed text — use cached result when available
1471
- const cached = this.mdLineCache.get(entry.id);
1472
- if (cached && cached.renderedAtWidth === mdContentWidth) {
1473
- for (const line of cached.lines) {
1474
- allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1475
- }
1476
- } else {
1477
- const md = new Markdown(entry.text, 0, 0, this.mdTheme);
1478
- const mdLines = md.render(mdContentWidth);
1479
- this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1480
- for (const line of mdLines) {
1481
- allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1482
- }
1483
- }
1484
- } else {
1485
- // While streaming, use plain text for speed and stability
1486
- const styledLines = wrapTextWithAnsi(entry.text, mdContentWidth);
1487
- for (const line of styledLines) {
1488
- allLines.push(`${blockIndent}${line}`);
1489
- }
1586
+ // Use the same Pi Markdown renderer for completed and streaming text.
1587
+ // Markdown is intentionally cheap here because the overlay already
1588
+ // coalesces streaming refreshes, and it avoids a visual mode switch at
1589
+ // the end of a response.
1590
+ const cached = this.mdLineCache.get(entry.id);
1591
+ const mdLines = cached && cached.renderedAtWidth === mdContentWidth
1592
+ ? cached.lines
1593
+ : renderBtwMarkdown(entry.text, mdContentWidth, this.theme, "assistant", this.mdTheme);
1594
+ this.mdLineCache.set(entry.id, { lines: mdLines, renderedAtWidth: mdContentWidth });
1595
+ for (const line of mdLines) {
1596
+ allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
1490
1597
  }
1491
1598
  markBlock(entry.id, blockStart);
1492
1599
  continue;
@@ -1520,10 +1627,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1520
1627
  this.followTranscript = false;
1521
1628
  }
1522
1629
  const maxScroll = Math.max(0, this.transcriptLines.length - this.transcriptViewportHeight);
1523
- this.transcriptScrollOffset = Math.max(
1630
+ const nextOffset = Math.max(
1524
1631
  0,
1525
1632
  Math.min(maxScroll, this.transcriptScrollOffset + delta),
1526
1633
  );
1634
+ if (nextOffset !== this.transcriptScrollOffset) this.scrollbarActive = true;
1635
+ this.transcriptScrollOffset = nextOffset;
1527
1636
  if (this.transcriptScrollOffset >= maxScroll) {
1528
1637
  this.followTranscript = true;
1529
1638
  }
@@ -1888,7 +1997,6 @@ export class BtwOverlayComponent extends Container implements Focusable {
1888
1997
  this.transcriptScrollOffset,
1889
1998
  this.transcriptScrollOffset + transcriptHeight,
1890
1999
  );
1891
- const transcriptPadCount = Math.max(0, transcriptHeight - visibleTranscript.length);
1892
2000
  const hiddenAbove = this.transcriptScrollOffset;
1893
2001
  const hiddenBelow = Math.max(0, maxScroll - this.transcriptScrollOffset);
1894
2002
  const summary =
@@ -1900,16 +2008,20 @@ export class BtwOverlayComponent extends Container implements Focusable {
1900
2008
 
1901
2009
  lines.push(this.titleLine(this.theme.fg("accent", this.theme.bold(this.modeTextValue.trim())), innerWidth));
1902
2010
  lines.push(this.frameLine(this.theme.fg("dim", summary), innerWidth));
1903
- lines.push(this.ruleLine(innerWidth));
1904
-
1905
- for (const line of visibleTranscript) {
1906
- lines.push(this.frameLine(line, innerWidth));
1907
- }
1908
- for (let i = 0; i < transcriptPadCount; i++) {
1909
- lines.push(this.frameLine("", innerWidth));
2011
+ lines.push(this.scrollRule(innerWidth, "top", hiddenAbove));
2012
+
2013
+ for (let i = 0; i < transcriptHeight; i++) {
2014
+ lines.push(this.frameScrollableLine(
2015
+ visibleTranscript[i] ?? "",
2016
+ innerWidth,
2017
+ transcriptLines.length,
2018
+ transcriptHeight,
2019
+ this.transcriptScrollOffset,
2020
+ i,
2021
+ ));
1910
2022
  }
1911
2023
 
1912
- lines.push(this.ruleLine(innerWidth));
2024
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
1913
2025
  lines.push(this.frameLine(this.theme.fg("warning", this.statusTextValue.trim()), innerWidth));
1914
2026
  lines.push(...this.inputFrameLines(innerWidth, inputLineCount));
1915
2027
  lines.push(this.frameLine(this.theme.fg("dim", this.hintsTextValue.trim()), innerWidth));
@@ -1920,6 +2032,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1920
2032
 
1921
2033
  setDraft(value: string): void {
1922
2034
  this.input.setText(value);
2035
+ this.resetDraftRecall();
1923
2036
  this.tui.requestRender();
1924
2037
  }
1925
2038
 
@@ -1973,13 +2086,23 @@ export class BtwOverlayComponent extends Container implements Focusable {
1973
2086
 
1974
2087
  private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1975
2088
  // Keep the preview read-only and complete. The viewport, not the data,
1976
- // supplies the bound: only the visible slice is emitted below.
1977
- const status = block.streaming ? "Status: STREAMING\n\n" : "";
1978
- const text = `${status}${getToolPreviewText(block)}`;
2089
+ // supplies the bound: only the visible slice is emitted below. The local
2090
+ // renderer owns the complete Input/Output card while the outer frame owns
2091
+ // the viewport and scrollbar.
2092
+ const input = block.toolInput || (block.type === "tool-call" ? block.text : "") || "(no input)";
2093
+ const output = block.toolOutput || (block.type === "tool-result" ? block.text : "") || "(no output)";
2094
+ const rendered = renderBtwToolOutput({
2095
+ input,
2096
+ output,
2097
+ width: Math.max(1, innerWidth - 1),
2098
+ isError: block.isError === true,
2099
+ }, this.theme);
1979
2100
  const lines: string[] = [];
1980
- for (const line of text.split("\n")) {
1981
- lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
2101
+ if (block.streaming) {
2102
+ lines.push(this.theme.fg("warning", "Status: STREAMING"));
2103
+ lines.push("");
1982
2104
  }
2105
+ lines.push(...rendered.lines);
1983
2106
  return lines.length > 0 ? lines : ["(no tool data)"];
1984
2107
  }
1985
2108
 
@@ -2035,10 +2158,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
2035
2158
  if (this.toolPreviewParent === null) return;
2036
2159
  const viewportHeight = Math.max(1, this.peekState.viewportHeight);
2037
2160
  const maxScroll = Math.max(0, this.peekToolPreviewLines.length - viewportHeight);
2038
- this.peekToolPreviewScrollOffset = Math.max(
2161
+ const nextOffset = Math.max(
2039
2162
  0,
2040
2163
  Math.min(maxScroll, this.peekToolPreviewScrollOffset + delta),
2041
2164
  );
2165
+ if (nextOffset !== this.peekToolPreviewScrollOffset) this.scrollbarActive = true;
2166
+ this.peekToolPreviewScrollOffset = nextOffset;
2042
2167
  this.tui.requestRender();
2043
2168
  }
2044
2169
 
@@ -2064,21 +2189,29 @@ export class BtwOverlayComponent extends Container implements Focusable {
2064
2189
 
2065
2190
  const streamingLabel = block.streaming ? " · STREAMING" : "";
2066
2191
  const title = `BTW Tool Output · ${getSemanticBlockLabel(block)}${streamingLabel} · read-only`;
2067
- const lines = [
2068
- this.borderLine(innerWidth, "top"),
2069
- this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2070
- this.ruleLine(innerWidth),
2071
- ];
2072
2192
  const visible = this.peekToolPreviewLines.slice(
2073
2193
  this.peekToolPreviewScrollOffset,
2074
2194
  this.peekToolPreviewScrollOffset + viewportHeight,
2075
2195
  );
2076
- for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2077
- for (let i = visible.length; i < viewportHeight; i++) lines.push(this.frameLine("", innerWidth));
2078
2196
  const hiddenAbove = this.peekToolPreviewScrollOffset;
2079
2197
  const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2198
+ const lines = [
2199
+ this.borderLine(innerWidth, "top"),
2200
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2201
+ this.scrollRule(innerWidth, "top", hiddenAbove),
2202
+ ];
2203
+ for (let i = 0; i < viewportHeight; i++) {
2204
+ lines.push(this.frameScrollableLine(
2205
+ visible[i] ?? "",
2206
+ innerWidth,
2207
+ this.peekToolPreviewLines.length,
2208
+ viewportHeight,
2209
+ this.peekToolPreviewScrollOffset,
2210
+ i,
2211
+ ));
2212
+ }
2213
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2080
2214
  const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2081
- lines.push(this.ruleLine(innerWidth));
2082
2215
  lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn Esc:back${counts}`), innerWidth));
2083
2216
  lines.push(this.borderLine(innerWidth, "bottom"));
2084
2217
  return lines.map((line) => this.fitRenderedLine(line, fullWidth));
@@ -2110,24 +2243,29 @@ export class BtwOverlayComponent extends Container implements Focusable {
2110
2243
  );
2111
2244
 
2112
2245
  const title = `BTW Peek · ${getSemanticBlockLabel(block)} · read-only`;
2113
- const lines = [
2114
- this.borderLine(innerWidth, "top"),
2115
- this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2116
- this.ruleLine(innerWidth),
2117
- ];
2118
2246
  const visible = this.peekToolPreviewLines.slice(
2119
2247
  this.peekToolPreviewScrollOffset,
2120
2248
  this.peekToolPreviewScrollOffset + viewportHeight,
2121
2249
  );
2122
- for (const line of visible) lines.push(this.frameLine(line, innerWidth));
2123
- while (visible.length < viewportHeight) {
2124
- visible.push("");
2125
- lines.push(this.frameLine("", innerWidth));
2126
- }
2127
2250
  const hiddenAbove = this.peekToolPreviewScrollOffset;
2128
2251
  const hiddenBelow = Math.max(0, maxScroll - this.peekToolPreviewScrollOffset);
2252
+ const lines = [
2253
+ this.borderLine(innerWidth, "top"),
2254
+ this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
2255
+ this.scrollRule(innerWidth, "top", hiddenAbove),
2256
+ ];
2257
+ for (let i = 0; i < viewportHeight; i++) {
2258
+ lines.push(this.frameScrollableLine(
2259
+ visible[i] ?? "",
2260
+ innerWidth,
2261
+ this.peekToolPreviewLines.length,
2262
+ viewportHeight,
2263
+ this.peekToolPreviewScrollOffset,
2264
+ i,
2265
+ ));
2266
+ }
2267
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2129
2268
  const counts = hiddenAbove || hiddenBelow ? ` · ↑${hiddenAbove} ↓${hiddenBelow}` : "";
2130
- lines.push(this.ruleLine(innerWidth));
2131
2269
  lines.push(this.frameLine(this.theme.fg("dim", `j/k ↑↓ g/G PgUp/PgDn q/Esc:back${counts}`), innerWidth));
2132
2270
  lines.push(this.borderLine(innerWidth, "bottom"));
2133
2271
  return lines.map((line) => this.fitRenderedLine(line, fullWidth));
@@ -2155,6 +2293,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2155
2293
  this.toolPreviewParent = "live";
2156
2294
  this.peekToolPreviewScrollOffset = 0;
2157
2295
  this.peekToolPreviewLines = [];
2296
+ this.scrollbarActive = false;
2158
2297
  this.tui.requestRender();
2159
2298
  }
2160
2299
 
@@ -2266,7 +2405,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
2266
2405
  }
2267
2406
 
2268
2407
  // ── Content ──────────────────────────────────────────────────────
2269
- const mdContentWidth = Math.max(1, innerWidth - 6);
2408
+ // Keep one inner cell free for the right-hand ScrollView rail.
2409
+ const mdContentWidth = Math.max(1, innerWidth - 7);
2270
2410
  this.peekContentTop = 4;
2271
2411
  // Build rendered lines and remember each block's starting line so j/k
2272
2412
  // can scroll by line while J/K still jump by message.
@@ -2308,21 +2448,14 @@ export class BtwOverlayComponent extends Container implements Focusable {
2308
2448
  if (this.expandedToolId === block.id && hasToolPreview(block)) {
2309
2449
  const toolLines = this.buildToolPreviewLines(block, innerWidth);
2310
2450
  for (const toolLine of toolLines) {
2311
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg(block.isError ? "error" : "dim", toolLine)}`);
2451
+ blockLines.push(`${isCurrent ? "▎ " : " "}${toolLine}`);
2312
2452
  }
2313
2453
  }
2314
2454
  } else if (block.text) {
2315
- if (block.type === "assistant-text" || block.type === "user") {
2316
- const md = new Markdown(block.text, 0, 0, this.mdTheme);
2317
- const mdLines = md.render(mdContentWidth);
2318
- for (const mdLine of mdLines) {
2319
- blockLines.push(`${isCurrent ? "▎ " : " "}${mdLine.replace(/[ \t]+$/u, "")}`);
2320
- }
2321
- } else if (block.type === "thinking") {
2322
- const styledLines = wrapTextWithAnsi(block.text, mdContentWidth);
2323
- for (const sl of styledLines) {
2324
- blockLines.push(`${isCurrent ? "▎ " : " "}${this.theme.fg("warning", this.theme.italic(sl))}`);
2325
- }
2455
+ const role = block.type === "user" ? "user" : block.type === "thinking" ? "thinking" : "assistant";
2456
+ const markdownLines = renderBtwMarkdown(block.text, mdContentWidth, this.theme, role, this.mdTheme);
2457
+ for (const markdownLine of markdownLines) {
2458
+ blockLines.push(`${isCurrent ? "▎ " : " "}${markdownLine.replace(/[ \t]+$/u, "")}`);
2326
2459
  }
2327
2460
  }
2328
2461
 
@@ -2342,6 +2475,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
2342
2475
  this.peekState.scrollOffset = Math.max(0, Math.min(this.peekState.scrollOffset, maxScroll));
2343
2476
 
2344
2477
  const visibleStart = this.peekState.scrollOffset;
2478
+ const hiddenAbove = visibleStart;
2479
+ const hiddenBelow = Math.max(0, maxScroll - visibleStart);
2480
+ // The header rule is the top ScrollView more indicator. It is emitted
2481
+ // before content so the hit-test coordinates remain stable.
2482
+ lines[2] = this.scrollRule(innerWidth, "top", hiddenAbove);
2345
2483
  this.peekStickyHeaderIndex = null;
2346
2484
  const displayLines = this.peekRenderedLines.slice(visibleStart, visibleStart + vh);
2347
2485
  if (blockCount === 0) {
@@ -2357,9 +2495,16 @@ export class BtwOverlayComponent extends Container implements Focusable {
2357
2495
  displayLines.push("");
2358
2496
  }
2359
2497
 
2360
- // Frame each line
2361
- for (const line of displayLines) {
2362
- lines.push(this.frameLine(line, innerWidth));
2498
+ // Frame each line and reserve the final inner cell for the scrollbar.
2499
+ for (let i = 0; i < vh; i++) {
2500
+ lines.push(this.frameScrollableLine(
2501
+ displayLines[i] ?? "",
2502
+ innerWidth,
2503
+ this.peekRenderedLines.length,
2504
+ vh,
2505
+ this.peekState.scrollOffset,
2506
+ i,
2507
+ ));
2363
2508
  }
2364
2509
 
2365
2510
  // ── Status bar ───────────────────────────────────────────────────
@@ -2371,7 +2516,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2371
2516
  const previewHint = hasToolPreview(selected) ? " w:preview" : "";
2372
2517
  const expandHint = hasToolPreview(selected) ? " Enter:expand" : "";
2373
2518
  const statusText = `j/k ↑↓ J/K msg g/G /search${searchHint} ${toolsHint}${previewHint} M:copy o:nvim${expandHint} q:exit`;
2374
- lines.push(this.ruleLine(innerWidth));
2519
+ lines.push(this.scrollRule(innerWidth, "bottom", hiddenBelow));
2375
2520
  lines.push(this.frameLine(this.theme.fg("dim", statusText), innerWidth));
2376
2521
  lines.push(this.borderLine(innerWidth, "bottom"));
2377
2522
 
@@ -2381,6 +2526,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
2381
2526
  enterPeekMode(): void {
2382
2527
  this.peekState = createPeekState();
2383
2528
  this.peekState.active = true;
2529
+ this.scrollbarActive = false;
2384
2530
  const entries = this.readTranscriptEntries();
2385
2531
  this.peekState.showTools = true;
2386
2532
  this.peekBlocks = this.hydrateToolBlocks(buildPeekBlocks(
@@ -3242,15 +3388,22 @@ export default function (pi: ExtensionAPI) {
3242
3388
  throw new Error(settings.fallbackReason || "No active model selected.");
3243
3389
  }
3244
3390
 
3245
- const { session } = await createAgentSession({
3391
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime | null }).runtime ?? undefined;
3392
+ const sessionOptions: Parameters<typeof createAgentSession>[0] & {
3393
+ modelRegistry?: ExtensionContext["modelRegistry"];
3394
+ modelRuntime?: ModelRuntime;
3395
+ } = {
3246
3396
  sessionManager: SessionManager.inMemory(),
3247
3397
  model: settings.model,
3248
- modelRegistry: ctx.modelRegistry as AgentSession["modelRegistry"],
3398
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
3249
3399
  thinkingLevel: settings.thinkingLevel,
3250
3400
  // Match pi's default coding-agent toolset (read/bash/edit/write).
3251
3401
  tools: ["read", "bash", "edit", "write"],
3252
3402
  resourceLoader: createBtwResourceLoader(ctx),
3253
- });
3403
+ // Keep the pre-ModelRuntime facade available for older Pi hosts.
3404
+ modelRegistry: ctx.modelRegistry,
3405
+ };
3406
+ const { session } = await createAgentSession(sessionOptions);
3254
3407
 
3255
3408
  const { messages: seedMessages, sideThreadStartIndex } = buildBtwSeedState(ctx, pendingThread, mode, settings.model);
3256
3409
  if (seedMessages.length > 0) {
@@ -3879,14 +4032,21 @@ export default function (pi: ExtensionAPI) {
3879
4032
  throw new Error(auth.ok ? `No credentials available for ${model.provider}/${model.id}.` : auth.error);
3880
4033
  }
3881
4034
 
3882
- const { session } = await createAgentSession({
4035
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime | null }).runtime ?? undefined;
4036
+ const sessionOptions: Parameters<typeof createAgentSession>[0] & {
4037
+ modelRegistry?: ExtensionContext["modelRegistry"];
4038
+ modelRuntime?: ModelRuntime;
4039
+ } = {
3883
4040
  sessionManager: SessionManager.inMemory(),
3884
4041
  model,
3885
- modelRegistry: ctx.modelRegistry as AgentSession["modelRegistry"],
4042
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
3886
4043
  thinkingLevel: "off",
3887
4044
  tools: [],
3888
4045
  resourceLoader: createBtwResourceLoader(ctx, [BTW_SUMMARIZE_SYSTEM_PROMPT]),
3889
- });
4046
+ // Keep the pre-ModelRuntime facade available for older Pi hosts.
4047
+ modelRegistry: ctx.modelRegistry,
4048
+ };
4049
+ const { session } = await createAgentSession(sessionOptions);
3890
4050
 
3891
4051
  try {
3892
4052
  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.13",
3
+ "version": "0.6.15",
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",