@narumitw/pi-starship 0.62.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.
Files changed (34) hide show
  1. package/README.md +23 -11
  2. package/dist/chunks/{chunk-PWTSHSP3.ts → chunk-A65IOGL6.ts} +6 -7
  3. package/dist/chunks/chunk-A65IOGL6.ts.map +7 -0
  4. package/dist/chunks/{chunk-HPZTMIZS.ts → chunk-DIHVBO5Z.ts} +41 -8
  5. package/dist/chunks/chunk-DIHVBO5Z.ts.map +7 -0
  6. package/dist/chunks/{chunk-43VIENBN.ts → chunk-UIKPE4UC.ts} +7 -7
  7. package/dist/chunks/{chunk-43VIENBN.ts.map → chunk-UIKPE4UC.ts.map} +2 -2
  8. package/dist/chunks/{command-configuration-menu-S2LXCOJG.ts → command-configuration-menu-ZN2VXU4L.ts} +3 -3
  9. package/dist/chunks/{command-settings-chat-O34BEU4X.ts → command-settings-chat-KLUVZXMO.ts} +632 -196
  10. package/dist/chunks/command-settings-chat-KLUVZXMO.ts.map +7 -0
  11. package/dist/chunks/{commands-ZYIJVIEJ.ts → commands-UAUSSHVS.ts} +25 -20
  12. package/dist/chunks/commands-UAUSSHVS.ts.map +7 -0
  13. package/dist/index.ts +116 -59
  14. package/dist/index.ts.map +3 -3
  15. package/package.json +1 -1
  16. package/skills/configure-pi-starship/SKILL.md +3 -1
  17. package/skills/configure-pi-starship/references/configuration.md +14 -12
  18. package/src/command-commit.ts +41 -7
  19. package/src/command-configuration.ts +8 -10
  20. package/src/command-settings-chat.ts +18 -48
  21. package/src/commands.ts +23 -26
  22. package/src/config.ts +6 -6
  23. package/src/pi-starship.ts +155 -88
  24. package/src/settings-chat-display.ts +11 -0
  25. package/src/settings-chat-fullscreen.ts +264 -0
  26. package/src/settings-chat-scroll.ts +17 -0
  27. package/src/settings-chat-tools.ts +207 -0
  28. package/src/settings-chat-transcript.ts +133 -62
  29. package/src/settings-chat-ui.ts +109 -98
  30. package/dist/chunks/chunk-HPZTMIZS.ts.map +0 -7
  31. package/dist/chunks/chunk-PWTSHSP3.ts.map +0 -7
  32. package/dist/chunks/command-settings-chat-O34BEU4X.ts.map +0 -7
  33. package/dist/chunks/commands-ZYIJVIEJ.ts.map +0 -7
  34. /package/dist/chunks/{command-configuration-menu-S2LXCOJG.ts.map → command-configuration-menu-ZN2VXU4L.ts.map} +0 -0
@@ -95,6 +95,9 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
95
95
  let chatCleanup: (() => Promise<void>) | undefined;
96
96
  let sessionOwner: ExtensionContext["sessionManager"] | undefined;
97
97
  let activeTarget: RefreshTarget | undefined;
98
+ let footerContext: ExtensionContext | undefined;
99
+ let disposeFooter: (() => void) | undefined;
100
+ let footerCollecting = false;
98
101
  let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;
99
102
  let githubPrRefreshTimer: ReturnType<typeof setInterval> | undefined;
100
103
  let githubPrExpiryTimer: ReturnType<typeof setTimeout> | undefined;
@@ -166,20 +169,22 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
166
169
  clearTimeout(eventDebounceTimer);
167
170
  eventDebounceTimer = undefined;
168
171
  };
