@narumitw/pi-btw 0.61.2 → 0.62.0

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.
@@ -2,7 +2,6 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  import {
3
3
  AssistantMessageComponent,
4
4
  getMarkdownTheme,
5
- type KeybindingsManager,
6
5
  type MarkdownTransformer,
7
6
  type Theme,
8
7
  UserMessageComponent,
@@ -13,27 +12,198 @@ import {
13
12
  Editor,
14
13
  type EditorTheme,
15
14
  type Focusable,
16
- Key,
17
- Loader,
18
- Markdown,
19
- matchesKey,
15
+ isKeyRelease,
16
+ type Keybindings,
17
+ type KeybindingsManager,
18
+ renderFakeCursor,
20
19
  ScrollView,
20
+ Spacer,
21
+ Text,
21
22
  type TUI,
22
23
  truncateToWidth,
23
24
  VStack,
24
25
  visibleWidth,
25
26
  } from "@earendil-works/pi-tui";
26
- import { BtwPasteGuard, type BtwShortcuts, getBtwShortcuts } from "./keybindings.js";
27
+ import {
28
+ type BtwDisplayModel,
29
+ BtwWorkingIndicator,
30
+ type BtwWorkspaceFocus,
31
+ renderConversationFooter,
32
+ renderWorkingBorder,
33
+ } from "./conversation-chrome.js";
34
+ import {
35
+ BtwPasteGuard,
36
+ type BtwShortcuts,
37
+ btwKeyHasReachableInput,
38
+ getBtwHostInputBlockers,
39
+ getBtwKeybindings,
40
+ getBtwShortcuts,
41
+ normalizeBtwKey,
42
+ } from "./keybindings.js";
27
43
  import type { BtwThinkingLevel, SideThreadTurn } from "./side-thread.js";
28
- import { sanitizeSingleLine } from "./text.js";
44
+ import { formatKeyLabel, sanitizeSingleLine } from "./text.js";
29
45
  import type { BtwFullscreenLayoutComponent } from "./workspace-layout.js";
30
46
 
31
- const TRANSCRIPT_CHROME_LINES = 2;
32
47
  const MAX_STEERING_DISPLAY_LINES = 3;
33
48
  const OSC133_MARKERS = ["\u001b]133;A\u0007", "\u001b]133;B\u0007", "\u001b]133;C\u0007"];
34
49
  // Pi renders a spacer above the custom component and a two-line built-in footer below it.
35
50
  const RESERVED_APP_LINES = 3;
36
51
 
52
+ // Native mouse focus can land directly on this Editor. Route keyboard input
53
+ // through its logical BTW owner without replacing native mouse/cursor handling.
54
+ class BtwComposer extends Editor {
55
+ constructor(
56
+ tui: TUI,
57
+ theme: EditorTheme,
58
+ private readonly dispatch: (data: string) => void,
59
+ private readonly loader?: BtwWorkingIndicator,
60
+ ) {
61
+ super(tui, theme);
62
+ }
63
+ override handleInput(data: string): void {
64
+ this.dispatch(data);
65
+ }
66
+ handleEditorInput(data: string): void {
67
+ super.handleInput(data);
68
+ }
69
+ override render(width: number): string[] {
70
+ if (width <= 0) return [];
71
+ // Core word wrapping cannot fit a two-cell grapheme into layoutWidth=1.
72
+ // Measure at least two text cells, then clip only the display boundary.
73
+ return super.render(Math.max(3, width)).map((line) => {
74
+ // A wide grapheme cannot fit a one-cell dock. Keep its cursor cell usable.
75
+ if (width <= 2 && line.includes(CURSOR_MARKER))
76
+ return CURSOR_MARKER + renderFakeCursor(" ") + " ".repeat(width - 1);
77
+ return truncateToWidth(line, width, "");
78
+ });
79
+ }
80
+ protected override renderTopBorder(width: number, hiddenLineCount: number): string {
81
+ if (!this.loader) return super.renderTopBorder(width, hiddenLineCount);
82
+ return (
83
+ renderWorkingBorder(width, hiddenLineCount, this.borderColor, this.loader) ??
84
+ super.renderTopBorder(width, hiddenLineCount)
85
+ );
86
+ }
87
+ }
88
+
89
+ const VIEWPORT_ACTIONS = [
90
+ "tui.altScreen.search",
91
+ "tui.altScreen.pageUp",
92
+ "tui.altScreen.pageDown",
93
+ "tui.altScreen.halfPageUp",
94
+ "tui.altScreen.halfPageDown",
95
+ "tui.altScreen.lineUp",
96
+ "tui.altScreen.lineDown",
97
+ "tui.altScreen.previousPrompt",
98
+ "tui.altScreen.nextPrompt",
99
+ "tui.altScreen.top",
100
+ "tui.altScreen.bottom",
101
+ ] as const;
102
+ // Editor's actual order before submit, with no autocomplete provider installed.
103
+ const BEFORE_SUBMIT = [
104
+ "tui.input.copy",
105
+ "tui.editor.undo",
106
+ "tui.input.tab",
107
+ "tui.editor.deleteToLineEnd",
108
+ "tui.editor.deleteToLineStart",
109
+ "tui.editor.deleteWordBackward",
110
+ "tui.editor.deleteWordForward",
111
+ "tui.editor.deleteCharBackward",
112
+ "tui.editor.deleteCharForward",
113
+ "tui.editor.yank",
114
+ "tui.editor.yankPop",
115
+ "tui.editor.historyPrevious",
116
+ "tui.editor.historyNext",
117
+ "tui.editor.cursorLineStart",
118
+ "tui.editor.cursorLineEnd",
119
+ "tui.editor.cursorWordLeft",
120
+ "tui.editor.cursorWordRight",
121
+ "tui.input.newLine",
122
+ ] as const;
123
+
124
+ function usableKeys(keybindings: KeybindingsManager, action: keyof Keybindings, blockers: readonly string[]): string[] {
125
+ return keybindings.getKeys(action).flatMap((candidate) => {
126
+ const key = normalizeBtwKey(candidate);
127
+ return key && btwKeyHasReachableInput(key, blockers) ? [key] : [];
128
+ });
129
+ }
130
+
131
+ function submitHint(tui: TUI, keybindings: KeybindingsManager, verb: string): string {
132
+ const earlier =
133
+ tui.mode === "fullscreen" ? VIEWPORT_ACTIONS : (["tui.altScreen.pageUp", "tui.altScreen.pageDown"] as const);
134
+ const blockers = [
135
+ ...getBtwHostInputBlockers(tui),
136
+ "ctrl+c",
137
+ "shift+backspace",
138
+ "shift+delete",
139
+ ...[...earlier, ...BEFORE_SUBMIT].flatMap((id) => keybindings.getKeys(id)),
140
+ ];
141
+ const key = usableKeys(keybindings, "tui.input.submit", blockers)[0];
142
+ return key ? `${formatKeyLabel(key)} ${verb}` : "";
143
+ }
144
+
145
+ function pagingHint(tui: TUI, keybindings: KeybindingsManager): string {
146
+ const actions = ["tui.altScreen.pageUp", "tui.altScreen.pageDown"] as const;
147
+ const labels = actions.flatMap((action) => {
148
+ const earlier =
149
+ tui.mode === "fullscreen"
150
+ ? VIEWPORT_ACTIONS.slice(0, VIEWPORT_ACTIONS.indexOf(action))
151
+ : action === "tui.altScreen.pageDown"
152
+ ? (["tui.altScreen.pageUp"] as const)
153
+ : [];
154
+ const blockers = [...getBtwHostInputBlockers(tui), "ctrl+c", ...earlier.flatMap((id) => keybindings.getKeys(id))];
155
+ const key = usableKeys(keybindings, action, blockers)[0];
156
+ return key
157
+ ? [
158
+ formatKeyLabel(key)
159
+ .replace(/Pageup$/u, "PgUp")
160
+ .replace(/Pagedown$/u, "PgDn"),
161
+ ]
162
+ : [];
163
+ });
164
+ return labels.length ? `${labels.join("/")} history` : "";
165
+ }
166
+
167
+ function handleFallbackPaging(
168
+ data: string,
169
+ tui: TUI,
170
+ keybindings: KeybindingsManager,
171
+ scrollView: ScrollView,
172
+ ): boolean {
173
+ // The native renderer already dispatched these before the focused component.
174
+ if (tui.mode === "fullscreen" || isKeyRelease(data)) return false;
175
+ for (const [action, direction] of [
176
+ ["tui.altScreen.pageUp", -1],
177
+ ["tui.altScreen.pageDown", 1],
178
+ ] as const) {
179
+ if (keybindings.matches(data, action)) {
180
+ scrollView.scrollBy(direction * Math.max(1, scrollView.viewportHeight - 4));
181
+ return true;
182
+ }
183
+ }
184
+ return false;
185
+ }
186
+
187
+ function fittingHint(width: number, variants: readonly string[]): string {
188
+ return variants.find((hint) => visibleWidth(hint) <= Math.max(0, width)) ?? "";
189
+ }
190
+
191
+ function compactHints(parts: readonly string[]): string {
192
+ return parts.filter(Boolean).join(" • ");
193
+ }
194
+
195
+ function releaseScrollbar(scrollView: ScrollView): void {
196
+ scrollView.setScrollbarActive(false);
197
+ // setScrollbar owns cancellation of its private native hide timer.
198
+ scrollView.setScrollbar("hidden");
199
+ }
200
+
201
+ function thinkingBorder(theme: Theme, level: BtwThinkingLevel | undefined, text: string): string {
202
+ return level && theme.getThinkingBorderColor
203
+ ? theme.getThinkingBorderColor(level)(text)
204
+ : theme.fg("borderMuted", text);
205
+ }
206
+
37
207
  // A temporary fit after manual scrolling must not silently resume following new output.
38
208
  class PreservingScrollView extends ScrollView {
39
209
  override updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void {
@@ -58,6 +228,8 @@ export interface BtwThinkingControl {
58
228
  }
59
229
 
60
230
  export interface BtwAnsweringViewOptions {
231
+ model?: BtwDisplayModel;
232
+ keybindings?: KeybindingsManager;
61
233
  markdownTransformers?: readonly MarkdownTransformer[];
62
234
  steering?: {
63
235
  questions: readonly string[];
@@ -67,10 +239,18 @@ export interface BtwAnsweringViewOptions {
67
239
  }
68
240
 
69
241
  export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusable {
242
+ private workspaceFocus: BtwWorkspaceFocus | undefined;
243
+ private get keybindings(): KeybindingsManager {
244
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.thinking?.keybindings);
245
+ }
246
+ setWorkspaceFocus(pane: "side" | "main", shortcutLabel: string | undefined): void {
247
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : undefined };
248
+ this.tui.requestRender();
249
+ }
70
250
  private readonly shortcuts: BtwShortcuts;
71
251
  private readonly pasteGuard = new BtwPasteGuard();
72
252
  private readonly transcriptComponents: Component[];
73
- private readonly editor: Editor;
253
+ private readonly editor: BtwComposer;
74
254
  private readonly canBringToMain: boolean;
75
255
  private readonly scrollView: ScrollView;
76
256
  private readonly layoutRoot: VStack;
@@ -86,18 +266,20 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
86
266
  turns: readonly SideThreadTurn[],
87
267
  private readonly onAction: (action: TranscriptPagerAction) => void,
88
268
  private readonly options: {
269
+ model?: BtwDisplayModel;
270
+ keybindings?: KeybindingsManager;
89
271
  startAtBottom?: boolean;
90
272
  initialQuestion?: string;
91
273
  markdownTransformers?: readonly MarkdownTransformer[];
92
274
  thinking?: BtwThinkingControl;
93
275
  } = {},
94
276
  ) {
95
- this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);
277
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
96
278
  this.transcriptComponents = buildTranscriptComponents(turns, this.theme, undefined, options.markdownTransformers);
97
279
  this.canBringToMain = turns.some((turn) => turn.kind === "answered");
98
280
  this.thinkingLevel = options.thinking?.level;
99
281
  const editorTheme: EditorTheme = {
100
- borderColor: (text) => this.theme.fg("accent", text),
282
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
101
283
  selectList: {
102
284
  selectedPrefix: (text) => this.theme.fg("accent", text),
103
285
  selectedText: (text) => this.theme.fg("accent", text),
@@ -106,7 +288,7 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
106
288
  noMatch: (text) => this.theme.fg("warning", text),
107
289
  },
108
290
  };
109
- this.editor = new Editor(this.tui, editorTheme);
291
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data));
110
292
  if (options.initialQuestion) this.editor.setText(options.initialQuestion);
111
293
  this.editor.onChange = () => {
112
294
  this.warning = undefined;
@@ -122,14 +304,20 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
122
304
  };
123
305
  const transcript = this.createTranscriptComponent();
124
306
  this.scrollView = new PreservingScrollView(transcript, {
125
- follow: options.startAtBottom ? "end" : "none",
307
+ follow: "end",
126
308
  primary: true,
309
+ scrollbar: "auto",
310
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
311
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text),
127
312
  });
