@narumitw/pi-btw 0.58.1 → 0.60.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.
@@ -1,26 +1,27 @@
1
1
  import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  import {
3
- AssistantMessageComponent,
4
- getMarkdownTheme,
5
- type KeybindingsManager,
6
- type Theme,
7
- UserMessageComponent,
3
+ AssistantMessageComponent,
4
+ getMarkdownTheme,
5
+ type KeybindingsManager,
6
+ type MarkdownTransformer,
7
+ type Theme,
8
+ UserMessageComponent,
8
9
  } from "@earendil-works/pi-coding-agent";
9
10
  import {
10
- type Component,
11
- CURSOR_MARKER,
12
- Editor,
13
- type EditorTheme,
14
- type Focusable,
15
- Key,
16
- Loader,
17
- Markdown,
18
- matchesKey,
19
- ScrollView,
20
- type TUI,
21
- truncateToWidth,
22
- VStack,
23
- visibleWidth,
11
+ type Component,
12
+ CURSOR_MARKER,
13
+ Editor,
14
+ type EditorTheme,
15
+ type Focusable,
16
+ Key,
17
+ Loader,
18
+ Markdown,
19
+ matchesKey,
20
+ ScrollView,
21
+ type TUI,
22
+ truncateToWidth,
23
+ VStack,
24
+ visibleWidth,
24
25
  } from "@earendil-works/pi-tui";
25
26
  import type { BtwFullscreenLayoutComponent } from "./fullscreen-ui.js";
26
27
  import { BtwPasteGuard, type BtwShortcuts, getBtwShortcuts } from "./keybindings.js";
@@ -35,688 +36,636 @@ const RESERVED_APP_LINES = 3;
35
36
 
36
37
  // A temporary fit after manual scrolling must not silently resume following new output.
37
38
  class PreservingScrollView extends ScrollView {
38
- override updateLayout(
39
- contentHeight: number,
40
- viewportHeight: number,
41
- requestRender: () => void,
42
- ): void {
43
- const preserveManualPosition = !this.isFollowingEnd;
44
- super.updateLayout(contentHeight, viewportHeight, requestRender);
45
- if (preserveManualPosition && this.isFollowingEnd) {
46
- this.scrollTo(this.scrollTop, { disableFollow: true });
47
- }
48
- }
39
+ override updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void {
40
+ const preserveManualPosition = !this.isFollowingEnd;
41
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
42
+ if (preserveManualPosition && this.isFollowingEnd) {
43
+ this.scrollTo(this.scrollTop, { disableFollow: true });
44
+ }
45
+ }
49
46
  }
50
47
 
51
48
  export type TranscriptPagerAction =
52
- | { kind: "submit"; question: string }
53
- | { kind: "bringToMain"; questionDraft: string }
54
- | { kind: "close" };
49
+ | { kind: "submit"; question: string }
50
+ | { kind: "bringToMain"; questionDraft: string }
51
+ | { kind: "close" };
55
52
 
56
53
  export interface BtwThinkingControl {
57
- level: BtwThinkingLevel;
58
- levels: readonly BtwThinkingLevel[];
59
- keybindings: KeybindingsManager;
60
- onChange: (level: BtwThinkingLevel) => void;
54
+ level: BtwThinkingLevel;
55
+ levels: readonly BtwThinkingLevel[];
56
+ keybindings: KeybindingsManager;
57
+ onChange: (level: BtwThinkingLevel) => void;
61
58
  }
62
59
 
63
60
  export interface BtwAnsweringViewOptions {
64
- steering?: {
65
- questions: readonly string[];
66
- onSubmit: (question: string) => void;
67
- thinking?: BtwThinkingControl;
68
- };
61
+ markdownTransformers?: readonly MarkdownTransformer[];
62
+ steering?: {
63
+ questions: readonly string[];
64
+ onSubmit: (question: string) => void;
65
+ thinking?: BtwThinkingControl;
66
+ };
69
67
  }
70
68
 
