@narumitw/pi-starship 0.63.0 → 0.64.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,40 +1,31 @@
1
+ import { stripVTControlCharacters } from "node:util";
1
2
  import type { Agent, AgentMessage } from "@earendil-works/pi-agent-core";
2
3
  import type { AssistantMessage } from "@earendil-works/pi-ai";
3
- import {
4
- AssistantMessageComponent,
5
- createEditToolDefinition,
6
- createReadToolDefinition,
7
- createWriteToolDefinition,
8
- ToolExecutionComponent,
9
- UserMessageComponent,
10
- } from "@earendil-works/pi-coding-agent";
11
- import type { Component, TUI } from "@earendil-works/pi-tui";
4
+ import { AssistantMessageComponent, UserMessageComponent } from "@earendil-works/pi-coding-agent";
5
+ import type { Component, TUI, TuiMouseEvent } from "@earendil-works/pi-tui";
12
6
  import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
13
7
 
14
- /** Display-only copies keep terminal controls out of native renderers without changing agent history. */
15
- function displayValue<T>(value: T): T {
16
- if (typeof value === "string") return sanitizeTerminalDocument(value) as T;
17
- if (Array.isArray(value)) return value.map(displayValue) as T;
18
- if (value && typeof value === "object") {
19
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, displayValue(item)])) as T;
20
- }
21
- return value;
22
- }
8
+ import { settingsChatDisplayValue as displayValue } from "./settings-chat-display.js";
9
+ import { createSettingsChatTools } from "./settings-chat-tools.js";
23
10
 
24
11
  export interface SettingsChatAnchor {
25
12
  message: AgentMessage | symbol;
26
13
  row: number;
14
+ width: number;
15
+ offset: number;
16
+ text: string;
27
17
  }
28
18
 
29
19
  /** Reuse Pi's public message components, not another extension's renderer or private settings. */