313
+ if (!options.startAtBottom) this.scrollView.scrollTo(0, { disableFollow: true });
314
+ const dock = new VStack([
315
+ { component: this.editor, basis: "auto", shrink: 1, minSize: 1 },
316
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 },
317
+ ]);
128
318
  this.layoutRoot = new VStack([
129
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
130
319
  { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
131
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
132
- { component: this.editor, basis: "auto", shrink: 1, minSize: 0 },
320
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 },
133
321
  ]);
134
322
  }
135
323
 
@@ -151,17 +339,16 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
151
339
  }
152
340
 
153
341
  render(width: number): string[] {
154
- if (width <= 0) return [];
342
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
155
343
  const safeWidth = Math.max(1, width);
156
344
  const editorLines = this.editor.render(safeWidth);
157
345
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
158
- const viewportHeight = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
159
346
  const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
160
347
  this.lastContentLineCount = contentLines.length;
348
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - this.renderFooter(safeWidth).length);
161
349
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
162
350
 
163
351
  return fitComposerLayout(
164
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
165
352
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
166
353
  this.renderFooter(safeWidth),
167
354
  editorLines,
@@ -172,7 +359,7 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
172
359
  handleInput(data: string): void {
173
360
  if (this.finished) return;
174
361
  if (this.pasteGuard.consume(data)) {
175
- this.editor.handleInput(data);
362
+ this.editor.handleEditorInput(data);
176
363
  this.tui.requestRender();
177
364
  return;
178
365
  }
@@ -198,17 +385,9 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
198
385
  }
199
386
  return;
200
387
  }
