@ftrdotdev/pi-tui 0.5.2 → 0.7.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.
@@ -0,0 +1,87 @@
1
+ import { afterEach, assert, it } from "@effect/vitest";
2
+ import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { readRuntimeInfo } from "./runtime.ts";
6
+
7
+ // Env-based runtimes (no marker file) would leak the host environment into
8
+ // the "no marker matches" case, so that test clears them.
9
+ const ENV_KEYS = [
10
+ "MESON_DEVENV",
11
+ "IN_NIX_SHELL",
12
+ "GUIX_ENVIRONMENT",
13
+ "CONDA_DEFAULT_ENV",
14
+ "PIXI_ENVIRONMENT_NAME",
15
+ "SPACK_ENV",
16
+ ] as const;
17
+
18
+ const dirs: string[] = [];
19
+
20
+ function tempDir(): string {
21
+ const dir = mkdtempSync(join(tmpdir(), "pi-tui-runtime-"));
22
+ dirs.push(dir);
23
+ return dir;
24
+ }
25
+
26
+ afterEach(() => {
27
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
28
+ });
29
+
30
+ it("returns every matching runtime in table order", async () => {
31
+ const dir = tempDir();
32
+ writeFileSync(join(dir, "CMakeLists.txt"), "");
33
+ const runtimes = await readRuntimeInfo(dir);
34
+ assert.deepStrictEqual(
35
+ runtimes.map((r) => r.name),
36
+ ["cpp", "c", "cmake"],
37
+ );
38
+ });
39
+
40
+ it("returns an empty list when no marker matches", async () => {
41
+ const dir = tempDir();
42
+ const saved = ENV_KEYS.map((key) => [key, process.env[key]] as const);
43
+ for (const key of ENV_KEYS) delete process.env[key];
44
+ try {
45
+ assert.deepStrictEqual(await readRuntimeInfo(dir), []);
46
+ } finally {
47
+ for (const [key, value] of saved) {
48
+ if (value === undefined) delete process.env[key];
49
+ else process.env[key] = value;
50
+ }
51
+ }
52
+ });
53
+
54
+ it("matches env-based runtimes without a marker file", async () => {
55
+ const dir = tempDir();
56
+ const key = "CONDA_DEFAULT_ENV";
57
+ const previous = process.env[key];
58
+ process.env[key] = "pi-tui-test";
59
+ try {
60
+ const runtimes = await readRuntimeInfo(dir);
61
+ assert.deepStrictEqual(
62
+ runtimes.map((r) => r.name),
63
+ ["conda"],
64
+ );
65
+ } finally {
66
+ if (previous === undefined) delete process.env[key];
67
+ else process.env[key] = previous;
68
+ }
69
+ });
70
+
71
+ it("reuses the cached entry until the marker fingerprint changes", async () => {
72
+ const dir = tempDir();
73
+ const marker = join(dir, "settings.gradle.kts");
74
+ writeFileSync(marker, "");
75
+ const first = await readRuntimeInfo(dir);
76
+ const second = await readRuntimeInfo(dir);
77
+ // A cache hit returns the same object, not a rebuilt one.
78
+ assert.strictEqual(first[0], second[0]);
79
+ assert.strictEqual(first[0]?.name, "kotlin");
80
+
81
+ // Touching the marker changes the fingerprint, so the next read rebuilds.
82
+ const future = new Date(Date.now() + 60_000);
83
+ utimesSync(marker, future, future);
84
+ const third = await readRuntimeInfo(dir);
85
+ assert.notStrictEqual(third[0], first[0]);
86
+ assert.strictEqual(third[0]?.name, "kotlin");
87
+ });
package/src/runtime.ts CHANGED
@@ -158,7 +158,7 @@ const RUNTIMES: readonly RuntimeDef[] = [
158
158
 
159
159
  interface CacheEntry {
160
160
  fingerprint: string;
161
- runtime: RuntimeInfo | null;
161
+ runtime: RuntimeInfo;
162
162
  }
163
163
 
164
164
  const cache = new Map<string, CacheEntry>();
@@ -221,36 +221,33 @@ async function fetchVersion(def: RuntimeDef, cwd: string): Promise<string | unde
221
221
  }
