@xynogen/pix-pretty 1.37.1 → 1.38.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-pretty",
3
- "version": "1.37.1",
3
+ "version": "1.38.0",
4
4
  "description": "Enhanced tool output rendering with syntax highlighting, file icons, tree views, diff rendering, and FFF search",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -10,6 +10,7 @@
10
10
  "./batch": "./src/batch.ts",
11
11
  "./confirm": "./src/confirm.ts",
12
12
  "./progress": "./src/progress.ts",
13
+ "./overlay-lifecycle": "./src/overlay-lifecycle.ts",
13
14
  "./config": "./src/config.ts",
14
15
  "./diff": "./src/diff.ts",
15
16
  "./diff-render": "./src/diff-render.ts",
@@ -70,7 +71,7 @@
70
71
  "access": "public"
71
72
  },
72
73
  "dependencies": {
73
- "@xynogen/pix-runtime": "^0.17.0",
74
+ "@xynogen/pix-runtime": "^0.18.0",
74
75
  "chalk": "^4.1.2",
75
76
  "cli-highlight": "^2.1.11",
76
77
  "@ff-labs/fff-node": "^0.10.6",
package/src/batch.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  /** Shared batching for read/grep/find/ls — N known targets, one tool result. */
2
2
 
3
+ import { truncateStringToBytes } from "@xynogen/pix-runtime/utf8";
4
+
3
5
  export const BATCH_MAX_TARGETS = 20;
4
6
  export const BATCH_MAX_BYTES = 50 * 1024;
5
7
 
6
8
  const encoder = new TextEncoder();
7
- const decoder = new TextDecoder();
8
9
 
9
10
  /** Merge a singular target with an optional array, trimming and de-duping. */
10
11
  export function resolveBatchStrings(single: string | undefined, many: unknown): string[] {
@@ -97,10 +98,8 @@ function byteLength(text: string): number {
97
98
  }
98
99
 
99
100
  function cutToBytes(text: string, maxBytes: number): string {
100
- const bytes = encoder.encode(text);
101
- if (bytes.length <= maxBytes) return text;
102
- let cut = decoder.decode(bytes.slice(0, maxBytes));
103
- if (cut.endsWith("\uFFFD")) cut = cut.slice(0, -1);
101
+ if (byteLength(text) <= maxBytes) return text;
102
+ const cut = truncateStringToBytes(text, maxBytes);
104
103
  const lastNl = cut.lastIndexOf("\n");
105
104
  return lastNl > 0 ? cut.slice(0, lastNl) : cut;
106
105
  }
@@ -40,32 +40,53 @@ export function commandPreview(
40
40
  }
41
41
  const current = slot;
42
42
  let replacement: string | undefined;
43
+ const text = new Text("", 0, 0);
44
+ let memo:
45
+ | { width: number; styled: string; replacement: string | undefined; lines: string[] }
46
+ | undefined;
47
+ const layout = (width: number): string[] => {
48
+ if (replacement !== undefined) {
49
+ text.setText(replacement);
50
+ return replacement ? text.render(width) : [];
51
+ }
52
+ const separator = theme.fg("muted", " · ");
53
+ if (!code.includes("\n") && visibleWidth(header) + 3 + visibleWidth(code) <= width) {
54
+ text.setText(`${header}${separator}${current.styled}`);
55
+ return text.render(width);
56
+ }
57
+ // ponytail: preserve shell syntax with native wrapping; use a parser only for semantic formatting.
58
+ const padding = " ".repeat(indent);
59
+ const lines = wrapTextWithAnsi(current.styled, Math.max(1, width - indent));
60
+ const shown = expanded ? lines : fadeRowsOf(lines.slice(0, 17), theme, 16);
61
+ return [
62
+ truncateToWidth(`${header}${separator}`, width, "…"),
63
+ ...shown.map((line) => `${padding}${line}`),
64
+ ...(shown.length < lines.length
65
+ ? [
66
+ `${theme.fg("muted", `${padding}… +${lines.length - shown.length} lines `)}${expandHint(theme, ctx)}`,
67
+ ]
68
+ : []),
69
+ ];
70
+ };
43
71
  return {
44
72
  setText(value: string) {
45
73
  replacement = value;
46
74
  },
47
75
  getText: () => replacement ?? `${header}${theme.fg("muted", " · ")}${current.styled}`,
48
- invalidate() {},
76
+ invalidate() {
77
+ memo = undefined;
78
+ text.invalidate();
79
+ },
49
80
  render(width: number): string[] {
50
- if (replacement !== undefined)
51
- return replacement ? new Text(replacement, 0, 0).render(width) : [];
52
- const separator = theme.fg("muted", " · ");
53
- if (!code.includes("\n") && visibleWidth(header) + 3 + visibleWidth(code) <= width) {
54
- return new Text(`${header}${separator}${current.styled}`, 0, 0).render(width);
55
- }
56
- // ponytail: wrap without rewriting shell syntax or quoted strings. Add a shell parser only for semantic formatting.
57
- const padding = " ".repeat(indent);
58
- const lines = wrapTextWithAnsi(current.styled, Math.max(1, width - indent));
59
- const shown = expanded ? lines : fadeRowsOf(lines.slice(0, 17), theme, 16);
60
- return [
61
- truncateToWidth(`${header}${separator}`, width, "…"),
62
- ...shown.map((line) => `${padding}${line}`),
63
- ...(shown.length < lines.length
64
- ? [
65
- `${theme.fg("muted", `${padding}… +${lines.length - shown.length} lines `)}${expandHint(theme, ctx)}`,
66
- ]
67
- : []),
68
- ];
81
+ if (
82
+ memo?.width === width &&
83
+ memo.styled === current.styled &&
84
+ memo.replacement === replacement
85
+ )
86
+ return memo.lines;
87
+ const lines = layout(width);
88
+ memo = { width, styled: current.styled, replacement, lines };
89
+ return lines;
69
90
  },
70
91
  };
71
92
  }
@@ -80,21 +101,35 @@ export function collapsedCommandRow(
80
101
  const prefix = `${header}${theme.fg("muted", " · ")}`;
81
102
  let text = `${prefix}${theme.fg("dim", plain)}`;
82
103
  let replaced = false;
104
+ const replacementText = new Text("", 0, 0);
105
+ let memo: { width: number; text: string; replaced: boolean; lines: string[] } | undefined;
83
106
  return {
84
107
  setText(value: string) {
85
108
  text = value;
86
109
  replaced = true;
87
110
  },
88
111
  getText: () => text,
89
- invalidate() {},
112
+ invalidate() {
113
+ memo = undefined;
114
+ replacementText.invalidate();
115
+ },
90
116
  render(width: number): string[] {
91
- if (replaced) return text ? new Text(text, 0, 0).render(width) : [];
117
+ if (memo?.width === width && memo.text === text && memo.replaced === replaced)
118
+ return memo.lines;
119
+ if (replaced) {
120
+ replacementText.setText(text);
121
+ const lines = text ? replacementText.render(width) : [];
122
+ memo = { width, text, replaced, lines };
123
+ return lines;
124
+ }
92
125
  const room = width - visibleWidth(prefix);
93
- return [
126
+ const lines = [
94
127
  room > 0
95
128
  ? `${prefix}${fadeText(plain, room, fadePaint(theme))}`
96
129
  : truncateToWidth(prefix, width, "…"),
97
130
  ];
131
+ memo = { width, text, replaced, lines };
132
+ return lines;
98
133
  },
99
134
  };
100
135
  }
package/src/confirm.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  selectListTheme,
16
16
  terminalModalHeight,
17
17
  } from "./modal-frame.ts";
18
+ import { createOverlayLifecycle } from "./overlay-lifecycle.ts";
18
19
 
19
20
  // Minimal structural type for the `ctx.ui.custom` host call.
20
21
  interface CustomTheme {
@@ -66,106 +67,110 @@ const COUNTDOWN_WARN_S = 5;
66
67
  /**
67
68
  * Show a Yes/No overlay. Resolves true on confirm, false otherwise.
68
69
  */
69
- export function confirmOverlay(ui: ConfirmUI, opts: ConfirmOptions): Promise<boolean> {
70
+ export async function confirmOverlay(ui: ConfirmUI, opts: ConfirmOptions): Promise<boolean> {
70
71
  const accent = opts.accent ?? "accent";
71
72
  const timeoutMs = opts.timeoutMs ?? 0;
72
73
 
73
- return new Promise((resolve) => {
74
- const controller = new AbortController();
75
- const timer = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : undefined;
76
-
77
- ui.custom<boolean>(
78
- (tui, theme, kb, done) => {
79
- let ticker: ReturnType<typeof setInterval> | undefined;
80
- let countdownLine: string | undefined;
81
- const pager = new ModalPager();
82
-
83
- const choices: SelectItem[] = [
84
- {
85
- value: "yes",
86
- label: opts.confirmLabel ?? "Yes",
87
- description: "Proceed",
88
- },
89
- {
90
- value: "no",
91
- label: opts.denyLabel ?? "No",
92
- description: "Cancel",
93
- },
94
- ];
95
-
96
- const selectList = new SelectList(choices, choices.length, selectListTheme(theme, accent));
97
-
98
- if (timeoutMs > 0) {
99
- const deadlineMs = Date.now() + timeoutMs;
100
- const updateCountdown = () => {
101
- const remaining = Math.max(0, Math.ceil((deadlineMs - Date.now()) / SECOND_MS));
102
- countdownLine =
103
- theme.fg("muted", "Auto-cancel in ") +
104
- theme.fg(remaining <= COUNTDOWN_WARN_S ? accent : "muted", `${remaining}s`);
105
- };
106
- updateCountdown();
107
- ticker = setInterval(() => {
74
+ const lifecycle = createOverlayLifecycle<boolean>();
75
+ const finish = lifecycle.finish;
76
+ try {
77
+ const timer = timeoutMs > 0 ? setTimeout(() => finish(false), timeoutMs) : undefined;
78
+ lifecycle.onCleanup(() => clearTimeout(timer));
79
+ return (
80
+ (await ui.custom<boolean>(
81
+ (tui, theme, kb, done) => {
82
+ let ticker: ReturnType<typeof setInterval> | undefined;
83
+ let countdownLine: string | undefined;
84
+ const pager = new ModalPager();
85
+ lifecycle.onCleanup(() => clearInterval(ticker));
86
+ lifecycle.bind(done);
87
+
88
+ const choices: SelectItem[] = [
89
+ {
90
+ value: "yes",
91
+ label: opts.confirmLabel ?? "Yes",
92
+ description: "Proceed",
93
+ },
94
+ {
95
+ value: "no",
96
+ label: opts.denyLabel ?? "No",
97
+ description: "Cancel",
98
+ },
99
+ ];
100
+
101
+ const selectList = new SelectList(
102
+ choices,
103
+ choices.length,
104
+ selectListTheme(theme, accent),
105
+ );
106
+
107
+ selectList.onSelect = (item) => finish(item.value === "yes");
108
+ selectList.onCancel = () => finish(false);
109
+ if (!lifecycle.closed && timeoutMs > 0) {
110
+ const deadlineMs = Date.now() + timeoutMs;
111
+ const updateCountdown = () => {
112
+ const remaining = Math.max(0, Math.ceil((deadlineMs - Date.now()) / SECOND_MS));
113
+ countdownLine =
114
+ theme.fg("muted", "Auto-cancel in ") +
115
+ theme.fg(remaining <= COUNTDOWN_WARN_S ? accent : "muted", `${remaining}s`);
116
+ };
108
117
  updateCountdown();
109
- tui.requestRender();
110
- }, SECOND_MS);
111
- }
112
-
113
- const finish = (value: boolean) => {
114
- if (timer !== undefined) clearTimeout(timer);
115
- if (ticker !== undefined) clearInterval(ticker);
116
- done(value);
117
- };
118
-
119
- selectList.onSelect = (item) => finish(item.value === "yes");
120
- selectList.onCancel = () => finish(false);
121
- controller.signal.addEventListener("abort", () => finish(false));
122
-
123
- return {
124
- render: (w: number) => {
125
- const mw = modalWidth(w);
126
- const inner = mw - 4;
127
- const footer = [theme.fg("muted", "─".repeat(inner))];
128
- if (countdownLine !== undefined) footer.push(countdownLine);
129
- footer.push(...selectList.render(inner));
130
- footer.push("");
131
- footer.push(
132
- theme.fg("muted", "↑↓ choose • ←→/PgUp/PgDn inspect • enter select • esc cancel"),
133
- );
134
-
135
- const result = frameModal({
136
- width: mw,
137
- maxHeight: terminalModalHeight(tui.terminal?.rows),
138
- minHeight: MIN_PERMISSION_MODAL_HEIGHT,
139
- header: [
140
- theme.fg(accent, theme.bold(opts.icon ? `${opts.icon} ${opts.title}` : opts.title)),
141
- ],
142
- body: (opts.body ?? []).map((line) => theme.fg("text", line)),
143
- footer,
144
- bodyOffset: pager.bodyOffset,
145
- color: (s) => theme.fg(accent, s),
146
- bg: (s) => theme.bg("customMessageBg", s),
147
- fg: (s) => theme.fg("text", s),
148
- overflowLine: ({ page, totalPages }) =>
149
- theme.fg("muted", `←→/PgUp/PgDn inspect • ${page}/${totalPages}`),
150
- });
151
- pager.sync(result);
152
- return result.lines;
153
- },
154
- invalidate: () => {},
155
- handleInput: (data: string) => {
156
- if (pager.handleInput(data, kb, true)) {
118
+ ticker = setInterval(() => {
119
+ updateCountdown();
157
120
  tui.requestRender();
158
- return;
159
- }
160
- selectList.handleInput(data);
161
- tui.requestRender();
162
- },
163
- };
164
- },
165
- { overlay: true, overlayOptions: modalOverlayOptions() },
166
- ).then((result) => {
167
- if (timer !== undefined) clearTimeout(timer);
168
- resolve(result ?? false);
169
- });
170
- });
121
+ }, SECOND_MS);
122
+ }
123
+
124
+ return {
125
+ render: (w: number) => {
126
+ const mw = modalWidth(w);
127
+ const inner = mw - 4;
128
+ const footer = [theme.fg("muted", "─".repeat(inner))];
129
+ if (countdownLine !== undefined) footer.push(countdownLine);
130
+ footer.push(...selectList.render(inner));
131
+ footer.push("");
132
+ footer.push(
133
+ theme.fg("muted", "↑↓ choose • ←→/PgUp/PgDn inspect • enter select • esc cancel"),
134
+ );
135
+
136
+ const result = frameModal({
137
+ width: mw,
138
+ maxHeight: terminalModalHeight(tui.terminal?.rows),
139
+ minHeight: MIN_PERMISSION_MODAL_HEIGHT,
140
+ header: [
141
+ theme.fg(
142
+ accent,
143
+ theme.bold(opts.icon ? `${opts.icon} ${opts.title}` : opts.title),
144
+ ),
145
+ ],
146
+ body: (opts.body ?? []).map((line) => theme.fg("text", line)),
147
+ footer,
148
+ bodyOffset: pager.bodyOffset,
149
+ color: (s) => theme.fg(accent, s),
150
+ bg: (s) => theme.bg("customMessageBg", s),
151
+ fg: (s) => theme.fg("text", s),
152
+ overflowLine: ({ page, totalPages }) =>
153
+ theme.fg("muted", `←→/PgUp/PgDn inspect • ${page}/${totalPages}`),
154
+ });
155
+ pager.sync(result);
156
+ return result.lines;
157
+ },
158
+ invalidate: () => {},
159
+ handleInput: (data: string) => {
160
+ if (lifecycle.closed) return;
161
+ if (pager.handleInput(data, kb, true)) {
162
+ tui.requestRender();
163
+ return;
164
+ }
165
+ selectList.handleInput(data);
166
+ tui.requestRender();
167
+ },
168
+ };
169
+ },
170
+ { overlay: true, overlayOptions: modalOverlayOptions() },
171
+ )) ?? false
172
+ );
173
+ } finally {
174
+ lifecycle.dispose();
175
+ }
171
176
  }
@@ -16,7 +16,8 @@
16
16
  * - Single source of truth for the overlay look across pix-gate, pix-sudo, and pix-ssh.
17
17
  */
18
18
 
19
- import { Input, type SelectItem, SelectList } from "@earendil-works/pi-tui";
19
+ import { Input, matchesKey, type SelectItem, SelectList } from "@earendil-works/pi-tui";
20
+ import { onAbort } from "@xynogen/pix-runtime/abort";
20
21
  import {
21
22
  frameModal,
22
23
  MIN_PERMISSION_MODAL_HEIGHT,
@@ -27,6 +28,7 @@ import {
27
28
  selectListTheme,
28
29
  terminalModalHeight,
29
30
  } from "./modal-frame.ts";
31
+ import { createOverlayLifecycle } from "./overlay-lifecycle.ts";
30
32
 
31
33
  // ── Types ─────────────────────────────────────────────────────────────────────
32
34
 
@@ -49,6 +51,7 @@ export interface OverlayChoice {
49
51
  }
50
52
 
51
53
  interface BaseConfig {
54
+ signal?: AbortSignal;
52
55
  /** Accent colour token (e.g. "error", "warning", "accent"). Default "accent". */
53
56
  accent?: string;
54
57
  /**
@@ -87,7 +90,7 @@ export interface SudoConfig extends BaseConfig {
87
90
  /** Label for the password input hint. Default "Sudo password:" */
88
91
  passwordLabel?: string;
89
92
  /** Validate an entered password without closing the overlay. */
90
- validatePassword?: (password: string) => Promise<boolean>;
93
+ validatePassword?: (password: string, signal?: AbortSignal) => Promise<boolean>;
91
94
  /** Number of validation attempts before closing as exhausted. Default 3. */
92
95
  maxPasswordAttempts?: number;
93
96
  }
@@ -265,168 +268,185 @@ function buildSections(opts: {
265
268
  * if (result.action === "approved") runWithSudo(cmd, result.password!);
266
269
  * ```
267
270
  */
268
- export function showOverlay(ui: OverlayUI, config: OverlayConfig): Promise<OverlayResult> {
271
+ export async function showOverlay(ui: OverlayUI, config: OverlayConfig): Promise<OverlayResult> {
272
+ if (config.signal?.aborted) return Promise.resolve({ action: "denied" });
269
273
  const accent = config.accent ?? "accent";
270
274
  const choices = config.choices ?? DEFAULT_CHOICES;
271
275
  const approveVals = [config.approveValue ?? "yes"].flat();
272
276
 
273
- return new Promise((resolve) => {
274
- ui.custom<OverlayResult>(
275
- (tui, theme, kb, done) => {
276
- const pageKeybindings = asPageKeybindings(kb);
277
- type Stage = "select" | "password";
278
- let stage: Stage = "select";
279
- let countdownLine: string | undefined;
280
- let passwordStatus: string | undefined;
281
- let passwordAttempts = 0;
282
- let validatingPassword = false;
283
- const pager = new ModalPager();
284
-
285
- // Dead-man's-switch timer: counts down only while untouched. The
286
- // first keypress cancels it (user is present → let them decide). If
287
- // it expires with no input, auto-deny so the agent isn't stuck.
288
- const timeoutMs = config.timeoutMs ?? 0;
289
- let remaining = Math.ceil(timeoutMs / 1000);
290
- let timer: ReturnType<typeof setInterval> | undefined;
291
- const cancelTimer = () => {
292
- if (timer) clearInterval(timer);
293
- timer = undefined;
294
- countdownLine = undefined;
295
- };
296
-
297
- // ── components ──────────────────────────────────────────────────
298
- const selectItems: SelectItem[] = choices.map((c) => ({
299
- value: c.value,
300
- label: c.label,
301
- description: c.description,
302
- }));
303
-
304
- const selectList = new SelectList(
305
- selectItems,
306
- selectItems.length,
307
- selectListTheme(theme, accent),
308
- );
309
- const maskedInput = new MaskedInput();
310
-
311
- // ── finish ───────────────────────────────────────────────────────
312
- const finish = (result: OverlayResult) => {
313
- cancelTimer();
314
- done(result);
315
- };
316
-
317
- // Arm the dead-man's switch (only when a timeout was requested).
318
- if (timeoutMs > 0) {
319
- const urgencyColor = (s: number): string =>
320
- s <= 5 ? "error" : s <= 15 ? "warning" : "muted";
321
- const countdownText = (s: number): string => {
322
- const color = urgencyColor(s);
323
- const text = `auto-deny in ${s}s`;
324
- return s <= 5 ? theme.bold(theme.fg(color, text)) : theme.fg(color, text);
277
+ const lifecycle = createOverlayLifecycle<OverlayResult>();
278
+ const finish = lifecycle.finish;
279
+ try {
280
+ return (
281
+ (await ui.custom<OverlayResult>(
282
+ (tui, theme, kb, done) => {
283
+ const pageKeybindings = asPageKeybindings(kb);
284
+ type Stage = "select" | "password";
285
+ let stage: Stage = "select";
286
+ const validation = new AbortController();
287
+ let countdownLine: string | undefined;
288
+ let passwordStatus: string | undefined;
289
+ let passwordAttempts = 0;
290
+ let validatingPassword = false;
291
+ const pager = new ModalPager();
292
+
293
+ // Dead-man's-switch timer: counts down only while untouched. The
294
+ // first keypress cancels it (user is present → let them decide). If
295
+ // it expires with no input, auto-deny so the agent isn't stuck.
296
+ const timeoutMs = config.timeoutMs ?? 0;
297
+ let remaining = Math.ceil(timeoutMs / 1000);
298
+ let timer: ReturnType<typeof setInterval> | undefined;
299
+ const cancelTimer = () => {
300
+ if (timer) clearInterval(timer);
301
+ timer = undefined;
302
+ countdownLine = undefined;
325
303
  };
326
- countdownLine = countdownText(remaining);
327
- timer = setInterval(() => {
328
- remaining -= 1;
329
- if (remaining <= 0) {
330
- finish({ action: "timeout" });
331
- return;
332
- }
333
- countdownLine = countdownText(remaining);
334
- tui.requestRender();
335
- }, 1000);
336
- }
337
-
338
- // ── event wiring ─────────────────────────────────────────────────
339
- selectList.onSelect = (item) => {
340
- if (!approveVals.includes(item.value)) {
341
- finish({ action: "denied", choice: item.value });
342
- } else if (config.mode === "sudo") {
343
- stage = "password";
344
- tui.requestRender();
345
- } else {
346
- finish({ action: "approved", choice: item.value });
347
- }
348
- };
349
- selectList.onCancel = () => finish({ action: "denied" });
350
304
 
351
- maskedInput.onSubmit = async (pw) => {
352
- if (config.mode !== "sudo" || !config.validatePassword) {
353
- finish({ action: "approved", password: pw });
354
- return;
355
- }
356
- if (!pw.trim() || validatingPassword) return;
357
-
358
- validatingPassword = true;
359
- passwordStatus = "Checking password…";
360
- tui.requestRender();
361
- const valid = await config.validatePassword(pw);
362
- validatingPassword = false;
363
- if (valid) {
364
- finish({ action: "approved", password: pw });
365
- return;
305
+ // ── components ──────────────────────────────────────────────────
306
+ const selectItems: SelectItem[] = choices.map((c) => ({
307
+ value: c.value,
308
+ label: c.label,
309
+ description: c.description,
310
+ }));
311
+
312
+ const selectList = new SelectList(
313
+ selectItems,
314
+ selectItems.length,
315
+ selectListTheme(theme, accent),
316
+ );
317
+ const maskedInput = new MaskedInput();
318
+
319
+ lifecycle.onCleanup(cancelTimer);
320
+ lifecycle.onCleanup(() => validation.abort());
321
+ lifecycle.bind(done);
322
+ lifecycle.onCleanup(onAbort(config.signal, () => finish({ action: "denied" })));
323
+
324
+ // Arm the dead-man's switch (only when a timeout was requested).
325
+ if (!lifecycle.closed && timeoutMs > 0) {
326
+ const urgencyColor = (s: number): string =>
327
+ s <= 5 ? "error" : s <= 15 ? "warning" : "muted";
328
+ const countdownText = (s: number): string => {
329
+ const color = urgencyColor(s);
330
+ const text = `auto-deny in ${s}s`;
331
+ return s <= 5 ? theme.bold(theme.fg(color, text)) : theme.fg(color, text);
332
+ };
333
+ countdownLine = countdownText(remaining);
334
+ timer = setInterval(() => {
335
+ remaining -= 1;
336
+ if (remaining <= 0) {
337
+ finish({ action: "timeout" });
338
+ return;
339
+ }
340
+ countdownLine = countdownText(remaining);
341
+ tui.requestRender();
342
+ }, 1000);
366
343
  }
367
344
 
368
- passwordAttempts += 1;
369
- const maxAttempts = config.maxPasswordAttempts ?? 3;
370
- if (passwordAttempts >= maxAttempts) {
371
- // Fail closed: a caller that ignores the flag must not run anything.
372
- finish({ action: "denied", passwordAttemptsExhausted: true });
373
- return;
374
- }
375
- maskedInput.setValue("");
376
- passwordStatus = `Incorrect password — attempt ${passwordAttempts} of ${maxAttempts}`;
377
- tui.requestRender();
378
- };
379
- maskedInput.onEscape = () => {
380
- if (!validatingPassword) finish({ action: "denied" });
381
- };
382
-
383
- // ── component interface ──────────────────────────────────────────
384
- return {
385
- render: (w) => {
386
- const mw = modalWidth(w);
387
- const sections = buildSections({
388
- theme,
389
- accent,
390
- config,
391
- stage,
392
- selectList,
393
- maskedInput,
394
- countdownLine,
395
- passwordStatus,
396
- width: mw,
397
- });
398
- const result = frameModal({
399
- width: mw,
400
- maxHeight: terminalModalHeight(tui.terminal?.rows),
401
- minHeight: MIN_PERMISSION_MODAL_HEIGHT,
402
- ...sections,
403
- bodyOffset: pager.bodyOffset,
404
- color: (s) => theme.fg(accent, s),
405
- bg: (s) => theme.bg("customMessageBg", s),
406
- fg: (s) => theme.fg("text", s),
407
- overflowLine: ({ page, totalPages }) =>
408
- theme.fg("muted", `←→/PgUp/PgDn inspect • ${page}/${totalPages}`),
409
- });
410
- pager.sync(result);
411
- return result.lines;
412
- },
413
- invalidate: () => {},
414
- handleInput: (data) => {
415
- cancelTimer(); // user is present — stop the auto-deny countdown
416
- if (validatingPassword) return;
417
- if (pager.handleInput(data, pageKeybindings, true)) {
345
+ // ── event wiring ─────────────────────────────────────────────────
346
+ selectList.onSelect = (item) => {
347
+ if (!approveVals.includes(item.value)) {
348
+ finish({ action: "denied", choice: item.value });
349
+ } else if (config.mode === "sudo") {
350
+ stage = "password";
418
351
  tui.requestRender();
352
+ } else {
353
+ finish({ action: "approved", choice: item.value });
354
+ }
355
+ };
356
+ selectList.onCancel = () => finish({ action: "denied" });
357
+
358
+ maskedInput.onSubmit = async (pw) => {
359
+ if (config.mode !== "sudo" || !config.validatePassword) {
360
+ finish({ action: "approved", password: pw });
419
361
  return;
420
362
  }
421
- if (stage === "select") selectList.handleInput(data);
422
- else maskedInput.handleInput(data);
363
+ if (!pw.trim() || validatingPassword) return;
364
+
365
+ validatingPassword = true;
366
+ passwordStatus = "Checking password…";
423
367
  tui.requestRender();
424
- },
425
- };
426
- },
427
- { overlay: true, overlayOptions: modalOverlayOptions() },
428
- ).then((result) => {
429
- resolve(result ?? { action: "denied" });
430
- });
431
- });
368
+ let valid: boolean;
369
+ try {
370
+ valid = await config.validatePassword(pw, validation.signal);
371
+ } catch {
372
+ finish({ action: "denied" });
373
+ return;
374
+ }
375
+ if (lifecycle.closed) return;
376
+ validatingPassword = false;
377
+ if (valid) {
378
+ finish({ action: "approved", password: pw });
379
+ return;
380
+ }
381
+
382
+ passwordAttempts += 1;
383
+ const maxAttempts = config.maxPasswordAttempts ?? 3;
384
+ if (passwordAttempts >= maxAttempts) {
385
+ // Fail closed: a caller that ignores the flag must not run anything.
386
+ finish({ action: "denied", passwordAttemptsExhausted: true });
387
+ return;
388
+ }
389
+ maskedInput.setValue("");
390
+ passwordStatus = `Incorrect password — attempt ${passwordAttempts} of ${maxAttempts}`;
391
+ tui.requestRender();
392
+ };
393
+ maskedInput.onEscape = () => {
394
+ finish({ action: "denied" });
395
+ };
396
+
397
+ // ── component interface ──────────────────────────────────────────
398
+ return {
399
+ render: (w) => {
400
+ const mw = modalWidth(w);
401
+ const sections = buildSections({
402
+ theme,
403
+ accent,
404
+ config,
405
+ stage,
406
+ selectList,
407
+ maskedInput,
408
+ countdownLine,
409
+ passwordStatus,
410
+ width: mw,
411
+ });
412
+ const result = frameModal({
413
+ width: mw,
414
+ maxHeight: terminalModalHeight(tui.terminal?.rows),
415
+ minHeight: MIN_PERMISSION_MODAL_HEIGHT,
416
+ ...sections,
417
+ bodyOffset: pager.bodyOffset,
418
+ color: (s) => theme.fg(accent, s),
419
+ bg: (s) => theme.bg("customMessageBg", s),
420
+ fg: (s) => theme.fg("text", s),
421
+ overflowLine: ({ page, totalPages }) =>
422
+ theme.fg("muted", `←→/PgUp/PgDn inspect • ${page}/${totalPages}`),
423
+ });
424
+ pager.sync(result);
425
+ return result.lines;
426
+ },
427
+ invalidate: () => {},
428
+ handleInput: (data) => {
429
+ if (lifecycle.closed) return;
430
+ if (matchesKey(data, "escape")) {
431
+ finish({ action: "denied" });
432
+ return;
433
+ }
434
+ cancelTimer(); // user is present — stop the auto-deny countdown
435
+ if (validatingPassword) return;
436
+ if (pager.handleInput(data, pageKeybindings, true)) {
437
+ tui.requestRender();
438
+ return;
439
+ }
440
+ if (stage === "select") selectList.handleInput(data);
441
+ else maskedInput.handleInput(data);
442
+ tui.requestRender();
443
+ },
444
+ };
445
+ },
446
+ { overlay: true, overlayOptions: modalOverlayOptions() },
447
+ )) ?? { action: "denied" }
448
+ );
449
+ } finally {
450
+ lifecycle.dispose();
451
+ }
432
452
  }
@@ -19,10 +19,11 @@ export interface ExecuteCtx {
19
19
  const INSTALL_TIMEOUT_MS = 60_000;
20
20
 
21
21
  /** Build a consent function that asks once per grammar package. */
22
- export function grammarConsent(ctx?: ExecuteCtx): ConsentFn | undefined {
22
+ export function grammarConsent(ctx?: ExecuteCtx, signal?: AbortSignal): ConsentFn | undefined {
23
23
  if (!ctx?.hasUI) return undefined;
24
24
  return async (pkg: string): Promise<boolean> => {
25
25
  const result = await showOverlay(ctx.ui, {
26
+ signal,
26
27
  mode: "confirm",
27
28
  title: "Install ast-grep grammar",
28
29
  body: [
@@ -39,6 +40,7 @@ export function grammarConsent(ctx?: ExecuteCtx): ConsentFn | undefined {
39
40
  { value: "no", label: "Skip", description: "Do not install; skip this language" },
40
41
  ],
41
42
  });
43
+ signal?.throwIfAborted();
42
44
  return result.action === "approved";
43
45
  };
44
46
  }
@@ -32,6 +32,7 @@ const PRETTY_CATALOG = {
32
32
  // ── agent mode (pix-core plan mode, footer) ───────────────────────────
33
33
  "mode.plan": { nerd: "\u{F034D}", unicode: `\u2630${VS}`, ascii: "P" },
34
34
  "mode.normal": { nerd: "\u{F0174}", unicode: `\u276F${VS}`, ascii: ">" },
35
+ "mode.nuclear": { nerd: "\u{F135}", unicode: "\u{1F680}", ascii: "^" },
35
36
  // ── model kind (pix-models picker) ─────────────────────────────────────
36
37
  "model.classifier": { nerd: "\u{F05D1}", unicode: `\u2696${VS}`, ascii: "C" },
37
38
  // ── steering hint (pix-nudge cards): advice, not a warning — keep it off `⚠` ──
@@ -0,0 +1,34 @@
1
+ import { onAbort } from "@xynogen/pix-runtime/abort";
2
+
3
+ /** Overlay lifetime with exactly-once completion; UI policy and timers stay with each component. */
4
+ export function createOverlayLifecycle<T>() {
5
+ const controller = new AbortController();
6
+ let done: ((value: T) => void) | undefined;
7
+ let result: { value: T } | undefined;
8
+ let notified = false;
9
+ const notify = () => {
10
+ if (!done || !result || notified) return;
11
+ notified = true;
12
+ done(result.value);
13
+ };
14
+ const dispose = () => controller.abort();
15
+ return {
16
+ get closed() {
17
+ return controller.signal.aborted;
18
+ },
19
+ onCleanup(cleanup: () => void) {
20
+ onAbort(controller.signal, cleanup);
21
+ },
22
+ bind(callback: (value: T) => void) {
23
+ done = callback;
24
+ notify();
25
+ },
26
+ finish(value: T) {
27
+ if (controller.signal.aborted) return;
28
+ result = { value };
29
+ dispose();
30
+ notify();
31
+ },
32
+ dispose,
33
+ };
34
+ }
package/src/progress.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  modalWidth,
21
21
  terminalModalHeight,
22
22
  } from "./modal-frame.ts";
23
+ import { createOverlayLifecycle } from "./overlay-lifecycle.ts";
23
24
  import { SPINNER } from "./widget-format.ts";
24
25
 
25
26
  interface ProgressTheme {
@@ -49,8 +50,8 @@ export interface ProgressUI {
49
50
  export interface ProgressHandle {
50
51
  /** Update the status line shown under the title. */
51
52
  setLabel(label: string): void;
52
- /** Close the overlay and release input ownership. */
53
- close(): void;
53
+ /** Close the overlay, release input ownership, and propagate any host UI failure. */
54
+ close(): Promise<void>;
54
55
  }
55
56
 
56
57
  // 120ms: smooth enough to read as motion, slow enough to barely touch the
@@ -63,51 +64,63 @@ const SPINNER_INTERVAL_MS = 120;
63
64
  */
64
65
  export function openProgress(ui: ProgressUI, title: string, accent = "accent"): ProgressHandle {
65
66
  let setLabelImpl: (label: string) => void = () => {};
66
- let closeImpl: () => void = () => {};
67
+ const lifecycle = createOverlayLifecycle<void>();
68
+ let pending: Promise<void>;
69
+ try {
70
+ pending = ui
71
+ .custom<void>(
72
+ (tui, theme, _kb, done) => {
73
+ let frame = 0;
74
+ let labelValue = "Working…";
75
+ lifecycle.bind(done);
67
76
 
68
- ui.custom<void>(
69
- (tui, theme, _kb, done) => {
70
- let frame = 0;
71
- let labelValue = "Working…";
77
+ const ticker = setInterval(() => {
78
+ frame = (frame + 1) % SPINNER.length;
79
+ if (lifecycle.closed) return;
80
+ tui.requestRender();
81
+ }, SPINNER_INTERVAL_MS);
82
+ lifecycle.onCleanup(() => clearInterval(ticker));
72
83
 
73
- const ticker = setInterval(() => {
74
- frame = (frame + 1) % SPINNER.length;
75
- tui.requestRender();
76
- }, SPINNER_INTERVAL_MS);
84
+ setLabelImpl = (label: string) => {
85
+ if (lifecycle.closed) return;
86
+ labelValue = label;
87
+ tui.requestRender();
88
+ };
77
89
 
78
- setLabelImpl = (label: string) => {
79
- labelValue = label;
80
- tui.requestRender();
81
- };
82
- closeImpl = () => {
83
- clearInterval(ticker);
84
- done();
85
- };
86
-
87
- return {
88
- render: (w: number) => {
89
- const mw = modalWidth(w);
90
- return frameModal({
91
- width: mw,
92
- maxHeight: terminalModalHeight(tui.terminal?.rows),
93
- minHeight: MIN_MODAL_HEIGHT,
94
- header: [theme.fg(accent, theme.bold(title))],
95
- body: [`${theme.fg(accent, SPINNER[frame] ?? "")} ${theme.fg("dim", labelValue)}`],
96
- color: (s) => theme.fg(accent, s),
97
- bg: (s) => theme.bg("customMessageBg", s),
98
- }).lines;
90
+ return {
91
+ render: (w: number) => {
92
+ const mw = modalWidth(w);
93
+ return frameModal({
94
+ width: mw,
95
+ maxHeight: terminalModalHeight(tui.terminal?.rows),
96
+ minHeight: MIN_MODAL_HEIGHT,
97
+ header: [theme.fg(accent, theme.bold(title))],
98
+ body: [`${theme.fg(accent, SPINNER[frame] ?? "")} ${theme.fg("dim", labelValue)}`],
99
+ color: (s) => theme.fg(accent, s),
100
+ bg: (s) => theme.bg("customMessageBg", s),
101
+ }).lines;
102
+ },
103
+ invalidate: () => {},
104
+ // Swallow every keystroke: a focused overlay owns input, so nothing
105
+ // reaches the editor while the update runs.
106
+ handleInput: () => {},
107
+ };
99
108
  },
100
- invalidate: () => {},
101
- // Swallow every keystroke: a focused overlay owns input, so nothing
102
- // reaches the editor while the update runs.
103
- handleInput: () => {},
104
- };
105
- },
106
- { overlay: true, overlayOptions: modalOverlayOptions() },
107
- );
109
+ { overlay: true, overlayOptions: modalOverlayOptions() },
110
+ )
111
+ .finally(lifecycle.dispose);
112
+ } catch (error) {
113
+ lifecycle.dispose();
114
+ throw error;
115
+ }
116
+ // Observe early UI failures until the owner awaits close() in its finally block.
117
+ void pending.catch(() => {});
108
118
 
109
119
  return {
110
120
  setLabel: (label) => setLabelImpl(label),
111
- close: () => closeImpl(),
121
+ close: async () => {
122
+ lifecycle.finish();
123
+ await pending;
124
+ },
112
125
  };
113
126
  }