@bismawy/pi-arnative 0.10.1 → 0.11.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 +29 -0
- package/README.md +6 -1
- package/extensions/arnative.ts +76 -23
- package/extensions/budget.ts +665 -0
- package/extensions/footer.ts +409 -26
- package/extensions/usage-export.ts +292 -0
- package/extensions/usage.ts +424 -147
- package/lib/compat.ts +36 -10
- package/lib/list-picker.ts +2 -2
- package/lib/model-heal.ts +12 -4
- package/lib/preset-store.ts +49 -5
- package/lib/provider.ts +29 -3
- package/lib/shortcuts.ts +12 -7
- package/lib/status-widget.ts +20 -0
- package/lib/usage-store.ts +913 -312
- package/package.json +3 -3
package/lib/compat.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* Two things ride along with the same probe: the real `contextWindow`/`maxTokens`, and
|
|
8
8
|
* (on demand) which `reasoning_effort` names the channel accepts.
|
|
9
9
|
*/
|
|
10
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
10
11
|
import { assert, isMain } from "./check.ts";
|
|
11
12
|
|
|
12
13
|
export type Compat = Record<string, unknown>;
|
|
@@ -254,6 +255,8 @@ export interface EffortProbeOptions {
|
|
|
254
255
|
key?: string;
|
|
255
256
|
headers?: Record<string, string>;
|
|
256
257
|
fetchImpl?: typeof fetch;
|
|
258
|
+
signal?: AbortSignal;
|
|
259
|
+
deadline?: number;
|
|
257
260
|
/** Called after each level, for a progress row. */
|
|
258
261
|
onLevel?: (level: string, accepted: boolean | undefined, index: number) => void;
|
|
259
262
|
}
|
|
@@ -265,47 +268,70 @@ function isParamRejection(status: number, body: string): boolean {
|
|
|
265
268
|
return REJECTION_RE.test(body);
|
|
266
269
|
}
|
|
267
270
|
|
|
268
|
-
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
269
|
-
|
|
270
271
|
/** Every effort name the channel accepts, found with one tiny completion per level.
|
|
271
272
|
* `[]` means nothing answered — never call that "nothing supported". */
|
|
272
273
|
export async function probeEffort(model: CompatModel, options: EffortProbeOptions): Promise<string[]> {
|
|
273
274
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
274
|
-
const
|
|
275
|
+
const responses = lower(model.api) === "openai-responses";
|
|
276
|
+
const url = `${options.baseUrl.replace(/\/+$/, "")}/${responses ? "responses" : "chat/completions"}`;
|
|
275
277
|
const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json", ...options.headers };
|
|
276
278
|
if (options.key) headers.authorization = `Bearer ${options.key}`;
|
|
277
279
|
const accepted: string[] = [];
|
|
278
|
-
|
|
280
|
+
const signal = AbortSignal.any([
|
|
281
|
+
...(options.signal ? [options.signal] : []),
|
|
282
|
+
...(options.deadline !== undefined ? [AbortSignal.timeout(Math.max(1, options.deadline - Date.now()))] : []),
|
|
283
|
+
]);
|
|
284
|
+
const checkStopped = (): void => {
|
|
285
|
+
signal.throwIfAborted();
|
|
286
|
+
if (options.deadline !== undefined && Date.now() >= options.deadline) {
|
|
287
|
+
throw new DOMException("Effort probe budget exhausted", "TimeoutError");
|
|
288
|
+
}
|
|
289
|
+
};
|
|
279
290
|
for (const [index, level] of EFFORT_RANK.entries()) {
|
|
280
|
-
|
|
291
|
+
checkStopped();
|
|
292
|
+
const body = JSON.stringify(responses ? {
|
|
293
|
+
model: model.id,
|
|
294
|
+
input: [{ role: "user", content: [{ type: "input_text", text: "ping" }] }],
|
|
295
|
+
...(model.compat?.supportsMaxOutputTokens === false ? {} : { max_output_tokens: PROBE_TOKENS }),
|
|
296
|
+
stream: false,
|
|
297
|
+
store: false,
|
|
298
|
+
reasoning: { effort: level },
|
|
299
|
+
} : {
|
|
281
300
|
model: model.id,
|
|
282
301
|
messages: [{ role: "user", content: "ping" }],
|
|
283
|
-
max_tokens: PROBE_TOKENS,
|
|
302
|
+
[model.compat?.maxTokensField === "max_completion_tokens" ? "max_completion_tokens" : "max_tokens"]: PROBE_TOKENS,
|
|
284
303
|
stream: false,
|
|
285
304
|
...(thinkingPayload(model.compat ?? {}, true) ?? {}),
|
|
286
305
|
reasoning_effort: level,
|
|
287
306
|
});
|
|
288
307
|
let verdict: boolean | undefined;
|
|
289
|
-
// Two attempts per level: a first 400 can be an upstream flake, a second confirms it.
|
|
290
308
|
for (let attempt = 0; attempt < 2 && verdict === undefined; attempt++) {
|
|
309
|
+
checkStopped();
|
|
291
310
|
let status: number;
|
|
292
311
|
let text: string;
|
|
293
312
|
try {
|
|
294
|
-
const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.timeout(LEVEL_TIMEOUT_MS) });
|
|
313
|
+
const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.any([signal, AbortSignal.timeout(LEVEL_TIMEOUT_MS)]) });
|
|
295
314
|
status = response.status;
|
|
296
315
|
text = (await response.text()).slice(0, 4000);
|
|
297
316
|
} catch {
|
|
317
|
+
checkStopped();
|
|
298
318
|
break; // network/timeout: inconclusive
|
|
299
319
|
}
|
|
320
|
+
checkStopped();
|
|
300
321
|
if (status < 300) {
|
|
301
322
|
verdict = true;
|
|
302
323
|
break;
|
|
303
324
|
}
|
|
304
325
|
if (status === 429) {
|
|
305
|
-
|
|
326
|
+
try {
|
|
327
|
+
await sleep(RETRY_PAUSE_MS, undefined, { signal });
|
|
328
|
+
} catch (error) {
|
|
329
|
+
checkStopped();
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
306
332
|
continue;
|
|
307
333
|
}
|
|
308
|
-
if (!isParamRejection(status, text)) break;
|
|
334
|
+
if (!isParamRejection(status, text)) break;
|
|
309
335
|
verdict = false;
|
|
310
336
|
}
|
|
311
337
|
if (verdict) accepted.push(level);
|
package/lib/list-picker.ts
CHANGED
|
@@ -386,8 +386,8 @@ export class InputPicker implements Component, Focusable {
|
|
|
386
386
|
|
|
387
387
|
// Self-check: `node lib/list-picker.ts`
|
|
388
388
|
if (isMain(import.meta.url)) {
|
|
389
|
-
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter]
|
|
390
|
-
assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter]
|
|
389
|
+
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Select [Esc] Close", "root legend pinned, no ← behind the root menu");
|
|
390
|
+
assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", "move legend pinned: Esc is Back where a parent exists");
|
|
391
391
|
assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [Esc] Back", "live legend pinned: Esc drops the preview and steps out");
|
|
392
392
|
const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
|
|
393
393
|
const quiet = (): void => undefined;
|
package/lib/model-heal.ts
CHANGED
|
@@ -509,10 +509,18 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
|
|
|
509
509
|
break;
|
|
510
510
|
}
|
|
511
511
|
const channel = channels.get(lower(model.provider))!;
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
512
|
+
let supported: string[];
|
|
513
|
+
try {
|
|
514
|
+
supported = await probeEffort(
|
|
515
|
+
{ ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
|
|
516
|
+
{ baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl, signal: deps.signal, deadline },
|
|
517
|
+
);
|
|
518
|
+
} catch (error) {
|
|
519
|
+
deps.signal?.throwIfAborted();
|
|
520
|
+
if (!(error instanceof Error) || error.name !== "TimeoutError" || Date.now() < deadline) throw error;
|
|
521
|
+
errors.push(`${model.provider}: probe budget exhausted`);
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
516
524
|
deps.signal?.throwIfAborted();
|
|
517
525
|
if (supported.length === 0) {
|
|
518
526
|
// Stamped as failed so the next run waits the short TTL instead of re-sending.
|
package/lib/preset-store.ts
CHANGED
|
@@ -17,6 +17,12 @@ import { assert, isMain } from "./check.ts";
|
|
|
17
17
|
|
|
18
18
|
export const HEADER_PRESET_KEY = "headerPreset";
|
|
19
19
|
export const FOOTER_PRESET_KEY = "footerPreset";
|
|
20
|
+
/** Footer cost cell: `"on"`/`"off"`, absent reads as off. */
|
|
21
|
+
export const FOOTER_COST_KEY = "footerCost";
|
|
22
|
+
/** Budget guardrail — day/month caps are amount strings (`"5"`, `""` = unset), enforce is `"on"`/`"off"`. */
|
|
23
|
+
export const BUDGET_DAY_KEY = "budgetDay";
|
|
24
|
+
export const BUDGET_MONTH_KEY = "budgetMonth";
|
|
25
|
+
export const BUDGET_ENFORCE_KEY = "budgetEnforce";
|
|
20
26
|
|
|
21
27
|
// Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
|
|
22
28
|
// Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
|
|
@@ -72,10 +78,19 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
|
|
|
72
78
|
return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
|
|
73
79
|
}
|
|
74
80
|
|
|
81
|
+
/** The stored value for `key` as a finite number in `[min, max]`, or undefined when absent, empty,
|
|
82
|
+
* unparsable or out of range. Amounts are stored as strings (`"5"`, `""` = unset) because
|
|
83
|
+
* `loadChoice` only accepts strings from an allowed set, so numbers get their own reader. */
|
|
84
|
+
export function loadNumber(key: string, range: { min: number; max: number }): number | undefined {
|
|
85
|
+
const raw = readConfig()[key];
|
|
86
|
+
const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
|
|
87
|
+
return Number.isFinite(n) && n >= range.min && n <= range.max ? n : undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
75
90
|
/** Reading order of `config.json`: the presets in the order the settings menu shows them,
|
|
76
91
|
* then `layoutVersion`, then anything else (a key from another module or a newer version).
|
|
77
92
|
* Times a user edits the file by hand or reads it back. */
|
|
78
|
-
const KEY_ORDER = ["headerPreset", "footerPreset", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
|
|
93
|
+
const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
|
|
79
94
|
|
|
80
95
|
/** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
|
|
81
96
|
function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
@@ -87,9 +102,15 @@ function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
|
87
102
|
|
|
88
103
|
/** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
|
|
89
104
|
export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
105
|
+
readConfig();
|
|
106
|
+
const { parsed, record } = readDisk();
|
|
107
|
+
if (!parsed && existsSync(configPath())) {
|
|
108
|
+
process.emitWarning("Arnative settings were not saved: config.json is unreadable or invalid.", { code: "ARNATIVE_PRESET_SAVE" });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
memo = record;
|
|
112
|
+
if (record[key] === value) return;
|
|
113
|
+
memo = { ...record, [key]: value };
|
|
93
114
|
try {
|
|
94
115
|
const path = configPath();
|
|
95
116
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
@@ -108,7 +129,7 @@ export function saveChoice(key: string, value: string, rename: (from: string, to
|
|
|
108
129
|
rmSync(tmp, { force: true });
|
|
109
130
|
}
|
|
110
131
|
} catch {
|
|
111
|
-
|
|
132
|
+
process.emitWarning("Arnative settings were not saved; the choice applies only to this session.", { code: "ARNATIVE_PRESET_SAVE" });
|
|
112
133
|
}
|
|
113
134
|
}
|
|
114
135
|
|
|
@@ -227,6 +248,29 @@ if (isMain(import.meta.url)) {
|
|
|
227
248
|
assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
|
|
228
249
|
rmSync(profile, { recursive: true, force: true });
|
|
229
250
|
|
|
251
|
+
// loadNumber: amounts are stored as strings ("" = unset); anything that is not a finite
|
|
252
|
+
// number in range reads as unset, so a hand-edited or corrupt value cannot become a cap.
|
|
253
|
+
const nums = mkdtempSync(join(tmpdir(), "arnative-preset-num-"));
|
|
254
|
+
process.env.PI_CODING_AGENT_DIR = nums;
|
|
255
|
+
resetPresetCache();
|
|
256
|
+
const range = { min: 0.01, max: 1_000_000 };
|
|
257
|
+
saveChoice(BUDGET_DAY_KEY, "5");
|
|
258
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === 5, "a stored amount parses");
|
|
259
|
+
saveChoice(BUDGET_DAY_KEY, "7.50");
|
|
260
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === 7.5, "a decimal amount parses");
|
|
261
|
+
saveChoice(BUDGET_DAY_KEY, "abc");
|
|
262
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "a non-numeric amount reads as unset");
|
|
263
|
+
saveChoice(BUDGET_DAY_KEY, "0");
|
|
264
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "below the range reads as unset");
|
|
265
|
+
saveChoice(BUDGET_DAY_KEY, "2000000");
|
|
266
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "above the range reads as unset");
|
|
267
|
+
saveChoice(BUDGET_DAY_KEY, "");
|
|
268
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "an empty amount reads as unset");
|
|
269
|
+
writeFileSync(join(nums, "arnative", "config.json"), JSON.stringify({ [BUDGET_DAY_KEY]: 7 }), "utf8");
|
|
270
|
+
resetPresetCache();
|
|
271
|
+
assert(loadNumber(BUDGET_DAY_KEY, range) === 7, "a hand-edited numeric value is accepted");
|
|
272
|
+
rmSync(nums, { recursive: true, force: true });
|
|
273
|
+
|
|
230
274
|
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
231
275
|
resetPresetCache();
|
|
232
276
|
|
package/lib/provider.ts
CHANGED
|
@@ -16,7 +16,7 @@ import { assert, isMain } from "../lib/check.ts";
|
|
|
16
16
|
import { buildEffortMap, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type Compat, type ModelMeta } from "./compat.ts";
|
|
17
17
|
import { screenTitle, type ScreenText } from "../lib/box.ts";
|
|
18
18
|
import { stripAnsi } from "../lib/ansi.ts";
|
|
19
|
-
import { statusRows } from "./status-widget.ts";
|
|
19
|
+
import { announce, statusRows } from "./status-widget.ts";
|
|
20
20
|
import { INPUT_LEGEND, InputPicker, LIST_LEGEND_MOVE, ListPicker, rowText, type ListRow } from "./list-picker.ts";
|
|
21
21
|
|
|
22
22
|
// ---------------------------------------------------------------- flavors
|
|
@@ -720,12 +720,36 @@ const addProviderFlow = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
|
720
720
|
return;
|
|
721
721
|
}
|
|
722
722
|
ctx.ui.notify(`[arnative] Provider saved: ${name} (${FLAVOR_LABELS[flavor]}, ${picked.length} models, ${levelsSummary(entry.models)}). Open /model to pick one.`, "info");
|
|
723
|
+
announce(ctx.ui, `Provider saved: ${name} (${picked.length} models).`);
|
|
723
724
|
};
|
|
724
725
|
|
|
725
726
|
const deleteProviderFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
|
|
726
|
-
|
|
727
|
+
const confirmed =
|
|
728
|
+
ctx.mode === "tui"
|
|
729
|
+
? await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
|
|
730
|
+
let picker: ListPicker;
|
|
731
|
+
picker = new ListPicker(
|
|
732
|
+
theme,
|
|
733
|
+
[{ label: "No" }, { label: "Yes" }],
|
|
734
|
+
"No",
|
|
735
|
+
{
|
|
736
|
+
preview: () => {},
|
|
737
|
+
revert: () => {},
|
|
738
|
+
done: () => done(picker.index === 1),
|
|
739
|
+
cancel: () => done(false),
|
|
740
|
+
requestRender: () => tui.requestRender(),
|
|
741
|
+
},
|
|
742
|
+
{ title: screenTitle("Delete provider"), description: `${name}? The stored key goes with it.`, legend: LIST_LEGEND_MOVE },
|
|
743
|
+
false,
|
|
744
|
+
ctx.thinkingLevel,
|
|
745
|
+
);
|
|
746
|
+
return picker;
|
|
747
|
+
})
|
|
748
|
+
: await ctx.ui.confirm("Delete provider", `${name}? The stored key goes with it.`);
|
|
749
|
+
if (confirmed !== true) return;
|
|
727
750
|
try {
|
|
728
751
|
ctx.ui.notify(deleteProviderNamed(name) ? `[arnative] Deleted ${name}.` : `[arnative] ${name} was already gone.`, "info");
|
|
752
|
+
announce(ctx.ui, `Provider deleted: ${name}.`);
|
|
729
753
|
} catch (error) {
|
|
730
754
|
ctx.ui.notify(`[arnative] Not deleted: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
731
755
|
}
|
|
@@ -822,7 +846,7 @@ const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry
|
|
|
822
846
|
await saveModelsNamed(ctx, name, mergeLevels(entry, picked, result.meta));
|
|
823
847
|
};
|
|
824
848
|
|
|
825
|
-
const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6]
|
|
849
|
+
const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6] Set level [p] Probe [a/r] All auto/off [Enter] Save [Esc] Back";
|
|
826
850
|
// minimal … max: the efforts a map can offer; off is pi's own switch, not an effort.
|
|
827
851
|
const EFFORT_LEVELS = THINKING_LEVELS.slice(1);
|
|
828
852
|
|
|
@@ -1101,6 +1125,7 @@ const editNameFlow = async (ctx: ExtensionCommandContext, name: string): Promise
|
|
|
1101
1125
|
return name;
|
|
1102
1126
|
}
|
|
1103
1127
|
ctx.ui.notify(`[arnative] Renamed ${name} → ${value}. Open /model to refresh.`, "info");
|
|
1128
|
+
announce(ctx.ui, `Provider renamed: ${name} → ${value}.`);
|
|
1104
1129
|
return value;
|
|
1105
1130
|
};
|
|
1106
1131
|
|
|
@@ -1118,6 +1143,7 @@ const editKeyFlow = async (ctx: ExtensionCommandContext, name: string, entry: Pr
|
|
|
1118
1143
|
return;
|
|
1119
1144
|
}
|
|
1120
1145
|
ctx.ui.notify(`[arnative] ${name}: API key replaced (${keyHint(value)}). Open /model to refresh.`, "info");
|
|
1146
|
+
announce(ctx.ui, `API key replaced: ${name} (${keyHint(value)}).`);
|
|
1121
1147
|
};
|
|
1122
1148
|
|
|
1123
1149
|
/** The Edit menu: one field per row, each write immediate. Returns the provider id to keep
|
package/lib/shortcuts.ts
CHANGED
|
@@ -78,18 +78,20 @@ export const UNDO_USAGE = keySet("U", "shift+u");
|
|
|
78
78
|
const legend = (...pairs: [string, string][]): string => pairs.map(([key, action]) => `[${key}] ${action}`).join(" ");
|
|
79
79
|
|
|
80
80
|
/** Root `/arnative` menu: nothing behind it, so Esc closes. */
|
|
81
|
-
export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "
|
|
81
|
+
export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Select"], [CANCEL.label, "Close"]);
|
|
82
82
|
/** Move-and-open list inside a submenu (the provider list, the provider actions): Esc steps
|
|
83
83
|
* back to the screen above, exactly like ←. */
|
|
84
|
-
export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "
|
|
84
|
+
export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Select"], [CANCEL.label, "Back"]);
|
|
85
85
|
/** Live-preview list: moving applies, Enter keeps, Esc drops the preview and steps out. */
|
|
86
86
|
export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [CANCEL.label, "Back"]);
|
|
87
87
|
/** A list you only read (the `/todos` recap): moving changes nothing, so there is no Open. */
|
|
88
88
|
export const LEGEND_READ_ONLY = legend([MOVE.label, "Move"], [CANCEL.label, "Close"]);
|
|
89
89
|
/** The usage dashboard. `reset` adds the key that deletes history, so a screen without
|
|
90
|
-
* that key never advertises it; `undo` appears only while a reset can be undone.
|
|
91
|
-
|
|
92
|
-
|
|
90
|
+
* that key never advertises it; `undo` appears only while a reset can be undone. `v` cycles
|
|
91
|
+
* the Provider → Project → Prices views, handled on every view; `next` names the view that
|
|
92
|
+
* key would show, so the legend states the destination instead of the generic word View. */
|
|
93
|
+
export function legendUsage(width: number, opts: { reset?: boolean; undo?: boolean; next?: string } = {}): string {
|
|
94
|
+
const pairs: [string, string][] = [[MOVE.label, "Move"], [RANGE.label, "Range"], ["Space/Click", "Show/Hide"], ["v", opts.next ? `Next: ${opts.next}` : "View"]];
|
|
93
95
|
if (opts.reset) pairs.push([CANCEL.label, "Back"], [RESET_USAGE.label, "Reset"]);
|
|
94
96
|
if (opts.undo) pairs.push([UNDO_USAGE.label, "Undo"]);
|
|
95
97
|
if (!opts.reset) pairs.push([CANCEL.label, "Back"]);
|
|
@@ -130,7 +132,7 @@ if (isMain(import.meta.url)) {
|
|
|
130
132
|
assert(!matchesBack("h"), "a bare letter is not the back key");
|
|
131
133
|
// The legends are built from the same keys the handlers match, so a key cannot be
|
|
132
134
|
// advertised on one screen and handled on none.
|
|
133
|
-
assert(LEGEND_MOVE === "[↑↓] Move [Enter]
|
|
135
|
+
assert(LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", `submenu legend pinned, got ${LEGEND_MOVE}`);
|
|
134
136
|
assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
|
|
135
137
|
assert(
|
|
136
138
|
LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${CANCEL.label}] Back`,
|
|
@@ -142,8 +144,11 @@ if (isMain(import.meta.url)) {
|
|
|
142
144
|
assert(CANCEL.matches("\x1b"), "[Esc] matches escape");
|
|
143
145
|
assert(!CANCEL.matches("\x1b[D"), "[Esc] is not the ← byte sequence");
|
|
144
146
|
assert(legendUsage(120).includes("[Esc] Back"), "a wide usage legend advertises Esc Back");
|
|
145
|
-
assert(legendUsage(
|
|
147
|
+
assert(legendUsage(140).includes("[Space/Click] Show/Hide"), "a wide usage legend advertises Space and the mouse");
|
|
148
|
+
assert(legendUsage(120).includes("[v] View"), "a wide usage legend advertises the view key the dashboard handles");
|
|
149
|
+
assert(legendUsage(120, { next: "Project" }).includes("[v] Next: Project"), "the legend names the view the key would show");
|
|
146
150
|
assert(legendUsage(20) === "[Esc] Back", "a narrow usage legend degrades to the one key that still fits");
|
|
151
|
+
assert(!legendUsage(20).includes("[v]"), "the narrow usage legend drops the view key with the rest");
|
|
147
152
|
assert(legendUsage(160, { reset: true }).includes("[R] Reset"), "a reset-capable dashboard advertises R Reset");
|
|
148
153
|
assert(!legendUsage(160).includes("Reset"), "the read-only dashboard does not advertise a key it lacks");
|
|
149
154
|
assert(RESET_USAGE.matches("R") && !RESET_USAGE.matches("r"), "a capital R is shift+r, not r");
|
package/lib/status-widget.ts
CHANGED
|
@@ -55,6 +55,26 @@ export function statusRows(th: FgTheme, rows: string[], width = Number.POSITIVE_
|
|
|
55
55
|
return Number.isFinite(width) ? lines.map((line) => truncateToWidth(line, width, "")) : lines;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/** Key for the one-line change notice above the editor. */
|
|
59
|
+
export const NOTICE_KEY = "arnative-notice";
|
|
60
|
+
/** How long a change notice stays before it clears itself. */
|
|
61
|
+
export const NOTICE_MS = 6_000;
|
|
62
|
+
let noticeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* State what the last change did, in the status slot above the editor, and clear it after
|
|
66
|
+
* {@link NOTICE_MS}. The next change replaces the line instead of stacking. A UI without
|
|
67
|
+
* widgets (RPC/headless) is left alone.
|
|
68
|
+
*/
|
|
69
|
+
export function announce(ui: { setWidget?(key: string, content: string[] | undefined): void } | undefined, message: string): void {
|
|
70
|
+
if (!ui?.setWidget) return;
|
|
71
|
+
ui.setWidget(NOTICE_KEY, [message]);
|
|
72
|
+
if (noticeTimer) clearTimeout(noticeTimer);
|
|
73
|
+
noticeTimer = setTimeout(() => ui.setWidget?.(NOTICE_KEY, undefined), NOTICE_MS);
|
|
74
|
+
// Do not hold the process open just to hide a notice.
|
|
75
|
+
(noticeTimer as { unref?(): void }).unref?.();
|
|
76
|
+
}
|
|
77
|
+
|
|
58
78
|
if (isMain(import.meta.url)) {
|
|
59
79
|
const tag = (color: string, text: string) => `<${color}>${text}</${color}>`;
|
|
60
80
|
assert(
|