@bismawy/pi-arnative 0.16.0 → 0.18.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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
@@ -12,22 +12,13 @@
12
12
  import type { AssistantMessage } from "@earendil-works/pi-ai";
13
13
  import { AssistantMessageComponent, UserMessageComponent, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
14
  import { sliceByColumn, visibleWidth } from "@earendil-works/pi-tui";
15
- import { ansiBgOpen, stripAnsi, themeOf } from "../lib/ansi.ts";
16
- import { assert, isMain } from "../lib/check.ts";
17
- import { markPatched, originalOf } from "../lib/patch.ts";
15
+ import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf } from "../ansi.ts";
16
+ import { markPatched, originalOf } from "../patch.ts";
17
+ import { getRuntime } from "../runtime.ts";
18
18
 
19
- // Shared across reloads: /reload re-imports this module (moduleCache: false), but the
20
- // prototype patches below survive on the class, so the patched closure and the newly
21
- // registered handlers must read the SAME map and theme. Module-local state would leave
22
- // the closure on stale data — and a captured ctx even on an invalidated one (pi throws
23
- // "stale after session replacement or reload" inside the render pass -> uncaughtException).
24
- type ThemeProxy = { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null;
25
- const TS_STATE_KEY = Symbol.for("pi-arnative.chatTimestampState");
26
- const tsState = ((globalThis as Record<symbol, unknown>)[TS_STATE_KEY] ??= {
27
- map: new Map<string, number>(),
28
- theme: null as ThemeProxy,
29
- }) as { map: Map<string, number>; theme: ThemeProxy };
30
- const USER_TIMESTAMPS_MAP = tsState.map;
19
+ // Shared across reloads via RuntimeState so prototype patches and newly registered
20
+ // handlers read the same map and shared active theme.
21
+ const USER_TIMESTAMPS_MAP = (getRuntime().userTimestamps ??= new Map<string, number>());
31
22
 
32
23
  function userTextOf(message: { content?: unknown }): string {
33
24
  const c = message.content;
@@ -61,7 +52,7 @@ function formatClock(timestamp?: number): string {
61
52
  return `${h}:${m}`;
62
53
  }
63
54
 
64
- export function formatTimeBadge(timeStr: string, th: { fg(color: string, text: string): string } | null): string {
55
+ function formatTimeBadge(timeStr: string, th: { fg(color: string, text: string): string } | null): string {
65
56
  if (th) {
66
57
  try {
67
58
  return th.fg("accent", timeStr);
@@ -90,6 +81,39 @@ const BUBBLE_BG_CACHE_MAX = 8192;
90
81
  let bubbleBgOpen = "";
91
82
  let bubbleBgCache = new Map<string, string>();
92
83
 
84
+ function insertBgAfterResets(line: string, bgOpen: string): string {
85
+ let out = "";
86
+ let i = 0;
87
+ const n = line.length;
88
+ while (i < n) {
89
+ const c0 = line.indexOf("\x1b[0m", i);
90
+ const c49 = line.indexOf("\x1b[49m", i);
91
+ let pos = -1;
92
+ let tokenLen = 0;
93
+ if (c0 >= 0 && (c49 < 0 || c0 < c49)) {
94
+ pos = c0;
95
+ tokenLen = 4;
96
+ } else if (c49 >= 0) {
97
+ pos = c49;
98
+ tokenLen = 5;
99
+ }
100
+ if (pos < 0) {
101
+ out += line.slice(i);
102
+ break;
103
+ }
104
+ const after = pos + tokenLen;
105
+ out += line.slice(i, after);
106
+ // Leave a trailing \x1b[49m alone (it closes the bubble bg), and avoid duplicating
107
+ // bgOpen when a prior repair already placed it right after the reset.
108
+ const isTrailingClose = tokenLen === 5 && after === n;
109
+ if (!isTrailingClose && !line.startsWith(bgOpen, after)) {
110
+ out += bgOpen;
111
+ }
112
+ i = after;
113
+ }
114
+ return out.endsWith(bgOpen) ? `${out}\x1b[49m` : out;
115
+ }
116
+
93
117
  export function repairBubbleBg(line: string, bgOpen: string): string {
94
118
  if (!bgOpen || (!line.includes("\x1b[0m") && !line.includes("\x1b[49m"))) return line;
95
119
  if (bgOpen !== bubbleBgOpen) {
@@ -98,13 +122,38 @@ export function repairBubbleBg(line: string, bgOpen: string): string {
98
122
  }
99
123
  const hit = bubbleBgCache.get(line);
100
124
  if (hit !== undefined) return hit;
101
- const patched = line.split("\x1b[0m").join(`\x1b[0m${bgOpen}`).split("\x1b[49m").join(`\x1b[49m${bgOpen}`);
102
- const result = patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
125
+ const result = insertBgAfterResets(line, bgOpen);
103
126
  if (bubbleBgCache.size >= BUBBLE_BG_CACHE_MAX) bubbleBgCache.clear();
104
127
  bubbleBgCache.set(line, result);
105
128
  return result;
106
129
  }
107
130
 
131
+ function resolveUserTimestamp(comp: { text?: string; timestamp?: string | number }): number | undefined {
132
+ if (typeof comp.timestamp === "number" && comp.timestamp > 0) return comp.timestamp;
133
+ if (typeof comp.timestamp === "string" && comp.timestamp) {
134
+ const parsed = Date.parse(comp.timestamp);
135
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
136
+ }
137
+ const textKey = comp.text?.trim() ?? "";
138
+ return USER_TIMESTAMPS_MAP.get(textKey);
139
+ }
140
+
141
+ type UserRenderCacheEntry = {
142
+ source: readonly string[];
143
+ width: number;
144
+ bgOpen: string;
145
+ badge: string;
146
+ lines: string[];
147
+ };
148
+ type AssistantRenderCacheEntry = {
149
+ source: readonly string[];
150
+ width: number;
151
+ badge: string;
152
+ lines: string[];
153
+ };
154
+ const userRenderCache = new WeakMap<object, UserRenderCacheEntry>();
155
+ const assistantRenderCache = new WeakMap<object, AssistantRenderCacheEntry>();
156
+
108
157
  /**
109
158
  * Paste the clock at the right end of a line, 1 column from the right edge.
110
159
  * When `bgOpen` is given (e.g. user chat) the padding and the clock use that bubble
@@ -127,72 +176,88 @@ export function placeTimeAtRight(
127
176
  }
128
177
 
129
178
  // Both patches reinstall on every load (lib/patch.ts) so a `/reload` applies them.
179
+ // Pi 1.6.0+ Container/Message `render()` returns a shared cached `readonly string[]`, so
180
+ // both wrappers copy before modifying and cache their own output per source array identity.
130
181
  if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.prototype?.render) {
131
182
  if (UserMessageComponent?.prototype?.render) {
132
183
  const proto = UserMessageComponent.prototype as any;
133
- const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
134
- proto.render = markPatched(function (this: any, width: number): string[] {
135
- const lines = origRender.call(this, width);
136
- if (lines.length < 2) return lines;
184
+ const origRender = originalOf<(this: any, width: number) => readonly string[]>(proto, "render");
185
+ proto.render = markPatched(function (this: any, width: number): readonly string[] {
186
+ const source = origRender.call(this, width);
187
+ if (source.length < 2) return source;
188
+
189
+ const activeTheme = getActiveTheme<ThemeProxy>();
190
+ const bgOpen = ansiBgOpen(activeTheme, "userMessageBg");
191
+ const ts = resolveUserTimestamp(this as { text?: string; timestamp?: string | number });
192
+ const timeStr = ts ? formatClock(ts) : "";
193
+ const badge = timeStr ? formatTimeBadge(timeStr, activeTheme) : "";
194
+
195
+ const prev = userRenderCache.get(this);
196
+ if (prev && prev.source === source && prev.width === width && prev.bgOpen === bgOpen && prev.badge === badge) {
197
+ return prev.lines;
198
+ }
137
199
 
138
200
  // Fix the bubble bg first (reset Markdown lines make padding dark),
139
201
  // then paste the clock (which deliberately drops the bg in the badge area).
140
- const bgOpen = ansiBgOpen(tsState.theme, "userMessageBg");
141
- for (let i = 0; i < lines.length; i++) lines[i] = repairBubbleBg(lines[i], bgOpen);
202
+ const lines = [...source];
203
+ for (let i = 0; i < lines.length; i++) lines[i] = repairBubbleBg(lines[i]!, bgOpen);
142
204
 
143
- const textKey = (this as { text?: string }).text?.trim() ?? "";
144
- const ts = USER_TIMESTAMPS_MAP.get(textKey);
145
205
  // No known timestamp -> no clock (a "now" clock would be a lie on old messages).
146
- if (!ts) return lines;
147
- const timeStr = formatClock(ts);
148
- const badge = formatTimeBadge(timeStr, tsState.theme);
149
- const timeW = visibleWidth(timeStr);
150
-
151
- // First text line sits at index 1 (below the box top padding)
152
- const contentLine = lines[1];
153
- const cleanContent = stripAnsi(contentLine).trimEnd();
154
- const contentW = visibleWidth(cleanContent);
155
- const minGap = 2;
206
+ if (timeStr) {
207
+ const timeW = visibleWidth(timeStr);
208
+ // First text line sits at index 1 (below the box top padding)
209
+ const contentLine = lines[1]!;
210
+ const cleanContent = stripAnsi(contentLine).trimEnd();
211
+ const contentW = visibleWidth(cleanContent);
212
+ const minGap = 2;
156
213
 
157
- if (contentW + minGap + timeW <= width) {
158
- // Fits on the first text line: paste right-aligned with a 1-space margin
159
- lines[1] = placeTimeAtRight(contentLine, width, badge, timeW, bgOpen);
160
- } else {
161
- // First text line is full: NEVER truncate content!
162
- // Clock goes to the TOP padding line (always empty, first line of the bubble)
163
- const topLine = lines[0];
164
- const oscMatch = topLine.match(/^(\x1b\]133;[A-Z]\x07)+/);
165
- const prefix = oscMatch ? oscMatch[0] : "";
166
- const rest = topLine.slice(prefix.length);
167
- lines[0] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, bgOpen)}`;
214
+ if (contentW + minGap + timeW <= width) {
215
+ // Fits on the first text line: paste right-aligned with a 1-space margin
216
+ lines[1] = placeTimeAtRight(contentLine, width, badge, timeW, bgOpen);
217
+ } else {
218
+ // First text line is full: NEVER truncate content!
219
+ // Clock goes to the TOP padding line (always empty, first line of the bubble)
220
+ const topLine = lines[0]!;
221
+ const oscMatch = topLine.match(/^(\x1b\]133;[A-Z]\x07)+/);
222
+ const prefix = oscMatch ? oscMatch[0] : "";
223
+ const rest = topLine.slice(prefix.length);
224
+ lines[0] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, bgOpen)}`;
225
+ }
168
226
  }
227
+
228
+ userRenderCache.set(this, { source, width, bgOpen, badge, lines });
169
229
  return lines;
170
230
  });
171
231
  }
172
232
 
173
233
  if (AssistantMessageComponent?.prototype?.render) {
174
234
  const proto = AssistantMessageComponent.prototype as any;
175
- const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
176
- proto.render = markPatched(function (this: any, width: number): string[] {
177
- const lines = origRender.call(this, width);
235
+ const origRender = originalOf<(this: any, width: number) => readonly string[]>(proto, "render");
236
+ proto.render = markPatched(function (this: any, width: number): readonly string[] {
237
+ const source = origRender.call(this, width);
178
238
  const lastMsg = (this as { lastMessage?: AssistantMessage }).lastMessage;
179
239
 
180
240
  // Clock only on the final reply (a message with no toolCall)
181
241
  const hasToolCalls = lastMsg?.content?.some((c) => c.type === "toolCall");
182
- if (hasToolCalls) return lines;
242
+ if (hasToolCalls) return source;
183
243
 
184
244
  // and only when there is real answer text (not thinking only)
185
245
  const hasText = lastMsg?.content?.some((c) => c.type === "text" && c.text.trim());
186
- if (!hasText || lines.length === 0) return lines;
246
+ if (!hasText || source.length === 0) return source;
187
247
 
188
248
  const timeStr = formatClock(lastMsg?.timestamp);
189
- const badge = formatTimeBadge(timeStr, tsState.theme);
249
+ const badge = formatTimeBadge(timeStr, getActiveTheme<ThemeProxy>());
250
+ const prev = assistantRenderCache.get(this);
251
+ if (prev && prev.source === source && prev.width === width && prev.badge === badge) {
252
+ return prev.lines;
253
+ }
254
+
190
255
  const timeW = visibleWidth(timeStr);
191
256
 
192
257
  // First text line that is neither an OSC zone nor a thinking header
193
258
  let targetIdx = -1;
194
- for (let i = 0; i < lines.length; i++) {
195
- const plain = stripAnsi(lines[i].replace(/^(\x1b\]133;[A-Z]\x07)+/, "")).trim();
259
+ for (let i = 0; i < source.length; i++) {
260
+ const plain = stripAnsi(source[i]!.replace(/^(\x1b\]133;[A-Z]\x07)+/, "")).trim();
196
261
  // Never paste onto the hidden thinking line: `Thinking...` while it streams, `Thought for 3s` once it ends (plain or with the \uec21 icon)
197
262
  if (plain.length > 0 && !/^(?:\uec21\s+)?(?:thinking|thought for)\b/i.test(plain)) {
198
263
  targetIdx = i;
@@ -202,7 +267,7 @@ if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.protot
202
267
 
203
268
  if (targetIdx !== -1) {
204
269
  let prefix = "";
205
- let rest = lines[targetIdx];
270
+ let rest = source[targetIdx]!;
206
271
  const oscMatch = rest.match(/^(\x1b\]133;[A-Z]\x07)+/);
207
272
  if (oscMatch) {
208
273
  prefix = oscMatch[0];
@@ -214,10 +279,13 @@ if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.protot
214
279
  const minGap = 2;
215
280
 
216
281
  if (textW + minGap + timeW <= width) {
282
+ const lines = [...source];
217
283
  lines[targetIdx] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, "")}`;
284
+ assistantRenderCache.set(this, { source, width, badge, lines });
285
+ return lines;
218
286
  }
219
287
  }
220
- return lines;
288
+ return source;
221
289
  });
222
290
  }
223
291
  }
@@ -243,81 +311,14 @@ export default function (pi: ExtensionAPI) {
243
311
  // manager already holds the restored history when session_start fires (all reasons:
244
312
  // startup/resume/fork/new/reload).
245
313
  pi.on("session_start", async (_event, ctx) => {
246
- tsState.theme = themeOf<ThemeProxy>(ctx) ?? tsState.theme;
314
+ const th = themeOf<ThemeProxy>(ctx);
315
+ if (th) setActiveTheme(th);
247
316
  prefillUserTimestamps(ctx.sessionManager.getBranch());
248
317
  });
249
318
  }
250
319
 
251
- // Self-check: `node extensions/timestamps.ts`
252
- if (isMain(import.meta.url)) {
253
- const badge = "\x1b[36m17:09\x1b[39m";
254
- const badgeW = 5;
255
-
256
- // Clock flush right with a 1-space margin
257
- const res1 = placeTimeAtRight("Short text", 30, badge, badgeW, "");
258
- assert(visibleWidth(res1) === 30, "line length matches the terminal width");
259
- assert(res1.endsWith(badge + " "), "badge sits 1 space from the right edge");
260
-
261
- // With the user bubble background
262
- const bg = "\x1b[48;2;52;53;61m";
263
- const res2 = placeTimeAtRight(`${bg}Short text`, 30, badge, badgeW, bg);
264
- assert(res2.includes(badge + " \x1b[49m"), "hours, margin space, then bg reset");
265
- assert(res2.endsWith("\x1b[49m"), "background closed at end of line");
266
- assert(visibleWidth(res2) === 30, "line length still matches the width");
267
-
268
- // bubble bg repair: padding after [0m] must be bg'd, line closed with [49m]
269
- const dirty = `${bg}Hello\x1b[0m${" ".repeat(5)}\x1b[49m`;
270
- const clean = repairBubbleBg(dirty, bg);
271
- assert(clean.includes(`\x1b[0m${bg}`), "bg re-applied after the reset");
272
- assert(clean.endsWith("\x1b[49m"), "bubble bg closed at end of line");
273
- assert(repairBubbleBg("plain", "") === "plain", "no bgOpen: unchanged");
274
-
275
- // memoized repair: a different bg code resets the cache, so nothing repairs
276
- // against a stale bubble background after a theme switch
277
- const dirty2 = `${bg}Second\x1b[0m pad \x1b[49m`;
278
- const otherBg = "\x1b[48;2;1;2;3m";
279
- assert(repairBubbleBg(dirty2, otherBg).includes(`\x1b[0m${otherBg}`), "a new bg code repairs against that bg");
280
- assert(repairBubbleBg(dirty2, bg).includes(`\x1b[0m${bg}`), "and back to the previous bg after another reset");
281
- assert(repairBubbleBg(dirty2, bg) === repairBubbleBg(dirty2, bg), "repeat repair stays stable");
282
- assert(ansiBgOpen(null, "userMessageBg") === "", "no theme: empty bgOpen");
283
- assert(
284
- ansiBgOpen({ bg: (_c, t) => `\x1b[48;2;52;53;61m${t}\x1b[49m` }, "userMessageBg") === "\x1b[48;2;52;53;61m",
285
- "bgOpen taken from the theme probe",
286
- );
287
-
288
- // Long text: sliceByColumn keeps the width intact (bg branch: badge area carries the bubble bg)
289
- const bgOpenTest = "\x1b[48;2;52;53;61m";
290
- const res3 = placeTimeAtRight("a".repeat(40), 30, badge, badgeW, bgOpenTest);
291
- assert(visibleWidth(res3) === 30, "long text sliced exactly at targetCol");
292
- assert(res3.includes(bgOpenTest), "bg branch: bubble bg applied in the badge area");
293
-
294
- // History prefill: old user messages get their real clock on restore
295
- assert(userTextOf({ content: "plain" }) === "plain", "userTextOf string content");
296
- assert(userTextOf({ content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] }) === "ab", "userTextOf text parts joined");
297
- prefillUserTimestamps([
298
- { type: "message", timestamp: "2026-01-02T03:04:05.000Z", message: { role: "user", content: "old question", timestamp: 1000 } },
299
- { type: "message", timestamp: "not-a-date", message: { role: "user", content: [{ type: "text", text: "old reply" }] } },
300
- ]);
301
- assert(USER_TIMESTAMPS_MAP.get("old question") === 1000, "prefill stores the message timestamp");
302
- assert((USER_TIMESTAMPS_MAP.get("old reply") ?? 0) > 0, "prefill falls back to the entry timestamp");
303
-
304
- // Reload invariant: /reload re-imports the module while the prototype patch below keeps
305
- // running, so the fresh handlers MUST write into the same map/theme the patched render reads.
306
- const reloaded = (await import(`${import.meta.url}?reload=1`)) as typeof import("./timestamps.ts");
307
- const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
308
- const theme = { fg: (_c: string, t: string) => t };
309
- reloaded.default({ on: (ev: string, h: never) => void (handlers[ev] = h) } as never);
310
- await handlers.session_start(
311
- {},
312
- {
313
- sessionManager: {
314
- getBranch: () => [{ timestamp: "", message: { role: "user", content: "after reload", timestamp: 4242 } }],
315
- },
316
- ui: { theme },
317
- },
318
- );
319
- assert(USER_TIMESTAMPS_MAP.get("after reload") === 4242, "reloaded module prefills the shared map read by the patched render");
320
- assert(!USER_TIMESTAMPS_MAP.has("old question"), "session_start clears the map first (bounded growth, current session only)");
321
- assert(tsState.theme === theme, "reloaded module shares the theme read by the patched render");
322
- console.log("timestamps.ts self-check OK");
323
- }
320
+ export const __test = {
321
+ USER_TIMESTAMPS_MAP,
322
+ userTextOf,
323
+ prefillUserTimestamps,
324
+ };
@@ -6,17 +6,15 @@
6
6
  * State lives in `<agent>/arnative/todos/<session id>.json`, so `/reload` and a resumed session
7
7
  * keep the list; every mutation rewrites the file.
8
8
  */
9
- import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
10
- import { tmpdir } from "node:os";
9
+ import { readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
11
10
  import { join } from "node:path";
12
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
13
- import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import { getAgentDir, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext } from "@earendil-works/pi-coding-agent";
14
12
  import type { TuiMouseEvent } from "@earendil-works/pi-tui";
15
- import { assert, isMain } from "../lib/check.ts";
16
- import { writeAtomicSync } from "../lib/preset-store.ts";
17
- import { inSpans, screenTitle, type TextSpan, textSpans } from "../lib/box.ts";
18
- import { ListPicker, type ListPickerText } from "../lib/list-picker.ts";
19
- import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../lib/shortcuts.ts";
13
+ import { writeJsonAtomicSync } from "../preset-store.ts";
14
+ import { getRuntime } from "../runtime.ts";
15
+ import { createHoldRepeat, inSpans, screenTitle, type TextSpan, textSpans } from "../box.ts";
16
+ import { ListPicker, type ListPickerText } from "../list-picker.ts";
17
+ import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../shortcuts.ts";
20
18
  import {
21
19
  HINT_COLLAPSE,
22
20
  HINT_EXPAND,
@@ -36,22 +34,15 @@ import {
36
34
  renderTodoBox,
37
35
  todoLayout,
38
36
  todoWindow,
39
- type TaskState,
37
+ type TodoState,
40
38
  type TodoStatus,
41
- } from "../lib/todos.ts";
39
+ } from "../todos.ts";
42
40
 
43
41
  /** pi widget key; the extension owns it, so a reload replaces its own box. */
44
- export const TODO_WIDGET_KEY = "arnative-todos";
45
-
46
- /** Delay before holding a `↑`/`↓ n more` row starts repeating, so a normal click scrolls once. */
47
- const HOLD_DELAY_MS = 250;
48
- /** Step interval while holding a `↑`/`↓ n more` counter row. */
49
- const HOLD_REPEAT_MS = 90;
50
-
51
- const STORE_KEY = Symbol.for("pi-arnative.todos.widget");
42
+ const TODO_WIDGET_KEY = "arnative-todos";
52
43
 
53
44
  interface WidgetStore {
54
- state: TaskState;
45
+ state: TodoState;
55
46
  expanded: boolean;
56
47
  /** First visible task after a scroll; null follows the active task. */
57
48
  top: number | null;
@@ -70,12 +61,11 @@ function doneHideMs(): number {
70
61
  return Number.isFinite(raw) && raw >= 0 ? raw : 30_000;
71
62
  }
72
63
 
73
- /** Module state on globalThis, like the other arnative extensions: `/reload` re-imports the
74
- * module, and a module-local copy would drop the list and the expanded flag. */
64
+ /** Module state on RuntimeState so `/reload` keeps the list and expanded flag. */
75
65
  function store(): WidgetStore {
76
- const holder = globalThis as Record<symbol, WidgetStore | undefined>;
77
- holder[STORE_KEY] ??= { state: emptyTodos(), expanded: false, top: null, registered: false };
78
- return holder[STORE_KEY]!;
66
+ const rt = getRuntime();
67
+ rt.todosWidget ??= { state: emptyTodos(), expanded: false, top: null, registered: false } satisfies WidgetStore;
68
+ return rt.todosWidget as WidgetStore;
79
69
  }
80
70
 
81
71
  /** Completed/empty session todo files older than this are pruned on session start. */
@@ -139,7 +129,7 @@ function loadState(ctx: ExtensionContext, reload = false): void {
139
129
 
140
130
  function saveState(ctx: ExtensionContext): void {
141
131
  try {
142
- writeAtomicSync(stateFile(ctx), `${JSON.stringify(store().state, null, 2)}\n`);
132
+ writeJsonAtomicSync(stateFile(ctx), store().state);
143
133
  } catch {
144
134
  // ignore: the list still renders from memory
145
135
  }
@@ -190,7 +180,7 @@ const PARAMS = {
190
180
  },
191
181
  } as never;
192
182
 
193
- const SUMMARY = (state: TaskState): string => {
183
+ const SUMMARY = (state: TodoState): string => {
194
184
  const { done, total, doing, queued } = countTodos(state);
195
185
  return `${total} tasks: ${doing} in progress, ${queued} queued, ${done} done`;
196
186
  };
@@ -302,7 +292,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
302
292
  if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
303
293
  else cancelHide(s);
304
294
  if (!force && s.registered) {
305
- s.tui?.requestRender(true);
295
+ s.tui?.requestRender(false);
306
296
  return;
307
297
  }
308
298
  ctx.ui?.setWidget?.(
@@ -316,24 +306,14 @@ function refresh(ctx: ExtensionContext, force = false): void {
316
306
  /** Swallows the follow-up release/click after a press on the hint or a counter, because
317
307
  * the re-render between press and click can remove `↑ 1 more` / `↓ 1 more` at that row. */
318
308
  let swallowClick = false;
319
- let holdDelay: ReturnType<typeof setTimeout> | undefined;
320
- let holdRepeat: ReturnType<typeof setInterval> | undefined;
321
- const stopHold = (): void => {
322
- if (holdDelay) {
323
- clearTimeout(holdDelay);
324
- holdDelay = undefined;
325
- }
326
- if (holdRepeat) {
327
- clearInterval(holdRepeat);
328
- holdRepeat = undefined;
329
- }
330
- };
309
+ const hold = createHoldRepeat();
310
+ const stopHold = (): void => hold.stop();
331
311
  const toggleExpanded = (): { handled: true; render: true } => {
332
312
  s.expanded = !s.expanded;
333
313
  s.top = null;
334
314
  if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
335
315
  else cancelHide(s);
336
- s.tui?.requestRender(true);
316
+ s.tui?.requestRender(false);
337
317
  return { handled: true, render: true };
338
318
  };
339
319
  /** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
@@ -341,32 +321,17 @@ function refresh(ctx: ExtensionContext, force = false): void {
341
321
  const scroll = (delta: number): void => {
342
322
  const { start } = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
343
323
  s.top = start + delta;
344
- s.tui?.requestRender(true);
324
+ s.tui?.requestRender(false);
345
325
  };
346
326
  const startHold = (delta: -1 | 1): void => {
347
- stopHold();
348
- const step = (): void => {
349
- if (!s.expanded) {
350
- stopHold();
351
- return;
352
- }
327
+ hold.start(() => {
328
+ if (!s.expanded) return false;
353
329
  const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
354
- if ((delta < 0 && win.above <= 0) || (delta > 0 && win.below <= 0)) {
355
- stopHold();
356
- return;
357
- }
330
+ if ((delta < 0 && win.above <= 0) || (delta > 0 && win.below <= 0)) return false;
358
331
  scroll(delta);
359
- };
360
- holdDelay = setTimeout(() => {
361
- holdDelay = undefined;
362
- step();
363
- if (s.expanded && holdRepeat === undefined) {
364
- const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
365
- if ((delta < 0 && win.above > 0) || (delta > 0 && win.below > 0)) {
366
- holdRepeat = setInterval(step, HOLD_REPEAT_MS);
367
- }
368
- }
369
- }, HOLD_DELAY_MS);
332
+ const next = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
333
+ return (delta < 0 && next.above > 0) || (delta > 0 && next.below > 0);
334
+ });
370
335
  };
371
336
  return {
372
337
  render: (width: number): string[] => {
@@ -508,11 +473,20 @@ export default function (pi: ExtensionAPI) {
508
473
 
509
474
  pi.on("session_start", async (event, ctx) => {
510
475
  const reload = (event as { reason?: string } | undefined)?.reason === "reload";
476
+ // Drop any pending hide timer from the previous session before its ctx goes stale.
477
+ cancelHide(store());
511
478
  loadState(ctx, reload);
512
479
  if (!reload) pruneCompletedTodos(todosDir(), { skipFile: stateFile(ctx) });
513
480
  refresh(ctx, true);
514
481
  });
515
482
 
483
+ pi.on("session_shutdown", () => {
484
+ const s = store();
485
+ cancelHide(s);
486
+ s.registered = false;
487
+ s.tui = undefined;
488
+ });
489
+
516
490
  pi.registerCommand("todos", {
517
491
  description: "Show every task in this session, in progress first",
518
492
  handler: (_args, ctx) => openRecap(ctx),
@@ -540,98 +514,10 @@ export default function (pi: ExtensionAPI) {
540
514
  }
541
515
  }
542
516
 
543
- // Self-check: `node extensions/todos.ts`
544
- if (isMain(import.meta.url)) {
545
- const created = runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua", note: "catatan" }] });
546
- assert(!("isError" in created) && created.content[0]!.text === "Added 2 tasks: #1, #2", `create reports both ids, got ${created.content[0]!.text}`);
547
- const patched = runTodo({ action: "update", id: 1, status: "in_progress", note: "sedang jalan" });
548
- assert(!("isError" in patched) && patched.content[0]!.text === "Updated #1", "update reports the id");
549
- assert(store().state.tasks[0]!.status === "in_progress" && store().state.tasks[0]!.note === "sedang jalan", "update lands in the store");
550
- assert(SUMMARY(store().state) === "2 tasks: 1 in progress, 1 queued, 0 done", `summary, got ${SUMMARY(store().state)}`);
551
- const empty = runTodo({ action: "create", subject: " " });
552
- assert("isError" in empty && empty.isError === true, "an empty create is an error, not a task");
553
- const missing = runTodo({ action: "update", id: 99, status: "completed" });
554
- assert("isError" in missing && missing.content[0]!.text === "no task with id 99", "an unknown id is reported");
555
- const listed = runTodo({ action: "list" });
556
- assert(listed.content[0]!.text.split("\n").length === 2, "list prints one line per task");
557
- assert(runTodo({ action: "delete", id: 2 }).content[0]!.text === "Removed #2", "delete reports the id");
558
- assert(runTodo({ action: "clear" }).content[0]!.text === "Cleared 1 task", "clear counts what it removed");
559
- // The widget's mouse: the hint text expands and folds the box, every other cell is left
560
- // to pi so the task names can be selected and copied.
561
- runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua" }] });
562
- store().expanded = false;
563
- let factory: any;
564
- const widgetCtx: any = { ui: { setWidget: (_key: string, f: any) => (factory = f), theme: null }, thinkingLevel: "off" };
565
- refresh(widgetCtx, true);
566
- const widget: any = factory(undefined, null);
567
- const clickAt = (x: number, y: number): void => {
568
- for (const type of ["press", "release", "click"]) widget.handleMouse({ type, button: "left", x, y });
569
- };
570
- widget.render(80);
571
- const closed = textSpans(widget.render(80), HINT_EXPAND)[0];
572
- assert(closed?.row === 1, `widget: the collapsed hint sits on the first content row, got ${closed?.row}`);
573
- clickAt(closed!.start, closed!.row);
574
- assert(store().expanded === true, "widget: a click on the hint expands");
575
- widget.render(80);
576
- const opened = textSpans(widget.render(80), HINT_COLLAPSE)[0];
577
- assert(opened !== undefined, "widget: the expanded box offers the fold hint");
578
- clickAt(opened!.start, opened!.row);
579
- assert(store().expanded === false, "widget: a click on the fold hint collapses");
580
- // Off the hint nothing is taken, so pi can start a selection over the task rows.
581
- for (const [x, y] of [[5, 1], [5, 2], [5, 3]] as const) {
582
- assert(widget.handleMouse({ type: "press", button: "left", x, y }) === undefined, `widget: a press at ${x},${y} is left to pi`);
583
- }
584
- // A finished list shows its `All tasks finished` row, then leaves: /todos still lists it.
585
- process.env.PI_ARNATIVE_TODO_HIDE_MS = "10";
586
- let lastFactory: any = "untouched";
587
- const hideCtx: any = { ui: { setWidget: (_key: string, f: any) => (lastFactory = f), theme: null }, thinkingLevel: "off" };
588
- for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
589
- refresh(hideCtx, true);
590
- assert(typeof lastFactory === "function", "widget: a finished list keeps its box for the wait");
591
- assert(allDone(store().state), "widget: the list really is finished");
592
- await new Promise((resolve) => setTimeout(resolve, 60));
593
- assert(lastFactory === undefined && store().registered === false, "widget: the box leaves once the wait is over");
594
- // A task reopened during the wait cancels it: the box must not vanish under live work.
595
- for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
596
- refresh(hideCtx, true);
597
- const reopened = store().state.tasks[0]!;
598
- runTodo({ action: "update", id: reopened.id, status: "in_progress" });
599
- refresh(hideCtx, true);
600
- await new Promise((resolve) => setTimeout(resolve, 60));
601
- assert(typeof lastFactory === "function" && store().registered === true, "widget: live work cancels the wait");
602
- delete process.env.PI_ARNATIVE_TODO_HIDE_MS;
603
- // A new task cancels nothing (the timer already fired) and brings the box back at once.
604
- runTodo({ action: "create", subject: "Lagi" });
605
- refresh(hideCtx, true);
606
- assert(typeof lastFactory === "function", "widget: a new task brings the box back");
607
- // A new session with no file on disk starts empty instead of inheriting the previous session's list.
608
- loadState({ sessionManager: { getSessionId: () => `empty-${process.pid}-${Date.now()}` } } as never);
609
- assert(store().state.tasks.length === 0 && store().expanded === false, "session_start: a fresh session starts with an empty list");
610
- // Auto-prune removes old completed/empty todo files while keeping open, recent, and active-session files.
611
- const pruneTmp = mkdtempSync(join(tmpdir(), "arnative-todos-prune-"));
612
- try {
613
- const now = Date.now();
614
- const oldSec = (now - TODO_PRUNE_AGE_MS - 60_000) / 1000;
615
- const put = (name: string, data: unknown, old: boolean): string => {
616
- const p = join(pruneTmp, name);
617
- writeFileSync(p, JSON.stringify(data));
618
- if (old) utimesSync(p, oldSec, oldSec);
619
- return p;
620
- };
621
- put("old-done.json", { nextId: 2, tasks: [{ id: 1, subject: "a", status: "completed" }] }, true);
622
- put("old-empty.json", { nextId: 1, tasks: [] }, true);
623
- put("old-open.json", { nextId: 2, tasks: [{ id: 1, subject: "b", status: "pending" }] }, true);
624
- put("recent-done.json", { nextId: 2, tasks: [{ id: 1, subject: "c", status: "completed" }] }, false);
625
- const activePath = put("active-done.json", { nextId: 2, tasks: [{ id: 1, subject: "d", status: "completed" }] }, true);
626
- const removed = pruneCompletedTodos(pruneTmp, { now, skipFile: activePath });
627
- const left = readdirSync(pruneTmp).sort();
628
- assert(removed === 2, `prune: expected 2 removed, got ${removed}`);
629
- assert(
630
- left.join(",") === "active-done.json,old-open.json,recent-done.json",
631
- `prune: expected open/recent/active kept, got ${left.join(",")}`,
632
- );
633
- } finally {
634
- rmSync(pruneTmp, { recursive: true, force: true });
635
- }
636
- console.log("todos extension self-check OK");
637
- }
517
+ export const __test = {
518
+ store,
519
+ TODO_PRUNE_AGE_MS,
520
+ loadState,
521
+ SUMMARY,
522
+ refresh,
523
+ };