30
- export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string) {
20
+ export function createSettingsChatTranscript(
21
+ agent: Agent,
22
+ tui: TUI,
23
+ cwd: string,
24
+ initialExpanded = false,
25
+ editablePath?: string,
26
+ ) {
31
27
  const messages = new Map<AgentMessage, Component>();
32
- const tools = new Map<string, { component: ToolExecutionComponent; result?: AgentMessage }>();
33
- const definitions = {
34
- read: createReadToolDefinition(cwd),
35
- write: createWriteToolDefinition(cwd),
36
- edit: createEditToolDefinition(cwd),
37
- };
28
+ const tools = createSettingsChatTools(tui, cwd, initialExpanded, editablePath);
38
29
  // Agent emits a new object for each partial update and another at finalization.
39
30
  // Keep one response identity across those events, including frames with no render.
40
31
  const identities = new WeakMap<AgentMessage, symbol>();
@@ -45,6 +36,8 @@ export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string
45
36
  identities.set(initial, streamingIdentity);
46
37
  }
47
38
  const unsubscribe = agent.subscribe((event) => {
39
+ if (disposed) return;
40
+ tools.onEvent(event);
48
41
  if (event.type === "agent_end") streamingIdentity = undefined;
49
42
  if (
50
43
  (event.type === "message_start" || event.type === "message_update" || event.type === "message_end") &&
@@ -56,13 +49,16 @@ export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string
56
49
  if (event.type === "message_end") streamingIdentity = undefined;
57
50
  }
58
51
  });
59
- let spans: Array<{ message: AgentMessage | symbol; start: number; end: number }> = [];
52
+ let spans: Array<{ message: AgentMessage | symbol; start: number; end: number; offsets: number[]; text: string }> =
53
+ [];
54
+ let toolSpans: Array<{ id: string; start: number; end: number }> = [];
55
+ let renderedWidth = 0;
60
56
  let streaming: AssistantMessageComponent | undefined;
61
57
  let disposed = false;
62
- let expanded = true;
63
58
  return {
64
59
  render(width: number): string[] {
65
60
  spans = [];
61
+ toolSpans = [];
66
62
  if (disposed || width <= 0) return [];
67
63
  const results = new Map(
68
64
  agent.state.messages.flatMap((message) =>
@@ -75,43 +71,28 @@ export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string
75
71
  const activeMessages = new Set<AgentMessage>();
76
72
  const activeTools = new Set<string>();
77
73
  const lines: string[] = [];
74
+ renderedWidth = width;
75
+ const recordSpan = (message: AgentMessage | symbol, start: number) => {
76
+ let offset = 0;
77
+ let text = "";
78
+ const offsets = lines.slice(start).map((line) => {
79
+ const before = offset;
80
+ // Display-only offsets ignore padding and wrap-boundary whitespace.
81
+ const content = stripVTControlCharacters(line).replace(/\s/gu, "");
82
+ text += content;
83
+ offset += content.length;
84
+ return before;
85
+ });
86
+ spans.push({ message, start, end: lines.length, offsets, text });
87
+ };
78
88
  const appendAssistant = (message: AssistantMessage, component: AssistantMessageComponent) => {
79
89
  lines.push(...component.render(width));
80
90
  for (const call of message.content) {
81
91
  if (call.type !== "toolCall") continue;
82
92
  activeTools.add(call.id);
83
- let tool = tools.get(call.id);
84
- if (!tool) {
85
- const definition =
86
- call.name === "read" || call.name === "write" || call.name === "edit"
87
- ? definitions[call.name]
88
- : undefined;
89
- const component = new ToolExecutionComponent(
90
- sanitizeTerminalDocument(call.name),
91
- sanitizeTerminalDocument(call.id),
92
- displayValue(call.arguments),
93
- { showImages: false, outputPad: 1 },
94
- definition,
95
- tui,
96
- sanitizeTerminalDocument(cwd),
97
- );
98
- component.setExpanded(expanded);
99
- component.setArgsComplete();
100
- component.markExecutionStarted();
101
- tool = { component };
102
- tools.set(call.id, tool);
103
- }
104
- const result = results.get(call.id);
105
- if (result && tool.result !== result) {
106
- tool.component.updateResult({
107
- content: displayValue(result.content),
108
- details: displayValue(result.details),
109
- isError: result.isError,
110
- durationMs: result.durationMs,
111
- });
112
- tool.result = result;
113
- }
114
- lines.push(...tool.component.render(width));
93
+ const start = lines.length;
94
+ lines.push(...tools.render(call, message, results.get(call.id), width));
95
+ toolSpans.push({ id: call.id, start, end: lines.length });
115
96
  }
116
97
  };
117
98
  for (const message of visible) {
@@ -140,42 +121,79 @@ export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string
140
121
  }
141
122
  appendAssistant(message, component as AssistantMessageComponent);
142
123
  }
143
- spans.push({ message: identities.get(message) ?? message, start, end: lines.length });
124
+ recordSpan(identities.get(message) ?? message, start);
144
125
  }
145
126
  const partial = agent.state.streamingMessage;
146
127
  if (partial?.role === "assistant") {
147
128
  streaming ??= new AssistantMessageComponent(undefined, true);
148
129
  streaming.updateContent(displayValue(partial), true);
149
- // Tool calls are rendered after finalization, not from incomplete streaming arguments.
150
130
  const start = lines.length;
151
- lines.push(...streaming.render(width));
152
- spans.push({ message: identities.get(partial) ?? partial, start, end: lines.length });
131
+ appendAssistant(partial, streaming);
132
+ recordSpan(identities.get(partial) ?? partial, start);
153
133
  } else streaming = undefined;
154
134
  for (const message of messages.keys()) if (!activeMessages.has(message)) messages.delete(message);
155
- for (const id of tools.keys()) if (!activeTools.has(id)) tools.delete(id);
135
+ tools.retain(activeTools);
156
136
  return lines;
157
137
  },
138
+ handleMouse(event: TuiMouseEvent) {
139
+ if (disposed) return undefined;
140
+ const span = toolSpans.find((item) => event.y >= item.start && event.y < item.end);
141
+ return span
142
+ ? tools.handleMouse(span.id, { ...event, y: event.y - span.start, height: span.end - span.start })
143
+ : undefined;
144
+ },
158
145
  anchorAt(row: number): SettingsChatAnchor | undefined {
159
146
  const span = spans.find((item) => row < item.end);
160
- return span ? { message: span.message, row: row - span.start } : undefined;
147
+ return span
148
+ ? {
149
+ message: span.message,
150
+ row: row - span.start,
151
+ width: renderedWidth,
152
+ offset: span.offsets[Math.max(0, row - span.start)] ?? 0,
153
+ text: span.text.slice(
154
+ span.offsets[Math.max(0, row - span.start)] ?? 0,
155
+ span.offsets[Math.max(0, row - span.start) + 1],
156
+ ),
157
+ }
158
+ : undefined;
161
159
  },
162
160
  rowAt(anchor: SettingsChatAnchor): number {
163
161
  const span = spans.find((item) => item.message === anchor.message);
164
162
  // If the anchored message was evicted, show the oldest retained content.
165
- return span ? Math.max(0, span.start + Math.min(anchor.row, span.end - span.start - 1)) : 0;
163
+ if (!span) return 0;
164
+ let row = anchor.row;
165
+ const currentText = span.text.slice(span.offsets[Math.max(0, row)], span.offsets[Math.max(0, row) + 1]);
166
+ if (anchor.width !== renderedWidth || currentText !== anchor.text) {
167
+ // Restore retained content after reflow or tool expansion/collapse.
168
+ // Match the row's content, not the accumulated length of earlier rows:
169
+ // Markdown rules and other decoration can change width independently.
170
+ let offset = anchor.offset;
171
+ if (anchor.text) {
172
+ let match = span.text.indexOf(anchor.text);
173
+ let best = -1;
174
+ while (match >= 0) {
175
+ if (best < 0 || Math.abs(match - anchor.offset) < Math.abs(best - anchor.offset)) best = match;
176
+ match = span.text.indexOf(anchor.text, match + 1);
177
+ }
178
+ if (best >= 0) offset = best;
179
+ }
180
+ row = 0;
181
+ for (let index = 0; index < span.offsets.length; index++) {
182
+ if (span.offsets[index] > offset) break;
183
+ row = index;
184
+ }
185
+ }
186
+ return Math.max(0, span.start + Math.min(row, span.end - span.start - 1));
166
187
  },
167
188
  toggleTools() {
168
- if (disposed) return;
169
- expanded = !expanded;
170
- for (const { component } of tools.values()) component.setExpanded(expanded);
171
- tui.requestRender();
189
+ return tools.toggle();
172
190
  },
173
191
  invalidate() {
174
192
  if (disposed) return;
175
193
  // Native Markdown themes can retain concrete colors. Recreate display components
176
194
  // rather than retaining colors captured before a host theme change.
177
195
  messages.clear();
178
- tools.clear();
196
+ tools.invalidate();
179
197
  streaming = undefined;
180
198
  },
181
199
  dispose() {
@@ -184,8 +202,9 @@ export function createSettingsChatTranscript(agent: Agent, tui: TUI, cwd: string
184
202
  unsubscribe();
185
203
  streamingIdentity = undefined;
186
204
  spans = [];
205
+ toolSpans = [];
187
206
  messages.clear();
188
- tools.clear();
207
+ tools.dispose();
189
208
  streaming = undefined;
190
209
  },
191
210
  };
@@ -7,8 +7,8 @@ import {
7
7
  type Theme,
8
8
  } from "@earendil-works/pi-coding-agent";
9
9
  import {
10
+ type Component,
10
11
  CURSOR_MARKER,
11
- decodeKittyPrintable,
12
12
  Editor,
13
13
  getKeybindings,
14
14
  isKeyRelease,
@@ -17,13 +17,15 @@ import {
17
17
  parseKey,
18
18
  type TUI,
19
19
  TUI_KEYBINDINGS,
20
- type TuiMouseEvent,
21
20
  truncateToWidth,
21
+ VStack,
22
22
  } from "@earendil-works/pi-tui";
23
- import { HorizontalRule, renderBoundedFrame, runCustomInteraction } from "@narumitw/pi-tui-kit";
23
+ import { HorizontalRule, renderBoundedFrame } from "@narumitw/pi-tui-kit";
24
24
  import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
25
25
  import type { WorkflowOwner } from "./command-configuration.js";
26
- import { createSettingsChatTranscript, type SettingsChatAnchor } from "./settings-chat-transcript.js";
26
+ import { runSettingsChatFullscreen } from "./settings-chat-fullscreen.js";
27
+ import { SettingsChatScrollView } from "./settings-chat-scroll.js";
28
+ import { createSettingsChatTranscript } from "./settings-chat-transcript.js";
27
29
  import type { SettingsDraft } from "./settings-draft.js";
28
30
 
29
31
  export type SettingsChatAction = "save" | "discard";
@@ -66,69 +68,16 @@ export function settingsChatSaveShortcut(
66
68
  export interface ChatViewState {
67
69
  input: string;
68
70
  error: string;
69
- }
70
-
71
- // Installed Editor.handleInput actions before pageUp/pageDown, in native order.
72
- // No autocomplete provider is installed in this chat. Jump triggers come AFTER paging.
73
- const BEFORE_PAGE_ACTIONS = [
74
- "tui.input.copy",
75
- "tui.editor.undo",
76
- "tui.input.tab",
77
- "tui.editor.deleteToLineEnd",
78
- "tui.editor.deleteToLineStart",
79
- "tui.editor.deleteWordBackward",
80
- "tui.editor.deleteWordForward",
81
- "tui.editor.deleteCharBackward",
82
- "tui.editor.deleteCharForward",
83
- "tui.editor.yank",
84
- "tui.editor.yankPop",
85
- "tui.editor.historyPrevious",
86
- "tui.editor.historyNext",
87
- "tui.editor.cursorLineStart",
88
- "tui.editor.cursorLineEnd",
89
- "tui.editor.cursorWordLeft",
90
- "tui.editor.cursorWordRight",
91
- "tui.input.newLine",
92
- "tui.input.submit",
93
- "tui.editor.cursorUp",
94
- "tui.editor.cursorDown",
95
- "tui.editor.cursorRight",
96
- "tui.editor.cursorLeft",
97
- ] as const;
98
-
99
- /** Match Editor's printable jump targets without a Jiti-incompatible package subpath. */
100
- function nativeJumpPrintable(data: string): boolean {
101
- if (decodeKittyPrintable(data) !== undefined || data.charCodeAt(0) >= 32) return true;
102
- // Editor also accepts plain/Shift modifyOtherKeys text, ignoring Caps/Num Lock bits.
103
- if (!data.startsWith("\x1b[27;")) return false;
104
- const match = /^(\d+);(\d+)~$/u.exec(data.slice(5));
105
- if (!match) return false;
106
- const modifier = Number(match[1]) - 1;
107
- const codepoint = Number(match[2]);
108
- return (modifier & ~(1 | 64 | 128)) === 0 && codepoint >= 32 && codepoint <= 0x10ffff;
109
- }
110
-
111
- function nativeBeforePage(data: string): boolean {
112
- return (
113
- BEFORE_PAGE_ACTIONS.some((action) => getKeybindings().matches(data, action)) ||
114
- matchesKey(data, "shift+backspace") ||
115
- matchesKey(data, "shift+delete") ||
116
- data.charCodeAt(0) === 10 ||
117
- data === "\x1b\r" ||
118
- data === "\x1b[13;2~" ||
119
- (data.length > 1 && data.includes("\x1b") && data.includes("\r"))
120
- );
71
+ toolsExpanded?: boolean;
121
72
  }
122
73
 
123
74
  /** Add labels only to the public Editor border hooks; native scroll indicators keep priority. */
124
75
  export class SettingsChatEditor extends CustomEditor {
125
- onTranscriptPage?: (direction: -1 | 1) => void;
126
- private awaitingJump: string | undefined;
127
76
  constructor(
128
77
  tui: TUI,
129
78
  private readonly chromeTheme: Theme,
130
79
  private readonly labels: () => { top: string; bottom: string },
131
- private readonly chatKeys: KeybindingsManager,
80
+ chatKeys: KeybindingsManager,
132
81
  ) {
133
82
  super(
134
83
  tui,
@@ -145,52 +94,8 @@ export class SettingsChatEditor extends CustomEditor {
145
94
  chatKeys,
146
95
  );
147
96
  }
148
- handleInput(data: string): void {
149
- const kb = getKeybindings();
150
- // These CustomEditor branches consume input before reaching Editor, even
151
- // without a handler. Explicit history bypasses registered message actions.
152
- const interrupt = this.chatKeys.matches(data, "app.interrupt");
153
- const appConsumes =
154
- this.chatKeys.matches(data, "app.clipboard.pasteImage") ||
155
- (interrupt && this.onEscape !== undefined) ||
156
- (!interrupt && this.chatKeys.matches(data, "app.exit") && this.getText().length === 0);
157
- const history =
158
- this.chatKeys.matches(data, "tui.editor.historyPrevious") ||
159
- this.chatKeys.matches(data, "tui.editor.historyNext");
160
- const registeredAction =
161
- !interrupt &&
162
- !history &&
163
- (this.chatKeys.matches(data, "app.message.followUp") ||
164
- this.chatKeys.matches(data, "app.message.dequeue") ||
165
- this.chatKeys.matches(data, "app.tools.expand"));
166
- if (appConsumes || registeredAction) {
167
- super.handleInput(data);
168
- return;
169
- }
170
- const jump = kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward");
171
- const pendingJump = this.awaitingJump;
172
- const jumpConsumes = pendingJump !== undefined && (jump || nativeJumpPrintable(data));
173
- this.awaitingJump = undefined;
174
- const earlier = nativeBeforePage(data);
175
- const direction = kb.matches(data, "tui.editor.pageUp")
176
- ? -1
177
- : kb.matches(data, "tui.editor.pageDown")
178
- ? 1
179
- : undefined;
180
- // The chat registers no interrupt handler. CustomEditor forwards it to
181
- // Editor, then returns; retain that branch and its jump-state transition.
182
- if (!interrupt && !jumpConsumes && !earlier && direction !== undefined && this.onTranscriptPage) {
183
- // Repeating the trigger cancels native jump mode without moving the editor.
184
- if (pendingJump !== undefined) Editor.prototype.handleInput.call(this, pendingJump);
185
- this.onTranscriptPage(direction);
186
- return;
187
- }
188
- if (!jumpConsumes && !earlier && direction === undefined && jump) this.awaitingJump = data;
189
- super.handleInput(data);
190
- }
191
97
  /** Bypass app shortcuts while the native Editor owns a bracketed paste. */
192
98
  handlePasteInput(data: string): void {
193
- this.awaitingJump = undefined;
194
99
  Editor.prototype.handleInput.call(this, data);
195
100
  }
196
101
  protected renderTopBorder(width: number, hiddenLineCount: number): string {
@@ -215,7 +120,23 @@ export class SettingsChatEditor extends CustomEditor {
215
120
  }
216
121
  }
217
122
 
218
- /** Editor actions win collisions. Escape remains a stop fallback for unusable cancel settings. */
123
+ // Native fullscreen actions evaluated before the focused root component. Search
124
+ // navigation/close are conditional on a focused search overlay, not this editor.
125
+ const ROOT_VIEWPORT_ACTIONS = [
126
+ "tui.altScreen.search",
127
+ "tui.altScreen.pageUp",
128
+ "tui.altScreen.pageDown",
129
+ "tui.altScreen.halfPageUp",
130
+ "tui.altScreen.halfPageDown",
131
+ "tui.altScreen.lineUp",
132
+ "tui.altScreen.lineDown",
133
+ "tui.altScreen.previousPrompt",
134
+ "tui.altScreen.nextPrompt",
135
+ "tui.altScreen.top",
136
+ "tui.altScreen.bottom",
137
+ ] as const;
138
+
139
+ /** Native viewport/editor actions win collisions; Escape is an executable stop fallback. */
219
140
  export function settingsChatStopInput(data: string, keybindings: Pick<KeybindingsManager, "matches">): boolean {
220
141
  const editorKeys = getKeybindings();
221
142
  const parsed = parseKey(data);
@@ -236,7 +157,8 @@ export function settingsChatStopInput(data: string, keybindings: Pick<Keybinding
236
157
  (Object.keys(TUI_KEYBINDINGS) as Array<keyof typeof TUI_KEYBINDINGS>)
237
158
  .filter((key) => key.startsWith("tui.editor.") || key.startsWith("tui.input."))
238
159
  .some((key) => editorKeys.matches(data, key));
239
- return !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape));
160
+ const viewport = ROOT_VIEWPORT_ACTIONS.some((action) => editorKeys.matches(data, action));
161
+ return !viewport && !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape));
240
162
  }
241
163
 
242
164
  export function createSettingsChatComponent(options: {
@@ -255,17 +177,6 @@ export function createSettingsChatComponent(options: {
255
177
  let inPaste = false;
256
178
  let pending: Promise<void> | undefined;
257
179
  let stopping = false;
258
- // Undefined follows output; message identity keeps retained history stable after eviction.
259
- let historyTop: number | undefined;
260
- let historyAnchor: SettingsChatAnchor | undefined;
261
- let historyRows = 0;
262
- let historyMaximum = 0;
263
- const scrollHistory = (delta: number) => {
264
- const next = Math.max(0, Math.min(historyMaximum, (historyTop ?? historyMaximum) + delta));
265
- historyTop = next === historyMaximum ? undefined : next;
266
- historyAnchor = historyTop === undefined ? undefined : transcript.anchorAt(historyTop);
267
- render();
268
- };
269
180
  const queued: Array<{ kind: "steer" | "followUp"; message: UserMessage; text: string }> = [];
270
181
  const editor = new SettingsChatEditor(
271
182
  tui,
@@ -289,13 +200,18 @@ export function createSettingsChatComponent(options: {
289
200
  },
290
201
  keybindings,
291
202
  );
292
- editor.onTranscriptPage = (direction) => scrollHistory(direction * Math.max(1, historyRows));
293
203
  editor.setText(state.input);
294
204
  const render = () => {
295
205
  if (!disposed && !signal.aborted) tui.requestRender();
296
206
  };
297
207
  // Update transcript identities before this listener requests the next frame.
298
- const transcript = createSettingsChatTranscript(agent, tui, draft.directory);
208
+ const transcript = createSettingsChatTranscript(
209
+ agent,
210
+ tui,
211
+ draft.directory,
212
+ state.toolsExpanded ?? false,
213
+ draft.path,
214
+ );
299
215
  const unsubscribe = agent.subscribe((event) => {
300
216
  if (event.type === "message_start") {
301
217
  const index = queued.findIndex((item) => item.message === event.message);
@@ -368,20 +284,15 @@ export function createSettingsChatComponent(options: {
368
284
  editor.onSubmit = (input) => submit(input, "steer");
369
285
  editor.onAction("app.message.followUp", () => submit(editor.getExpandedText().trim(), "followUp"));
370
286
  editor.onAction("app.message.dequeue", restoreQueue);
371
- editor.onAction("app.tools.expand", () => transcript.toggleTools());
372
- return {
373
- get focused() {
374
- return editor.focused;
375
- },
376
- set focused(value: boolean) {
377
- editor.focused = value;
378
- },
287
+ editor.onAction("app.tools.expand", () => {
288
+ state.toolsExpanded = transcript.toggleTools();
289
+ });
290
+ const dock: Component = {
379
291
  render(width: number): string[] {
380
- historyRows = 0;
381
292
  if (disposed || signal.aborted || width <= 0) return [];
382
293
  const rows = Math.max(0, Math.floor(Number.isFinite(tui.terminal.rows) ? tui.terminal.rows : 24));
383
294
  if (rows === 0) return [];
384
- const input = editor.render(width);
295
+ const input = editor.render(Math.max(3, width)).map((line) => truncateToWidth(line, width, ""));
385
296
  const cursor = Math.max(
386
297
  0,
387
298
  input.findIndex((line) => line.includes(CURSOR_MARKER)),
@@ -391,8 +302,7 @@ export function createSettingsChatComponent(options: {
391
302
  .split("\n")
392
303
  .filter(Boolean)
393
304
  .slice(0, 3);
394
- // Match Pi's transcript -> editor -> footer hierarchy. The fullscreen overlay
395
- // covers the parent footer, so the real draft preview is part of this dock.
305
+ // Keep the draft preview outside the scrollable history.
396
306
  const details = diagnostics.map((line) => theme.fg("muted", line));
397
307
  // Render the footer without extra rules, matching its saved position at the terminal bottom.
398
308
  if (input.length + preview.length > rows) {
@@ -419,22 +329,48 @@ export function createSettingsChatComponent(options: {
419
329
  ),
420
330
  );
421
331
  const content = [...queueLines, ...input, ...detailLines, ...preview];
422
- const available = rows - content.length;
423
- historyRows = available;
424
- // Keep the anchor while the dock temporarily leaves no room for history.
425
- if (available === 0) return content.map((line) => truncateToWidth(line, width, ""));
426
- const lines = transcript.render(width);
427
- historyMaximum = Math.max(0, lines.length - available);
428
- if (historyTop !== undefined) {
429
- historyTop = Math.min(historyAnchor ? transcript.rowAt(historyAnchor) : historyTop, historyMaximum);
430
- if (historyTop === historyMaximum) historyTop = undefined;
431
- }
432
- const top = historyTop ?? historyMaximum;
433
- historyAnchor = historyTop === undefined ? undefined : transcript.anchorAt(top);
434
- const history = lines.slice(top, top + available);
435
- return [...history, ...Array.from({ length: available - history.length }, () => ""), ...content].map((line) =>
436
- truncateToWidth(line, width, ""),
437
- );
332
+ return content.map((line) => truncateToWidth(line, width, ""));
333
+ },
334
+ invalidate() {
335
+ editor.invalidate();
336
+ },
337
+ };
338
+ const history: Component = {
339
+ render(width) {
340
+ // Capture against the previous frame's spans before rebuilding identities.
341
+ scroll.anchor = scroll.isFollowingEnd ? undefined : transcript.anchorAt(scroll.scrollTop);
342
+ return transcript.render(width);
343
+ },
344
+ invalidate() {
345
+ transcript.invalidate();
346
+ },
347
+ handleMouse: (event) => transcript.handleMouse(event),
348
+ };
349
+ const scroll = new SettingsChatScrollView(history, {
350
+ primary: true,
351
+ follow: "end",
352
+ scrollbar: "auto",
353
+ scrollbarTrackStyle: (text) => theme.fg("scrollbarTrack", text),
354
+ scrollbarThumbStyle: (text) => theme.fg("scrollbarThumb", text),
355
+ });
356
+ scroll.restoreAnchor = (anchor) => transcript.rowAt(anchor);
357
+ const layout = new VStack([
358
+ { component: scroll, basis: 0, grow: 1, minSize: 0 },
359
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 },
360
+ ]);
361
+ return {
362
+ getFullscreenLayout() {
363
+ return layout;
364
+ },
365
+ get focused() {
366
+ return editor.focused;
367
+ },
368
+ set focused(value: boolean) {
369
+ editor.focused = value;
370
+ },
371
+ render(width: number): string[] {
372
+ if (disposed || signal.aborted || width <= 0 || tui.terminal.rows <= 0) return [];
373
+ return layout.render(width);
438
374
  },
439
375
  invalidate() {
440
376
  editor.invalidate();
@@ -462,12 +398,6 @@ export function createSettingsChatComponent(options: {
462
398
  } else editor.handleInput(data);
463
399
  render();
464
400
  },
465
- handleMouse(event: TuiMouseEvent) {
466
- if (disposed || signal.aborted || inPaste || historyRows === 0 || event.type !== "wheel" || !event.wheelDelta)
467
- return undefined;
468
- scrollHistory(event.wheelDelta < 0 ? -3 : 3);
469
- return { handled: true, render: true };
470
- },
471
401
  dispose() {
472
402
  if (disposed) return;
473
403
  disposed = true;
@@ -475,6 +405,8 @@ export function createSettingsChatComponent(options: {
475
405
  signal.removeEventListener("abort", abort);
476
406
  unsubscribe();
477
407
  transcript.dispose();
408
+ scroll.setScrollbarActive(false);
409
+ scroll.setScrollbar("hidden");
478
410
  abort();
479
411
  },
480
412
  async waitForPending() {
@@ -492,35 +424,14 @@ export async function showSettingsChat(
492
424
  owner: WorkflowOwner,
493
425
  preview: (width: number) => string[],
494
426
  ): Promise<SettingsChatAction> {
495
- // Keep Kit's cancellation/disposal runner, but mount through Pi's public overlay API.
496
- // No second TUI, terminal handoff, or manipulation of unrelated overlay handles is needed.
497
- const fullscreenContext: ExtensionCommandContext = {
498
- ...ctx,
499
- ui: {
500
- ...ctx.ui,
501
- custom: (factory) =>
502
- ctx.ui.custom(factory, {
503
- overlay: true,
504
- overlayOptions: { width: "100%", maxHeight: "100%", anchor: "top-left", margin: 0 },
505
- }),
506
- },
507
- };
508
- const result = await runCustomInteraction<SettingsChatAction>(fullscreenContext, {
509
- signal: owner.signal,
510
- isCurrent: owner.isCurrent,
511
- create: ({ tui, theme, keybindings, signal, complete }) =>
512
- createSettingsChatComponent({
513
- agent,
514
- draft,
515
- state,
516
- tui,
517
- theme,
518
- keybindings,
519
- signal,
520
- preview,
521
- complete,
522
- }),
523
- });
524
- if (result.kind === "error") throw result.error;
525
- return result.kind === "completed" ? result.value : "discard";
427
+ // Seed this side thread once from the public parent display preference. Its
428
+ // later Ctrl+O changes remain local, including across review/name cancellation.
429
+ state.toolsExpanded ??= ctx.ui.getToolsExpanded?.() ?? false;
430
+ return runSettingsChatFullscreen(
431
+ ctx,
432
+ owner,
433
+ ({ tui, theme, keybindings, signal, complete }) =>
434
+ createSettingsChatComponent({ agent, draft, state, tui, theme, keybindings, signal, preview, complete }),
435
+ "discard" as SettingsChatAction,
436
+ );
526
437
  }