@bismawy/pi-arnative 0.8.1 → 0.9.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/CHANGELOG.md +92 -63
- package/README.md +52 -83
- package/extensions/arnative.ts +27 -4
- package/extensions/autocompact.ts +1 -1
- package/extensions/footer.ts +14 -10
- package/extensions/section-headers.ts +132 -51
- package/extensions/timestamps.ts +12 -11
- package/extensions/todos.ts +489 -0
- package/extensions/tools.ts +419 -127
- package/extensions/ui-render-tweaks.ts +34 -45
- package/lib/box.ts +77 -12
- package/lib/list-picker.ts +0 -3
- package/lib/patch.ts +87 -0
- package/lib/preset-store.ts +83 -4
- package/lib/shortcuts.ts +8 -0
- package/lib/spinner.ts +1 -1
- package/lib/todos.ts +473 -0
- package/package.json +3 -3
|
@@ -43,6 +43,7 @@ import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf, softSec
|
|
|
43
43
|
import { assert, isMain } from "../lib/check.ts";
|
|
44
44
|
import { contrast, oklchToRgb, parseOklch, toHex } from "../lib/color.ts";
|
|
45
45
|
import { expandKeyName } from "../lib/format.ts";
|
|
46
|
+
import { patchOnce } from "../lib/patch.ts";
|
|
46
47
|
|
|
47
48
|
type ActiveTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null;
|
|
48
49
|
const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
|
|
@@ -68,16 +69,15 @@ export function shouldHideReloadBox(lines: readonly string[]): boolean {
|
|
|
68
69
|
const rows = lines.map((l) => stripAnsi(l).trim());
|
|
69
70
|
return rows.every((r) => r === "" || /^[─-]+$/.test(r) || RELOAD_TEXT.includes(r));
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
72
|
+
// Every patch below reinstalls on each load (lib/patch.ts): `/reload` re-evaluates the
|
|
73
|
+
// module in the same process, so a `globalThis` guard would freeze the first load.
|
|
74
|
+
if (UserMessageComponent?.prototype) {
|
|
74
75
|
const containerProto = Object.getPrototypeOf(UserMessageComponent.prototype) as { render?: (width: number) => string[] };
|
|
75
76
|
if (typeof containerProto?.render === "function") {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const lines = origContainerRender.call(this, width);
|
|
77
|
+
patchOnce(containerProto, "render", (orig) => function (this: any, width: number): string[] {
|
|
78
|
+
const lines = orig.call(this, width);
|
|
79
79
|
return shouldHideReloadBox(lines) ? [] : lines;
|
|
80
|
-
};
|
|
80
|
+
});
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -86,7 +86,6 @@ if (UserMessageComponent?.prototype && !(globalThis as Record<symbol, boolean>)[
|
|
|
86
86
|
// Drag selection in pi fullscreen: pi only wraps the selection in reverse video
|
|
87
87
|
// (\x1b[7m), unreadable in some terminals/themes. Replaced with explicit colors
|
|
88
88
|
// (bg selectedBg + fg text) so text always stays visible.
|
|
89
|
-
const SELECTION_COLOR_KEY = Symbol.for("pi-arnative.selectionColorsPatched");
|
|
90
89
|
|
|
91
90
|
export function recolorSelection(highlighted: string, fgOpen: string, bgOpen: string): string {
|
|
92
91
|
return highlighted.split("\x1b[7m").join(fgOpen + bgOpen).split("\x1b[27m").join("\x1b[39m\x1b[49m");
|
|
@@ -107,7 +106,6 @@ export function ansiFgOpen(th: { fg?(c: string, t: string): string } | null, col
|
|
|
107
106
|
// (grey) -> accent bg + darkened canvas text (contrast 9.6:1, WCAG AA). pi has no bg
|
|
108
107
|
// token for `accent` (7 exist, see PILL_INK), so the SGR escapes are swapped;
|
|
109
108
|
// `bg("accent")` would throw "Unknown theme background color" and stay unchanged.
|
|
110
|
-
const PILL_KEY = Symbol.for("pi-arnative.accentPill");
|
|
111
109
|
const PILL_MARK = "↓ Jump to latest message";
|
|
112
110
|
const PILL_INK = "toolPendingBg";
|
|
113
111
|
|
|
@@ -143,41 +141,37 @@ export function withAccentPill<T>(
|
|
|
143
141
|
}
|
|
144
142
|
}
|
|
145
143
|
|
|
146
|
-
if (TuiAltScreen?.prototype
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const highlighted = origHighlight.call(this, text);
|
|
144
|
+
if (TuiAltScreen?.prototype) {
|
|
145
|
+
const proto = TuiAltScreen.prototype as any;
|
|
146
|
+
if (typeof proto.applySelectionHighlight === "function") {
|
|
147
|
+
patchOnce(proto, "applySelectionHighlight", (orig) => function (this: any, text: string): string {
|
|
148
|
+
const highlighted = orig.call(this, text);
|
|
152
149
|
const fgOpen = ansiFgOpen(activeTheme());
|
|
153
150
|
const bgOpen = ansiBgOpen(activeTheme(), "selectedBg");
|
|
154
151
|
return fgOpen && bgOpen ? recolorSelection(highlighted, fgOpen, bgOpen) : highlighted;
|
|
155
|
-
};
|
|
152
|
+
});
|
|
156
153
|
}
|
|
157
154
|
}
|
|
158
155
|
|
|
159
|
-
if (TuiAltScreen?.prototype
|
|
160
|
-
(globalThis as Record<symbol, boolean>)[PILL_KEY] = true;
|
|
156
|
+
if (TuiAltScreen?.prototype) {
|
|
161
157
|
const proto = TuiAltScreen.prototype as unknown as {
|
|
162
158
|
compositeScrollToEndIndicator?: (screen: string[], layout: unknown, width: number) => string[];
|
|
163
159
|
};
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
proto.compositeScrollToEndIndicator = function (
|
|
160
|
+
if (typeof proto.compositeScrollToEndIndicator === "function") {
|
|
161
|
+
patchOnce(proto, "compositeScrollToEndIndicator", (origComposite) => function (
|
|
167
162
|
this: { scrollToEndIndicator?: (() => string) | undefined },
|
|
168
163
|
screen: string[],
|
|
169
164
|
layout: unknown,
|
|
170
165
|
width: number,
|
|
171
166
|
) {
|
|
172
167
|
return withAccentPill(this, () => origComposite.call(this, screen, layout, width), activeTheme());
|
|
173
|
-
};
|
|
168
|
+
});
|
|
174
169
|
}
|
|
175
170
|
}
|
|
176
171
|
|
|
177
172
|
// 6. Select menus (ctx.ui.select -> ExtensionSelectorComponent.updateList): pi colors the
|
|
178
173
|
// whole selected row accent. Arnative keeps accent on the `→` marker and `·` separators
|
|
179
174
|
// and moves the selected text to soft (accent on themes without the token).
|
|
180
|
-
const SELECT_ROW_KEY = Symbol.for("pi-arnative.selectRowColors");
|
|
181
175
|
|
|
182
176
|
/** Selected row body: `·` separators accent, the text around them soft. */
|
|
183
177
|
export function selectRowText(row: string, th: { fg(c: string, t: string): string }): string {
|
|
@@ -188,16 +182,14 @@ export function selectRowText(row: string, th: { fg(c: string, t: string): strin
|
|
|
188
182
|
.join(th.fg("accent", "·"));
|
|
189
183
|
}
|
|
190
184
|
|
|
191
|
-
if (ExtensionSelectorComponent?.prototype
|
|
192
|
-
(globalThis as Record<symbol, boolean>)[SELECT_ROW_KEY] = true;
|
|
185
|
+
if (ExtensionSelectorComponent?.prototype) {
|
|
193
186
|
const proto = ExtensionSelectorComponent.prototype as unknown as {
|
|
194
187
|
options: string[];
|
|
195
188
|
selectedIndex: number;
|
|
196
189
|
listContainer: { clear(): void; addChild(c: unknown): void };
|
|
197
190
|
updateList(): void;
|
|
198
191
|
};
|
|
199
|
-
|
|
200
|
-
proto.updateList = function (this: typeof proto) {
|
|
192
|
+
patchOnce(proto, "updateList", (origUpdateList) => function (this: typeof proto) {
|
|
201
193
|
const th = activeTheme();
|
|
202
194
|
if (!th) return origUpdateList.call(this); // no theme yet -> pi's default
|
|
203
195
|
this.listContainer.clear();
|
|
@@ -208,7 +200,7 @@ if (ExtensionSelectorComponent?.prototype && !(globalThis as Record<symbol, bool
|
|
|
208
200
|
: ` ${th.fg("text", this.options[i]!)}`;
|
|
209
201
|
this.listContainer.addChild(new Text(text, 1, 0));
|
|
210
202
|
}
|
|
211
|
-
};
|
|
203
|
+
});
|
|
212
204
|
}
|
|
213
205
|
|
|
214
206
|
export default function uiRenderTweaks(pi: ExtensionAPI) {
|
|
@@ -255,13 +247,11 @@ export class PackageUpdateBoxComponent implements Component {
|
|
|
255
247
|
}
|
|
256
248
|
}
|
|
257
249
|
|
|
258
|
-
|
|
259
|
-
if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[PACKAGE_BOX_KEY]) {
|
|
260
|
-
(globalThis as Record<symbol, boolean>)[PACKAGE_BOX_KEY] = true;
|
|
250
|
+
if (InteractiveMode?.prototype) {
|
|
261
251
|
const proto = InteractiveMode.prototype as unknown as {
|
|
262
252
|
showPackageUpdateNotification(packages: string[]): void;
|
|
263
253
|
};
|
|
264
|
-
proto
|
|
254
|
+
patchOnce(proto, "showPackageUpdateNotification", () => function (this: typeof proto, packages: string[]) {
|
|
265
255
|
const self = this as unknown as {
|
|
266
256
|
chatContainer: { addChild(c: unknown): void };
|
|
267
257
|
ui: { requestRender(): void };
|
|
@@ -269,7 +259,7 @@ if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[PACKA
|
|
|
269
259
|
self.chatContainer.addChild(new Spacer(1));
|
|
270
260
|
self.chatContainer.addChild(new PackageUpdateBoxComponent(packages, activeTheme()));
|
|
271
261
|
self.ui.requestRender();
|
|
272
|
-
};
|
|
262
|
+
});
|
|
273
263
|
}
|
|
274
264
|
|
|
275
265
|
// arnative box border helper -> lib/box.ts (one definition for every box)
|
|
@@ -278,14 +268,16 @@ if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[PACKA
|
|
|
278
268
|
// array into unstyled `Text`, so an extension's status line ignores the theme and lands in
|
|
279
269
|
// the default foreground. Every such array is handed to a component factory instead, which
|
|
280
270
|
// receives the live theme: the arnative mark leads the block and every row is `dim`.
|
|
281
|
-
|
|
282
|
-
if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[STATUS_WIDGET_KEY]) {
|
|
283
|
-
(globalThis as Record<symbol, boolean>)[STATUS_WIDGET_KEY] = true;
|
|
271
|
+
if (InteractiveMode?.prototype) {
|
|
284
272
|
const proto = InteractiveMode.prototype as unknown as {
|
|
285
273
|
setExtensionWidget(key: string, content: unknown, options?: { placement?: string }): void;
|
|
286
274
|
};
|
|
287
|
-
|
|
288
|
-
|
|
275
|
+
patchOnce(proto, "setExtensionWidget", (origSetWidget) => function (
|
|
276
|
+
this: typeof proto,
|
|
277
|
+
key: string,
|
|
278
|
+
content: unknown,
|
|
279
|
+
options?: { placement?: string },
|
|
280
|
+
) {
|
|
289
281
|
if (Array.isArray(content) && content.every((line) => typeof line === "string")) {
|
|
290
282
|
const rows = content as string[];
|
|
291
283
|
content = (_tui: unknown, th: Parameters<typeof statusRows>[0]) => ({
|
|
@@ -301,7 +293,7 @@ if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[STATU
|
|
|
301
293
|
});
|
|
302
294
|
}
|
|
303
295
|
return origSetWidget.call(this, key, content, options);
|
|
304
|
-
};
|
|
296
|
+
});
|
|
305
297
|
}
|
|
306
298
|
|
|
307
299
|
export class JevReviewBoxComponent implements Component {
|
|
@@ -367,12 +359,9 @@ export function customMessageText(content: unknown): string {
|
|
|
367
359
|
return "";
|
|
368
360
|
}
|
|
369
361
|
|
|
370
|
-
|
|
371
|
-
if (CompactionSummaryMessageComponent?.prototype && !(globalThis as Record<symbol, boolean>)[COMPACTION_KEY]) {
|
|
372
|
-
(globalThis as Record<symbol, boolean>)[COMPACTION_KEY] = true;
|
|
362
|
+
if (CompactionSummaryMessageComponent?.prototype) {
|
|
373
363
|
const proto = CompactionSummaryMessageComponent.prototype as any;
|
|
374
|
-
|
|
375
|
-
proto.updateDisplay = function (): void {
|
|
364
|
+
patchOnce(proto, "updateDisplay", (origUpdateDisplay) => function (this: any): void {
|
|
376
365
|
const th = activeTheme();
|
|
377
366
|
if (!th) return origUpdateDisplay.call(this);
|
|
378
367
|
const message = this.message as { tokensBefore?: number; summary?: string } | undefined;
|
|
@@ -401,7 +390,7 @@ if (CompactionSummaryMessageComponent?.prototype && !(globalThis as Record<symbo
|
|
|
401
390
|
return { handled: true };
|
|
402
391
|
}),
|
|
403
392
|
);
|
|
404
|
-
};
|
|
393
|
+
});
|
|
405
394
|
}
|
|
406
395
|
|
|
407
396
|
// Self-check: `node extensions/ui-render-tweaks.ts`
|
package/lib/box.ts
CHANGED
|
@@ -4,9 +4,42 @@
|
|
|
4
4
|
* never loads it as an extension.
|
|
5
5
|
*/
|
|
6
6
|
import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
7
|
-
import { thinkingColorOf } from "./ansi.ts";
|
|
7
|
+
import { stripAnsi, thinkingColorOf } from "./ansi.ts";
|
|
8
8
|
import { assert, isMain } from "./check.ts";
|
|
9
9
|
|
|
10
|
+
/** A clickable span inside rendered lines: 0-based cell columns, inclusive. */
|
|
11
|
+
export interface TextSpan {
|
|
12
|
+
row: number;
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Where `text` sits in each rendered line, in cell columns. A mouse handler needs this to
|
|
19
|
+
* make one piece of a box clickable and leave the rest to pi: a press the handler does not
|
|
20
|
+
* take stays with the text selection, so a box can be clicked and copied at once.
|
|
21
|
+
* A line that shows the text in part (narrow width) yields no span, so a clipped label is
|
|
22
|
+
* never half-clickable.
|
|
23
|
+
*/
|
|
24
|
+
export function textSpans(lines: readonly string[], text: string): TextSpan[] {
|
|
25
|
+
if (!text) return [];
|
|
26
|
+
const width = visibleWidth(text) - 1;
|
|
27
|
+
const spans: TextSpan[] = [];
|
|
28
|
+
lines.forEach((line, row) => {
|
|
29
|
+
const plain = stripAnsi(line);
|
|
30
|
+
const at = plain.indexOf(text);
|
|
31
|
+
if (at >= 0) {
|
|
32
|
+
const start = visibleWidth(plain.slice(0, at));
|
|
33
|
+
spans.push({ row, start, end: start + width });
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
return spans;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Whether the 0-based cell `x` on `row` lands inside one of `spans`. */
|
|
40
|
+
export const inSpans = (spans: readonly TextSpan[], row: number, x: number): boolean =>
|
|
41
|
+
spans.some((span) => span.row === row && x >= span.start && x <= span.end);
|
|
42
|
+
|
|
10
43
|
export type BoxTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string };
|
|
11
44
|
type Dim = (s: string) => string;
|
|
12
45
|
|
|
@@ -72,26 +105,47 @@ export function renderScreen(
|
|
|
72
105
|
].map((l) => truncateToWidth(l, width, ""));
|
|
73
106
|
}
|
|
74
107
|
|
|
75
|
-
/**
|
|
76
|
-
*
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
/** Border paint: a theme token name, or a painter for a tier that has no token (the thinking
|
|
109
|
+
* slots, which `thinkingColorOf` resolves). */
|
|
110
|
+
export type BoxBorder = string | ((text: string) => string);
|
|
111
|
+
|
|
112
|
+
/** `renderBoxLines` plus where each input row landed: `starts[i]` is the first line index of
|
|
113
|
+
* `rows[i]`. A caller that hit-tests a row (the task list's scroll counters) needs this,
|
|
114
|
+
* because a row long enough to wrap occupies more than one line. */
|
|
115
|
+
export function renderBoxRows(
|
|
116
|
+
theme: BoxTheme | null,
|
|
117
|
+
width: number,
|
|
118
|
+
rows: string[],
|
|
119
|
+
bgType?: string,
|
|
120
|
+
border: BoxBorder = "dim",
|
|
121
|
+
): { lines: string[]; starts: number[] } {
|
|
122
|
+
const dim = typeof border === "string" ? (s: string) => (theme ? theme.fg(border, s) : s) : border;
|
|
81
123
|
const inner = Math.max(8, width - 4);
|
|
82
124
|
const lines = [boxEdge("╭", "╮", width, dim)];
|
|
125
|
+
const starts: number[] = [];
|
|
83
126
|
for (const row of rows) {
|
|
127
|
+
starts.push(lines.length);
|
|
84
128
|
for (const line of wrapTextWithAnsi(row, inner)) lines.push(boxRow(line, width, dim));
|
|
85
129
|
}
|
|
86
130
|
lines.push(boxEdge("╰", "╯", width, dim));
|
|
87
|
-
|
|
131
|
+
const paint = (input: string[]) => {
|
|
132
|
+
if (!bgType || !theme?.bg) return input;
|
|
88
133
|
try {
|
|
89
|
-
return
|
|
134
|
+
return input.map((l) => applyBg(l, width, (s) => theme!.bg!(bgType, s)));
|
|
90
135
|
} catch {
|
|
91
|
-
return
|
|
136
|
+
return input;
|
|
92
137
|
}
|
|
93
|
-
}
|
|
94
|
-
return lines;
|
|
138
|
+
};
|
|
139
|
+
return { lines: paint(lines), starts };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The box around `rows`. `bgType` = theme bg name (no-op when the theme has no `bg`);
|
|
143
|
+
* `borderColor` = border color.
|
|
144
|
+
* `theme` may be null: a box is patched in at module load, before `session_start`
|
|
145
|
+
* delivers the active theme. An uncolored box for that first frame beats a null
|
|
146
|
+
* deref that kills the process. */
|
|
147
|
+
export function renderBoxLines(theme: BoxTheme | null, width: number, rows: string[], bgType?: string, border: BoxBorder = "dim"): string[] {
|
|
148
|
+
return renderBoxRows(theme, width, rows, bgType, border).lines;
|
|
95
149
|
}
|
|
96
150
|
|
|
97
151
|
if (isMain(import.meta.url)) {
|
|
@@ -146,5 +200,16 @@ if (isMain(import.meta.url)) {
|
|
|
146
200
|
`a long description keeps the right wall at width ${w}`,
|
|
147
201
|
);
|
|
148
202
|
}
|
|
203
|
+
// Click target on a piece of text: cells, not characters, and nothing when clipped.
|
|
204
|
+
const line = renderBoxRows(th, 40, ["Todos (3/7) [click to expand]"], undefined, undefined).lines[1]!;
|
|
205
|
+
const spans = textSpans([line], "[click to expand]");
|
|
206
|
+
assert(spans.length === 1 && spans[0]!.row === 0, "textSpans finds the hint on its row");
|
|
207
|
+
assert(spans[0]!.start === visibleWidth("│ Todos (3/7) "), `span starts at the hint, got ${spans[0]!.start}`);
|
|
208
|
+
assert(inSpans(spans, 0, spans[0]!.start) && inSpans(spans, 0, spans[0]!.end), "span covers the first and last cell");
|
|
209
|
+
assert(!inSpans(spans, 0, spans[0]!.start - 1) && !inSpans(spans, 1, spans[0]!.start), "span excludes the cell before and other rows");
|
|
210
|
+
assert(textSpans([boxRow("Todos (3/7) [click to exp…", 24, (t) => t)], "[click to expand]").length === 0, "a clipped hint is not clickable");
|
|
211
|
+
// Wide characters before the hint shift cells, not characters.
|
|
212
|
+
const wide = textSpans([boxRow("日本 [x]", 24, (t) => t)], "[x]");
|
|
213
|
+
assert(wide[0]!.start === visibleWidth("│ 日本 "), `a wide glyph shifts by cells, got ${wide[0]!.start}`);
|
|
149
214
|
console.log("lib/box.ts OK");
|
|
150
215
|
}
|
package/lib/list-picker.ts
CHANGED
|
@@ -310,9 +310,6 @@ export class InputPicker implements Component, Focusable {
|
|
|
310
310
|
}
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
/** Title of a sub-screen, derived from `screenTitle` so the format lives in one place. */
|
|
314
|
-
export const pickerTitle = (setting: string): ScreenText["title"] => screenTitle(setting);
|
|
315
|
-
|
|
316
313
|
// Self-check: `node lib/list-picker.ts`
|
|
317
314
|
if (isMain(import.meta.url)) {
|
|
318
315
|
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
|
package/lib/patch.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prototype patches that survive `/reload`.
|
|
3
|
+
*
|
|
4
|
+
* pi re-evaluates an extension in the SAME process on `/reload`, so a patch guarded
|
|
5
|
+
* by a `globalThis` flag is installed once and then frozen: every later reload keeps
|
|
6
|
+
* the first load's closures, and a UI fix looks broken until pi restarts.
|
|
7
|
+
*
|
|
8
|
+
* Two rules make a patch reload-safe:
|
|
9
|
+
* 1. the pi method behind a patched slot is kept ON the prototype (a symbol key),
|
|
10
|
+
* so it outlives the module instance and never becomes a previous patch;
|
|
11
|
+
* 2. every function we install is marked, so a reload cannot mistake our own patch
|
|
12
|
+
* for pi's original and wrap a box around a box.
|
|
13
|
+
*
|
|
14
|
+
* `originalOf` throws when a slot holds a marked method but no original was recorded:
|
|
15
|
+
* that can only happen if the bookkeeping was bypassed, and silently skipping the
|
|
16
|
+
* patch would leave the UI in the state this file exists to prevent.
|
|
17
|
+
*/
|
|
18
|
+
const ORIGINALS_KEY = Symbol.for("pi-arnative.protoOriginals");
|
|
19
|
+
const PATCHED_KEY = Symbol.for("pi-arnative.patchedMethod");
|
|
20
|
+
|
|
21
|
+
type AnyFn = (...args: any[]) => any;
|
|
22
|
+
type Marked = AnyFn & { [PATCHED_KEY]?: true };
|
|
23
|
+
|
|
24
|
+
/** Mark an installed patch so a later load never reads it back as an original. */
|
|
25
|
+
export function markPatched<T extends AnyFn>(fn: T): T {
|
|
26
|
+
(fn as Marked)[PATCHED_KEY] = true;
|
|
27
|
+
return fn;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** pi's own method for `key`, recorded once per prototype and returned on every load. */
|
|
31
|
+
export function originalOf<T extends AnyFn>(proto: Record<symbol | string, any>, key: string): T {
|
|
32
|
+
const originals = (proto[ORIGINALS_KEY] ??= {} as Record<string, Marked>);
|
|
33
|
+
const current: Marked | undefined = proto[key];
|
|
34
|
+
if (current && !current[PATCHED_KEY]) originals[key] = current;
|
|
35
|
+
const original = originals[key];
|
|
36
|
+
if (!original) throw new Error(`pi-arnative: ${key} has no recorded original (already patched by another package?)`);
|
|
37
|
+
return original as T;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Install `build(pi's method)` on `proto[key]`, reinstalled on every load. */
|
|
41
|
+
export function patchOnce(proto: Record<symbol | string, any>, key: string, build: (original: AnyFn) => AnyFn): void {
|
|
42
|
+
proto[key] = markPatched(build(originalOf(proto, key)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Self-check: `node lib/patch.ts`.
|
|
46
|
+
import { assert, isMain } from "./check.ts";
|
|
47
|
+
if (isMain(import.meta.url)) {
|
|
48
|
+
const proto: any = { render(): string { return "pi"; } };
|
|
49
|
+
const first = originalOf<() => string>(proto, "render");
|
|
50
|
+
assert(first() === "pi", "the original is pi's own method");
|
|
51
|
+
proto.render = markPatched(function (): string {
|
|
52
|
+
return first();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// A reload: the slot holds OUR patch, and the second load must still see pi's method.
|
|
56
|
+
const second = originalOf<() => string>(proto, "render");
|
|
57
|
+
assert(second === first, "reload: the recorded original never becomes a previous patch");
|
|
58
|
+
const reinstalled = markPatched(function (): string {
|
|
59
|
+
return second();
|
|
60
|
+
});
|
|
61
|
+
proto.render = reinstalled;
|
|
62
|
+
assert(proto.render() === "pi", "the reinstalled patch still calls pi, not itself");
|
|
63
|
+
assert(proto.render !== first && proto.render === reinstalled, "the slot holds the newest patch");
|
|
64
|
+
assert(proto[Symbol.for("pi-arnative.protoOriginals")].render === first, "originals stay on the prototype (outlive the module)");
|
|
65
|
+
|
|
66
|
+
// A slot patched without bookkeeping cannot silently disable the patch.
|
|
67
|
+
const lost: any = { render: markPatched(() => "x") };
|
|
68
|
+
let threw = false;
|
|
69
|
+
try {
|
|
70
|
+
originalOf(lost, "render");
|
|
71
|
+
} catch {
|
|
72
|
+
threw = true;
|
|
73
|
+
}
|
|
74
|
+
assert(threw, "a marked slot with no recorded original fails loudly");
|
|
75
|
+
|
|
76
|
+
// patchOnce: the one-call form, still reload-safe.
|
|
77
|
+
const twice: any = { render(): string { return "pi"; } };
|
|
78
|
+
patchOnce(twice, "render", (orig) => function (this: any): string {
|
|
79
|
+
return `${orig.call(this)}!`;
|
|
80
|
+
});
|
|
81
|
+
patchOnce(twice, "render", (orig) => function (this: any): string {
|
|
82
|
+
return `${orig.call(this)}?`;
|
|
83
|
+
});
|
|
84
|
+
assert(twice.render() === "pi?", "patchOnce: the second load patches pi's method again, not the first patch");
|
|
85
|
+
|
|
86
|
+
console.log("OK");
|
|
87
|
+
}
|
package/lib/preset-store.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* Reads are memoised per process; every write re-reads the file and replaces it atomically
|
|
10
10
|
* (temp file + rename), so concurrent pi sessions that write different keys keep both.
|
|
11
11
|
*/
|
|
12
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
13
|
import { tmpdir } from "node:os";
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
15
15
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
@@ -72,8 +72,21 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
|
|
|
72
72
|
return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/** Reading order of `config.json`: the presets in the order the settings menu shows them,
|
|
76
|
+
* then `layoutVersion`, then anything else (a key from another module or a newer version).
|
|
77
|
+
* Times a user edits the file by hand or reads it back. */
|
|
78
|
+
const KEY_ORDER = ["headerPreset", "footerPreset", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
|
|
79
|
+
|
|
80
|
+
/** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
|
|
81
|
+
function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
82
|
+
const out: Record<string, unknown> = {};
|
|
83
|
+
for (const key of KEY_ORDER) if (Object.hasOwn(record, key)) out[key] = record[key];
|
|
84
|
+
for (const [key, value] of Object.entries(record)) if (!Object.hasOwn(out, key)) out[key] = value;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
75
88
|
/** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
|
|
76
|
-
export function saveChoice(key: string, value: string): void {
|
|
89
|
+
export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
77
90
|
if (readConfig()[key] === value) return;
|
|
78
91
|
// Re-read: another pi session may have written its own key since this one loaded.
|
|
79
92
|
memo = { ...readDisk().record, [key]: value };
|
|
@@ -81,13 +94,35 @@ export function saveChoice(key: string, value: string): void {
|
|
|
81
94
|
const path = configPath();
|
|
82
95
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
83
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
84
|
-
|
|
85
|
-
|
|
97
|
+
const payload = `${JSON.stringify(ordered(memo), null, 2)}\n`;
|
|
98
|
+
writeFileSync(tmp, payload, "utf8");
|
|
99
|
+
try {
|
|
100
|
+
rename(tmp, path);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
// Windows: a running pi session can hold config.json open, and then the atomic
|
|
103
|
+
// replace fails with EPERM while an in-place write still lands. A setting that
|
|
104
|
+
// silently never reaches disk is worse than the small truncation window here.
|
|
105
|
+
const code = (e as NodeJS.ErrnoException).code;
|
|
106
|
+
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
|
|
107
|
+
writeFileSync(path, payload, "utf8");
|
|
108
|
+
rmSync(tmp, { force: true });
|
|
109
|
+
}
|
|
86
110
|
} catch {
|
|
87
111
|
// ignore: the choice still applies for this session
|
|
88
112
|
}
|
|
89
113
|
}
|
|
90
114
|
|
|
115
|
+
/** Record the choices in use, so `config.json` names every preset instead of only the ones a
|
|
116
|
+
* user changed — a fresh install then reads a complete profile instead of an empty file.
|
|
117
|
+
* Runs at `session_start`; after the first run every key already matches and nothing is
|
|
118
|
+
* written. A present-but-unreadable config is never replaced by this partial record (the
|
|
119
|
+
* same rule the layout stamp follows), because that would drop the other keys. */
|
|
120
|
+
export function ensureChoices(values: Record<string, string>): void {
|
|
121
|
+
const { parsed } = readDisk();
|
|
122
|
+
if (!parsed && existsSync(configPath())) return;
|
|
123
|
+
for (const [key, value] of Object.entries(values)) saveChoice(key, value);
|
|
124
|
+
}
|
|
125
|
+
|
|
91
126
|
/** Drop the in-memory copy so the next read hits disk (a restart, in a test). */
|
|
92
127
|
export function resetPresetCache(): void {
|
|
93
128
|
memo = null;
|
|
@@ -148,6 +183,50 @@ if (isMain(import.meta.url)) {
|
|
|
148
183
|
const stamped = JSON.parse(readFileSync(join(stamp, "arnative", "config.json"), "utf8")) as Record<string, unknown>;
|
|
149
184
|
assert(stamped.headerPreset === "b" && stamped.layoutVersion === "1", "stamping merges, it does not replace");
|
|
150
185
|
rmSync(stamp, { recursive: true, force: true });
|
|
186
|
+
|
|
187
|
+
// The startup record names every choice, including the ones still at their default.
|
|
188
|
+
const profile = mkdtempSync(join(tmpdir(), "arnative-preset-profile-"));
|
|
189
|
+
process.env.PI_CODING_AGENT_DIR = profile;
|
|
190
|
+
resetPresetCache();
|
|
191
|
+
ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
|
|
192
|
+
assert(loadChoice(HEADER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "a default choice is written, not skipped");
|
|
193
|
+
assert(loadChoice(FOOTER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "every key in the batch is written");
|
|
194
|
+
const profiled = readFileSync(join(profile, "arnative", "config.json"), "utf8");
|
|
195
|
+
ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
|
|
196
|
+
assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === profiled, "a second record writes nothing");
|
|
197
|
+
|
|
198
|
+
// The file keeps one key order whatever order the writes arrived in.
|
|
199
|
+
const keyOrder = () => Object.keys(JSON.parse(readFileSync(join(profile, "arnative", "config.json"), "utf8")) as Record<string, unknown>);
|
|
200
|
+
assert(
|
|
201
|
+
keyOrder().join(",") === "headerPreset,footerPreset,layoutVersion",
|
|
202
|
+
"known keys follow KEY_ORDER, layoutVersion after the presets: " + keyOrder().join(","),
|
|
203
|
+
);
|
|
204
|
+
saveChoice("spinnerPreset", "Circle Wave");
|
|
205
|
+
saveChoice("zzz-other", "x");
|
|
206
|
+
assert(
|
|
207
|
+
keyOrder().join(",") === "headerPreset,footerPreset,spinnerPreset,layoutVersion,zzz-other",
|
|
208
|
+
"a newly written key slots into place, an unknown one goes last: " + keyOrder().join(","),
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
// Windows: a running pi session can hold the file open, so the atomic replace fails
|
|
212
|
+
// while the setting still has to land. The seam stands in for that rename.
|
|
213
|
+
const locked = () => {
|
|
214
|
+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
|
|
215
|
+
};
|
|
216
|
+
saveChoice(HEADER_PRESET_KEY, "b", locked);
|
|
217
|
+
resetPresetCache();
|
|
218
|
+
assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a refused rename still writes the choice in place");
|
|
219
|
+
saveChoice(FOOTER_PRESET_KEY, "a", locked);
|
|
220
|
+
resetPresetCache();
|
|
221
|
+
assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a" && loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the in-place write keeps the other keys");
|
|
222
|
+
assert(!existsSync(join(profile, "arnative")) || readdirSync(join(profile, "arnative")).every((f) => !f.endsWith(".tmp")), "no temp file is left behind");
|
|
223
|
+
|
|
224
|
+
writeFileSync(join(profile, "arnative", "config.json"), "{not json", "utf8");
|
|
225
|
+
resetPresetCache();
|
|
226
|
+
ensureChoices({ headerPreset: "b" });
|
|
227
|
+
assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
|
|
228
|
+
rmSync(profile, { recursive: true, force: true });
|
|
229
|
+
|
|
151
230
|
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
152
231
|
resetPresetCache();
|
|
153
232
|
|
package/lib/shortcuts.ts
CHANGED
|
@@ -35,6 +35,11 @@ export const SHORTCUT_RELOAD = build("r");
|
|
|
35
35
|
/** Expand/collapse the minimal footer. Ctrl+alt+m on macOS/Linux, alt+m on Windows/WSL
|
|
36
36
|
* (same platform split as the shortcuts above). */
|
|
37
37
|
export const SHORTCUT_TOGGLE_FOOTER = build("m");
|
|
38
|
+
/** Expand/collapse the task list widget. Same platform split: Alt+o on Windows/WSL. */
|
|
39
|
+
export const SHORTCUT_TOGGLE_TODOS = build("o");
|
|
40
|
+
/** Scroll the expanded task list: `j` down, `k` up, one task per press. */
|
|
41
|
+
export const SHORTCUT_SCROLL_TODOS_DOWN = build("j");
|
|
42
|
+
export const SHORTCUT_SCROLL_TODOS_UP = build("k");
|
|
38
43
|
|
|
39
44
|
/** The one "go back" key: `←` leaves a screen for its parent, while Esc closes or reverts
|
|
40
45
|
* it. Defined here so no screen can advertise a key another screen does not handle. */
|
|
@@ -71,6 +76,8 @@ export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"],
|
|
|
71
76
|
export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [BACK.label, "Back"], [CANCEL.label, "Close"]);
|
|
72
77
|
/** Live-preview list: moving applies, Enter keeps, `←` steps out, Esc reverts. */
|
|
73
78
|
export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [BACK.label, "Back"], [CANCEL.label, "Revert"]);
|
|
79
|
+
/** A list you only read (the `/todos` recap): moving changes nothing, so there is no Open. */
|
|
80
|
+
export const LEGEND_READ_ONLY = legend([MOVE.label, "Move"], [CANCEL.label, "Close"]);
|
|
74
81
|
/** The read-only usage dashboard. The full legend needs the room, so a narrow box degrades. */
|
|
75
82
|
export function legendUsage(width: number): string {
|
|
76
83
|
const full = legend([MOVE.label, "Move"], ["Click", "Open/close"], [BACK.label, "Back"], [QUIT.label, "Exit"]);
|
|
@@ -112,6 +119,7 @@ if (isMain(import.meta.url)) {
|
|
|
112
119
|
// advertised on one screen and handled on none.
|
|
113
120
|
assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", `root menu legend pinned, got ${LEGEND_MOVE}`);
|
|
114
121
|
assert(LEGEND_MOVE.includes("[←] Back"), "the root menu advertises ← Back");
|
|
122
|
+
assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
|
|
115
123
|
assert(
|
|
116
124
|
LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${BACK_KEY_LABEL}] Back [Esc] Revert`,
|
|
117
125
|
`live legend pinned, got ${LEGEND_LIVE}`,
|
package/lib/spinner.ts
CHANGED
|
@@ -52,7 +52,7 @@ interface Preset {
|
|
|
52
52
|
* Only one rule decides the set: every frame must be a glyph the terminal font *itself* carries,
|
|
53
53
|
* so it advances exactly one cell. A glyph the font lacks is served by a fallback font, and
|
|
54
54
|
* fallbacks are not monospaced — measured in the terminal face (JetBrainsMono Nerd Font), the
|
|
55
|
-
* Dingbats marks `✢` `✤` `✻` `✽` `❋` advance **1.48** cells and
|
|
55
|
+
* Dingbats marks `✢` `✤` `✻` `✽` `❋` advance **1.48** cells and `U+2733` **2.29**, against a **1.00**
|
|
56
56
|
* native cell, which walks the label sideways on every tick that uses one. `·` `*` `⋆` `✶` all
|
|
57
57
|
* advance 1.00 in that face (and in Consolas, Cascadia, Lucida, Courier), so the four-mark swell
|
|
58
58
|
* `· → * → ⋆ → ✶` is smooth on all of them. A scan of all 86 installed families found none that
|