@bismawy/pi-arnative 0.8.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,489 @@
1
+ /**
2
+ * Task list for the agent: the `todo` tool, the boxed widget above the editor, the `/todos`
3
+ * recap screen and the expand shortcut. Replaces `@juicesharp/rpiv-todo`, which registered the
4
+ * same tool name, so only one of the two may be installed.
5
+ *
6
+ * State lives in `<agent>/arnative/todos/<session id>.json`, so `/reload` and a resumed session
7
+ * keep the list; every mutation rewrites the file.
8
+ */
9
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
13
+ import { StringEnum, Type } from "@earendil-works/pi-ai";
14
+ import type { TuiMouseEvent } from "@earendil-works/pi-tui";
15
+ import { assert, isMain } from "../lib/check.ts";
16
+ import { inSpans, screenTitle, type TextSpan, textSpans } from "../lib/box.ts";
17
+ import { ListPicker, type ListPickerText } from "../lib/list-picker.ts";
18
+ import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../lib/shortcuts.ts";
19
+ import {
20
+ HINT_COLLAPSE,
21
+ HINT_EXPAND,
22
+ LIST_STATUSES,
23
+ addTodo,
24
+ allDone,
25
+ clearTodos,
26
+ countTodos,
27
+ emptyTodos,
28
+ actionWord,
29
+ listRowsFor,
30
+ normalizeState,
31
+ patchTodo,
32
+ recapRows,
33
+ recapSummary,
34
+ removeTodo,
35
+ renderTodoBox,
36
+ todoLayout,
37
+ todoWindow,
38
+ type TaskState,
39
+ type TodoStatus,
40
+ } from "../lib/todos.ts";
41
+
42
+ /** pi widget key; the extension owns it, so a reload replaces its own box. */
43
+ export const TODO_WIDGET_KEY = "arnative-todos";
44
+
45
+ const STORE_KEY = Symbol.for("pi-arnative.todos.widget");
46
+
47
+ interface WidgetStore {
48
+ state: TaskState;
49
+ expanded: boolean;
50
+ /** First visible task after a scroll; null follows the active task. */
51
+ top: number | null;
52
+ /** False until the widget is registered with this session's `ctx.ui`. */
53
+ registered: boolean;
54
+ /** The TUI handle from the widget factory, for a redraw after a shortcut or a mutation. */
55
+ tui?: { requestRender(force?: boolean): void };
56
+ /** Pending removal of a finished list's box; see {@link doneHideMs}. */
57
+ hideTimer?: ReturnType<typeof setTimeout>;
58
+ }
59
+
60
+ /** How long the finished box stays: long enough to read `All tasks finished`, short enough
61
+ * that the screen clears itself. `PI_ARNATIVE_TODO_HIDE_MS` overrides it (0 removes at once). */
62
+ function doneHideMs(): number {
63
+ const raw = Number(process.env.PI_ARNATIVE_TODO_HIDE_MS);
64
+ return Number.isFinite(raw) && raw >= 0 ? raw : 30_000;
65
+ }
66
+
67
+ /** Module state on globalThis, like the other arnative extensions: `/reload` re-imports the
68
+ * module, and a module-local copy would drop the list and the expanded flag. */
69
+ function store(): WidgetStore {
70
+ const holder = globalThis as Record<symbol, WidgetStore | undefined>;
71
+ holder[STORE_KEY] ??= { state: emptyTodos(), expanded: false, top: null, registered: false };
72
+ return holder[STORE_KEY]!;
73
+ }
74
+
75
+ /** `<agent>/arnative/todos/<session id>.json` — one file per session, so two sessions in the
76
+ * same checkout never overwrite each other's list. */
77
+ const stateFile = (ctx: ExtensionContext): string =>
78
+ join(getAgentDir(), "arnative", "todos", `${ctx.sessionManager.getSessionId()}.json`);
79
+
80
+ function loadState(ctx: ExtensionContext, reload = false): void {
81
+ const s = store();
82
+ cancelHide(s);
83
+ if (!reload) {
84
+ s.expanded = false;
85
+ s.top = null;
86
+ }
87
+ try {
88
+ s.state = normalizeState(JSON.parse(readFileSync(stateFile(ctx), "utf8")) as unknown) ?? emptyTodos();
89
+ } catch {
90
+ // absent, unreadable or not JSON: the session starts with an empty list
91
+ s.state = emptyTodos();
92
+ }
93
+ if (allDone(s.state)) s.expanded = false;
94
+ }
95
+
96
+ function saveState(ctx: ExtensionContext): void {
97
+ const path = stateFile(ctx);
98
+ try {
99
+ mkdirSync(dirname(path), { recursive: true });
100
+ const payload = `${JSON.stringify(store().state, null, 2)}\n`;
101
+ const tmp = `${path}.${process.pid}.tmp`;
102
+ writeFileSync(tmp, payload, "utf8");
103
+ try {
104
+ renameSync(tmp, path);
105
+ } catch (error) {
106
+ // Windows refuses the replace while another process holds the file; an in-place
107
+ // write still lands, and a lost list is worse than the truncation window.
108
+ const code = (error as NodeJS.ErrnoException).code;
109
+ if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw error;
110
+ writeFileSync(path, payload, "utf8");
111
+ rmSync(tmp, { force: true });
112
+ }
113
+ } catch {
114
+ // ignore: the list still renders from memory
115
+ }
116
+ }
117
+
118
+ const PARAMS = Type.Object({
119
+ action: StringEnum(["create", "update", "delete", "clear", "list"], {
120
+ description: "create adds tasks, update changes one, delete removes one, clear empties the list, list reads it back",
121
+ }),
122
+ id: Type.Optional(Type.Number({ description: "Task id: required by update and delete, ignored by the other actions" })),
123
+ subject: Type.Optional(Type.String({ description: "Task title: the new task on create, the new title on update" })),
124
+ status: Type.Optional(StringEnum([...LIST_STATUSES], { description: "New status of the task named by id" })),
125
+ note: Type.Optional(Type.String({ description: "One short line about what is happening now; shown while the task is in progress" })),
126
+ activeForm: Type.Optional(Type.String({ description: "Alias for note, kept for existing sessions" })),
127
+ tasks: Type.Optional(
128
+ Type.Array(Type.Object({ subject: Type.String(), note: Type.Optional(Type.String()) }), {
129
+ description: "Several tasks to add at once",
130
+ }),
131
+ ),
132
+ });
133
+
134
+ const SUMMARY = (state: TaskState): string => {
135
+ const { done, total, doing, queued } = countTodos(state);
136
+ return `${total} tasks: ${doing} in progress, ${queued} queued, ${done} done`;
137
+ };
138
+
139
+ /** The `todo` tool body: mutate the store and answer the model. Persisting and redrawing are
140
+ * the caller's job, so a failed action cannot leave a half-saved file behind. */
141
+ export function runTodo(params: Record<string, unknown>) {
142
+ const s = store();
143
+ const action = String(params.action ?? "");
144
+ const id = typeof params.id === "number" ? params.id : undefined;
145
+ // `activeForm` is the field name older sessions used for the same line.
146
+ const note = typeof params.note === "string" ? params.note : typeof params.activeForm === "string" ? params.activeForm : undefined;
147
+ const fail = (text: string) => ({ content: [{ type: "text" as const, text }], details: { state: s.state }, isError: true });
148
+
149
+ if (action === "create") {
150
+ const batch = Array.isArray(params.tasks) ? (params.tasks as { subject?: unknown; note?: unknown }[]) : [];
151
+ const queue = batch.length > 0 ? batch : typeof params.subject === "string" ? [{ subject: params.subject, note }] : [];
152
+ const added: number[] = [];
153
+ for (const item of queue) {
154
+ const subject = typeof item.subject === "string" ? item.subject.trim() : "";
155
+ if (!subject) continue;
156
+ const result = addTodo(s.state, subject, typeof item.note === "string" ? item.note : undefined);
157
+ s.state = result.state;
158
+ added.push(result.id);
159
+ }
160
+ if (added.length === 0) return fail("create needs a subject or a non-empty tasks list");
161
+ const label = added.length === 1 ? "task" : "tasks";
162
+ return {
163
+ content: [{ type: "text" as const, text: `Added ${added.length} ${label}: #${added.join(", #")}` }],
164
+ details: { state: s.state, detail: actionWord(action) },
165
+ };
166
+ }
167
+
168
+ if (action === "update") {
169
+ if (id === undefined) return fail("update needs id");
170
+ const status = LIST_STATUSES.includes(params.status as TodoStatus) ? (params.status as TodoStatus) : undefined;
171
+ const patch: Parameters<typeof patchTodo>[2] = {};
172
+ if (status) patch.status = status;
173
+ if (typeof params.subject === "string") patch.subject = params.subject;
174
+ if (note !== undefined) patch.note = note;
175
+ if (Object.keys(patch).length === 0) return fail("update needs status, subject or note");
176
+ const next = patchTodo(s.state, id, patch);
177
+ if (!next) return fail(`no task with id ${id}`);
178
+ s.state = next;
179
+ return {
180
+ content: [{ type: "text" as const, text: `Updated #${id}` }],
181
+ details: { state: s.state, detail: actionWord(action, status) },
182
+ };
183
+ }
184
+
185
+ if (action === "delete") {
186
+ if (id === undefined) return fail("delete needs id");
187
+ const next = removeTodo(s.state, id);
188
+ if (!next) return fail(`no task with id ${id}`);
189
+ s.state = next;
190
+ return { content: [{ type: "text" as const, text: `Removed #${id}` }], details: { state: s.state, detail: actionWord(action) } };
191
+ }
192
+
193
+ if (action === "clear") {
194
+ const removed = s.state.tasks.length;
195
+ s.state = clearTodos(s.state);
196
+ const label = removed === 1 ? "task" : "tasks";
197
+ return { content: [{ type: "text" as const, text: `Cleared ${removed} ${label}` }], details: { state: s.state, detail: actionWord(action) } };
198
+ }
199
+
200
+ if (action === "list") {
201
+ const lines = s.state.tasks.map((task) => {
202
+ const note = task.note && task.status === "in_progress" ? ` · ${task.note}` : "";
203
+ return `#${task.id} [${task.status}] ${task.subject}${note}`;
204
+ });
205
+ return { content: [{ type: "text" as const, text: lines.length > 0 ? lines.join("\n") : "The list is empty" }], details: { state: s.state, detail: actionWord(action) } };
206
+ }
207
+
208
+ return fail(`unknown action: ${action}`);
209
+ }
210
+
211
+ /** Queue the removal of a finished list's box. Idempotent: a redraw or a click must not
212
+ * restart the wait, or the box could outlive the interest in it. */
213
+ function scheduleHide(ctx: ExtensionContext, s: WidgetStore): void {
214
+ if (s.hideTimer) return;
215
+ s.hideTimer = setTimeout(() => {
216
+ s.hideTimer = undefined;
217
+ ctx.ui?.setWidget?.(TODO_WIDGET_KEY, undefined);
218
+ s.registered = false;
219
+ s.tui = undefined;
220
+ }, doneHideMs());
221
+ // Never hold pi's process open for a cosmetic row.
222
+ s.hideTimer.unref?.();
223
+ }
224
+
225
+ function cancelHide(s: WidgetStore): void {
226
+ if (!s.hideTimer) return;
227
+ clearTimeout(s.hideTimer);
228
+ s.hideTimer = undefined;
229
+ }
230
+
231
+ /** Register the widget with this session, or redraw it. `force` re-registers after `/reload`,
232
+ * where pi keeps the key but the old component is gone. */
233
+ function refresh(ctx: ExtensionContext, force = false): void {
234
+ const s = store();
235
+ if (s.state.tasks.length === 0) {
236
+ cancelHide(s);
237
+ ctx.ui?.setWidget?.(TODO_WIDGET_KEY, undefined);
238
+ s.registered = false;
239
+ return;
240
+ }
241
+ // Work left keeps the box; a finished list folds to its `All tasks finished` row and
242
+ // leaves after {@link doneHideMs}, unless the user opened the box to read it.
243
+ if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
244
+ else cancelHide(s);
245
+ if (!force && s.registered) {
246
+ s.tui?.requestRender(true);
247
+ return;
248
+ }
249
+ ctx.ui?.setWidget?.(
250
+ TODO_WIDGET_KEY,
251
+ (tui: WidgetStore["tui"], factoryTheme: Parameters<typeof renderTodoBox>[0]) => {
252
+ s.tui = tui;
253
+ let height = 0;
254
+ let layout: ReturnType<typeof todoLayout> = { lines: [], up: null, down: null };
255
+ /** Cells of the hint in the drawn box: the only place a press expands or folds it. */
256
+ let spans: TextSpan[] = [];
257
+ /** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
258
+ * window parks at the end of the list instead of drifting. */
259
+ const scroll = (delta: number): void => {
260
+ const { start } = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
261
+ s.top = start + delta;
262
+ s.tui?.requestRender(true);
263
+ };
264
+ return {
265
+ render: (width: number): string[] => {
266
+ // The live theme, so a theme switch repaints without re-registering.
267
+ const theme = (ctx.ui?.theme ?? factoryTheme) as Parameters<typeof renderTodoBox>[0];
268
+ layout = todoLayout(theme, s.state, s.expanded, width, {
269
+ top: s.top,
270
+ rows: listRowsFor(process.stdout.rows),
271
+ thinking: ctx.thinkingLevel,
272
+ });
273
+ height = layout.lines.length;
274
+ spans = textSpans(layout.lines, s.expanded ? HINT_COLLAPSE : HINT_EXPAND);
275
+ return layout.lines;
276
+ },
277
+ invalidate: (): void => {},
278
+ // Two click targets, both drawn as affordances: the hint text expands or folds the
279
+ // box, and the counter rows scroll the window. Every other cell is left to pi, so
280
+ // the task names stay selectable and copyable. The work is done on the press: pi
281
+ // only synthesizes a click when the pointer did not move at all.
282
+ handleMouse: (event: TuiMouseEvent) => {
283
+ if (event.button !== "left" || event.y >= height) return undefined;
284
+ const onHint = inSpans(spans, event.y, event.x);
285
+ const onCounter = event.y === layout.up || event.y === layout.down;
286
+ if (!onHint && !onCounter) return undefined;
287
+ // The press already did it, so the release and the click that may follow are
288
+ // swallowed: toggling again on the click would undo the press.
289
+ if (event.type !== "press") return { handled: true, render: false };
290
+ if (onCounter) {
291
+ scroll(event.y === layout.up ? -1 : 1);
292
+ return { handled: true, render: true };
293
+ }
294
+ s.expanded = !s.expanded;
295
+ s.top = null;
296
+ if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
297
+ else cancelHide(s);
298
+ s.tui?.requestRender(true);
299
+ return { handled: true, render: true };
300
+ },
301
+ dispose: (): void => {},
302
+ };
303
+ },
304
+ { placement: "aboveEditor" },
305
+ );
306
+ s.registered = true;
307
+ }
308
+
309
+ /** Scroll the expanded box from the keyboard: the counters are mouse-only in fullscreen mode,
310
+ * and pi leaves mouse input to the terminal everywhere else. */
311
+ function scrollKeyboard(ctx: ExtensionContext, delta: number): void {
312
+ const s = store();
313
+ if (!s.expanded || s.state.tasks.length <= listRowsFor(process.stdout.rows)) return;
314
+ const { start } = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
315
+ s.top = start + delta;
316
+ refresh(ctx);
317
+ }
318
+
319
+ /** Expand or collapse, then redraw. This is the keyboard path in regular mode, where pi leaves
320
+ * mouse input to the terminal and the click never arrives. */
321
+ function toggle(ctx: ExtensionContext): void {
322
+ const s = store();
323
+ if (s.state.tasks.length === 0) return;
324
+ s.expanded = !s.expanded;
325
+ // Opening or closing shows the active task again, so a scroll never outlives the view.
326
+ s.top = null;
327
+ refresh(ctx);
328
+ }
329
+
330
+ const RECAP_TEXT: ListPickerText = {
331
+ title: screenTitle("Tasks"),
332
+ description: "",
333
+ legend: LEGEND_READ_ONLY,
334
+ };
335
+
336
+ /** `/todos`: the whole list in the arnative screen chrome, in progress first. */
337
+ async function openRecap(ctx: ExtensionCommandContext): Promise<void> {
338
+ const s = store();
339
+ if (s.state.tasks.length === 0) {
340
+ ctx.ui.notify("No tasks yet. Ask the agent to add some.", "info");
341
+ return;
342
+ }
343
+ const rows = recapRows(s.state);
344
+ if (ctx.mode !== "tui") {
345
+ ctx.ui.notify([recapSummary(s.state), ...rows.map((row) => `${row.label} · ${row.note}`)].join("\n"), "info");
346
+ return;
347
+ }
348
+ // The in-progress row is the one the list marks as current.
349
+ const active = rows.find((row) => row.note.startsWith("in progress"))?.label;
350
+ await ctx.ui.custom<boolean>((tui, theme, _keybindings, done) =>
351
+ new ListPicker(
352
+ theme,
353
+ rows,
354
+ active,
355
+ { preview: () => {}, revert: () => {}, done: () => done(false), requestRender: () => tui.requestRender() },
356
+ { ...RECAP_TEXT, description: recapSummary(s.state) },
357
+ false,
358
+ ctx.thinkingLevel,
359
+ 12,
360
+ ),
361
+ );
362
+ }
363
+
364
+ export default function (pi: ExtensionAPI) {
365
+ pi.registerTool({
366
+ name: "todo",
367
+ label: "Todo",
368
+ description:
369
+ "Manage the task list shown above the editor. Actions: create (one subject or tasks[]), update (id + status/subject/note), delete (id), clear, list. Status: pending, in_progress, completed. Exactly one task is in progress at a time.",
370
+ promptGuidelines: [
371
+ "Mark a task in_progress before starting it and completed immediately when it is done, never in batches.",
372
+ "Set note to a short line about what you are doing now; the widget shows it in dim next to the in-progress task.",
373
+ ],
374
+ parameters: PARAMS,
375
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
376
+ // A mutation brings the view back to the active task; a scroll should not hide the row
377
+ // that just changed.
378
+ const s = store();
379
+ s.top = null;
380
+ const result = runTodo(params as unknown as Record<string, unknown>);
381
+ // Nothing left to watch: the widget folds away, and the next task opens folded.
382
+ if (allDone(s.state)) s.expanded = false;
383
+ saveState(ctx);
384
+ refresh(ctx);
385
+ return result;
386
+ },
387
+ });
388
+
389
+ pi.on("session_start", async (event, ctx) => {
390
+ loadState(ctx, (event as { reason?: string } | undefined)?.reason === "reload");
391
+ refresh(ctx, true);
392
+ });
393
+
394
+ pi.registerCommand("todos", {
395
+ description: "Show every task in this session, in progress first",
396
+ handler: (_args, ctx) => openRecap(ctx),
397
+ });
398
+
399
+ for (const key of SHORTCUT_TOGGLE_TODOS.keys) {
400
+ pi.registerShortcut(key, {
401
+ description: "Expand or collapse the task list",
402
+ handler: (ctx: ExtensionContext) => toggle(ctx),
403
+ });
404
+ }
405
+
406
+ for (const key of SHORTCUT_SCROLL_TODOS_DOWN.keys) {
407
+ pi.registerShortcut(key, {
408
+ description: "Scroll the task list down one task",
409
+ handler: (ctx: ExtensionContext) => scrollKeyboard(ctx, 1),
410
+ });
411
+ }
412
+
413
+ for (const key of SHORTCUT_SCROLL_TODOS_UP.keys) {
414
+ pi.registerShortcut(key, {
415
+ description: "Scroll the task list up one task",
416
+ handler: (ctx: ExtensionContext) => scrollKeyboard(ctx, -1),
417
+ });
418
+ }
419
+ }
420
+
421
+ // Self-check: `node extensions/todos.ts`
422
+ if (isMain(import.meta.url)) {
423
+ const created = runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua", note: "catatan" }] });
424
+ assert(!("isError" in created) && created.content[0]!.text === "Added 2 tasks: #1, #2", `create reports both ids, got ${created.content[0]!.text}`);
425
+ const patched = runTodo({ action: "update", id: 1, status: "in_progress", note: "sedang jalan" });
426
+ assert(!("isError" in patched) && patched.content[0]!.text === "Updated #1", "update reports the id");
427
+ assert(store().state.tasks[0]!.status === "in_progress" && store().state.tasks[0]!.note === "sedang jalan", "update lands in the store");
428
+ assert(SUMMARY(store().state) === "2 tasks: 1 in progress, 1 queued, 0 done", `summary, got ${SUMMARY(store().state)}`);
429
+ const empty = runTodo({ action: "create", subject: " " });
430
+ assert("isError" in empty && empty.isError === true, "an empty create is an error, not a task");
431
+ const missing = runTodo({ action: "update", id: 99, status: "completed" });
432
+ assert("isError" in missing && missing.content[0]!.text === "no task with id 99", "an unknown id is reported");
433
+ const listed = runTodo({ action: "list" });
434
+ assert(listed.content[0]!.text.split("\n").length === 2, "list prints one line per task");
435
+ assert(runTodo({ action: "delete", id: 2 }).content[0]!.text === "Removed #2", "delete reports the id");
436
+ assert(runTodo({ action: "clear" }).content[0]!.text === "Cleared 1 task", "clear counts what it removed");
437
+ // The widget's mouse: the hint text expands and folds the box, every other cell is left
438
+ // to pi so the task names can be selected and copied.
439
+ runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua" }] });
440
+ store().expanded = false;
441
+ let factory: any;
442
+ const widgetCtx: any = { ui: { setWidget: (_key: string, f: any) => (factory = f), theme: null }, thinkingLevel: "off" };
443
+ refresh(widgetCtx, true);
444
+ const widget: any = factory(undefined, null);
445
+ const clickAt = (x: number, y: number): void => {
446
+ for (const type of ["press", "release", "click"]) widget.handleMouse({ type, button: "left", x, y });
447
+ };
448
+ widget.render(80);
449
+ const closed = textSpans(widget.render(80), HINT_EXPAND)[0];
450
+ assert(closed?.row === 1, `widget: the collapsed hint sits on the first content row, got ${closed?.row}`);
451
+ clickAt(closed!.start, closed!.row);
452
+ assert(store().expanded === true, "widget: a click on the hint expands");
453
+ widget.render(80);
454
+ const opened = textSpans(widget.render(80), HINT_COLLAPSE)[0];
455
+ assert(opened !== undefined, "widget: the expanded box offers the fold hint");
456
+ clickAt(opened!.start, opened!.row);
457
+ assert(store().expanded === false, "widget: a click on the fold hint collapses");
458
+ // Off the hint nothing is taken, so pi can start a selection over the task rows.
459
+ for (const [x, y] of [[5, 1], [5, 2], [5, 3]] as const) {
460
+ assert(widget.handleMouse({ type: "press", button: "left", x, y }) === undefined, `widget: a press at ${x},${y} is left to pi`);
461
+ }
462
+ // A finished list shows its `All tasks finished` row, then leaves: /todos still lists it.
463
+ process.env.PI_ARNATIVE_TODO_HIDE_MS = "10";
464
+ let lastFactory: any = "untouched";
465
+ const hideCtx: any = { ui: { setWidget: (_key: string, f: any) => (lastFactory = f), theme: null }, thinkingLevel: "off" };
466
+ for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
467
+ refresh(hideCtx, true);
468
+ assert(typeof lastFactory === "function", "widget: a finished list keeps its box for the wait");
469
+ assert(allDone(store().state), "widget: the list really is finished");
470
+ await new Promise((resolve) => setTimeout(resolve, 60));
471
+ assert(lastFactory === undefined && store().registered === false, "widget: the box leaves once the wait is over");
472
+ // A task reopened during the wait cancels it: the box must not vanish under live work.
473
+ for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
474
+ refresh(hideCtx, true);
475
+ const reopened = store().state.tasks[0]!;
476
+ runTodo({ action: "update", id: reopened.id, status: "in_progress" });
477
+ refresh(hideCtx, true);
478
+ await new Promise((resolve) => setTimeout(resolve, 60));
479
+ assert(typeof lastFactory === "function" && store().registered === true, "widget: live work cancels the wait");
480
+ delete process.env.PI_ARNATIVE_TODO_HIDE_MS;
481
+ // A new task cancels nothing (the timer already fired) and brings the box back at once.
482
+ runTodo({ action: "create", subject: "Lagi" });
483
+ refresh(hideCtx, true);
484
+ assert(typeof lastFactory === "function", "widget: a new task brings the box back");
485
+ // A new session with no file on disk starts empty instead of inheriting the previous session's list.
486
+ loadState({ sessionManager: { getSessionId: () => `empty-${process.pid}-${Date.now()}` } } as never);
487
+ assert(store().state.tasks.length === 0 && store().expanded === false, "session_start: a fresh session starts with an empty list");
488
+ console.log("todos extension self-check OK");
489
+ }