@ftrdotdev/pi-tracker 0.2.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/LICENSE +21 -0
- package/README.md +164 -0
- package/package.json +71 -0
- package/src/domain.test.ts +157 -0
- package/src/domain.ts +62 -0
- package/src/index.ts +455 -0
- package/src/persistence.test.ts +192 -0
- package/src/persistence.ts +47 -0
- package/src/store.test.ts +809 -0
- package/src/store.ts +517 -0
- package/src/tool-metadata.test.ts +213 -0
- package/src/tool-metadata.ts +302 -0
- package/src/ui.test.ts +204 -0
- package/src/ui.ts +468 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
3
|
+
import { makeBorderedBox } from "@ftrdotdev/pi-tui";
|
|
4
|
+
import { Effect, Layer, ManagedRuntime, Option, Result } from "effect";
|
|
5
|
+
import { TodoItem, TodoList, TrackerState, emptyState, encodeState } from "./domain.ts";
|
|
6
|
+
import { TrackerPersistence } from "./persistence.ts";
|
|
7
|
+
import { TrackerError, TrackerStore, type UpdateItemPatch } from "./store.ts";
|
|
8
|
+
import {
|
|
9
|
+
TRACKER_TOOL_METADATA,
|
|
10
|
+
doneMarkReminder,
|
|
11
|
+
validateTrackerCall,
|
|
12
|
+
type TrackerToolAction,
|
|
13
|
+
type TrackerToolDetails,
|
|
14
|
+
type TrackerToolParams,
|
|
15
|
+
} from "./tool-metadata.ts";
|
|
16
|
+
import { makeTrackerOverlay, makeTrackerWidget, type TrackerUiAction } from "./ui.ts";
|
|
17
|
+
|
|
18
|
+
/** Custom-entry type used to persist the tracker state in the session. */
|
|
19
|
+
const CUSTOM_TYPE = "tracker/state";
|
|
20
|
+
|
|
21
|
+
// --------------------------------------------------------------------------
|
|
22
|
+
// Effect bridge
|
|
23
|
+
// --------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Run a store operation: `TrackerStore` (the service key) is itself an
|
|
27
|
+
* Effect that yields the service instance.
|
|
28
|
+
*/
|
|
29
|
+
const withStore = <A, E>(
|
|
30
|
+
f: (store: TrackerStore["Service"]) => Effect.Effect<A, E>,
|
|
31
|
+
): Effect.Effect<A, E, TrackerStore> => Effect.flatMap(TrackerStore, f);
|
|
32
|
+
|
|
33
|
+
const withPersistence = <A, E>(
|
|
34
|
+
f: (persistence: TrackerPersistence["Service"]) => Effect.Effect<A, E>,
|
|
35
|
+
): Effect.Effect<A, E, TrackerPersistence> => Effect.flatMap(TrackerPersistence, f);
|
|
36
|
+
|
|
37
|
+
/** Throw for a missing required tool parameter; caught in `execute`. */
|
|
38
|
+
const requireParam = <T>(value: T | undefined, name: string): T => {
|
|
39
|
+
if (value === undefined) throw new Error(`${name} is required for this tracker action`);
|
|
40
|
+
return value;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// --------------------------------------------------------------------------
|
|
44
|
+
// Extension
|
|
45
|
+
// --------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
export default function (pi: ExtensionAPI): void {
|
|
48
|
+
const runtime = ManagedRuntime.make(
|
|
49
|
+
TrackerStore.layer.pipe(
|
|
50
|
+
Layer.provideMerge(
|
|
51
|
+
TrackerPersistence.layer((encoded) => pi.appendEntry(CUSTOM_TYPE, encoded)),
|
|
52
|
+
),
|
|
53
|
+
),
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
/** Mirror of the store state, read by the widget and tool renderers. */
|
|
57
|
+
let state: TrackerState = emptyState();
|
|
58
|
+
|
|
59
|
+
const buildToolProgram = (
|
|
60
|
+
params: TrackerToolParams,
|
|
61
|
+
): Effect.Effect<unknown, TrackerError, TrackerStore> => {
|
|
62
|
+
switch (params.action) {
|
|
63
|
+
case "list":
|
|
64
|
+
return withStore((store) => store.state);
|
|
65
|
+
case "create_list":
|
|
66
|
+
return withStore((store) =>
|
|
67
|
+
store.createList(requireParam(params.name, "name"), {
|
|
68
|
+
activate: params.activate ?? true,
|
|
69
|
+
...(params.initial_items !== undefined ? { initialItems: params.initial_items } : {}),
|
|
70
|
+
}),
|
|
71
|
+
);
|
|
72
|
+
case "delete_list":
|
|
73
|
+
return withStore((store) => store.deleteList(requireParam(params.list_id, "list_id")));
|
|
74
|
+
case "set_active":
|
|
75
|
+
return withStore((store) => store.setActiveList(params.list_id ?? null));
|
|
76
|
+
case "add_item": {
|
|
77
|
+
const raw = requireParam(params.text, "text");
|
|
78
|
+
const texts = Array.isArray(raw) ? raw : [raw];
|
|
79
|
+
return withStore((store) => store.addItems(requireParam(params.list_id, "list_id"), texts));
|
|
80
|
+
}
|
|
81
|
+
case "update_item": {
|
|
82
|
+
if (params.items !== undefined) {
|
|
83
|
+
// Wire format is snake_case (item_id); the store uses itemId.
|
|
84
|
+
const batch = params.items.map(({ item_id, ...patch }) => ({
|
|
85
|
+
itemId: item_id,
|
|
86
|
+
...patch,
|
|
87
|
+
}));
|
|
88
|
+
return withStore((store) => store.updateItems(batch));
|
|
89
|
+
}
|
|
90
|
+
const patch: UpdateItemPatch = {
|
|
91
|
+
...(params.text !== undefined && !Array.isArray(params.text)
|
|
92
|
+
? { text: params.text }
|
|
93
|
+
: {}),
|
|
94
|
+
...(params.done !== undefined ? { done: params.done } : {}),
|
|
95
|
+
};
|
|
96
|
+
return withStore((store) =>
|
|
97
|
+
store.updateItems([{ itemId: requireParam(params.item_id, "item_id"), ...patch }]),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
case "remove_item":
|
|
101
|
+
return withStore((store) => store.removeItem(requireParam(params.item_id, "item_id")));
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const uiActionProgram = (
|
|
106
|
+
action: TrackerUiAction,
|
|
107
|
+
): Effect.Effect<unknown, TrackerError, TrackerStore> => {
|
|
108
|
+
switch (action.type) {
|
|
109
|
+
case "createList":
|
|
110
|
+
return withStore((store) => store.createList(action.name));
|
|
111
|
+
case "deleteList":
|
|
112
|
+
return withStore((store) => store.deleteList(action.listId));
|
|
113
|
+
case "setActive":
|
|
114
|
+
return withStore((store) => store.setActiveList(action.listId));
|
|
115
|
+
case "addItem":
|
|
116
|
+
return withStore((store) => store.addItem(action.listId, action.text));
|
|
117
|
+
case "updateItem":
|
|
118
|
+
return withStore((store) => store.updateItem(action.itemId, action.patch));
|
|
119
|
+
case "removeItem":
|
|
120
|
+
return withStore((store) => store.removeItem(action.itemId));
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Persist the current store state and refresh the widget pane. Called after
|
|
126
|
+
* every successful mutation, from both the tool and the /tracker UI, so the
|
|
127
|
+
* two entry points can never diverge.
|
|
128
|
+
*/
|
|
129
|
+
const applyMutation = async (ctx: ExtensionContext): Promise<void> => {
|
|
130
|
+
state = await runtime.runPromise(withStore((store) => store.state));
|
|
131
|
+
await runtime.runPromise(
|
|
132
|
+
withPersistence((p) => p.save(state)).pipe(
|
|
133
|
+
Effect.catch((err) =>
|
|
134
|
+
Effect.logWarning(
|
|
135
|
+
`tracker: persist failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
136
|
+
),
|
|
137
|
+
),
|
|
138
|
+
),
|
|
139
|
+
);
|
|
140
|
+
refreshWidget(ctx);
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const refreshWidget = (ctx: ExtensionContext): void => {
|
|
144
|
+
// The widget is the opt-in view of the *active* list: hidden when no list
|
|
145
|
+
// is active (including after a deselect), regardless of list count.
|
|
146
|
+
if (state.activeListId === null) {
|
|
147
|
+
ctx.ui.setWidget("tracker", undefined);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
ctx.ui.setWidget("tracker", (_tui, theme) => {
|
|
151
|
+
// BorderedBox caches per width; the widget is re-registered on every
|
|
152
|
+
// state change and invalidate() clears the cache on theme changes, so
|
|
153
|
+
// stale themed output (ANSI colors baked into the cached strings) is
|
|
154
|
+
// never served.
|
|
155
|
+
const widget = makeTrackerWidget(state, theme);
|
|
156
|
+
// pi calls render/invalidate as methods of the object returned here,
|
|
157
|
+
// so hand over arrows, never detached methods — an unbound reference
|
|
158
|
+
// would rebind `this` to this wrapper and crash inside BorderedBox.
|
|
159
|
+
return {
|
|
160
|
+
render: (width) => widget.render(width),
|
|
161
|
+
invalidate: () => widget.invalidate(),
|
|
162
|
+
};
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/** Rebuild state from the latest tracker custom entry on the current branch. */
|
|
167
|
+
const reconstructState = async (ctx: ExtensionContext): Promise<void> => {
|
|
168
|
+
let snapshot: unknown = null;
|
|
169
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
170
|
+
if (entry.type === "custom" && entry.customType === CUSTOM_TYPE) {
|
|
171
|
+
snapshot = entry.data;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (snapshot === null) {
|
|
176
|
+
state = emptyState();
|
|
177
|
+
} else {
|
|
178
|
+
const result = await runtime.runPromise(
|
|
179
|
+
Effect.result(withPersistence((p) => p.restore(snapshot))),
|
|
180
|
+
);
|
|
181
|
+
if (Result.isFailure(result)) {
|
|
182
|
+
ctx.ui.notify("tracker: saved state could not be decoded — starting empty", "warning");
|
|
183
|
+
state = emptyState();
|
|
184
|
+
} else {
|
|
185
|
+
state = Option.getOrThrow(Result.getSuccess(result));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
await runtime.runPromise(withStore((store) => store.reset(state)));
|
|
189
|
+
refreshWidget(ctx);
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// --- Session lifecycle -------------------------------------------------
|
|
193
|
+
|
|
194
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
195
|
+
await reconstructState(ctx);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
pi.on("session_tree", async (_event, ctx) => {
|
|
199
|
+
await reconstructState(ctx);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
pi.on("session_shutdown", async () => {
|
|
203
|
+
await runtime.dispose();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// --- Tool ---------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
const listSummary = (current: TrackerState): string => {
|
|
209
|
+
if (current.lists.length === 0) return "No lists";
|
|
210
|
+
return current.lists
|
|
211
|
+
.map((list) => {
|
|
212
|
+
const done = list.items.filter((item) => item.done).length;
|
|
213
|
+
const active = list.id === current.activeListId ? " (active)" : "";
|
|
214
|
+
const items =
|
|
215
|
+
list.items.length === 0
|
|
216
|
+
? " (no items)"
|
|
217
|
+
: list.items
|
|
218
|
+
.map(
|
|
219
|
+
(item, i) => ` [${item.done ? "x" : " "}] #${list.name}:${i + 1}: ${item.text}`,
|
|
220
|
+
)
|
|
221
|
+
.join("\n");
|
|
222
|
+
return `[${list.id}] ${list.name} — ${done}/${list.items.length}${active}\n${items}`;
|
|
223
|
+
})
|
|
224
|
+
.join("\n");
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const toolSuccess = (
|
|
228
|
+
params: TrackerToolParams,
|
|
229
|
+
value: unknown,
|
|
230
|
+
current: TrackerState,
|
|
231
|
+
): { content: Array<{ type: "text"; text: string }>; details: TrackerToolDetails } => {
|
|
232
|
+
const details: TrackerToolDetails = { action: params.action };
|
|
233
|
+
let text = "";
|
|
234
|
+
switch (params.action) {
|
|
235
|
+
case "list":
|
|
236
|
+
details.snapshot = encodeState(current);
|
|
237
|
+
text = listSummary(current);
|
|
238
|
+
break;
|
|
239
|
+
case "create_list": {
|
|
240
|
+
const list = value as TodoList;
|
|
241
|
+
details.list = list;
|
|
242
|
+
text = `Created list #${list.id}: ${list.name}`;
|
|
243
|
+
if (list.items.length > 0) {
|
|
244
|
+
text += ` with ${list.items.length} initial item${list.items.length === 1 ? "" : "s"}`;
|
|
245
|
+
}
|
|
246
|
+
if (list.id === current.activeListId) text += " (active)";
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
case "delete_list":
|
|
250
|
+
details.listId = params.list_id;
|
|
251
|
+
text = `Deleted list #${params.list_id}`;
|
|
252
|
+
break;
|
|
253
|
+
case "set_active": {
|
|
254
|
+
details.listId = params.list_id;
|
|
255
|
+
if (params.list_id === undefined) {
|
|
256
|
+
text = "Active list cleared (widget hidden)";
|
|
257
|
+
} else {
|
|
258
|
+
const list = current.lists.find((l) => l.id === params.list_id);
|
|
259
|
+
text = `Active list: ${list ? list.name : `#${params.list_id}`}`;
|
|
260
|
+
}
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
case "add_item": {
|
|
264
|
+
const items = value as TodoItem[];
|
|
265
|
+
const list = current.lists.find((l) => l.id === params.list_id);
|
|
266
|
+
details.list = list;
|
|
267
|
+
details.items = items;
|
|
268
|
+
const listName = list ? list.name : `#${params.list_id}`;
|
|
269
|
+
// The new items are the last ones in the list, so their ids follow
|
|
270
|
+
// directly from the position they now occupy.
|
|
271
|
+
const firstId = list ? list.items.length - items.length + 1 : 1;
|
|
272
|
+
const ids = items.map((_, i) => `${listName}:${firstId + i}`);
|
|
273
|
+
text =
|
|
274
|
+
items.length === 1
|
|
275
|
+
? `Added item #${ids[0]} to ${listName}: ${items[0]!.text}`
|
|
276
|
+
: `Added ${items.length} items to ${listName}: ${ids.map((id, i) => `#${id}: ${items[i]!.text}`).join(", ")}`;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
case "update_item": {
|
|
280
|
+
const items = value as TodoItem[];
|
|
281
|
+
details.items = items;
|
|
282
|
+
const patches =
|
|
283
|
+
params.items !== undefined
|
|
284
|
+
? params.items
|
|
285
|
+
: [{ item_id: params.item_id, text: params.text, done: params.done }];
|
|
286
|
+
const parts = items.map((item, i) => {
|
|
287
|
+
const patch = patches[i]!;
|
|
288
|
+
const changes: string[] = [];
|
|
289
|
+
if (patch.done !== undefined) changes.push(item.done ? "completed" : "uncompleted");
|
|
290
|
+
if (patch.text !== undefined) changes.push(`text: ${item.text}`);
|
|
291
|
+
return `${patch.item_id}${changes.length === 0 ? " (no change)" : ` (${changes.join(", ")})`}`;
|
|
292
|
+
});
|
|
293
|
+
text = `Updated ${items.length} item${items.length === 1 ? "" : "s"}: ${parts.join(", ")}`;
|
|
294
|
+
// Anti-pattern guard: batch-marking done items at once is the
|
|
295
|
+
// terminal-batch signature; the reminder lands in the result so the
|
|
296
|
+
// caller sees it exactly where the behavior happens.
|
|
297
|
+
const reminder = doneMarkReminder(patches);
|
|
298
|
+
if (reminder !== null) text += `\n${reminder}`;
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
case "remove_item":
|
|
302
|
+
details.itemId = params.item_id;
|
|
303
|
+
text = `Removed item ${params.item_id} (items after it renumbered)`;
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
return { content: [{ type: "text", text }], details };
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const toolError = (
|
|
310
|
+
action: TrackerToolAction,
|
|
311
|
+
message: string,
|
|
312
|
+
): { content: Array<{ type: "text"; text: string }>; details: TrackerToolDetails } => ({
|
|
313
|
+
content: [{ type: "text", text: message }],
|
|
314
|
+
details: { action, error: message },
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
pi.registerTool({
|
|
318
|
+
...TRACKER_TOOL_METADATA,
|
|
319
|
+
|
|
320
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
321
|
+
const action = params.action;
|
|
322
|
+
// Error-nudging gate: reject incorrect calls (missing required fields,
|
|
323
|
+
// unknown fields, mixed update_item forms) with a precise message that
|
|
324
|
+
// tells the agent exactly what to fix, before any state is touched.
|
|
325
|
+
const validation = validateTrackerCall(params);
|
|
326
|
+
if (!validation.ok) {
|
|
327
|
+
return toolError(action, validation.message);
|
|
328
|
+
}
|
|
329
|
+
let program: Effect.Effect<unknown, TrackerError, TrackerStore>;
|
|
330
|
+
try {
|
|
331
|
+
program = buildToolProgram(params);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
return toolError(action, err instanceof Error ? err.message : String(err));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const result = await runtime.runPromise(Effect.result(program));
|
|
337
|
+
if (Result.isFailure(result)) {
|
|
338
|
+
const failure = Option.getOrThrow(Result.getFailure(result));
|
|
339
|
+
return toolError(action, failure.message);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (action !== "list") {
|
|
343
|
+
await applyMutation(ctx);
|
|
344
|
+
}
|
|
345
|
+
return toolSuccess(params, Option.getOrThrow(Result.getSuccess(result)), state);
|
|
346
|
+
},
|
|
347
|
+
|
|
348
|
+
renderCall(args, theme, _context) {
|
|
349
|
+
// Args can come from failed validation too, so read them loosely.
|
|
350
|
+
const raw = args as unknown as Record<string, unknown>;
|
|
351
|
+
const action = String(raw.action ?? "list");
|
|
352
|
+
let text = theme.fg("toolTitle", theme.bold("tracker ")) + theme.fg("muted", action);
|
|
353
|
+
if (typeof raw.name === "string") text += ` ${theme.fg("dim", `"${raw.name}"`)}`;
|
|
354
|
+
if (typeof raw.text === "string") {
|
|
355
|
+
text += ` ${theme.fg("dim", `"${raw.text}"`)}`;
|
|
356
|
+
} else if (Array.isArray(raw.text)) {
|
|
357
|
+
text += ` ${theme.fg("dim", raw.text.map((t) => `"${t}"`).join(" "))}`;
|
|
358
|
+
}
|
|
359
|
+
if (Array.isArray(raw.initial_items)) {
|
|
360
|
+
text += ` ${theme.fg("dim", raw.initial_items.map((t) => `"${t}"`).join(" "))}`;
|
|
361
|
+
}
|
|
362
|
+
if (Array.isArray(raw.items)) text += ` ${theme.fg("accent", `${raw.items.length} items`)}`;
|
|
363
|
+
if (raw.activate === false) text += ` ${theme.fg("muted", "(no auto-switch)")}`;
|
|
364
|
+
if (typeof raw.list_id === "number") text += ` ${theme.fg("accent", `#${raw.list_id}`)}`;
|
|
365
|
+
if (typeof raw.item_id === "string") text += ` ${theme.fg("accent", `item #${raw.item_id}`)}`;
|
|
366
|
+
return new Text(text, 0, 0);
|
|
367
|
+
},
|
|
368
|
+
|
|
369
|
+
renderResult(result, { expanded }, theme, _context) {
|
|
370
|
+
const details = result.details as TrackerToolDetails | undefined;
|
|
371
|
+
if (!details) {
|
|
372
|
+
const text = result.content[0];
|
|
373
|
+
return new Text(text?.type === "text" ? text.text : "", 0, 0);
|
|
374
|
+
}
|
|
375
|
+
if (details.error) {
|
|
376
|
+
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
|
|
377
|
+
}
|
|
378
|
+
if (details.action === "list") {
|
|
379
|
+
const snapshot = details.snapshot;
|
|
380
|
+
if (!snapshot || snapshot.lists.length === 0) {
|
|
381
|
+
return new Text(theme.fg("dim", "No lists"), 0, 0);
|
|
382
|
+
}
|
|
383
|
+
const parts: string[] = [];
|
|
384
|
+
for (const list of snapshot.lists) {
|
|
385
|
+
const done = list.items.filter((item) => item.done).length;
|
|
386
|
+
const active = list.id === snapshot.activeListId ? " ●" : "";
|
|
387
|
+
parts.push(
|
|
388
|
+
theme.fg("accent", `[${list.id}] ${list.name}`) +
|
|
389
|
+
theme.fg("muted", ` (${done}/${list.items.length})${active}`),
|
|
390
|
+
);
|
|
391
|
+
const display = expanded ? list.items : list.items.slice(0, 5);
|
|
392
|
+
for (const [idx, item] of display.entries()) {
|
|
393
|
+
const check = item.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
|
|
394
|
+
const itemText = item.done ? theme.fg("dim", item.text) : item.text;
|
|
395
|
+
parts.push(` ${check} ${theme.fg("accent", `#${list.name}:${idx + 1}`)} ${itemText}`);
|
|
396
|
+
}
|
|
397
|
+
if (!expanded && list.items.length > 5) {
|
|
398
|
+
parts.push(theme.fg("dim", ` ... ${list.items.length - 5} more`));
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return new Text(parts.join("\n"), 0, 0);
|
|
402
|
+
}
|
|
403
|
+
const text = result.content[0];
|
|
404
|
+
const msg = text?.type === "text" ? text.text : "";
|
|
405
|
+
return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
|
|
406
|
+
},
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
// --- Command ------------------------------------------------------------
|
|
410
|
+
|
|
411
|
+
const runUiAction = async (
|
|
412
|
+
ctx: ExtensionContext,
|
|
413
|
+
action: TrackerUiAction,
|
|
414
|
+
): Promise<string | null> => {
|
|
415
|
+
const result = await runtime.runPromise(Effect.result(uiActionProgram(action)));
|
|
416
|
+
if (Result.isFailure(result)) {
|
|
417
|
+
return Option.getOrThrow(Result.getFailure(result)).message;
|
|
418
|
+
}
|
|
419
|
+
await applyMutation(ctx);
|
|
420
|
+
return null;
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
pi.registerCommand("tracker", {
|
|
424
|
+
description: "Open the interactive tracker (lists and items)",
|
|
425
|
+
handler: async (_args, ctx) => {
|
|
426
|
+
if (ctx.mode !== "tui") {
|
|
427
|
+
ctx.ui.notify("/tracker requires interactive mode", "error");
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
await ctx.ui.custom<void>((tui, theme, _kb, done) => {
|
|
431
|
+
// The overlay content is framed by the same house rounded box as the
|
|
432
|
+
// widget. makeBorderedBox's own cache is disabled so an overlay
|
|
433
|
+
// mutation at an unchanged width is never served stale rails; the
|
|
434
|
+
// overlay caches by its own (width, state, signature) fingerprint.
|
|
435
|
+
const overlay = makeTrackerOverlay({
|
|
436
|
+
getState: () => state,
|
|
437
|
+
theme,
|
|
438
|
+
requestRender: () => tui.requestRender(),
|
|
439
|
+
onAction: (action) => runUiAction(ctx, action),
|
|
440
|
+
onClose: () => done(),
|
|
441
|
+
});
|
|
442
|
+
const framed = makeBorderedBox(overlay, theme, {
|
|
443
|
+
label: "Tracker",
|
|
444
|
+
color: "border",
|
|
445
|
+
cache: false,
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
render: (width) => framed.render(width),
|
|
449
|
+
invalidate: () => framed.invalidate(),
|
|
450
|
+
handleInput: (data) => overlay.handleInput(data),
|
|
451
|
+
};
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { assert, layer } from "@effect/vitest";
|
|
2
|
+
import { Effect, Option, Result } from "effect";
|
|
3
|
+
import { TodoItem, TodoList, TrackerState, emptyState, encodeState } from "./domain.ts";
|
|
4
|
+
import { TrackerPersistence } from "./persistence.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The suite shares one `TrackerPersistence.layer`, whose `append` callback
|
|
8
|
+
* writes into this module-level capture. Every test resets the capture first.
|
|
9
|
+
*/
|
|
10
|
+
const capture: { latest: unknown; snapshots: unknown[] } = { latest: undefined, snapshots: [] };
|
|
11
|
+
const resetCapture = () => {
|
|
12
|
+
capture.latest = undefined;
|
|
13
|
+
capture.snapshots = [];
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
layer(
|
|
17
|
+
TrackerPersistence.layer((encoded) => {
|
|
18
|
+
capture.latest = encoded;
|
|
19
|
+
capture.snapshots.push(encoded);
|
|
20
|
+
}),
|
|
21
|
+
)("TrackerPersistence", (it) => {
|
|
22
|
+
const sampleState = (): TrackerState =>
|
|
23
|
+
new TrackerState({
|
|
24
|
+
lists: [
|
|
25
|
+
new TodoList({
|
|
26
|
+
id: 1,
|
|
27
|
+
name: "Work",
|
|
28
|
+
items: [
|
|
29
|
+
new TodoItem({ text: "write plan", done: true }),
|
|
30
|
+
new TodoItem({ text: "implement tracker", done: false }),
|
|
31
|
+
],
|
|
32
|
+
}),
|
|
33
|
+
new TodoList({
|
|
34
|
+
id: 2,
|
|
35
|
+
name: "Home",
|
|
36
|
+
items: [new TodoItem({ text: "water plants", done: false })],
|
|
37
|
+
}),
|
|
38
|
+
],
|
|
39
|
+
activeListId: 1,
|
|
40
|
+
nextListId: 3,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const decodeFailureOf = (snapshot: unknown) =>
|
|
44
|
+
Effect.gen(function* () {
|
|
45
|
+
const persistence = yield* TrackerPersistence;
|
|
46
|
+
const result = yield* Effect.result(persistence.restore(snapshot));
|
|
47
|
+
assert(Result.isFailure(result), `expected ${JSON.stringify(snapshot)} to fail`);
|
|
48
|
+
const failure = Option.getOrThrow(Result.getFailure(result));
|
|
49
|
+
assert.strictEqual(failure._tag, "SchemaError");
|
|
50
|
+
return failure.message;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it.effect("save writes the encoded snapshot", () =>
|
|
54
|
+
Effect.gen(function* () {
|
|
55
|
+
resetCapture();
|
|
56
|
+
const persistence = yield* TrackerPersistence;
|
|
57
|
+
const state = sampleState();
|
|
58
|
+
|
|
59
|
+
yield* persistence.save(state);
|
|
60
|
+
|
|
61
|
+
assert.deepStrictEqual(capture.latest, encodeState(state));
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
it.effect("save then restore round-trips the state", () =>
|
|
66
|
+
Effect.gen(function* () {
|
|
67
|
+
resetCapture();
|
|
68
|
+
const persistence = yield* TrackerPersistence;
|
|
69
|
+
const state = sampleState();
|
|
70
|
+
|
|
71
|
+
yield* persistence.save(state);
|
|
72
|
+
const restored = yield* persistence.restore(capture.latest);
|
|
73
|
+
|
|
74
|
+
assert.deepStrictEqual(encodeState(restored), encodeState(state));
|
|
75
|
+
}),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
it.effect("restore returns real class instances", () =>
|
|
79
|
+
Effect.gen(function* () {
|
|
80
|
+
resetCapture();
|
|
81
|
+
const persistence = yield* TrackerPersistence;
|
|
82
|
+
yield* persistence.save(sampleState());
|
|
83
|
+
|
|
84
|
+
const restored = yield* persistence.restore(capture.latest);
|
|
85
|
+
assert(restored instanceof TrackerState);
|
|
86
|
+
assert(restored.lists[0] instanceof TodoList);
|
|
87
|
+
assert(restored.lists[0]?.items[0] instanceof TodoItem);
|
|
88
|
+
}),
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
it.effect("saved snapshots are JSON-serializable", () =>
|
|
92
|
+
Effect.gen(function* () {
|
|
93
|
+
resetCapture();
|
|
94
|
+
const persistence = yield* TrackerPersistence;
|
|
95
|
+
yield* persistence.save(sampleState());
|
|
96
|
+
|
|
97
|
+
const roundTripped = JSON.parse(JSON.stringify(capture.latest)) as unknown;
|
|
98
|
+
assert.deepStrictEqual(roundTripped, capture.latest);
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
it.effect("every save is captured, restore decodes the latest", () =>
|
|
103
|
+
Effect.gen(function* () {
|
|
104
|
+
resetCapture();
|
|
105
|
+
const persistence = yield* TrackerPersistence;
|
|
106
|
+
const first = emptyState();
|
|
107
|
+
const second = sampleState();
|
|
108
|
+
|
|
109
|
+
yield* persistence.save(first);
|
|
110
|
+
yield* persistence.save(second);
|
|
111
|
+
|
|
112
|
+
assert.strictEqual(capture.snapshots.length, 2);
|
|
113
|
+
assert.deepStrictEqual(capture.snapshots[0], encodeState(first));
|
|
114
|
+
const restored = yield* persistence.restore(capture.latest);
|
|
115
|
+
assert.deepStrictEqual(encodeState(restored), encodeState(second));
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
it.effect("empty state round-trips with activeListId null", () =>
|
|
120
|
+
Effect.gen(function* () {
|
|
121
|
+
resetCapture();
|
|
122
|
+
const persistence = yield* TrackerPersistence;
|
|
123
|
+
yield* persistence.save(emptyState());
|
|
124
|
+
|
|
125
|
+
const restored = yield* persistence.restore(capture.latest);
|
|
126
|
+
assert.deepStrictEqual(encodeState(restored), encodeState(emptyState()));
|
|
127
|
+
assert.strictEqual(restored.activeListId, null);
|
|
128
|
+
assert("activeListId" in (capture.latest as object));
|
|
129
|
+
}),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
it.effect("restore ignores unknown extra keys (forward compatibility)", () =>
|
|
133
|
+
Effect.gen(function* () {
|
|
134
|
+
resetCapture();
|
|
135
|
+
const persistence = yield* TrackerPersistence;
|
|
136
|
+
const state = sampleState();
|
|
137
|
+
yield* persistence.save(state);
|
|
138
|
+
|
|
139
|
+
const snapshot = {
|
|
140
|
+
...(capture.latest as object),
|
|
141
|
+
futureKey: { anything: 1 },
|
|
142
|
+
};
|
|
143
|
+
const restored = yield* persistence.restore(snapshot);
|
|
144
|
+
assert.deepStrictEqual(encodeState(restored), encodeState(state));
|
|
145
|
+
}),
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
it.effect("restore accepts legacy snapshots (stored item ids are ignored)", () =>
|
|
149
|
+
Effect.gen(function* () {
|
|
150
|
+
resetCapture();
|
|
151
|
+
const persistence = yield* TrackerPersistence;
|
|
152
|
+
const legacy = {
|
|
153
|
+
lists: [{ id: 1, name: "Work", items: [{ id: 7, text: "a", done: false }] }],
|
|
154
|
+
activeListId: 1,
|
|
155
|
+
nextListId: 2,
|
|
156
|
+
nextItemId: 8,
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const restored = yield* persistence.restore(legacy);
|
|
160
|
+
const expected = new TrackerState({
|
|
161
|
+
lists: [
|
|
162
|
+
new TodoList({ id: 1, name: "Work", items: [new TodoItem({ text: "a", done: false })] }),
|
|
163
|
+
],
|
|
164
|
+
activeListId: 1,
|
|
165
|
+
nextListId: 2,
|
|
166
|
+
});
|
|
167
|
+
assert.deepStrictEqual(encodeState(restored), encodeState(expected));
|
|
168
|
+
assert.deepStrictEqual(restored.lists[0]?.items, [new TodoItem({ text: "a", done: false })]);
|
|
169
|
+
}),
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
it.effect("restore rejects non-object garbage", () =>
|
|
173
|
+
Effect.gen(function* () {
|
|
174
|
+
for (const bad of ["not json", 42, null, undefined, [1, 2]]) {
|
|
175
|
+
yield* decodeFailureOf(bad);
|
|
176
|
+
}
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
it.effect("restore rejects structurally invalid snapshots", () =>
|
|
181
|
+
Effect.gen(function* () {
|
|
182
|
+
yield* decodeFailureOf({ lists: 42 });
|
|
183
|
+
yield* decodeFailureOf({ lists: [] }); // missing counters + activeListId
|
|
184
|
+
yield* decodeFailureOf({
|
|
185
|
+
lists: [{ id: 1, name: "Work", items: [{ text: "x", done: "yes" }] }],
|
|
186
|
+
activeListId: null,
|
|
187
|
+
nextListId: 2,
|
|
188
|
+
});
|
|
189
|
+
yield* decodeFailureOf({ ...encodeState(emptyState()), nextListId: 1.5 });
|
|
190
|
+
}),
|
|
191
|
+
);
|
|
192
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Context, Effect, Layer, Schema } from "effect";
|
|
2
|
+
import { TrackerState, decodeStateEffect, encodeStateEffect } from "./domain.ts";
|
|
3
|
+
|
|
4
|
+
/** The plain JSON shape of a `TrackerState` (what goes into the session). */
|
|
5
|
+
export type EncodedState = Schema.Codec.Encoded<typeof TrackerState>;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Persistence boundary for the tracker state.
|
|
9
|
+
*
|
|
10
|
+
* `save` encodes a `TrackerState` into its plain JSON shape and hands it to an
|
|
11
|
+
* injected `append` callback — the live wiring in `src/index.ts` passes
|
|
12
|
+
* `(encoded) => pi.appendEntry("tracker/state", encoded)`, so the state is
|
|
13
|
+
* stored in the session file and survives restarts, resumes, and forks.
|
|
14
|
+
*
|
|
15
|
+
* `restore` decodes an untrusted snapshot (e.g. `data` from a session custom
|
|
16
|
+
* entry) back into a validated `TrackerState`, failing with a `SchemaError`
|
|
17
|
+
* on malformed input.
|
|
18
|
+
*
|
|
19
|
+
* The service has no Pi dependency: `append` is injected, which keeps the
|
|
20
|
+
* whole persistence path testable with an in-memory capture.
|
|
21
|
+
*/
|
|
22
|
+
export class TrackerPersistence extends Context.Service<
|
|
23
|
+
TrackerPersistence,
|
|
24
|
+
{
|
|
25
|
+
readonly save: (state: TrackerState) => Effect.Effect<void, Schema.SchemaError>;
|
|
26
|
+
readonly restore: (snapshot: unknown) => Effect.Effect<TrackerState, Schema.SchemaError>;
|
|
27
|
+
}
|
|
28
|
+
>()("tracker/TrackerPersistence") {
|
|
29
|
+
static readonly layer = (
|
|
30
|
+
append: (encoded: EncodedState) => void,
|
|
31
|
+
): Layer.Layer<TrackerPersistence> =>
|
|
32
|
+
Layer.sync(TrackerPersistence, () => {
|
|
33
|
+
const save = Effect.fn("TrackerPersistence.save")(function* (state: TrackerState) {
|
|
34
|
+
// encodeState throws only on invalid input; state comes from the
|
|
35
|
+
// store, so a throw here is a defect (fail loudly, never persist
|
|
36
|
+
// garbage).
|
|
37
|
+
const encoded = yield* encodeStateEffect(state);
|
|
38
|
+
yield* Effect.sync(() => append(encoded));
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const restore = Effect.fn("TrackerPersistence.restore")(function* (snapshot: unknown) {
|
|
42
|
+
return yield* decodeStateEffect(snapshot);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
return TrackerPersistence.of({ save, restore });
|
|
46
|
+
});
|
|
47
|
+
}
|