71
69
  export class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusable {
72
- private readonly shortcuts: BtwShortcuts;
73
- private readonly pasteGuard = new BtwPasteGuard();
74
- private readonly transcriptComponents: Component[];
75
- private readonly editor: Editor;
76
- private readonly canBringToMain: boolean;
77
- private readonly scrollView: ScrollView;
78
- private readonly layoutRoot: VStack;
79
- private lastContentLineCount = 0;
80
- private warning: string | undefined;
81
- private finished = false;
82
- private isFocused = false;
83
- private thinkingLevel: BtwThinkingLevel | undefined;
84
-
85
- constructor(
86
- private readonly tui: TUI,
87
- private readonly theme: Theme,
88
- turns: readonly SideThreadTurn[],
89
- private readonly onAction: (action: TranscriptPagerAction) => void,
90
- private readonly options: {
91
- startAtBottom?: boolean;
92
- initialQuestion?: string;
93
- thinking?: BtwThinkingControl;
94
- } = {},
95
- ) {
96
- this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);
97
- this.transcriptComponents = buildTranscriptComponents(turns, this.theme);
98
- this.canBringToMain = turns.some((turn) => turn.kind === "answered");
99
- this.thinkingLevel = options.thinking?.level;
100
- const editorTheme: EditorTheme = {
101
- borderColor: (text) => this.theme.fg("accent", text),
102
- selectList: {
103
- selectedPrefix: (text) => this.theme.fg("accent", text),
104
- selectedText: (text) => this.theme.fg("accent", text),
105
- description: (text) => this.theme.fg("muted", text),
106
- scrollInfo: (text) => this.theme.fg("dim", text),
107
- noMatch: (text) => this.theme.fg("warning", text),
108
- },
109
- };
110
- this.editor = new Editor(this.tui, editorTheme);
111
- if (options.initialQuestion) this.editor.setText(options.initialQuestion);
112
- this.editor.onChange = () => {
113
- this.warning = undefined;
114
- };
115
- this.editor.onSubmit = (text) => {
116
- const question = text.trim();
117
- if (!question) {
118
- this.warning = "Question cannot be empty";
119
- return;
120
- }
121
- this.finished = true;
122
- this.onAction({ kind: "submit", question });
123
- };
124
- const transcript = this.createTranscriptComponent();
125
- this.scrollView = new PreservingScrollView(transcript, {
126
- follow: options.startAtBottom ? "end" : "none",
127
- primary: true,
128
- });
129
- this.layoutRoot = new VStack([
130
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
131
- { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
132
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
133
- { component: this.editor, basis: "auto", shrink: 1, minSize: 0 },
134
- ]);
135
- }
136
-
137
- get focused(): boolean {
138
- return this.isFocused;
139
- }
140
-
141
- set focused(value: boolean) {
142
- this.isFocused = value;
143
- this.editor.focused = value;
144
- }
145
-
146
- getFullscreenLayout(): Component {
147
- return this.layoutRoot;
148
- }
149
-
150
- render(width: number): string[] {
151
- if (width <= 0) return [];
152
- const safeWidth = Math.max(1, width);
153
- const editorLines = this.editor.render(safeWidth);
154
- const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
155
- const viewportHeight = Math.max(
156
- 0,
157
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES,
158
- );
159
- const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
160
- this.lastContentLineCount = contentLines.length;
161
- this.scrollView.updateLayout(contentLines.length, viewportHeight, () =>
162
- this.tui.requestRender(),
163
- );
164
-
165
- return fitComposerLayout(
166
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
167
- contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
168
- this.renderFooter(safeWidth),
169
- editorLines,
170
- availableRows,
171
- ).map((line) => truncateToWidth(line, safeWidth));
172
- }
173
-
174
- handleInput(data: string): void {
175
- if (this.finished) return;
176
- if (this.pasteGuard.consume(data)) {
177
- this.editor.handleInput(data);
178
- this.tui.requestRender();
179
- return;
180
- }
181
- if (this.shortcuts.matches(data, "exit")) {
182
- this.finished = true;
183
- this.onAction({ kind: "close" });
184
- return;
185
- }
186
- if (this.canBringToMain && this.shortcuts.matches(data, "bringToMain")) {
187
- this.finished = true;
188
- this.onAction({ kind: "bringToMain", questionDraft: this.editor.getExpandedText() });
189
- return;
190
- }
191
- const thinking = this.options.thinking;
192
- if (
193
- thinking &&
194
- thinking.levels.length > 1 &&
195
- this.shortcuts.matches(data, "cycleThinkingLevel")
196
- ) {
197
- const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
198
- const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
199
- if (nextLevel) {
200
- this.thinkingLevel = nextLevel;
201
- thinking.onChange(nextLevel);
202
- this.warning = undefined;
203
- this.tui.requestRender();
204
- }
205
- return;
206
- }
207
- if (matchesKey(data, Key.pageUp)) {
208
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
209
- this.tui.requestRender();
210
- return;
211
- }
212
- if (matchesKey(data, Key.pageDown)) {
213
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
214
- this.tui.requestRender();
215
- return;
216
- }
217
- this.editor.handleInput(data);
218
- if (!this.finished) this.tui.requestRender();
219
- }
220
-
221
- invalidate(): void {
222
- this.layoutRoot.invalidate();
223
- }
224
-
225
- dispose(): void {
226
- if (this.finished) return;
227
- this.finished = true;
228
- this.onAction({ kind: "close" });
229
- }
230
-
231
- private renderFooter(width: number): string {
232
- const exit = this.shortcuts.label("exit");
233
- const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
234
- const bringKey = this.shortcuts.label("bringToMain");
235
- if (this.warning) {
236
- const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} exit`;
237
- return truncateToWidth(this.theme.fg("warning", warning), width);
238
- }
239
- const scrollable = this.getMaxScrollOffset() > 0;
240
- const thinking = this.options.thinking;
241
- const cycleHint =
242
- thinking &&
243
- thinking.levels.length > 1 &&
244
- this.thinkingLevel &&
245
- this.shortcuts.keys.cycleThinkingLevel.length
246
- ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
247
- : "";
248
- const base = bring
249
- ? `btw Enter send • ${bringKey} bring to main • ${exit} exit`
250
- : `btw • Enter send • ${exit} exit`;
251
- const fullBase = `${base}${cycleHint}`;
252
- const fallbackBase = `btw • Enter • ${exit}`;
253
- const compactBase = bring ? `btw Enter ${bringKey} • ${exit}` : fallbackBase;
254
- const compactWithThinking = `${compactBase}${cycleHint}`;
255
- let hints =
256
- visibleWidth(fullBase) <= width
257
- ? fullBase
258
- : visibleWidth(compactWithThinking) <= width
259
- ? compactWithThinking
260
- : visibleWidth(compactBase) <= width
261
- ? compactBase
262
- : fallbackBase;
263
- if (scrollable) {
264
- const history = ` • ${this.scrollView.scrollTop > 0 ? "↑ older" : "↓ newer"} PgUp/PgDn history`;
265
- const compactHistory = " • PgUp/PgDn";
266
- const compactScrollable = bring
267
- ? `Enter • ${bringKey} • ${exit} • PgUp/PgDn`
268
- : `${fallbackBase}${compactHistory}`;
269
- if (visibleWidth(`${hints}${history}`) <= width) {
270
- hints += history;
271
- } else if (visibleWidth(`${compactBase}${history}`) <= width) {
272
- hints = `${compactBase}${history}`;
273
- } else if (visibleWidth(`${hints}${compactHistory}`) <= width) {
274
- hints += compactHistory;
275
- } else if (visibleWidth(`${compactBase}${compactHistory}`) <= width) {
276
- hints = `${compactBase}${compactHistory}`;
277
- } else if (visibleWidth(compactScrollable) <= width) {
278
- hints = compactScrollable;
279
- }
280
- }
281
- return truncateToWidth(this.theme.fg("muted", hints), width);
282
- }
283
-
284
- private createHeaderComponent(): Component {
285
- return {
286
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
287
- invalidate() {},
288
- };
289
- }
290
-
291
- private createTranscriptComponent(): Component {
292
- return {
293
- render: (width) => {
294
- const lines = renderTranscriptLines(this.transcriptComponents, width);
295
- this.lastContentLineCount = lines.length;
296
- return lines;
297
- },
298
- invalidate: () => {
299
- for (const component of this.transcriptComponents) component.invalidate();
300
- },
301
- };
302
- }
303
-
304
- private createFooterComponent(): Component {
305
- return {
306
- render: (width) => [this.renderFooter(width)],
307
- invalidate() {},
308
- };
309
- }
310
-
311
- private getMaxScrollOffset(): number {
312
- return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
313
- }
70
+ private readonly shortcuts: BtwShortcuts;
71
+ private readonly pasteGuard = new BtwPasteGuard();
72
+ private readonly transcriptComponents: Component[];
73
+ private readonly editor: Editor;
74
+ private readonly canBringToMain: boolean;
75
+ private readonly scrollView: ScrollView;
76
+ private readonly layoutRoot: VStack;
77
+ private lastContentLineCount = 0;
78
+ private warning: string | undefined;
79
+ private finished = false;
80
+ private isFocused = false;
81
+ private thinkingLevel: BtwThinkingLevel | undefined;
82
+
83
+ constructor(
84
+ private readonly tui: TUI,
85
+ private readonly theme: Theme,
86
+ turns: readonly SideThreadTurn[],
87
+ private readonly onAction: (action: TranscriptPagerAction) => void,
88
+ private readonly options: {
89
+ startAtBottom?: boolean;
90
+ initialQuestion?: string;
91
+ markdownTransformers?: readonly MarkdownTransformer[];
92
+ thinking?: BtwThinkingControl;
93
+ } = {},
94
+ ) {
95
+ this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);
96
+ this.transcriptComponents = buildTranscriptComponents(turns, this.theme, undefined, options.markdownTransformers);
97
+ this.canBringToMain = turns.some((turn) => turn.kind === "answered");
98
+ this.thinkingLevel = options.thinking?.level;
99
+ const editorTheme: EditorTheme = {
100
+ borderColor: (text) => this.theme.fg("accent", text),
101
+ selectList: {
102
+ selectedPrefix: (text) => this.theme.fg("accent", text),
103
+ selectedText: (text) => this.theme.fg("accent", text),
104
+ description: (text) => this.theme.fg("muted", text),
105
+ scrollInfo: (text) => this.theme.fg("dim", text),
106
+ noMatch: (text) => this.theme.fg("warning", text),
107
+ },
108
+ };
109
+ this.editor = new Editor(this.tui, editorTheme);
110
+ if (options.initialQuestion) this.editor.setText(options.initialQuestion);
111
+ this.editor.onChange = () => {
112
+ this.warning = undefined;
113
+ };
114
+ this.editor.onSubmit = (text) => {
115
+ const question = text.trim();
116
+ if (!question) {
117
+ this.warning = "Question cannot be empty";
118
+ return;
119
+ }
120
+ this.finished = true;
121
+ this.onAction({ kind: "submit", question });
122
+ };
123
+ const transcript = this.createTranscriptComponent();
124
+ this.scrollView = new PreservingScrollView(transcript, {
125
+ follow: options.startAtBottom ? "end" : "none",
126
+ primary: true,
127
+ });
128
+ this.layoutRoot = new VStack([
129
+ { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
130
+ { 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 },
133
+ ]);
134
+ }
135
+
136
+ get focused(): boolean {
137
+ return this.isFocused;
138
+ }
139
+
140
+ set focused(value: boolean) {
141
+ this.isFocused = value;
142
+ this.editor.focused = value;
143
+ }
144
+
145
+ getFullscreenLayout(): Component {
146
+ return this.layoutRoot;
147
+ }
148
+
149
+ render(width: number): string[] {
150
+ if (width <= 0) return [];
151
+ const safeWidth = Math.max(1, width);
152
+ const editorLines = this.editor.render(safeWidth);
153
+ const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
154
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
155
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
156
+ this.lastContentLineCount = contentLines.length;
157
+ this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
158
+
159
+ return fitComposerLayout(
160
+ renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
161
+ contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
162
+ this.renderFooter(safeWidth),
163
+ editorLines,
164
+ availableRows,
165
+ ).map((line) => truncateToWidth(line, safeWidth));
166
+ }
167
+
168
+ handleInput(data: string): void {
169
+ if (this.finished) return;
170
+ if (this.pasteGuard.consume(data)) {
171
+ this.editor.handleInput(data);
172
+ this.tui.requestRender();
173
+ return;
174
+ }
175
+ if (this.shortcuts.matches(data, "exit")) {
176
+ this.finished = true;
177
+ this.onAction({ kind: "close" });
178
+ return;
179
+ }
180
+ if (this.canBringToMain && this.shortcuts.matches(data, "bringToMain")) {
181
+ this.finished = true;
182
+ this.onAction({ kind: "bringToMain", questionDraft: this.editor.getExpandedText() });
183
+ return;
184
+ }
185
+ const thinking = this.options.thinking;
186
+ if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, "cycleThinkingLevel")) {
187
+ const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
188
+ const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
189
+ if (nextLevel) {
190
+ this.thinkingLevel = nextLevel;
191
+ thinking.onChange(nextLevel);
192
+ this.warning = undefined;
193
+ this.tui.requestRender();
194
+ }
195
+ return;
196
+ }
197
+ if (matchesKey(data, Key.pageUp)) {
198
+ this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
199
+ this.tui.requestRender();
200
+ return;
201
+ }
202
+ if (matchesKey(data, Key.pageDown)) {
203
+ this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
204
+ this.tui.requestRender();
205
+ return;
206
+ }
207
+ this.editor.handleInput(data);
208
+ if (!this.finished) this.tui.requestRender();
209
+ }
210
+
211
+ invalidate(): void {
212
+ this.layoutRoot.invalidate();
213
+ }
214
+
215
+ dispose(): void {
216
+ if (this.finished) return;
217
+ this.finished = true;
218
+ this.onAction({ kind: "close" });
219
+ }
220
+
221
+ private renderFooter(width: number): string {
222
+ const exit = this.shortcuts.label("exit");
223
+ const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
224
+ const bringKey = this.shortcuts.label("bringToMain");
225
+ if (this.warning) {
226
+ const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} exit`;
227
+ return truncateToWidth(this.theme.fg("warning", warning), width);
228
+ }
229
+ const scrollable = this.getMaxScrollOffset() > 0;
230
+ const thinking = this.options.thinking;
231
+ const cycleHint =
232
+ thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length
233
+ ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
234
+ : "";
235
+ const base = bring
236
+ ? `btw • Enter send • ${bringKey} bring to main • ${exit} exit`
237
+ : `btw Enter send • ${exit} exit`;
238
+ const fullBase = `${base}${cycleHint}`;
239
+ const fallbackBase = `btw • Enter • ${exit}`;
240
+ const compactBase = bring ? `btw • Enter • ${bringKey} • ${exit}` : fallbackBase;
241
+ const compactWithThinking = `${compactBase}${cycleHint}`;
242
+ let hints =
243
+ visibleWidth(fullBase) <= width
244
+ ? fullBase
245
+ : visibleWidth(compactWithThinking) <= width
246
+ ? compactWithThinking
247
+ : visibleWidth(compactBase) <= width
248
+ ? compactBase
249
+ : fallbackBase;
250
+ if (scrollable) {
251
+ const history = ` • ${this.scrollView.scrollTop > 0 ? "↑ older" : "↓ newer"} • PgUp/PgDn history`;
252
+ const compactHistory = " • PgUp/PgDn";
253
+ const compactScrollable = bring
254
+ ? `Enter • ${bringKey} • ${exit} • PgUp/PgDn`
255
+ : `${fallbackBase}${compactHistory}`;
256
+ if (visibleWidth(`${hints}${history}`) <= width) {
257
+ hints += history;
258
+ } else if (visibleWidth(`${compactBase}${history}`) <= width) {
259
+ hints = `${compactBase}${history}`;
260
+ } else if (visibleWidth(`${hints}${compactHistory}`) <= width) {
261
+ hints += compactHistory;
262
+ } else if (visibleWidth(`${compactBase}${compactHistory}`) <= width) {
263
+ hints = `${compactBase}${compactHistory}`;
264
+ } else if (visibleWidth(compactScrollable) <= width) {
265
+ hints = compactScrollable;
266
+ }
267
+ }
268
+ return truncateToWidth(this.theme.fg("muted", hints), width);
269
+ }
270
+
271
+ private createHeaderComponent(): Component {
272
+ return {
273
+ render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
274
+ invalidate() {},
275
+ };
276
+ }
277
+
278
+ private createTranscriptComponent(): Component {
279
+ return {
280
+ render: (width) => {
281
+ const lines = renderTranscriptLines(this.transcriptComponents, width);
282
+ this.lastContentLineCount = lines.length;
283
+ return lines;
284
+ },
285
+ invalidate: () => {
286
+ for (const component of this.transcriptComponents) component.invalidate();
287
+ },
288
+ };
289
+ }
290
+
291
+ private createFooterComponent(): Component {
292
+ return {
293
+ render: (width) => [this.renderFooter(width)],
294
+ invalidate() {},
295
+ };
296
+ }
297
+
298
+ private getMaxScrollOffset(): number {
299
+ return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
300
+ }
314
301
  }