169
- const isActiveTarget = (target: RefreshTarget) =>
170
- activeTarget?.cwd === target.cwd &&
171
- activeTarget.generation === target.generation &&
172
- activeTarget.sessionManager === target.sessionManager &&
173
- target.generation === sessionGeneration;
172
+ const isActiveTarget = (target: RefreshTarget) => activeTarget === target && target.generation === sessionGeneration;
174
173
 
175
174
  const requestRefresh = (target: RefreshTarget, reason: WorkspaceRefreshInput["reason"] = "event") => {
176
- if (!loaded || !isActiveTarget(target)) return;
175
+ if (!loaded || isNativeFooter(loaded) || !isActiveTarget(target)) return;
177
176
  gitController.request({ cwd: target.cwd, config: loaded.config });
178
177
  workspaceController.request(workspaceInput(target.cwd, loaded.config, reason, runtime.workspace));
179
178
  };
180
179
  const scheduleRefresh = (ctx: ExtensionContext) => {
181
180
  const target = activeTarget;
182
- if (!target || target.cwd !== ctx.cwd || target.sessionManager !== ctx.sessionManager) {
181
+ if (
182
+ !loaded ||
183
+ isNativeFooter(loaded) ||
184
+ !target ||
185
+ target.cwd !== ctx.cwd ||
186
+ target.sessionManager !== ctx.sessionManager
187
+ ) {
183
188
  return;
184
189
  }
185
190
  clearDebounce();
@@ -190,7 +195,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
190
195
  };
191
196
 
192
197
  function restartLocalControllers(target: RefreshTarget) {
193
- if (!isActiveTarget(target)) return;
198
+ if (!loaded || isNativeFooter(loaded) || !isActiveTarget(target)) return;
194
199
  gitController.start(target.generation);
195
200
  workspaceController.start(target.generation);
196
201
  }
@@ -209,7 +214,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
209
214
  }
210
215
 
211
216
  function githubPrReachable(): boolean {
212
- return Boolean(loaded && reachableModuleRequirements(loaded.config).has("github_pr"));
217
+ return Boolean(loaded && !isNativeFooter(loaded) && reachableModuleRequirements(loaded.config).has("github_pr"));
213
218
  }
214
219
 
215
220
  function startGithubPr(target: RefreshTarget): boolean {
@@ -253,14 +258,14 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
253
258
  githubPrExpiryTimer.unref?.();
254
259
  }
255
260
 