201
- if (matchesKey(data, Key.pageUp)) {
202
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
203
- this.tui.requestRender();
204
- return;
205
- }
206
- if (matchesKey(data, Key.pageDown)) {
207
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
208
- this.tui.requestRender();
209
- return;
388
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
389
+ this.editor.handleEditorInput(data);
210
390
  }
211
- this.editor.handleInput(data);
212
391
  if (!this.finished) this.tui.requestRender();
213
392
  }
214
393
 
@@ -217,72 +396,51 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
217
396
  }
218
397
 
219
398
  dispose(): void {
399
+ releaseScrollbar(this.scrollView);
220
400
  if (this.finished) return;
221
401
  this.finished = true;
222
402
  this.onAction({ kind: "close" });
223
403
  }
224
404
 
225
- private renderFooter(width: number): string {
405
+ private renderFooter(width: number): string[] {
406
+ return renderConversationFooter(width, this.theme, {
407
+ model: this.options.model,
408
+ thinkingLevel: this.thinkingLevel,
409
+ focus: this.workspaceFocus,
410
+ hint: this.renderHints(width),
411
+ warning: this.warning !== undefined,
412
+ });
413
+ }
414
+
415
+ private renderHints(width: number): string {
226
416
  const exit = this.shortcuts.label("exit");
227
417
  const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
228
418
  const bringKey = this.shortcuts.label("bringToMain");
229
- if (this.warning) {
230
- const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} exit`;
231
- return truncateToWidth(this.theme.fg("warning", warning), width);
232
- }
233
- const scrollable = this.getMaxScrollOffset() > 0;
419
+ if (this.warning) return fittingHint(width, [`${this.warning} • ${exit} exit`, `Empty • ${exit}`, exit]);
234
420
  const thinking = this.options.thinking;
235
- const cycleHint =
236
- thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length
237
- ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
421
+ const cycle =
422
+ thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length
423
+ ? `${this.shortcuts.label("cycleThinkingLevel")} thinking`
238
424
  : "";
239
- const base = bring
240
- ? `btw • Enter send • ${bringKey} bring to main • ${exit} exit`
241
- : `btw • Enter send • ${exit} exit`;
242
- const fullBase = `${base}${cycleHint}`;
243
- const fallbackBase = `btw • Enter • ${exit}`;
244
- const compactBase = bring ? `btw • Enter • ${bringKey} • ${exit}` : fallbackBase;
245
- const compactWithThinking = `${compactBase}${cycleHint}`;
246
- let hints =
247
- visibleWidth(fullBase) <= width
248
- ? fullBase
249
- : visibleWidth(compactWithThinking) <= width
250
- ? compactWithThinking
251
- : visibleWidth(compactBase) <= width
252
- ? compactBase
253
- : fallbackBase;
254
- if (scrollable) {
255
- const history = ` • ${this.scrollView.scrollTop > 0 ? "↑ older" : "↓ newer"} • PgUp/PgDn history`;
256
- const compactHistory = " • PgUp/PgDn";
257
- const compactScrollable = bring
258
- ? `Enter • ${bringKey} • ${exit} • PgUp/PgDn`
259
- : `${fallbackBase}${compactHistory}`;
260
- if (visibleWidth(`${hints}${history}`) <= width) {
261
- hints += history;
262
- } else if (visibleWidth(`${compactBase}${history}`) <= width) {
263
- hints = `${compactBase}${history}`;
264
- } else if (visibleWidth(`${hints}${compactHistory}`) <= width) {
265
- hints += compactHistory;
266
- } else if (visibleWidth(`${compactBase}${compactHistory}`) <= width) {
267
- hints = `${compactBase}${compactHistory}`;
268
- } else if (visibleWidth(compactScrollable) <= width) {
269
- hints = compactScrollable;
270
- }
271
- }
272
- return truncateToWidth(this.theme.fg("muted", hints), width);
273
- }
274
-
275
- private createHeaderComponent(): Component {
276
- return {
277
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
278
- invalidate() {},
279
- };
425
+ const submit = submitHint(this.tui, this.keybindings, "send");
426
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
427
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
428
+ const submitKey = submit.split(" ")[0] ?? "";
429
+ return fittingHint(width, [
430
+ compactHints([submit, bring ? `${bringKey} bring to main` : "", `${exit} exit`, cycle, history, switchPane]),
431
+ compactHints([submit, bring ? bringKey : "", exit, cycle, history, switchPane]),
432
+ compactHints([submitKey, bring ? bringKey : "", exit, cycle, history.replace(/ history$/u, ""), switchPane]),
433
+ compactHints([submitKey, bring ? bringKey : "", exit, history.replace(/ history$/u, "")]),
434
+ compactHints([submitKey, bring ? bringKey : "", exit]),
435
+ compactHints([submitKey, exit]),
436
+ exit,
437
+ ]);
280
438
  }
281
439
 
282
440
  private createTranscriptComponent(): Component {
283
441
  return {
284
442
  render: (width) => {
285
- const lines = renderTranscriptLines(this.transcriptComponents, width);
443
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
286
444
  this.lastContentLineCount = lines.length;
287
445
  return lines;
288
446
  },
@@ -294,7 +452,7 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
294
452
 
295
453
  private createFooterComponent(): Component {
296
454
  return {
297
- render: (width) => [this.renderFooter(width)],
455
+ render: (width) => this.renderFooter(width),
298
456
  invalidate() {},
299
457
  };
300
458
  }
@@ -305,11 +463,19 @@ export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusab
305
463
  }
306
464
 
307
465
  export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable {
466
+ private workspaceFocus: BtwWorkspaceFocus | undefined;
467
+ private get keybindings(): KeybindingsManager {
468
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.steering?.thinking?.keybindings);
469
+ }
470
+ setWorkspaceFocus(pane: "side" | "main", shortcutLabel: string | undefined): void {
471
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : undefined };
472
+ this.tui.requestRender();
473
+ }
308
474
  private readonly shortcuts: BtwShortcuts;
309
475
  private readonly pasteGuard = new BtwPasteGuard();
310
476
  private readonly transcriptComponents: Component[];
311
- private readonly loader: Loader;
312
- private readonly editor: Editor | undefined;
477
+ private readonly loader: BtwWorkingIndicator;
478
+ private readonly editor: BtwComposer | undefined;
313
479
  private readonly controller = new AbortController();
314
480
  private readonly scrollView: ScrollView;
315
481
  private readonly layoutRoot: VStack;
@@ -328,7 +494,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
328
494
  thinkingLevel?: BtwThinkingLevel,
329
495
  private readonly options: BtwAnsweringViewOptions = {},
330
496
  ) {
331
- this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);
497
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
332
498
  this.transcriptComponents = buildTranscriptComponents(
333
499
  turns,
334
500
  this.theme,
@@ -336,7 +502,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
336
502
  options.markdownTransformers,
337
503
  );
338
504
  this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
339
- this.loader = new Loader(
505
+ this.loader = new BtwWorkingIndicator(
340
506
  this.tui,
341
507
  (text) => this.theme.fg("accent", text),
342
508
  (text) => this.theme.fg("muted", text),
@@ -344,7 +510,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
344
510
  );
345
511
  if (options.steering) {
346
512
  const editorTheme: EditorTheme = {
347
- borderColor: (text) => this.theme.fg("accent", text),
513
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
348
514
  selectList: {
349
515
  selectedPrefix: (text) => this.theme.fg("accent", text),
350
516
  selectedText: (text) => this.theme.fg("accent", text),
@@ -353,7 +519,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
353
519
  noMatch: (text) => this.theme.fg("warning", text),
354
520
  },
355
521
  };
356
- this.editor = new Editor(this.tui, editorTheme);
522
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data), this.loader);
357
523
  this.editor.onChange = () => {
358
524
  this.warning = undefined;
359
525
  };
@@ -368,10 +534,14 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
368
534
  };
369
535
  }
370
536
  const transcript = this.createTranscriptComponent();
371
- this.scrollView = new PreservingScrollView(transcript, { follow: "end", primary: true });
372
- this.layoutRoot = new VStack([
373
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
374
- { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
537
+ this.scrollView = new PreservingScrollView(transcript, {
538
+ follow: "end",
539
+ primary: true,
540
+ scrollbar: "auto",
541
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
542
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text),
543
+ });
544
+ const dock = new VStack([
375
545
  {
376
546
  component: this.createSteeringComponent(),
377
547
  basis: "auto",
@@ -379,8 +549,12 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
379
549
  minSize: 0,
380
550
  maxSize: MAX_STEERING_DISPLAY_LINES,
381
551
  },
382
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
383
- ...(this.editor ? [{ component: this.editor, basis: "auto" as const, shrink: 1, minSize: 0 }] : []),
552
+ { component: this.editor ?? this.createWorkingComponent(), basis: "auto", shrink: 1, minSize: 1 },
553
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 },
554
+ ]);
555
+ this.layoutRoot = new VStack([
556
+ { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
557
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 },
384
558
  ]);
385
559
  }
386
560
 
@@ -406,27 +580,24 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
406
580
  }
407
581
 
408
582
  render(width: number): string[] {
409
- if (width <= 0) return [];
583
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
410
584
  const safeWidth = Math.max(1, width);
411
585
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
412
- const editorLines = this.editor?.render(safeWidth) ?? [];
413
- const steeringCapacity = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
586
+ const editorLines = this.editor?.render(safeWidth) ?? this.renderWorking(safeWidth);
587
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
588
+ this.lastContentLineCount = contentLines.length;
589
+ const footerLines = this.renderFooter(safeWidth);
590
+ const steeringCapacity = Math.max(0, availableRows - editorLines.length - footerLines.length);
414
591
  const steeringLines = renderSteeringLines(
415
592
  this.options.steering?.questions ?? [],
416
593
  safeWidth,
417
594
  this.theme,
418
595
  Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity),
419
596
  );
420
- const viewportHeight = Math.max(
421
- 0,
422
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length,
423
- );
424
- const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
425
- this.lastContentLineCount = contentLines.length;
597
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - footerLines.length - steeringLines.length);
426
598
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
427
599
 
428
600
  return fitComposerLayout(
429
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
430
601
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
431
602
  this.renderFooter(safeWidth),
432
603
  editorLines,
@@ -438,7 +609,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
438
609
  handleInput(data: string): void {
439
610
  if (this.finished) return;
440
611
  if (this.pasteGuard.consume(data)) {
441
- this.editor?.handleInput(data);
612
+ this.editor?.handleEditorInput(data);
442
613
  this.tui.requestRender();
443
614
  return;
444
615
  }
@@ -461,17 +632,9 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
461
632
  }
462
633
  return;
463
634
  }
464
- if (matchesKey(data, Key.pageUp)) {
465
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
466
- this.tui.requestRender();
467
- return;
468
- }
469
- if (matchesKey(data, Key.pageDown)) {
470
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
471
- this.tui.requestRender();
472
- return;
635
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
636
+ this.editor?.handleEditorInput(data);
473
637
  }
474
- this.editor?.handleInput(data);
475
638
  this.tui.requestRender();
476
639
  }
477
640
 
@@ -481,10 +644,12 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
481
644
 
482
645
  finish(): void {
483
646
  this.finished = true;
647
+ releaseScrollbar(this.scrollView);
484
648
  this.loader.stop();
485
649
  }
486
650
 
487
651
  dispose(): void {
652
+ releaseScrollbar(this.scrollView);
488
653
  if (this.finished) {
489
654
  this.loader.stop();
490
655
  this.controller.abort();
@@ -496,38 +661,50 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
496
661
  this.onCancel();
497
662
  }
498
663
 
499
- private renderFooter(width: number): string {
664
+ private renderFooter(width: number): string[] {
665
+ return renderConversationFooter(width, this.theme, {
666
+ model: this.options.model,
667
+ thinkingLevel: this.thinkingLevel,
668
+ focus: this.workspaceFocus,
669
+ hint: this.renderHints(width),
670
+ warning: this.warning !== undefined,
671
+ });
672
+ }
673
+
674
+ private renderHints(width: number): string {
500
675
  const exit = this.shortcuts.label("exit");
501
- if (this.warning) {
502
- const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} cancel`;
503
- return truncateToWidth(this.theme.fg("warning", warning), width);
504
- }
505
- const baseHint = this.editor ? `Enter steer • ${exit} cancel` : `${exit} cancel`;
676
+ if (this.warning) return fittingHint(width, [`${this.warning} • ${exit} cancel`, `Empty • ${exit}`, exit]);
677
+ const submit = this.editor ? submitHint(this.tui, this.keybindings, "queue next") : "";
506
678
  const thinking = this.options.steering?.thinking;
507
- const cycleHint =
508
- thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length
509
- ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
679
+ const cycle =
680
+ thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length
681
+ ? `${this.shortcuts.label("cycleThinkingLevel")} thinking`
510
682
  : "";
511
- const scrollHint = this.getMaxScrollOffset() > 0 ? " • PgUp/PgDn history" : "";
512
- const hints = `${baseHint}${cycleHint}${scrollHint}`;
513
- const compactHints = this.editor ? `Enter • ${exit}` : exit;
514
- const selectedHints = visibleWidth(hints) <= width ? hints : compactHints;
515
- const loaderWidth = Math.max(1, width - visibleWidth(selectedHints) - 3);
516
- const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering…";
517
- return truncateToWidth(`${loaderLine} • ${this.theme.fg("muted", selectedHints)}`, width);
683
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
684
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
685
+ const submitKey = submit.split(" ")[0] ?? "";
686
+ return fittingHint(width, [
687
+ compactHints([submit, `${exit} cancel`, cycle, history, switchPane]),
688
+ compactHints([submit, exit, cycle, history, switchPane]),
689
+ compactHints([submitKey, exit, cycle, history.replace(/ history$/u, ""), switchPane]),
690
+ compactHints([submitKey, exit, history.replace(/ history$/u, "")]),
691
+ compactHints([submitKey, exit]),
692
+ exit,
693
+ ]);
518
694
  }