315
302
 
316
303
  export class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable {
317
- private readonly shortcuts: BtwShortcuts;
318
- private readonly pasteGuard = new BtwPasteGuard();
319
- private readonly transcriptComponents: Component[];
320
- private readonly loader: Loader;
321
- private readonly editor: Editor | undefined;
322
- private readonly controller = new AbortController();
323
- private readonly scrollView: ScrollView;
324
- private readonly layoutRoot: VStack;
325
- private lastContentLineCount = 0;
326
- private warning: string | undefined;
327
- private finished = false;
328
- private isFocused = false;
329
- private thinkingLevel: BtwThinkingLevel | undefined;
330
-
331
- constructor(
332
- private readonly tui: TUI,
333
- private readonly theme: Theme,
334
- turns: readonly SideThreadTurn[],
335
- pendingQuestion: string,
336
- private readonly onCancel: () => void,
337
- thinkingLevel?: BtwThinkingLevel,
338
- private readonly options: BtwAnsweringViewOptions = {},
339
- ) {
340
- this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);
341
- this.transcriptComponents = buildTranscriptComponents(turns, this.theme, pendingQuestion);
342
- this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
343
- this.loader = new Loader(
344
- this.tui,
345
- (text) => this.theme.fg("accent", text),
346
- (text) => this.theme.fg("muted", text),
347
- "Answering…",
348
- );
349
- if (options.steering) {
350
- const editorTheme: EditorTheme = {
351
- borderColor: (text) => this.theme.fg("accent", text),
352
- selectList: {
353
- selectedPrefix: (text) => this.theme.fg("accent", text),
354
- selectedText: (text) => this.theme.fg("accent", text),
355
- description: (text) => this.theme.fg("muted", text),
356
- scrollInfo: (text) => this.theme.fg("dim", text),
357
- noMatch: (text) => this.theme.fg("warning", text),
358
- },
359
- };
360
- this.editor = new Editor(this.tui, editorTheme);
361
- this.editor.onChange = () => {
362
- this.warning = undefined;
363
- };
364
- this.editor.onSubmit = (text) => {
365
- const question = text.trim();
366
- if (!question) {
367
- this.warning = "Question cannot be empty";
368
- return;
369
- }
370
- options.steering?.onSubmit(question);
371
- this.warning = undefined;
372
- };
373
- }
374
- const transcript = this.createTranscriptComponent();
375
- this.scrollView = new PreservingScrollView(transcript, { follow: "end", primary: true });
376
- this.layoutRoot = new VStack([
377
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
378
- { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
379
- {
380
- component: this.createSteeringComponent(),
381
- basis: "auto",
382
- shrink: 1,
383
- minSize: 0,
384
- maxSize: MAX_STEERING_DISPLAY_LINES,
385
- },
386
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
387
- ...(this.editor
388
- ? [{ component: this.editor, basis: "auto" as const, shrink: 1, minSize: 0 }]
389
- : []),
390
- ]);
391
- }
392
-
393
- get focused(): boolean {
394
- return this.isFocused;
395
- }
396
-
397
- set focused(value: boolean) {
398
- this.isFocused = value;
399
- if (this.editor) this.editor.focused = value;
400
- }
401
-
402
- get signal(): AbortSignal {
403
- return this.controller.signal;
404
- }
405
-
406
- getFullscreenLayout(): Component {
407
- return this.layoutRoot;
408
- }
409
-
410
- render(width: number): string[] {
411
- if (width <= 0) return [];
412
- const safeWidth = Math.max(1, width);
413
- const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
414
- const editorLines = this.editor?.render(safeWidth) ?? [];
415
- const steeringCapacity = Math.max(
416
- 0,
417
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES,
418
- );
419
- const steeringLines = renderSteeringLines(
420
- this.options.steering?.questions ?? [],
421
- safeWidth,
422
- this.theme,
423
- Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity),
424
- );
425
- const viewportHeight = Math.max(
426
- 0,
427
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length,
428
- );
429
- const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
430
- this.lastContentLineCount = contentLines.length;
431
- this.scrollView.updateLayout(contentLines.length, viewportHeight, () =>
432
- this.tui.requestRender(),
433
- );
434
-
435
- return fitComposerLayout(
436
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
437
- contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
438
- this.renderFooter(safeWidth),
439
- editorLines,
440
- availableRows,
441
- steeringLines,
442
- ).map((line) => truncateToWidth(line, safeWidth));
443
- }
444
-
445
- handleInput(data: string): void {
446
- if (this.finished) return;
447
- if (this.pasteGuard.consume(data)) {
448
- this.editor?.handleInput(data);
449
- this.tui.requestRender();
450
- return;
451
- }
452
- if (this.shortcuts.matches(data, "exit")) {
453
- this.finished = true;
454
- this.loader.stop();
455
- this.controller.abort();
456
- this.onCancel();
457
- return;
458
- }
459
- const thinking = this.options.steering?.thinking;
460
- if (
461
- thinking &&
462
- thinking.levels.length > 1 &&
463
- this.shortcuts.matches(data, "cycleThinkingLevel")
464
- ) {
465
- const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
466
- const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
467
- if (nextLevel) {
468
- this.thinkingLevel = nextLevel;
469
- thinking.onChange(nextLevel);
470
- this.warning = undefined;
471
- this.tui.requestRender();
472
- }
473
- return;
474
- }
475
- if (matchesKey(data, Key.pageUp)) {
476
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
477
- this.tui.requestRender();
478
- return;
479
- }
480
- if (matchesKey(data, Key.pageDown)) {
481
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
482
- this.tui.requestRender();
483
- return;
484
- }
485
- this.editor?.handleInput(data);
486
- this.tui.requestRender();
487
- }
488
-
489
- invalidate(): void {
490
- this.layoutRoot.invalidate();
491
- }
492
-
493
- finish(): void {
494
- this.finished = true;
495
- this.loader.stop();
496
- }
497
-
498
- dispose(): void {
499
- if (this.finished) {
500
- this.loader.stop();
501
- this.controller.abort();
502
- return;
503
- }
504
- this.finished = true;
505
- this.loader.stop();
506
- this.controller.abort();
507
- this.onCancel();
508
- }
509
-
510
- private renderFooter(width: number): string {
511
- const exit = this.shortcuts.label("exit");
512
- if (this.warning) {
513
- const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} cancel`;
514
- return truncateToWidth(this.theme.fg("warning", warning), width);
515
- }
516
- const baseHint = this.editor ? `Enter steer ${exit} cancel` : `${exit} cancel`;
517
- const thinking = this.options.steering?.thinking;
518
- const cycleHint =
519
- thinking &&
520
- thinking.levels.length > 1 &&
521
- this.thinkingLevel &&
522
- this.shortcuts.keys.cycleThinkingLevel.length
523
- ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
524
- : "";
525
- const scrollHint = this.getMaxScrollOffset() > 0 ? " • PgUp/PgDn history" : "";
526
- const hints = `${baseHint}${cycleHint}${scrollHint}`;
527
- const compactHints = this.editor ? `Enter • ${exit}` : exit;
528
- const selectedHints = visibleWidth(hints) <= width ? hints : compactHints;
529
- const loaderWidth = Math.max(1, width - visibleWidth(selectedHints) - 3);
530
- const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering…";
531
- return truncateToWidth(`${loaderLine} • ${this.theme.fg("muted", selectedHints)}`, width);
532
- }
533
-
534
- private createHeaderComponent(): Component {
535
- return {
536
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
537
- invalidate() {},
538
- };
539
- }
540
-
541
- private createTranscriptComponent(): Component {
542
- return {
543
- render: (width) => {
544
- const lines = renderTranscriptLines(this.transcriptComponents, width);
545
- this.lastContentLineCount = lines.length;
546
- return lines;
547
- },
548
- invalidate: () => {
549
- for (const component of this.transcriptComponents) component.invalidate();
550
- },
551
- };
552
- }
553
-
554
- private createSteeringComponent(): Component {
555
- return {
556
- render: (width) =>
557
- renderSteeringLines(
558
- this.options.steering?.questions ?? [],
559
- width,
560
- this.theme,
561
- MAX_STEERING_DISPLAY_LINES,
562
- ),
563
- invalidate() {},
564
- };
565
- }
566
-
567
- private createFooterComponent(): Component {
568
- return {
569
- render: (width) => [this.renderFooter(width)],
570
- invalidate: () => this.loader.invalidate(),
571
- };
572
- }
573
-
574
- private getMaxScrollOffset(): number {
575
- return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
576
- }
304
+ private readonly shortcuts: BtwShortcuts;
305
+ private readonly pasteGuard = new BtwPasteGuard();
306
+ private readonly transcriptComponents: Component[];
307
+ private readonly loader: Loader;
308
+ private readonly editor: Editor | undefined;
309
+ private readonly controller = new AbortController();
310
+ private readonly scrollView: ScrollView;
311
+ private readonly layoutRoot: VStack;
312
+ private lastContentLineCount = 0;
313
+ private warning: string | undefined;
314
+ private finished = false;
315
+ private isFocused = false;
316
+ private thinkingLevel: BtwThinkingLevel | undefined;
317
+
318
+ constructor(
319
+ private readonly tui: TUI,
320
+ private readonly theme: Theme,
321
+ turns: readonly SideThreadTurn[],
322
+ pendingQuestion: string,
323
+ private readonly onCancel: () => void,
324
+ thinkingLevel?: BtwThinkingLevel,
325
+ private readonly options: BtwAnsweringViewOptions = {},
326
+ ) {
327
+ this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);
328
+ this.transcriptComponents = buildTranscriptComponents(
329
+ turns,
330
+ this.theme,
331
+ pendingQuestion,
332
+ options.markdownTransformers,
333
+ );
334
+ this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
335
+ this.loader = new Loader(
336
+ this.tui,
337
+ (text) => this.theme.fg("accent", text),
338
+ (text) => this.theme.fg("muted", text),
339
+ "Answering…",
340
+ );
341
+ if (options.steering) {
342
+ const editorTheme: EditorTheme = {
343
+ borderColor: (text) => this.theme.fg("accent", text),
344
+ selectList: {
345
+ selectedPrefix: (text) => this.theme.fg("accent", text),
346
+ selectedText: (text) => this.theme.fg("accent", text),
347
+ description: (text) => this.theme.fg("muted", text),
348
+ scrollInfo: (text) => this.theme.fg("dim", text),
349
+ noMatch: (text) => this.theme.fg("warning", text),
350
+ },
351
+ };
352
+ this.editor = new Editor(this.tui, editorTheme);
353
+ this.editor.onChange = () => {
354
+ this.warning = undefined;
355
+ };
356
+ this.editor.onSubmit = (text) => {
357
+ const question = text.trim();
358
+ if (!question) {
359
+ this.warning = "Question cannot be empty";
360
+ return;
361
+ }
362
+ options.steering?.onSubmit(question);
363
+ this.warning = undefined;
364
+ };
365
+ }
366
+ const transcript = this.createTranscriptComponent();
367
+ this.scrollView = new PreservingScrollView(transcript, { follow: "end", primary: true });
368
+ this.layoutRoot = new VStack([
369
+ { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
370
+ { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
371
+ {
372
+ component: this.createSteeringComponent(),
373
+ basis: "auto",
374
+ shrink: 1,
375
+ minSize: 0,
376
+ maxSize: MAX_STEERING_DISPLAY_LINES,
377
+ },
378
+ { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
379
+ ...(this.editor ? [{ component: this.editor, basis: "auto" as const, shrink: 1, minSize: 0 }] : []),
380
+ ]);
381
+ }
382
+
383
+ get focused(): boolean {
384
+ return this.isFocused;
385
+ }
386
+
387
+ set focused(value: boolean) {
388
+ this.isFocused = value;
389
+ if (this.editor) this.editor.focused = value;
390
+ }
391
+
392
+ get signal(): AbortSignal {
393
+ return this.controller.signal;
394
+ }
395
+
396
+ getFullscreenLayout(): Component {
397
+ return this.layoutRoot;
398
+ }
399
+
400
+ render(width: number): string[] {
401
+ if (width <= 0) return [];
402
+ const safeWidth = Math.max(1, width);
403
+ const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
404
+ const editorLines = this.editor?.render(safeWidth) ?? [];
405
+ const steeringCapacity = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
406
+ const steeringLines = renderSteeringLines(
407
+ this.options.steering?.questions ?? [],
408
+ safeWidth,
409
+ this.theme,
410
+ Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity),
411
+ );
412
+ const viewportHeight = Math.max(
413
+ 0,
414
+ availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length,
415
+ );
416
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
417
+ this.lastContentLineCount = contentLines.length;
418
+ this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
419
+
420
+ return fitComposerLayout(
421
+ renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
422
+ contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
423
+ this.renderFooter(safeWidth),
424
+ editorLines,
425
+ availableRows,
426
+ steeringLines,
427
+ ).map((line) => truncateToWidth(line, safeWidth));
428
+ }
429
+
430
+ handleInput(data: string): void {
431
+ if (this.finished) return;
432
+ if (this.pasteGuard.consume(data)) {
433
+ this.editor?.handleInput(data);
434
+ this.tui.requestRender();
435
+ return;
436
+ }
437
+ if (this.shortcuts.matches(data, "exit")) {
438
+ this.finished = true;
439
+ this.loader.stop();
440
+ this.controller.abort();
441
+ this.onCancel();
442
+ return;
443
+ }
444
+ const thinking = this.options.steering?.thinking;
445
+ if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, "cycleThinkingLevel")) {
446
+ const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
447
+ const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
448
+ if (nextLevel) {
449
+ this.thinkingLevel = nextLevel;
450
+ thinking.onChange(nextLevel);
451
+ this.warning = undefined;
452
+ this.tui.requestRender();
453
+ }
454
+ return;
455
+ }
456
+ if (matchesKey(data, Key.pageUp)) {
457
+ this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
458
+ this.tui.requestRender();
459
+ return;
460
+ }
461
+ if (matchesKey(data, Key.pageDown)) {
462
+ this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
463
+ this.tui.requestRender();
464
+ return;
465
+ }
466
+ this.editor?.handleInput(data);
467
+ this.tui.requestRender();
468
+ }
469
+
470
+ invalidate(): void {
471
+ this.layoutRoot.invalidate();
472
+ }
473
+
474
+ finish(): void {
475
+ this.finished = true;
476
+ this.loader.stop();
477
+ }
478
+
479
+ dispose(): void {
480
+ if (this.finished) {
481
+ this.loader.stop();
482
+ this.controller.abort();
483
+ return;
484
+ }
485
+ this.finished = true;
486
+ this.loader.stop();
487
+ this.controller.abort();
488
+ this.onCancel();
489
+ }
490
+
491
+ private renderFooter(width: number): string {
492
+ const exit = this.shortcuts.label("exit");
493
+ if (this.warning) {
494
+ const warning = width < 32 ? `Empty • ${exit}` : `${this.warning} • ${exit} cancel`;
495
+ return truncateToWidth(this.theme.fg("warning", warning), width);
496
+ }
497
+ const baseHint = this.editor ? `Enter steer • ${exit} cancel` : `${exit} cancel`;
498
+ const thinking = this.options.steering?.thinking;
499
+ const cycleHint =
500
+ thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length
501
+ ? ` • thinking ${this.thinkingLevel} • ${this.shortcuts.label("cycleThinkingLevel")} cycle`
502
+ : "";
503
+ const scrollHint = this.getMaxScrollOffset() > 0 ? "PgUp/PgDn history" : "";
504
+ const hints = `${baseHint}${cycleHint}${scrollHint}`;
505
+ const compactHints = this.editor ? `Enter • ${exit}` : exit;
506
+ const selectedHints = visibleWidth(hints) <= width ? hints : compactHints;
507
+ const loaderWidth = Math.max(1, width - visibleWidth(selectedHints) - 3);
508
+ const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering…";
509
+ return truncateToWidth(`${loaderLine} • ${this.theme.fg("muted", selectedHints)}`, width);
510
+ }
511
+
512
+ private createHeaderComponent(): Component {
513
+ return {
514
+ render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
515
+ invalidate() {},
516
+ };
517
+ }
518
+
519
+ private createTranscriptComponent(): Component {
520
+ return {
521
+ render: (width) => {
522
+ const lines = renderTranscriptLines(this.transcriptComponents, width);
523
+ this.lastContentLineCount = lines.length;
524
+ return lines;
525
+ },
526
+ invalidate: () => {
527
+ for (const component of this.transcriptComponents) component.invalidate();
528
+ },
529
+ };
530
+ }
531
+
532
+ private createSteeringComponent(): Component {
533
+ return {
534
+ render: (width) =>
535
+ renderSteeringLines(this.options.steering?.questions ?? [], width, this.theme, MAX_STEERING_DISPLAY_LINES),
536
+ invalidate() {},
537
+ };
538
+ }
539
+
540
+ private createFooterComponent(): Component {
541
+ return {
542
+ render: (width) => [this.renderFooter(width)],
543
+ invalidate: () => this.loader.invalidate(),
544
+ };
545
+ }
546
+
547
+ private getMaxScrollOffset(): number {
548
+ return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
549
+ }
577
550
  }
578
551
 
579
552
  export function formatSideTranscript(turns: readonly SideThreadTurn[]): string {
580
- return turns
581
- .map((turn) => {
582
- const question = escapeTerminalControls(turn.question);
583
- const rawAnswer = escapeTerminalControls(turn.answer);
584
- const answer = turn.kind === "error" ? `Error: ${rawAnswer}` : rawAnswer;
585
- return `${question}\n\n${answer}`;
586
- })
587
- .join("\n\n");
553
+ return turns
554
+ .map((turn) => {
555
+ const question = escapeTerminalControls(turn.question);
556
+ const rawAnswer = escapeTerminalControls(turn.answer);
557
+ const answer = turn.kind === "error" ? `Error: ${rawAnswer}` : rawAnswer;
558
+ return `${question}\n\n${answer}`;
559
+ })
560
+ .join("\n\n");
588
561
  }
589
562
 
590
563
  function buildTranscriptComponents(
591
- turns: readonly SideThreadTurn[],
592
- theme: Theme,
593
- pendingQuestion?: string,
564
+ turns: readonly SideThreadTurn[],
565
+ theme: Theme,
566
+ pendingQuestion?: string,
567
+ markdownTransformers: readonly MarkdownTransformer[] = [],
594
568
  ): Component[] {
595
- const components = turns.flatMap((turn): Component[] => {
596
- const question = new UserMessageComponent(
597
- escapeTerminalControls(turn.question),
598
- getMarkdownTheme(),
599
- 1,
600
- );
601
- if (turn.kind === "error") {
602
- const error = new Markdown(
603
- `Error: ${escapeTerminalControls(turn.answer)}`,
604
- 1,
605
- 1,
606
- getMarkdownTheme(),
607
- { color: (text) => theme.fg("error", text) },
608
- );
609
- return [question, error];
610
- }
611
- const response: AssistantMessage = {
612
- ...turn.response,
613
- content: [{ type: "text", text: escapeTerminalControls(turn.answer) }],
614
- stopReason: "stop",
615
- errorMessage: undefined,
616
- };
617
- return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1)];
618
- });
619
- if (pendingQuestion) {
620
- components.push(
621
- new UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1),
622
- );
623
- }
624
- return components;
569
+ const components = turns.flatMap((turn): Component[] => {
570
+ const question = new UserMessageComponent(
571
+ escapeTerminalControls(turn.question),
572
+ getMarkdownTheme(),
573
+ 1,
574
+ markdownTransformers,
575
+ );
576
+ if (turn.kind === "error") {
577
+ const error = new Markdown(`Error: ${escapeTerminalControls(turn.answer)}`, 1, 1, getMarkdownTheme(), {
578
+ color: (text) => theme.fg("error", text),
579
+ });
580
+ return [question, error];
581
+ }
582
+ const response: AssistantMessage = {
583
+ ...turn.response,
584
+ content: [{ type: "text", text: escapeTerminalControls(turn.answer) }],
585
+ stopReason: "stop",
586
+ errorMessage: undefined,
587
+ };
588
+ return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)];
589
+ });
590
+ if (pendingQuestion) {
591
+ components.push(
592
+ new UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers),
593
+ );
594
+ }
595
+ return components;
625
596
  }
626
597
 
627
598
  function renderTranscriptLines(components: readonly Component[], width: number): string[] {
628
- return components
629
- .flatMap((component) => component.render(width))
630
- .map(stripShellIntegrationMarkers);
599
+ return components.flatMap((component) => component.render(width)).map(stripShellIntegrationMarkers);
631
600
  }
632
601
 
633
- function renderSideThreadHeader(
634
- width: number,
635
- theme: Theme,
636
- thinkingLevel?: BtwThinkingLevel,
637
- ): string {
638
- const thinking = thinkingLevel ? ` · thinking ${thinkingLevel}` : "";
639
- const title = truncateToWidth(`─ btw · side thread${thinking} `, width);
640
- const ruleWidth = Math.max(0, width - visibleWidth(title));
641
- return theme.fg("muted", `${title}${"─".repeat(ruleWidth)}`);
602
+ function renderSideThreadHeader(width: number, theme: Theme, thinkingLevel?: BtwThinkingLevel): string {
603
+ const thinking = thinkingLevel ? ` · thinking ${thinkingLevel}` : "";
604
+ const title = truncateToWidth(`─ btw · side thread${thinking} `, width);
605
+ const ruleWidth = Math.max(0, width - visibleWidth(title));
606
+ return theme.fg("muted", `${title}${"─".repeat(ruleWidth)}`);
642
607
  }
643
608
 
644
609
  function fitComposerLayout(
645
- header: string,
646
- contentLines: string[],
647
- footer: string,
648
- editorLines: string[],
649
- availableRows: number,
650
- statusLines: string[] = [],
610
+ header: string,
611
+ contentLines: string[],
612
+ footer: string,
613
+ editorLines: string[],
614
+ availableRows: number,
615
+ statusLines: string[] = [],
651
616
  ): string[] {
652
- const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];
653
- if (lines.length <= availableRows) return lines;
654
- if (availableRows <= 1) return [header];
655
- const editorBudget = Math.max(0, availableRows - 2);
656
- return [header, footer, ...fitEditorLines(editorLines, editorBudget)];
617
+ const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];
618
+ if (lines.length <= availableRows) return lines;
619
+ if (availableRows <= 1) return [header];
620
+ const editorBudget = Math.max(0, availableRows - 2);
621
+ return [header, footer, ...fitEditorLines(editorLines, editorBudget)];
657
622
  }
658
623
 
659
624
  function fitEditorLines(editorLines: string[], budget: number): string[] {
660
- if (budget <= 0) return [];
661
- if (editorLines.length <= budget) return editorLines;
662
- const cursorIndex = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));
663
- if (cursorIndex < 0) return editorLines.slice(-budget);
664
- const start = Math.min(cursorIndex, editorLines.length - budget);
665
- return editorLines.slice(start, start + budget);
625
+ if (budget <= 0) return [];
626
+ if (editorLines.length <= budget) return editorLines;
627
+ const cursorIndex = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));
628
+ if (cursorIndex < 0) return editorLines.slice(-budget);
629
+ const start = Math.min(cursorIndex, editorLines.length - budget);
630
+ return editorLines.slice(start, start + budget);
666
631
  }
667
632
 
668
- function renderSteeringLines(
669
- questions: readonly string[],
670
- width: number,
671
- theme: Theme,
672
- maxLines: number,
673
- ): string[] {
674
- if (questions.length === 0 || maxLines <= 0) return [];
675
- const formatQuestion = (question: string) =>
676
- sanitizeSingleLine(question) || "(non-printing message)";
677
- if (maxLines === 1 && questions.length > 1) {
678
- return [
679
- truncateToWidth(
680
- theme.fg(
681
- "dim",
682
- `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`,
683
- ),
684
- width,
685
- ),
686
- ];
687
- }
688
- const hasOverflow = questions.length > maxLines;
689
- const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
690
- const lines = questions
691
- .slice(0, questionLimit)
692
- .map((question) =>
693
- truncateToWidth(theme.fg("dim", `Steering: ${formatQuestion(question)}`), width),
694
- );
695
- if (hasOverflow) {
696
- lines.push(
697
- truncateToWidth(
698
- theme.fg("dim", `Steering: … +${questions.length - questionLimit} more`),
699
- width,
700
- ),
701
- );
702
- }
703
- return lines;
633
+ function renderSteeringLines(questions: readonly string[], width: number, theme: Theme, maxLines: number): string[] {
634
+ if (questions.length === 0 || maxLines <= 0) return [];
635
+ const formatQuestion = (question: string) => sanitizeSingleLine(question) || "(non-printing message)";
636
+ if (maxLines === 1 && questions.length > 1) {
637
+ return [
638
+ truncateToWidth(
639
+ theme.fg("dim", `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
640
+ width,
641
+ ),
642
+ ];
643
+ }
644
+ const hasOverflow = questions.length > maxLines;
645
+ const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
646
+ const lines = questions
647
+ .slice(0, questionLimit)
648
+ .map((question) => truncateToWidth(theme.fg("dim", `Steering: ${formatQuestion(question)}`), width));
649
+ if (hasOverflow) {
650
+ lines.push(truncateToWidth(theme.fg("dim", `Steering: … +${questions.length - questionLimit} more`), width));
651
+ }
652
+ return lines;
704
653
  }
705
654
 
706
655
  function stripShellIntegrationMarkers(line: string): string {
707
- return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, ""), line);
656
+ return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, ""), line);
708
657
  }
709
658
 
710
659
  function escapeTerminalControls(text: string): string {
711
- return [...text]
712
- .map((character) => {
713
- if (character === "\n") return character;
714
- if (character === "\t") return " ";
715
- const code = character.charCodeAt(0);
716
- if (code <= 31 || (code >= 127 && code <= 159)) {
717
- return `\\x${code.toString(16).padStart(2, "0")}`;
718
- }
719
- return character;
720
- })
721
- .join("");
660
+ return [...text]
661
+ .map((character) => {
662
+ if (character === "\n") return character;
663
+ if (character === "\t") return " ";
664
+ const code = character.charCodeAt(0);
665
+ if (code <= 31 || (code >= 127 && code <= 159)) {
666
+ return `\\x${code.toString(16).padStart(2, "0")}`;
667
+ }
668
+ return character;
669
+ })
670
+ .join("");
722
671
  }