256
- const installFooter = (ctx: ExtensionContext) => {
257
- const generation = ++sessionGeneration;
258
- commandInFlight = undefined;
259
- sessionOwner = ctx.sessionManager;
260
- previewLoaded = undefined;
261
- menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
262
- menuController = new AbortController();
263
- const target: RefreshTarget = { cwd: ctx.cwd, generation, sessionManager: ctx.sessionManager };
261
+ const releaseFooter = () => {
262
+ const context = footerContext;
263
+ footerContext = undefined;
264
+ const dispose = disposeFooter;
265
+ disposeFooter = undefined;
266
+ footerCollecting = false;
267
+ dispose?.();
268
+ activeTarget = undefined;
264
269
  clearDebounce();
265
270
  gitController.stop();
266
271
  workspaceController.stop();
@@ -271,12 +276,32 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
271
276
  runtime.renderPreview = undefined;
272
277
  runtime.inspect = undefined;
273
278
  runtime.footerWidth = undefined;
274
- activeTarget = ctx.mode === "tui" ? target : undefined;
275
- ctx.ui.setStatus("starship", undefined);
276
- if (!activeTarget || !loaded) return;
277
- gitController.start(generation);
278
- workspaceController.start(generation);
279
- startGithubPr(target);
279
+ context?.ui.setFooter(undefined);
280
+ };
281
+
282
+ const syncFooter = (ctx: ExtensionContext) => {
283
+ const current = previewLoaded ?? loaded;
284
+ if (ctx.mode !== "tui" || !current || isNativeFooter(current)) {
285
+ releaseFooter();
286
+ return;
287
+ }
288
+ // A preview can replace the visible footer, but only applied settings own collectors.
289
+ const collect = Boolean(loaded && !isNativeFooter(loaded));
290
+ if (activeTarget && footerCollecting === collect) return;
291
+ if (activeTarget) releaseFooter();
292
+ footerCollecting = collect;
293
+ const target: RefreshTarget = {
294
+ cwd: ctx.cwd,
295
+ generation: sessionGeneration,
296
+ sessionManager: ctx.sessionManager,
297
+ };
298
+ activeTarget = target;
299
+ footerContext = ctx;
300
+ if (collect) {
301
+ gitController.start(target.generation);
302
+ workspaceController.start(target.generation);
303
+ startGithubPr(target);
304
+ }
280
305
 
281
306
  ctx.ui.setFooter((tui, theme, footerData) => {
282
307
  runtime.requestRender = () => tui.requestRender();
@@ -291,6 +316,10 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
291
316
  inspectStatuslineModules(current.config, runtimeSnapshot(ctx, footerData, runtime), runtime.footerWidth ?? 80);
292
317
  const unsubscribe = footerData.onBranchChange(() => {
293
318
  if (!isActiveTarget(target)) return;
319
+ if (!collect) {
320
+ tui.requestRender();
321
+ return;
322
+ }
294
323
  runtime.git = undefined;
295
324
  restartLocalControllers(target);
296
325
  clearDebounce();
@@ -307,62 +336,67 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
307
336
  width: number;
308
337
  }
309
338
  | undefined;
310
- const timer = setInterval(() => {
311
- if (!isActiveTarget(target)) return;
312
- clearDebounce();
313
- requestRefresh(target, "periodic");
314
- // Collectors publish only changed snapshots. The clock is the sole value
315
- // that changes without publication; reuse the last render's session data.
316
- if (!lastRender) return;
317
- const clock = reachableModuleRequirements(lastRender.config).get("time");
318
- const range = lastRender.config.modules.time.options.time_range;
319
- if (!clock || (!clock.has("time") && (!range || range === "-"))) return;
320
- const now = new Date();
321
- const previous = lastRender.snapshot.now;
322
- if (
323
- !lastRender.config.modules.time.options.time_format &&
324
- lastRender.config.modules.time.options.utc_time_offset === "local" &&
325
- (!range || range === "-") &&
326
- now.getHours() === previous.getHours() &&
327
- now.getMinutes() === previous.getMinutes()
328
- )
329
- return;
330
- const lines = wrapFormattedStatusline(
331
- renderStatusline(
332
- lastRender.config,
333
- { ...lastRender.snapshot, now },
334
- lastRender.width,
335
- getCapabilities().trueColor,
336
- theme.colors,
337
- ).ansi,
338
- lastRender.width,
339
- );
340
- const previousLines = lastRender.lines;
341
- if (lines.length !== previousLines.length || lines.some((line, index) => line !== previousLines[index]))
342
- tui.requestRender();
343
- }, REFRESH_INTERVAL_MS);
339
+ const timer = collect
340
+ ? setInterval(() => {
341
+ if (!isActiveTarget(target)) return;
342
+ clearDebounce();
343
+ requestRefresh(target, "periodic");
344
+ // Collectors publish only changed snapshots. The clock is the sole value
345
+ // that changes without publication; reuse the last render's session data.
346
+ if (!lastRender) return;
347
+ const clock = reachableModuleRequirements(lastRender.config).get("time");
348
+ const range = lastRender.config.modules.time.options.time_range;
349
+ if (!clock || (!clock.has("time") && (!range || range === "-"))) return;
350
+ const now = new Date();
351
+ const previous = lastRender.snapshot.now;
352
+ if (
353
+ !lastRender.config.modules.time.options.time_format &&
354
+ lastRender.config.modules.time.options.utc_time_offset === "local" &&
355
+ (!range || range === "-") &&
356
+ now.getHours() === previous.getHours() &&
357
+ now.getMinutes() === previous.getMinutes()
358
+ )
359
+ return;
360
+ const lines = wrapFormattedStatusline(
361
+ renderStatusline(
362
+ lastRender.config,
363
+ { ...lastRender.snapshot, now },
364
+ lastRender.width,
365
+ getCapabilities().trueColor,
366
+ theme.colors,
367
+ ).ansi,
368
+ lastRender.width,
369
+ );
370
+ const previousLines = lastRender.lines;
371
+ if (lines.length !== previousLines.length || lines.some((line, index) => line !== previousLines[index]))
372
+ tui.requestRender();
373
+ }, REFRESH_INTERVAL_MS)
374
+ : undefined;
344
375
  let disposed = false;
345
376
 
377
+ const dispose = () => {
378
+ if (disposed) return;
379
+ disposed = true;
380
+ unsubscribe();
381
+ clearInterval(timer);
382
+ if (isActiveTarget(target)) {
383
+ activeTarget = undefined;
384
+ footerCollecting = false;
385
+ clearDebounce();
386
+ gitController.stop();
387
+ workspaceController.stop();
388
+ stopGithubPr();
389
+ runtime.git = undefined;
390
+ runtime.workspace = undefined;
391
+ runtime.requestRender = undefined;
392
+ runtime.renderPreview = undefined;
393
+ runtime.inspect = undefined;
394
+ runtime.footerWidth = undefined;
395
+ }
396
+ };
397
+ disposeFooter = dispose;
346
398
  return {
347
- dispose() {
348
- if (disposed) return;
349
- disposed = true;
350
- unsubscribe();
351
- clearInterval(timer);
352
- if (isActiveTarget(target)) {
353
- activeTarget = undefined;
354
- clearDebounce();
355
- gitController.stop();
356
- workspaceController.stop();
357
- stopGithubPr();
358
- runtime.git = undefined;
359
- runtime.workspace = undefined;
360
- runtime.requestRender = undefined;
361
- runtime.renderPreview = undefined;
362
- runtime.inspect = undefined;
363
- runtime.footerWidth = undefined;
364
- }
365
- },
399
+ dispose,
366
400
  invalidate() {},
367
401
  render(width: number): string[] {
368
402
  runtime.footerWidth = width;
@@ -382,6 +416,18 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
382
416
  requestGithubPr(target);
383
417
  };
384
418
 
419
+ const installFooter = (ctx: ExtensionContext) => {
420
+ releaseFooter();
421
+ sessionGeneration += 1;
422
+ commandInFlight = undefined;
423
+ sessionOwner = ctx.sessionManager;
424
+ previewLoaded = undefined;
425
+ menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
426
+ menuController = new AbortController();
427
+ ctx.ui.setStatus("starship", undefined);
428
+ syncFooter(ctx);
429
+ };
430
+
385
431
  const configPath = settingsFilePath(getAgentDir());
386
432
  const commandOptions: StarshipCommandOptions = {
387
433
  settingsPath: configPath,
@@ -402,6 +448,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
402
448
  return {
403
449
  signal: menuController.signal,
404
450
  isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,
451
+ canRestoreTerminal: () => sessionOwner !== undefined,
405
452
  };
406
453
  },
407
454
  apply(next, ctx) {
@@ -411,8 +458,10 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
411
458
  previewLoaded = undefined;
412
459
  loaded = next;
413
460
  loadedRevision += 1;
461
+ const previousTarget = activeTarget;
462
+ syncFooter(ctx);
414
463
  const target = activeTarget;
415
- if (target) {
464
+ if (target && target === previousTarget) {
416
465
  restartLocalControllers(target);
417
466
  startGithubPr(target);
418
467
  requestRefresh(target);
@@ -423,10 +472,31 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
423
472
  preview(next, ctx) {
424
473
  if (sessionOwner !== ctx.sessionManager) return;
425
474
  previewLoaded = next;
475
+ syncFooter(ctx);
426
476
  refresh();
427
477
  },
428
- renderPreview(preview, width) {
429
- return runtime.renderPreview?.(preview, width) ?? ["Live preview is unavailable until the footer is ready."];
478
+ renderPreview(preview, width, ctx) {
479
+ if (isNativeFooter(preview)) return ["Pi built-in footer"];
480
+ if (runtime.renderPreview) return runtime.renderPreview(preview, width);
481
+ // Native mode has no custom footer provider. Render the candidate with
482
+ // session data only; collectors start when a custom footer is installed.
483
+ return wrapFormattedStatusline(
484
+ renderStatusline(
485
+ preview.config,
486
+ runtimeSnapshot(
487
+ ctx,
488
+ {
489
+ getGitBranch: () => null,
490
+ getExtensionStatuses: () => new Map(),
491
+ },
492
+ runtime,
493
+ ),
494
+ width,
495
+ getCapabilities().trueColor,
496
+ ctx.ui.theme.colors,
497
+ ).ansi,
498
+ width,
499
+ );
430
500
  },
431
501
  };
432
502
  pi.registerCommand("starship", {
@@ -477,13 +547,7 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
477
547
  previewLoaded = undefined;
478
548
  sessionGeneration += 1;
479
549
  menuController.abort(new DOMException("Starship session shut down", "AbortError"));
480
- activeTarget = undefined;
481
- clearDebounce();
482
- gitController.stop();
483
- workspaceController.stop();
484
- stopGithubPr();
485
- runtime.git = undefined;
486
- runtime.workspace = undefined;
550
+ releaseFooter();
487
551
  runtime.activeTools.clear();
488
552
  runtime.isStreaming = false;
489
553
  runtime.uiPrompt = undefined;
@@ -492,7 +556,6 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
492
556
  runtime.renderPreview = undefined;
493
557
  runtime.inspect = undefined;
494
558
  runtime.footerWidth = undefined;
495
- ctx.ui.setFooter(undefined);
496
559
  ctx.ui.setStatus("starship", undefined);
497
560
  const cleanup = chatCleanup;
498
561
  chatCleanup = undefined;
@@ -547,6 +610,10 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
547
610
  });
548
611
  }
549
612
 
613
+ function isNativeFooter(loaded: LoadedStarshipConfig): boolean {
614
+ return loaded.rawDocument === undefined && loaded.diagnostics.length === 0;
615
+ }
616
+
550
617
  function workspaceInput(
551
618
  cwd: string,
552
619
  config: StarshipConfig,
@@ -639,7 +706,7 @@ function safeUsername(): string {
639
706
 
640
707
  function runtimeSnapshot(
641
708
  ctx: ExtensionContext,
642
- footerData: ReadonlyFooterDataProvider,
709
+ footerData: Pick<ReadonlyFooterDataProvider, "getGitBranch" | "getExtensionStatuses">,
643
710
  runtime: RuntimeState,
644
711
  ): StarshipRuntimeSnapshot {
645
712
  return {
@@ -0,0 +1,11 @@
1
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
2
+
3
+ /** Keep terminal controls out of native renderers without changing agent payloads. */
4
+ export function settingsChatDisplayValue<T>(value: T): T {
5
+ if (typeof value === "string") return sanitizeTerminalDocument(value) as T;
6
+ if (Array.isArray(value)) return value.map(settingsChatDisplayValue) as T;
7
+ if (value && typeof value === "object") {
8
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, settingsChatDisplayValue(item)])) as T;
9
+ }
10
+ return value;
11
+ }
@@ -0,0 +1,264 @@
1
+ import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ isKeyRelease,
5
+ matchesKey,
6
+ type OverlayHandle,
7
+ type TUI,
8
+ TuiAltScreen,
9
+ type TuiInputListener,
10
+ } from "@earendil-works/pi-tui";
11
+ import type { WorkflowOwner } from "./command-configuration.js";
12
+
13
+ export type SettingsChatFullscreenComponent = Component & {
14
+ dispose?(): void;
15
+ waitForPending?(): Promise<void>;
16
+ getFullscreenLayout?(): Component;
17
+ };
18
+
19
+ export interface SettingsChatFullscreenOptions<Value> {
20
+ tui: TUI;
21
+ theme: Theme;
22
+ keybindings: KeybindingsManager;
23
+ signal: AbortSignal;
24
+ complete(value: Value): void;
25
+ }
26
+
27
+ export interface SettingsChatFullscreenDependencies {
28
+ createTui?(parent: TUI, createDefault: () => TuiAltScreen): TuiAltScreen;
29
+ }
30
+
31
+ type Outcome<Value> = { value: Value } | { error: unknown };
32
+
33
+ // The base constructor registers the native viewport listener through this public
34
+ // method. Install the guard first, without reading or changing Pi's listener set.
35
+ class SettingsChatTui extends TuiAltScreen {
36
+ declare private guardInstalled: boolean | undefined;
37
+ declare guard: TuiInputListener | undefined;
38
+
39
+ override addInputListener(listener: TuiInputListener): () => void {
40
+ if (!this.guardInstalled) {
41
+ this.guardInstalled = true;
42
+ super.addInputListener((data) => this.guard?.(data));
43
+ }
44
+ return super.addInputListener(listener);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Pi recommends one renderer. This isolated chat intentionally transfers the
50
+ * shared terminal to a native fullscreen viewport, then returns it before review.
51
+ * The parent custom overlay owns only the handoff lifetime, never child layout.
52
+ */
53
+ export async function runSettingsChatFullscreen<Value>(
54
+ ctx: ExtensionCommandContext,
55
+ owner: WorkflowOwner,
56
+ create: (options: SettingsChatFullscreenOptions<Value>) => SettingsChatFullscreenComponent,
57
+ cancelledValue: Value,
58
+ dependencies: SettingsChatFullscreenDependencies = {},
59
+ ): Promise<Value> {
60
+ const current = () => !owner.signal.aborted && !ctx.signal?.aborted && owner.isCurrent();
61
+ const canRestoreTerminal = () => (owner.canRestoreTerminal ?? owner.isSessionCurrent ?? owner.isCurrent)();
62
+ if (ctx.mode !== "tui" || !current()) return cancelledValue;
63
+
64
+ let mount: ((handle: OverlayHandle) => void) | undefined;
65
+ let releaseHost: (() => Promise<void>) | undefined;
66
+ let completedOutcome: Outcome<Value> | undefined;
67
+ const outcome = await ctx.ui
68
+ .custom<Outcome<Value>>(
69
+ (parent, theme, keybindings, done) => {
70
+ const controller = new AbortController();
71
+ let child: TuiAltScreen | undefined;
72
+ let component: SettingsChatFullscreenComponent | undefined;
73
+ let overlay: OverlayHandle | undefined;
74
+ let parentStopped = false;
75
+ let entry: Promise<void> | undefined;
76
+ let entryDrainStarted = false;
77
+ let finished = false;
78
+ let closing = false;
79
+ let cleanup: Promise<void> | undefined;
80
+ let pasting = false;
81
+ let result: Outcome<Value> = { value: cancelledValue };
82
+ const errors: unknown[] = [];
83
+ const removers: (() => void)[] = [];
84
+ const attempt = (action: () => void) => {
85
+ try {
86
+ action();
87
+ } catch (error) {
88
+ errors.push(error);
89
+ }
90
+ };
91
+
92
+ const finish = (next: Outcome<Value>) => {
93
+ if (closing) return cleanup;
94
+ closing = true;
95
+ result = next;
96
+ // Root work must stop synchronously, even when a nested overlay has focus.
97
+ controller.abort();
98
+ cleanup = Promise.resolve().then(async () => {
99
+ // Do not stop the terminal or start a second drain while entry still
100
+ // owns the native drain. Its finally block restores the input handler.
101
+ await entry;
102
+ if (parentStopped) {
103
+ try {
104
+ await parent.terminal.drainInput?.();
105
+ } catch (error) {
106
+ errors.push(error);
107
+ }
108
+ }
109
+ if (entryDrainStarted && !parentStopped) {
110
+ // Native drain disables keyboard protocols even if entry is then
111
+ // cancelled or fails. Reset them through the normal stop/start path.
112
+ parentStopped = true;
113
+ attempt(() => parent.stop({ preserveScreen: true }));
114
+ }
115
+ for (const remove of removers.splice(0)) attempt(remove);
116
+ attempt(() => component?.dispose?.());
117
+ if (child) attempt(() => child?.stop({ preserveScreen: true }));
118
+ // Only this interaction's handle can be hidden. Pi's done callback
119
+ // removes it; calling hide() here would bypass custom's lifecycle.
120
+ if (parentStopped) {
121
+ attempt(() => overlay?.setHidden(true));
122
+ attempt(() => {
123
+ // Session/tree replacement can keep this physical TUI alive.
124
+ // Restore its input without calling any stale context UI methods.
125
+ if (canRestoreTerminal()) {
126
+ attempt(() => parent.start());
127
+ attempt(() => parent.renderNow(false));
128
+ }
129
+ });
130
+ }
131
+ // Return input ownership promptly, then join cancelled root work.
132
+ // A late stream must settle before the owning command releases its draft.
133
+ try {
134
+ await component?.waitForPending?.();
135
+ } catch (error) {
136
+ errors.push(error);
137
+ }
138
+ attempt(() => {
139
+ if (!current() && !("error" in result)) result = { value: cancelledValue };
140
+ });
141
+ finished = true;
142
+ if ("error" in result) errors.unshift(result.error);
143
+ completedOutcome = errors.length
144
+ ? { error: errors.length === 1 ? errors[0] : new AggregateError(errors, "Fullscreen cleanup failed") }
145
+ : result;
146
+ done(completedOutcome);
147
+ });
148
+ return cleanup;
149
+ };
150
+ releaseHost = () => finish({ value: cancelledValue }) ?? Promise.resolve();
151
+ const cancel = () => finish({ value: cancelledValue });
152
+ const guard: TuiInputListener = (data) => {
153
+ if (closing) return { consume: true };
154
+ if (!current()) {
155
+ cancel();
156
+ return { consume: true };
157
+ }
158
+ // A terminal can deliver bracketed paste as one packet or separate
159
+ // packets. Ctrl+C in either form is text, not a screen shortcut.
160
+ const wasPasting = pasting;
161
+ for (const part of data.split("\x1b").slice(1)) {
162
+ if (part.startsWith("[200~")) pasting = true;
163
+ else if (part.startsWith("[201~")) pasting = false;
164
+ }
165
+ if (wasPasting || pasting || data.includes("\x1b[200~") || data.includes("\x1b[201~")) {
166
+ try {
167
+ // Paste belongs to the focused editor or native search overlay,
168
+ // not necessarily to the root chat. Bypass viewport shortcuts only.
169
+ child?.getFocusedComponent()?.handleInput?.(data);
170
+ child?.requestRender();
171
+ } catch (error) {
172
+ finish({ error });
173
+ }
174
+ return { consume: true };
175
+ }
176
+ if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) {
177
+ cancel();
178
+ return { consume: true };
179
+ }
180
+ };
181
+
182
+ for (const signal of new Set([owner.signal, ctx.signal])) {
183
+ if (!signal) continue;
184
+ signal.addEventListener("abort", cancel, { once: true });
185
+ removers.push(() => signal.removeEventListener("abort", cancel));
186
+ }
187
+ const host: SettingsChatFullscreenComponent = {
188
+ render: () => [],
189
+ invalidate() {},
190
+ dispose() {
191
+ if (!finished) cancel();
192
+ },
193
+ };
194
+ mount = (handle) => {
195
+ overlay = handle;
196
+ // The custom factory and any active terminal callback must unwind before
197
+ // terminal ownership changes. onHandle runs only after Pi mounts host.
198
+ queueMicrotask(() => {
199
+ if (closing) return;
200
+ entry = (async () => {
201
+ try {
202
+ if (!current()) {
203
+ cancel();
204
+ return;
205
+ }
206
+ entryDrainStarted = parent.terminal.drainInput !== undefined;
207
+ await parent.terminal.drainInput?.();
208
+ if (closing) return;
209
+ if (!current()) {
210
+ cancel();
211
+ return;
212
+ }
213
+ parentStopped = true;
214
+ parent.stop({ preserveScreen: true });
215
+ if (closing) return;
216
+ const createDefault = () =>
217
+ new SettingsChatTui(parent.terminal, parent.getShowHardwareCursor(), undefined, { mouse: true });
218
+ child = dependencies.createTui?.(parent, createDefault) ?? createDefault();
219
+ if (child instanceof SettingsChatTui) child.guard = guard;
220
+ else removers.push(child.addInputListener(guard));
221
+ component = create({
222
+ tui: child,
223
+ theme,
224
+ keybindings,
225
+ signal: controller.signal,
226
+ complete: (value) => finish({ value }),
227
+ });
228
+ if (closing) return;
229
+ if (!current()) {
230
+ cancel();
231
+ return;
232
+ }
233
+ child.setLayoutRoot(component.getFullscreenLayout?.() ?? component);
234
+ child.setFocus(component);
235
+ child.start();
236
+ } catch (error) {
237
+ if (closing) errors.push(error);
238
+ else finish({ error });
239
+ }
240
+ })();
241
+ });
242
+ };
243
+ if (!current()) cancel();
244
+ return host;
245
+ },
246
+ { overlay: true, onHandle: (handle) => mount?.(handle) },
247
+ )
248
+ .catch(async (error: unknown) => {
249
+ // Pi can reject while mounting the custom overlay without disposing the
250
+ // factory result. Release upstream listeners even when onHandle never ran.
251
+ await releaseHost?.();
252
+ if (completedOutcome && "error" in completedOutcome) {
253
+ throw new AggregateError([error, completedOutcome.error], "Fullscreen mount and cleanup failed");
254
+ }
255
+ throw error;
256
+ });
257
+ // External custom disposal can resolve undefined before host.dispose finishes.
258
+ // Terminal restoration and cleanup failures still belong to this command.
259
+ await releaseHost?.();
260
+ const completion = completedOutcome ?? outcome;
261
+ if (!completion) return cancelledValue;
262
+ if ("error" in completion) throw completion.error;
263
+ return completion.value;
264
+ }
@@ -0,0 +1,17 @@
1
+ import { ScrollView } from "@earendil-works/pi-tui";
2
+ import type { SettingsChatAnchor } from "./settings-chat-transcript.js";
3
+
4
+ /** Native layout owns clipping; this adapter retains message identity across history changes. */
5
+ export class SettingsChatScrollView extends ScrollView {
6
+ anchor: SettingsChatAnchor | undefined;
7
+ restoreAnchor?: (anchor: SettingsChatAnchor) => number;
8
+
9
+ override updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void {
10
+ const manual = !this.isFollowingEnd;
11
+ const target = manual && this.anchor ? this.restoreAnchor?.(this.anchor) : undefined;
12
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
13
+ // Resizing or collapsing output can temporarily make the content fit. That must
14
+ // not silently enable follow-end after the user chose an older message.
15
+ if (manual) this.scrollTo(target ?? this.scrollTop, { disableFollow: true });
16
+ }
17
+ }