222
222
  }
223
223
 
224
- export async function readRuntimeInfo(cwd: string): Promise<RuntimeInfo | null> {
224
+ /**
225
+ * Every runtime that matches `cwd`, in table order. Each match carries its
226
+ * version when the runtime's version command answers. Results are cached per
227
+ * `(cwd, runtime)` and invalidated by a fingerprint of the marker files.
228
+ */
229
+ export async function readRuntimeInfo(cwd: string): Promise<RuntimeInfo[]> {
230
+ const matches: RuntimeInfo[] = [];
225
231
  for (const def of RUNTIMES) {
226
232
  if (!matchesDef(cwd, def)) continue;
227
- const fp = fingerprint(cwd, def);
228
- const cacheKey = `${cwd}\0${def.name}`;
229
- const cached = cache.get(cacheKey);
230
- if (cached && cached.fingerprint === fp) {
231
- return cached.runtime;
232
- }
233
-
234
- for (const key of cache.keys()) {
235
- if (key === cacheKey || key.startsWith(`${cwd}\0`)) cache.delete(key);
236
- }
237
-
238
- const version = await fetchVersion(def, cwd);
239
- const info: RuntimeInfo = {
240
- name: def.name,
241
- version,
242
- };
243
- cache.set(cacheKey, { fingerprint: fp, runtime: info });
244
- while (cache.size > CACHE_MAX) {
245
- const oldest = cache.keys().next().value;
246
- if (oldest === undefined) break;
247
- cache.delete(oldest);
248
- }
249
- return info;
233
+ matches.push(await resolveRuntime(cwd, def));
250
234
  }
251
- return null;
235
+ return matches;
252
236
  }
253
237
 
254
- export function clearRuntimeCache(): void {
255
- cache.clear();
238
+ async function resolveRuntime(cwd: string, def: RuntimeDef): Promise<RuntimeInfo> {
239
+ const fp = fingerprint(cwd, def);
240
+ const cacheKey = `${cwd}\0${def.name}`;
241
+ const cached = cache.get(cacheKey);
242
+ if (cached && cached.fingerprint === fp) return cached.runtime;
243
+
244
+ const version = await fetchVersion(def, cwd);
245
+ const info: RuntimeInfo = { name: def.name, version };
246
+ cache.set(cacheKey, { fingerprint: fp, runtime: info });
247
+ while (cache.size > CACHE_MAX) {
248
+ const oldest = cache.keys().next().value;
249
+ if (oldest === undefined) break;
250
+ cache.delete(oldest);
251
+ }
252
+ return info;
256
253
  }
@@ -1,17 +1,14 @@
1
1
  export class SessionLifecycle {
2
2
  private current = 0;
3
- private deferred: Array<() => void> = [];
4
3
  private shutDown = false;
5
4
 
6
5
  start(): void {
7
6
  this.current++;
8
7
  this.shutDown = false;
9
- this.flushDeferred();
10
8
  }
11
9
 
12
10
  shutdown(): void {
13
11
  this.shutDown = true;
14
- this.deferred = [];
15
12
  }
16
13
 
17
14
  isCurrent(generation?: number): boolean {
@@ -23,19 +20,4 @@ export class SessionLifecycle {
23
20
  currentGeneration(): number {
24
21
  return this.current;
25
22
  }
26
-
27
- defer(fn: () => void): void {
28
- if (this.shutDown) return;
29
- this.deferred.push(fn);
30
- }
31
-
32
- private flushDeferred(): void {
33
- const pending = this.deferred;
34
- this.deferred = [];
35
- for (const fn of pending) {
36
- try {
37
- fn();
38
- } catch {}
39
- }
40
- }
41
23
  }
package/src/state.test.ts CHANGED
@@ -13,4 +13,4 @@ it("createInitialState starts with a fresh tracker and no done figure", () => {
13
13
  assert.strictEqual(s.tracker.isRunOpen(), false);
14
14
  assert.strictEqual(s.tracker.isWaiting(), false);
15
15
  assert.deepStrictEqual(s.tracker.breakdown(0), { inference: 0, tool: 0, wait: 0, total: 0 });
16
- });
16
+ });
package/src/state.ts CHANGED
@@ -7,7 +7,7 @@ import { formatProviderLabel } from "./utils.ts";
7
7
 
8
8
  export interface FooterState {
9
9
  git: GitStatus;
10
- runtime: RuntimeInfo | null;
10
+ runtime: RuntimeInfo[];
11
11
  sessionStartEpoch: number;
12
12
  /** Frozen active-work total from the last finished run, as today. */
13
13
  lastDoneIn: number | undefined;
@@ -71,7 +71,7 @@ export function invalidateUsageCache(): void {
71
71
  export function createInitialState(): FooterState {
72
72
  return {
73
73
  git: GitStatus.empty(),
74
- runtime: null,
74
+ runtime: [],
75
75
  sessionStartEpoch: Date.now(),
76
76
  lastDoneIn: undefined,
77
77
  tracker: new ActivityTracker(),
@@ -1,4 +1,4 @@
1
- import { afterEach, assert, it } from "@effect/vitest";
1
+ import { assert, it } from "@effect/vitest";
2
2
  import { Effect } from "effect";
3
3
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
4
4
  import {
@@ -1,5 +1,6 @@
1
1
  import { Context, Layer } from "effect";
2
2
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
3
+ import type { Color } from "@earendil-works/pi-tui";
3
4
 
4
5
  /**
5
6
  * A border-tint contribution. `id` stamps the contributor so a later
@@ -10,7 +11,7 @@ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
10
11
  */
11
12
  export interface BorderTintProvider {
12
13
  readonly id: string;
13
- readonly getTint: () => ThemeColor | undefined;
14
+ readonly getTint: () => ThemeColor | Color | undefined;
14
15
  }
15
16
 
16
17
  /**
@@ -33,7 +34,7 @@ export class EditorTintService extends Context.Service<
33
34
  readonly configure: (
34
35
  update: (current: readonly BorderTintProvider[]) => readonly BorderTintProvider[],
35
36
  ) => void;
36
- readonly getTint: () => ThemeColor | undefined;
37
+ readonly getTint: () => ThemeColor | Color | undefined;
37
38
  }
38
39
  >()("tui/editor/EditorTintService") {
39
40
  static readonly layer = Layer.sync(EditorTintService, () => {
package/src/ui/editor.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  type Theme,
7
7
  type ThemeColor,
8
8
  } from "@earendil-works/pi-coding-agent";
9
- import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
9
+ import type { Color, EditorTheme, TUI } from "@earendil-works/pi-tui";
10
10
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
11
  import {
12
12
  inspectAutocompleteInternals,
@@ -23,6 +23,20 @@ import { renderSelection } from "../vim/selection-render.ts";
23
23
  import { type Cursor, type Range, type VimTextModelShape } from "../vim/text-model.ts";
24
24
  import { wordBackward, wordEnd, wordForward } from "../vim/word-motion.ts";
25
25
 
26
+ /** A status indicator embedded in the editor's top border, at two sizes. */
27
+ interface BorderStatus {
28
+ /** Spinner plus message, as pi renders it inside a border. */
29
+ readonly full: string;
30
+ /** Spinner only, for widths where the message does not fit. */
31
+ readonly spinner: string;
32
+ }
33
+
34
+ /** Join defined, non-empty label parts with the house separator. */
35
+ function joinLabel(...parts: Array<string | undefined>): string | undefined {
36
+ const kept = parts.filter((part): part is string => part !== undefined && part.length > 0);
37
+ return kept.length === 0 ? undefined : kept.join(" · ");
38
+ }
39
+
26
40
  /**
27
41
  * Top or bottom border of the editor frame, composed from the shared
28
42
  * {@link buildBoxFrame} model and {@link composeBorderLine} so every box in
@@ -38,17 +52,26 @@ function roundedBorder(
38
52
  paint: (s: string) => string,
39
53
  sourceLine?: string,
40
54
  modeGlyph?: string,
55
+ status?: BorderStatus,
41
56
  ): string {
42
57
  const scrollLabel =
43
58
  sourceLine === undefined ? undefined : stripAnsi(sourceLine).match(/([↑↓]\s+\d+\s+more)/)?.[1];
44
- // The mode glyph and the scroll hint share the border's single label slot;
45
- // join them with the house separator so a narrow editor drops both together.
46
- const label =
47
- modeGlyph === undefined
48
- ? scrollLabel
49
- : scrollLabel === undefined
50
- ? modeGlyph
51
- : `${modeGlyph} · ${scrollLabel}`;
59
+ // An embedded status takes the top border's left segment, like pi's own
60
+ // editor: `╭─ <status> ─────╮`. The status outranks the mode glyph and the
61
+ // scroll hint, and the spinner alone is the last resort before the plain
62
+ // border. Narrow widths therefore keep the status instead of dropping it.
63
+ if (kind === "top" && status !== undefined) {
64
+ const inner = Math.max(0, width - 2);
65
+ const glyph = modeGlyph === undefined || modeGlyph.length === 0 ? "" : `${modeGlyph} · `;
66
+ for (const text of [`${glyph}${status.full}`, `${glyph}${status.spinner}`, status.spinner]) {
67
+ const textWidth = visibleWidth(text);
68
+ const dashes = inner - 2 - textWidth - 1;
69
+ if (textWidth > 0 && dashes >= 0) {
70
+ return paint("╭─ ") + text + paint(` ${"─".repeat(dashes)}`) + paint("╮");
71
+ }
72
+ }
73
+ }
74
+ const label = joinLabel(modeGlyph, scrollLabel);
52
75
  const frame = buildBoxFrame(width, {
53
76
  label,
54
77
  labelWidth: label === undefined ? undefined : visibleWidth(label),
@@ -74,9 +97,9 @@ export interface TuiEditorOptions {
74
97
  * undefined to keep pi's own border color. Generic — the editor has no
75
98
  * notion of what supplied the color.
76
99
  */
77
- readonly getBorderTint?: () => ThemeColor | undefined;
78
- /** Paints a given theme color onto text (e.g. `theme.fg(color, s)`). */
79
- readonly tintPaint?: (color: ThemeColor, s: string) => string;
100
+ readonly getBorderTint?: () => ThemeColor | Color | undefined;
101
+ /** Paints a given theme color onto text (e.g. `theme.style(s, { fg: color })`). */
102
+ readonly tintPaint?: (color: ThemeColor | Color, s: string) => string;
80
103
  /**
81
104
  * Live mode indicator for the top border (e.g. vim's N/I/V letter), or
82
105
  * undefined for none. A thunk so the glyph follows mode changes on every
@@ -95,9 +118,15 @@ export class TuiEditor extends CustomEditor {
95
118
  private readonly boxTheme: Theme;
96
119
  private readonly onAutocompleteMismatch?: (detail: string) => void;
97
120
  private readonly paintSelection: (s: string) => string;
98
- private readonly getBorderTint?: () => ThemeColor | undefined;
99
- private readonly tintPaint?: (color: ThemeColor, s: string) => string;
121
+ private readonly getBorderTint?: () => ThemeColor | Color | undefined;
122
+ private readonly tintPaint?: (color: ThemeColor | Color, s: string) => string;
100
123
  private readonly getModeIndicator?: () => string | undefined;
124
+ /**
125
+ * The status indicator pi embeds in the top border. pi only calls
126
+ * `setWorkingStatusIndicator()` when `embedWorkingStatus` is true, so we
127
+ * capture it to render the house border ourselves.
128
+ */
129
+ private statusIndicator?: Parameters<CustomEditor["setWorkingStatusIndicator"]>[0];
101
130
  /** The modal state machine backing vim; read by the package's tint wiring. */
102
131
  readonly vimState: VimEditorState;
103
132
  private autocompleteDiagnosed = false;
@@ -108,9 +137,10 @@ export class TuiEditor extends CustomEditor {
108
137
  keybindings: KeybindingsManager,
109
138
  options: TuiEditorOptions = {},
110
139
  ) {
111
- super(tui, editorTheme, keybindings, { paddingX: 0 });
140
+ super(tui, editorTheme, keybindings, { paddingX: 0, embedWorkingStatus: true });
112
141
  this.boxTheme = {
113
142
  fg: (_color: ThemeColor, s: string) => this.borderPaint(s),
143
+ style: (s: string) => this.borderPaint(s),
114
144
  } as unknown as Theme;
115
145
  this.onAutocompleteMismatch = options.onAutocompleteMismatch;
116
146
  this.paintSelection = options.paintSelection ?? ((s: string) => s);
@@ -132,6 +162,13 @@ export class TuiEditor extends CustomEditor {
132
162
  super.setPaddingX(0);
133
163
  }
134
164
 
165
+ override setWorkingStatusIndicator(
166
+ indicator: Parameters<CustomEditor["setWorkingStatusIndicator"]>[0],
167
+ ): void {
168
+ this.statusIndicator = indicator;
169
+ super.setWorkingStatusIndicator(indicator);
170
+ }
171
+
135
172
  /**
136
173
  * Validated view of pi's autocomplete internals. When the contract no
137
174
  * longer matches (pi internals changed shape), report once and return
@@ -315,7 +352,16 @@ export class TuiEditor extends CustomEditor {
315
352
  : undefined;
316
353
 
317
354
  const result: string[] = [];
318
- result.push(roundedBorder(width, "top", borderPaint, baseLines[0], this.getModeIndicator?.()));
355
+ const indicator = this.statusIndicator;
356
+ const status: BorderStatus | undefined = indicator
357
+ ? {
358
+ full: indicator.renderInBorder(Math.max(1, width - 5)),
359
+ spinner: indicator.renderSpinnerInBorder(width),
360
+ }
361
+ : undefined;
362
+ result.push(
363
+ roundedBorder(width, "top", borderPaint, baseLines[0], this.getModeIndicator?.(), status),
364
+ );
319
365
 
320
366
  for (let i = 1; i < bottomIdx; i++) {
321
367
  const line = contentLines ? (contentLines[i - 1] ?? "") : (baseLines[i] ?? "");
@@ -362,8 +408,8 @@ export function installEditor(
362
408
  ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => {
363
409
  const editor = new TuiEditor(tui, editorTheme, keybindings, {
364
410
  getVimEnabled: options.getVimEnabled,
365
- // Paints the resolved border tint through the theme's color fg().
366
- tintPaint: (color, s) => ctx.ui.theme.fg(color, s),
411
+ // Paints the resolved border tint through the theme's color style().
412
+ tintPaint: (color, s) => ctx.ui.theme.style(s, { fg: color }),
367
413
  // The editor stays generic: it asks the shared service for a tint and
368
414
  // knows nothing about vim. vim is just one provider registered here.
369
415
  getBorderTint: () => options.tint.getTint(),
@@ -43,7 +43,7 @@ const state: FooterState = {
43
43
  deleted: 0,
44
44
  commit: null,
45
45
  }),
46
- runtime: null,
46
+ runtime: [],
47
47
  sessionStartEpoch: 1_700_000_000_000,
48
48
  lastDoneIn: undefined,
49
49
  tracker: new ActivityTracker(),
@@ -76,6 +76,13 @@ const config: TuiConfig = {
76
76
  stalls: true,
77
77
  cost: true,
78
78
  },
79
+ smartCompaction: {
80
+ enabled: true,
81
+ classifier: null,
82
+ needsContextProbabilityThreshold: 0.5,
83
+ minAnswerConfidence: 0.5,
84
+ maxCandidates: 8,
85
+ },
79
86
  };
80
87
  const getConfig = () => config;
81
88
 
@@ -1,7 +1,8 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { vi } from "vitest";
2
3
  import { Effect, Random } from "effect";
3
4
  import { VERSION, type Theme } from "@earendil-works/pi-coding-agent";
4
- import { HeaderRenderService, installHeader } from "./header.ts";
5
+ import { HeaderRenderService, installHeader, resetScreenClearMemory } from "./header.ts";
5
6
 
6
7
  // Pixel parity: the header must render byte-identically through makeBorderedBox
7
8
  // as it did with its hand-rolled box (captured before the refactor). The tips
@@ -12,6 +13,7 @@ const plainTheme = {
12
13
  fg: (_color: string, text: string) => text,
13
14
  bg: (_color: string, text: string) => text,
14
15
  bold: (text: string) => `*${text}*`,
16
+ style: (text: string) => text,
15
17
  } as unknown as Theme;
16
18
 
17
19
  const pi = {
@@ -243,13 +245,13 @@ it("installHeader registers a closure component at mount and unregisters on clea
243
245
  const cleanup = installHeader(pi, mountCtx);
244
246
 
245
247
  assert.strictEqual(typeof captured, "function");
246
- const componentA = captured!(undefined, plainTheme) as {
248
+ const componentA = captured!({ mode: "fullscreen" }, plainTheme) as {
247
249
  render: (width: number) => string[];
248
250
  };
249
251
  const linesA = componentA.render(80);
250
252
 
251
253
  // Re-mount swaps the slot to a fresh component; both render the header.
252
- const componentB = captured!(undefined, plainTheme) as {
254
+ const componentB = captured!({ mode: "fullscreen" }, plainTheme) as {
253
255
  render: (width: number) => string[];
254
256
  };
255
257
  assert.notStrictEqual(componentA, componentB);
@@ -274,3 +276,48 @@ it("installHeader registers a closure component at mount and unregisters on clea
274
276
  assert.strictEqual(unregistered, true);
275
277
  assert.strictEqual(captured, undefined);
276
278
  });
279
+
280
+ /** Mount context that captures the header factory pi would invoke. */
281
+ const captureMountCtx = (
282
+ onFactory: (factory: ((tui: unknown, theme: unknown) => unknown) | undefined) => void,
283
+ ) =>
284
+ ({
285
+ model: { provider: "anthropic", id: "claude-sonnet-4" },
286
+ cwd: "/projects/pi-mono/packages/tui",
287
+ ui: {
288
+ theme: plainTheme,
289
+ setHeader(factory: ((tui: unknown, theme: unknown) => unknown) | undefined) {
290
+ onFactory(factory);
291
+ },
292
+ },
293
+ }) as never;
294
+
295
+ it("clears the screen once per process, and only in regular mode", () => {
296
+ const originalIsTTY = process.stdout.isTTY;
297
+ Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
298
+ const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
299
+ try {
300
+ resetScreenClearMemory();
301
+ let captured: ((tui: unknown, theme: unknown) => unknown) | undefined;
302
+ const mountCtx = captureMountCtx((factory) => {
303
+ captured = factory;
304
+ });
305
+
306
+ installHeader(pi, mountCtx);
307
+ captured!({ mode: "fullscreen" }, plainTheme);
308
+ assert.strictEqual(write.mock.calls.length, 0, "fullscreen must not clear");
309
+
310
+ captured!({ mode: "regular" }, plainTheme);
311
+ assert.deepStrictEqual(write.mock.calls[0]?.[0], "\x1b[2J\x1b[H");
312
+
313
+ // A reload re-mounts in regular mode while pi-tui still holds the
314
+ // previous lines. The once guard must keep it from writing escape codes
315
+ // behind the renderer's back (the blank-widget regression).
316
+ captured!({ mode: "regular" }, plainTheme);
317
+ assert.strictEqual(write.mock.calls.length, 1, "re-mount must not clear again");
318
+ } finally {
319
+ write.mockRestore();
320
+ Object.defineProperty(process.stdout, "isTTY", { value: originalIsTTY, configurable: true });
321
+ resetScreenClearMemory();
322
+ }
323
+ });
package/src/ui/header.ts CHANGED
@@ -19,6 +19,38 @@ import {
19
19
  pickSlashCommandTips,
20
20
  } from "../utils.ts";
21
21
 
22
+ /**
23
+ * Process-wide flag: the raw screen clear runs at most once per launch.
24
+ * `Symbol.for` keeps the same key across extension module reloads, so a
25
+ * `/reload` re-import does not reset it.
26
+ */
27
+ const SCREEN_CLEARED_KEY = Symbol.for("@ftrdotdev/pi-tui/screen-cleared");
28
+
29
+ type ScreenClearedGlobal = typeof globalThis & { [SCREEN_CLEARED_KEY]?: boolean };
30
+
31
+ /** Test seam: forget that the screen was cleared, so a test can assert it. */
32
+ export function resetScreenClearMemory(): void {
33
+ delete (globalThis as ScreenClearedGlobal)[SCREEN_CLEARED_KEY];
34
+ }
35
+
36
+ /**
37
+ * Clear the visible screen and home the cursor, at most once per process.
38
+ *
39
+ * The write bypasses pi-tui, so it is only safe before the TUI has painted:
40
+ * on the first regular-mode mount, when the screen still holds the shell
41
+ * prompt. Every later mount (reload, new, fork, resume, settings toggle)
42
+ * happens while pi-tui holds the previous lines and its cursor row; clearing
43
+ * then desyncs the differential renderer and leaves regions such as an
44
+ * extension widget blank until the next full repaint.
45
+ */
46
+ function clearVisibleScreenOnce(): void {
47
+ if (!process.stdout.isTTY) return;
48
+ const globals = globalThis as ScreenClearedGlobal;
49
+ if (globals[SCREEN_CLEARED_KEY]) return;
50
+ globals[SCREEN_CLEARED_KEY] = true;
51
+ process.stdout.write("\x1b[2J\x1b[H");
52
+ }
53
+
22
54
  /**
23
55
  * Pi header widget (`setHeader`), framed in the house rounded box.
24
56
  *
@@ -138,7 +170,12 @@ export class HeaderRenderService extends Context.Service<
138
170
  */
139
171
  export function installHeader(pi: ExtensionAPI, ctx: ExtensionContext): () => void {
140
172
  let header: DisposableComponent | undefined;
141
- ctx.ui.setHeader(() => {
173
+ ctx.ui.setHeader((tui) => {
174
+ // Regular mode keeps the terminal's scrollback, so the first mount clears
175
+ // the previous screen. Fullscreen owns the alternate screen, which is
176
+ // already fresh; clearing there only flickers. The once guard keeps a
177
+ // re-mount from desyncing pi-tui's differential renderer.
178
+ if (tui.mode === "regular") clearVisibleScreenOnce();
142
179
  // Re-mount: dispose the previous instance before building the new one.
143
180
  if (header?.dispose) header.dispose();
144
181
  // Build the service layer and run construction synchronously at mount.