519
695
 
520
- private createHeaderComponent(): Component {
521
- return {
522
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
523
- invalidate() {},
524
- };
696
+ private renderWorking(width: number): string[] {
697
+ return [this.loader.renderInBorder(Math.max(0, width))];
698
+ }
699
+
700
+ private createWorkingComponent(): Component {
701
+ return { render: (width) => this.renderWorking(width), invalidate: () => this.loader.invalidate() };
525
702
  }
526
703
 
527
704
  private createTranscriptComponent(): Component {
528
705
  return {
529
706
  render: (width) => {
530
- const lines = renderTranscriptLines(this.transcriptComponents, width);
707
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
531
708
  this.lastContentLineCount = lines.length;
532
709
  return lines;
533
710
  },
@@ -547,7 +724,7 @@ export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable
547
724
 
548
725
  private createFooterComponent(): Component {
549
726
  return {
550
- render: (width) => [this.renderFooter(width)],
727
+ render: (width) => this.renderFooter(width),
551
728
  invalidate: () => this.loader.invalidate(),
552
729
  };
553
730
  }
@@ -574,7 +751,10 @@ function buildTranscriptComponents(
574
751
  pendingQuestion?: string,
575
752
  markdownTransformers: readonly MarkdownTransformer[] = [],
576
753
  ): Component[] {
577
- const components = turns.flatMap((turn): Component[] => {
754
+ const components = turns.flatMap((turn, index): Component[] => {
755
+ // Pi inserts a spacer before a later user message, outside that message's
756
+ // own Markdown padding. Keep the same separation between side exchanges.
757
+ const preceding = index > 0 ? [new Spacer(1)] : [];
578
758
  const question = new UserMessageComponent(
579
759
  escapeTerminalControls(turn.question),
580
760
  getMarkdownTheme(),
@@ -582,10 +762,12 @@ function buildTranscriptComponents(
582
762
  markdownTransformers,
583
763
  );
584
764
  if (turn.kind === "error") {
585
- const error = new Markdown(`Error: ${escapeTerminalControls(turn.answer)}`, 1, 1, getMarkdownTheme(), {
586
- color: (text) => theme.fg("error", text),
587
- });
588
- return [question, error];
765
+ const error: Component = {
766
+ render: (width) =>
767
+ new Text(theme.fg("error", `Error: ${escapeTerminalControls(turn.answer)}`), 1, 0).render(width),
768
+ invalidate() {},
769
+ };
770
+ return [...preceding, question, new Spacer(1), error];
589
771
  }
590
772
  const response: AssistantMessage = {
591
773
  ...turn.response,
@@ -593,9 +775,14 @@ function buildTranscriptComponents(
593
775
  stopReason: "stop",
594
776
  errorMessage: undefined,
595
777
  };
596
- return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)];
778
+ return [
779
+ ...preceding,
780
+ question,
781
+ new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers),
782
+ ];
597
783
  });
598
784
  if (pendingQuestion) {
785
+ if (components.length > 0) components.push(new Spacer(1));
599
786
  components.push(
600
787
  new UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers),
601
788
  );
@@ -603,30 +790,44 @@ function buildTranscriptComponents(
603
790
  return components;
604
791
  }
605
792
 
606
- function renderTranscriptLines(components: readonly Component[], width: number): string[] {
607
- return components.flatMap((component) => component.render(width)).map(stripShellIntegrationMarkers);
608
- }
609
-
610
- function renderSideThreadHeader(width: number, theme: Theme, thinkingLevel?: BtwThinkingLevel): string {
611
- const thinking = thinkingLevel ? ` · thinking ${thinkingLevel}` : "";
612
- const title = truncateToWidth(`─ btw · side thread${thinking} `, width);
613
- const ruleWidth = Math.max(0, width - visibleWidth(title));
614
- return theme.fg("muted", `${title}${"─".repeat(ruleWidth)}`);
793
+ function renderTranscriptLines(components: readonly Component[], width: number, native = false): string[] {
794
+ return components.flatMap((component) => {
795
+ const lines = component.render(width);
796
+ // Pi adds these exact prefixes outside Markdown. Never trust payload/transformer
797
+ // markers, even when they happen to use the same OSC number.
798
+ const trusted = component instanceof UserMessageComponent || component instanceof AssistantMessageComponent;
799
+ return lines.map((line, index) => {
800
+ let prefix = "";
801
+ if (native && trusted) {
802
+ if (index === 0 && line.startsWith(OSC133_MARKERS[0] ?? "")) prefix += OSC133_MARKERS[0];
803
+ const end = `${OSC133_MARKERS[1]}${OSC133_MARKERS[2]}`;
804
+ if (index === lines.length - 1 && line.slice(prefix.length).startsWith(end)) prefix += end;
805
+ }
806
+ return prefix + truncateToWidth(stripShellIntegrationMarkers(line), Math.max(0, width), "");
807
+ });
808
+ });
615
809
  }
616
810
 
617
811
  function fitComposerLayout(
618
- header: string,
619
812
  contentLines: string[],
620
- footer: string,
813
+ footerLines: string[],
621
814
  editorLines: string[],
622
815
  availableRows: number,
623
816
  statusLines: string[] = [],
624
817
  ): string[] {
625
- const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];
626
- if (lines.length <= availableRows) return lines;
627
- if (availableRows <= 1) return [header];
628
- const editorBudget = Math.max(0, availableRows - 2);
629
- return [header, footer, ...fitEditorLines(editorLines, editorBudget)];
818
+ if (availableRows <= 0) return [];
819
+ // Keep the active input first in the row budget, while retaining native
820
+ // conversation order: transcript, pending questions, editor, then footer.
821
+ const editorBudget = Math.min(editorLines.length, availableRows);
822
+ const footerBudget = Math.min(footerLines.length, availableRows - editorBudget);
823
+ const statusBudget = Math.min(statusLines.length, availableRows - editorBudget - footerBudget);
824
+ const transcriptBudget = availableRows - editorBudget - footerBudget - statusBudget;
825
+ return [
826
+ ...contentLines.slice(0, transcriptBudget),
827
+ ...statusLines.slice(0, statusBudget),
828
+ ...fitEditorLines(editorLines, editorBudget),
829
+ ...footerLines.slice(0, footerBudget),
830
+ ];
630
831
  }
631
832
 
632
833
  function fitEditorLines(editorLines: string[], budget: number): string[] {
@@ -644,7 +845,7 @@ function renderSteeringLines(questions: readonly string[], width: number, theme:
644
845
  if (maxLines === 1 && questions.length > 1) {
645
846
  return [
646
847
  truncateToWidth(
647
- theme.fg("dim", `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
848
+ theme.fg("dim", ` Steering next (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
648
849
  width,
649
850
  ),
650
851
  ];
@@ -653,15 +854,16 @@ function renderSteeringLines(questions: readonly string[], width: number, theme:
653
854
  const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
654
855
  const lines = questions
655
856
  .slice(0, questionLimit)
656
- .map((question) => truncateToWidth(theme.fg("dim", `Steering: ${formatQuestion(question)}`), width));
857
+ .map((question) => truncateToWidth(theme.fg("dim", ` Steering next: ${formatQuestion(question)}`), width));
657
858
  if (hasOverflow) {
658
- lines.push(truncateToWidth(theme.fg("dim", `Steering: … +${questions.length - questionLimit} more`), width));
859
+ lines.push(truncateToWidth(theme.fg("dim", ` Steering next: … +${questions.length - questionLimit} more`), width));
659
860
  }
660
861
  return lines;
661
862
  }
662
863
 
663
864
  function stripShellIntegrationMarkers(line: string): string {
664
- return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, ""), line);
865
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: remove the exact OSC terminal protocol, not printable text.
866
+ return line.replace(/\u001b\]133;[^\u0007\u001b]*(?:\u0007|\u001b\\)/gu, "");
665
867
  }
666
868
 
667
869
  function escapeTerminalControls(text: string): string {