pi-todo-ledger 0.5.0 → 0.7.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.
@@ -12,14 +12,35 @@
12
12
  * `message_end` runs after).
13
13
  */
14
14
 
15
- import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
16
- import { type TUI, truncateToWidth } from "@earendil-works/pi-tui";
17
- import { COLLAPSE_KEY_OFF, getMaxWidgetLines, resolveCollapseKey } from "./config.ts";
15
+ import type {
16
+ ExtensionUIContext,
17
+ Theme,
18
+ } from "@earendil-works/pi-coding-agent";
19
+ import {
20
+ type TUI,
21
+ truncateToWidth,
22
+ visibleWidth,
23
+ } from "@earendil-works/pi-tui";
24
+ import {
25
+ COLLAPSE_KEY_OFF,
26
+ getMaxWidgetLines,
27
+ getView,
28
+ resolveCollapseKey,
29
+ } from "./config.ts";
18
30
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
19
- import { selectHasActive, selectOverlayLayout, selectShowTaskIds, selectTodoCounts } from "./state/selectors.ts";
31
+ import {
32
+ selectHasActive,
33
+ selectOverlayLayout,
34
+ selectShowTaskIds,
35
+ selectTodoCounts,
36
+ } from "./state/selectors.ts";
20
37
  import { getRenderState } from "./state/store.ts";
21
38
  import { formatPlanTaskLine } from "./view/format.ts";
22
- import { planView } from "./view/plan.ts";
39
+ import { type PlanRow, planView } from "./view/plan.ts";
40
+ import type { Task } from "./tool/types.ts";
41
+
42
+ import { history } from "./ledger/herdr-runs.ts";
43
+ import { liveRows, runLine, runState, type Query, type RunRow } from "./view/live-runs.ts";
23
44
 
24
45
  const WIDGET_KEY = "rpiv-todos";
25
46
 
@@ -28,6 +49,19 @@ const OVERLAY_HEADING = "Todos";
28
49
  const OVERLAY_MORE = "more";
29
50
  const OVERLAY_EXPAND_HINT = "{key} to expand";
30
51
  const OVERLAY_COLLAPSED = "collapsed";
52
+ const OVERLAY_SEPARATOR = ", ";
53
+
54
+ /** What one frame's row drawing needs, shared by the full and focus views. */
55
+ interface DrawContext {
56
+ theme: Theme;
57
+ width: number;
58
+ truncate: (line: string) => string;
59
+ bound: Map<number, ReturnType<typeof history>>;
60
+ live: ReturnType<typeof liveRows>;
61
+ showIds: boolean;
62
+ now: number;
63
+ evidence: "inline" | "screen" | undefined;
64
+ }
31
65
 
32
66
  export class TodoOverlay {
33
67
  private uiCtx: ExtensionUIContext | undefined;
@@ -38,10 +72,126 @@ export class TodoOverlay {
38
72
  private lastNextId: number | undefined;
39
73
  private collapsed = false;
40
74
 
75
+ private previous: string[] = [];
76
+ private claimed: string[] = [];
77
+ /** Run rows (with markers) drawn on the frame being painted, awaiting the screen check. */
78
+ private onScreen?: Map<string, string>;
79
+ private screenCheckQueued = false;
80
+ private markers = new Map<string, string>();
81
+ private readonly nonce = Math.random().toString(36).slice(2, 10);
82
+ private tick?: ReturnType<typeof setInterval>;
83
+ private query?: Query;
84
+ constructor(query?: Query) {
85
+ this.query = query;
86
+ }
87
+
88
+ private sendClaim(ids: string[]) {
89
+ // An empty claim is a release; send it only to retract an earlier claim.
90
+ if (!ids.length && !this.claimed.length) return;
91
+ this.claimed = ids;
92
+ try {
93
+ this.query?.({ claim: { by: "pi-todo-ledger", ids } });
94
+ } catch {
95
+ /* host lease expires */
96
+ }
97
+ }
98
+
99
+ /**
100
+ * How the panel learns that a drawn run row reached the screen.
101
+ * - `inline`: Pi's regular renderer writes every widget line.
102
+ * - `screen`: Pi's fullscreen layout clips the widget after render() returns,
103
+ * so each run row carries a marker and the painted frame is searched for it.
104
+ * - `undefined`: no evidence; nothing is claimed.
105
+ */
106
+ private evidence(): "inline" | "screen" | undefined {
107
+ const tui = this.tui as
108
+ | { mode?: string; getScreenLines?: unknown }
109
+ | undefined;
110
+ if (tui?.mode === "regular") return "inline";
111
+ if (tui?.mode === "fullscreen" && typeof tui.getScreenLines === "function")
112
+ return "screen";
113
+ return undefined;
114
+ }
115
+
116
+ /**
117
+ * An invisible marker unique to this panel and run. It has the form of an OSC 8
118
+ * sequence with an `id` parameter and no URI; Pi counts it as zero width, and
119
+ * terminals drop it (Ghostty and Herdr discard it as an invalid OSC 8). It only
120
+ * makes the row's text unique, so the screen check can find the row.
121
+ */
122
+ private marker(id: string): string {
123
+ let m = this.markers.get(id);
124
+ if (!m) {
125
+ m = `\x1b]8;id=pi-todo-ledger-${this.nonce}-${this.markers.size};\x07`;
126
+ this.markers.set(id, m);
127
+ }
128
+ return m;
129
+ }
130
+
131
+ /**
132
+ * Claim the rows Pi painted unchanged on the frame it just wrote. render() runs
133
+ * inside Pi's synchronous frame, so a microtask reads that frame's screen. A
134
+ * row counts only when a screen line starts with the exact row drawn: a clipped
135
+ * row is absent, and a popup, highlight or selection drawn over it changes the
136
+ * line. A changed claim asks for one more frame so the Subagents widget follows.
137
+ */
138
+ private checkScreen(rows: Map<string, string>) {
139
+ this.onScreen = rows;
140
+ if (this.screenCheckQueued) return;
141
+ this.screenCheckQueued = true;
142
+ queueMicrotask(() => {
143
+ this.screenCheckQueued = false;
144
+ const pending = this.onScreen;
145
+ this.onScreen = undefined;
146
+ if (!pending) return;
147
+ let screen: string[] = [];
148
+ try {
149
+ screen =
150
+ (this.tui as { getScreenLines?: () => string[] } | undefined)
151
+ ?.getScreenLines?.() ?? [];
152
+ } catch {
153
+ /* no evidence */
154
+ }
155
+ const ids = [...pending]
156
+ .filter(([, row]) => screen.some((line) => line.startsWith(row)))
157
+ .map(([id]) => id);
158
+ const changed =
159
+ ids.length !== this.claimed.length ||
160
+ ids.some((id) => !this.claimed.includes(id));
161
+ this.sendClaim(ids);
162
+ if (changed) this.tui?.requestRender();
163
+ });
164
+ }
165
+
166
+ private finishFrame(
167
+ ids: string[],
168
+ ticking = ids.length > 0,
169
+ rows?: Map<string, string>,
170
+ ) {
171
+ if (rows?.size) {
172
+ this.previous = [];
173
+ this.checkScreen(rows);
174
+ } else {
175
+ this.onScreen = undefined;
176
+ // Inline: only renew claims for children drawn on both this and the preceding frame.
177
+ this.sendClaim(this.previous.filter((id) => ids.includes(id)));
178
+ this.previous = ids;
179
+ }
180
+ if (ticking && !this.tick) {
181
+ this.tick = setInterval(() => this.tui?.requestRender(), 1000);
182
+ this.tick.unref();
183
+ }
184
+ if (!ticking && this.tick) {
185
+ clearInterval(this.tick);
186
+ this.tick = undefined;
187
+ }
188
+ }
189
+
41
190
  setUICtx(ctx: ExtensionUIContext): void {
42
191
  // Identity-compare so repeat session_start handlers are idempotent;
43
192
  // on identity change (/reload) invalidate so update() re-registers.
44
193
  if (ctx !== this.uiCtx) {
194
+ this.finishFrame([]);
45
195
  this.uiCtx = ctx;
46
196
  this.widgetRegistered = false;
47
197
  this.tui = undefined;
@@ -54,6 +204,7 @@ export class TodoOverlay {
54
204
  const visible = this.selectOverlayTasks(snapshot);
55
205
 
56
206
  if (visible.length === 0) {
207
+ this.finishFrame([]);
57
208
  if (this.widgetRegistered) {
58
209
  this.uiCtx.setWidget(WIDGET_KEY, undefined);
59
210
  this.widgetRegistered = false;
@@ -68,7 +219,8 @@ export class TodoOverlay {
68
219
  (tui, factoryTheme) => {
69
220
  this.tui = tui;
70
221
  return {
71
- render: (width: number) => this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),
222
+ render: (width: number) =>
223
+ this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),
72
224
  invalidate: () => {
73
225
  // No rendered strings are cached. Pi invalidates on theme changes;
74
226
  // the next render reads uiCtx.theme.
@@ -84,6 +236,7 @@ export class TodoOverlay {
84
236
  }
85
237
 
86
238
  resetCompletedDisplayState(): void {
239
+ this.finishFrame([]);
87
240
  this.completedTaskIdsPendingHide.clear();
88
241
  this.hiddenCompletedTaskIds.clear();
89
242
  this.lastNextId = undefined;
@@ -100,6 +253,8 @@ export class TodoOverlay {
100
253
 
101
254
  toggleCollapse(): void {
102
255
  this.collapsed = !this.collapsed;
256
+ // Release before the redraw: the host may draw its widget first in that frame.
257
+ if (this.collapsed) this.finishFrame([]);
103
258
  // Forced full redraw on the collapsed↔expanded height step, mirroring the
104
259
  // lane-dock's requestRender(shapeChanged); distinct from the non-forced
105
260
  // requestRender() refresh paths in update()/hideCompletedTasksFromPreviousTurn().
@@ -117,45 +272,73 @@ export class TodoOverlay {
117
272
  }
118
273
  this.lastNextId = state.nextId;
119
274
  const completedTaskIds = new Set(
120
- state.tasks.filter((task) => task.status === "completed").map((task) => task.id),
275
+ state.tasks
276
+ .filter((task) => task.status === "completed")
277
+ .map((task) => task.id),
121
278
  );
122
279
  for (const taskId of this.completedTaskIdsPendingHide) {
123
- if (!completedTaskIds.has(taskId)) this.completedTaskIdsPendingHide.delete(taskId);
280
+ if (!completedTaskIds.has(taskId))
281
+ this.completedTaskIdsPendingHide.delete(taskId);
124
282
  }
125
283
  for (const taskId of this.hiddenCompletedTaskIds) {
126
- if (!completedTaskIds.has(taskId)) this.hiddenCompletedTaskIds.delete(taskId);
284
+ if (!completedTaskIds.has(taskId))
285
+ this.hiddenCompletedTaskIds.delete(taskId);
127
286
  }
128
287
  return { tasks: [...state.tasks], nextId: state.nextId };
129
288
  }
130
289
 
131
290
  private selectOverlayTasks(snapshot: ReturnType<TodoOverlay["getSnapshot"]>) {
132
- return snapshot.tasks.filter((task) => task.status !== "deleted" && !this.shouldHideCompletedTask(task));
291
+ return snapshot.tasks.filter(
292
+ (task) =>
293
+ task.status !== "deleted" && !this.shouldHideCompletedTask(task),
294
+ );
133
295
  }
134
296
 
135
- private shouldHideCompletedTask(task: ReturnType<TodoOverlay["getSnapshot"]>["tasks"][number]): boolean {
136
- return task.status === "completed" && this.hiddenCompletedTaskIds.has(task.id);
297
+ private shouldHideCompletedTask(
298
+ task: ReturnType<TodoOverlay["getSnapshot"]>["tasks"][number],
299
+ ): boolean {
300
+ return (
301
+ task.status === "completed" && this.hiddenCompletedTaskIds.has(task.id)
302
+ );
137
303
  }
138
304
 
139
305
  private renderWidget(theme: Theme, width: number): string[] {
140
306
  const snapshot = this.getSnapshot();
141
307
  const overlayTasks = this.selectOverlayTasks(snapshot);
142
- if (overlayTasks.length === 0) return [];
308
+ if (overlayTasks.length === 0) {
309
+ this.finishFrame([]);
310
+ return [];
311
+ }
312
+ const bound = new Map(
313
+ overlayTasks.map((t) => [t.id, history(t.metadata?.herdr)] as const),
314
+ );
315
+ const hasRuns = [...bound.values()].some((h) => h.runs.length > 0);
316
+ // Ask the host only when some todo has bound runs and the tree is shown.
317
+ const live =
318
+ hasRuns && !this.collapsed ? liveRows(this.query) : undefined;
143
319
 
144
320
  const plan = planView(overlayTasks);
145
321
  // Keep completed rows in their old slots; fill open slots in display order before budgeting.
146
322
  let nextOpen = 0;
147
- const tasks = overlayTasks.map(t => t.status === "completed" ? t : plan.ordered[nextOpen++]);
323
+ const tasks = overlayTasks.map((t) =>
324
+ t.status === "completed" ? t : plan.ordered[nextOpen++],
325
+ );
148
326
  const overlayState = { tasks, nextId: snapshot.nextId };
149
- const truncate = (line: string): string => truncateToWidth(line, width, "…");
327
+ const truncate = (line: string): string =>
328
+ truncateToWidth(line, width, "…");
150
329
  const counts = selectTodoCounts(overlayState);
151
330
  const hasActive = selectHasActive(overlayState);
152
- const showIds = selectShowTaskIds(overlayState);
331
+ const showIds = !!live?.size || selectShowTaskIds(overlayState);
153
332
 
154
333
  const headingColor = hasActive ? "accent" : "dim";
155
334
  const headingIcon = hasActive ? "●" : "○";
156
335
  const headingText = `${t("overlay.heading", OVERLAY_HEADING)} (${counts.completed}/${counts.total})`;
157
- const graph = plan.sharedGraph ? ` · ${theme.fg("dim", plan.sharedGraph)}` : "";
158
- const heading = truncate(`${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}${graph}`);
336
+ const graph = plan.sharedGraph
337
+ ? ` · ${theme.fg("dim", hasRuns && plan.sharedGraph === "fan-out/fan-in" ? "fan-out" : plan.sharedGraph)}`
338
+ : "";
339
+ const heading = truncate(
340
+ `${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}${graph}`,
341
+ );
159
342
 
160
343
  // Collapsed view: just the heading + a dim "└─" expand hint, then the
161
344
  // trailing spacer. Short-circuit before the budget math and the completed-
@@ -167,25 +350,41 @@ export class TodoOverlay {
167
350
  // shortcut was bound and the overlay collapsed) — render a static collapsed
168
351
  // label instead of splicing the sentinel into the placeholder.
169
352
  if (this.collapsed) {
353
+ this.finishFrame([]);
170
354
  const key = resolveCollapseKey();
171
355
  const hint =
172
356
  key === COLLAPSE_KEY_OFF
173
357
  ? t("overlay.collapsed", OVERLAY_COLLAPSED)
174
358
  : t("overlay.expandHint", OVERLAY_EXPAND_HINT).replace("{key}", key);
175
- return this.withTrailingSpacer([heading, truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", hint)}`)]);
359
+ return this.withTrailingSpacer([
360
+ heading,
361
+ truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", hint)}`),
362
+ ]);
176
363
  }
177
364
 
178
- const lines: string[] = [heading];
179
- // Budget for content rows (heading + tasks/summary). The rendered widget is
180
- // one line taller — withTrailingSpacer() appends a blank row below the panel.
181
- // Pi's global tool-output expansion mode is read on every render so its
182
- // expand/collapse shortcut also expands this live widget. Optional chaining
183
- // preserves compatibility with hosts predating getToolsExpanded().
184
- const bodyBudget = this.uiCtx?.getToolsExpanded?.() === true ? overlayTasks.length : getMaxWidgetLines() - 1;
185
- const layout = selectOverlayLayout(overlayState, bodyBudget);
186
- for (const task of layout.visible) {
187
- lines.push(truncate(`${theme.fg("dim", "├─")} ${formatPlanTaskLine(task, theme, showIds, plan.rows.get(task.id))}`));
188
- }
365
+ // Budget for content rows below the heading (tasks, run rows, summary). The
366
+ // rendered widget is one line taller — withTrailingSpacer() appends a blank row
367
+ // below the panel. Pi's global tool-output expansion mode is read on every
368
+ // render so its expand/collapse shortcut also lifts this budget. Optional
369
+ // chaining preserves compatibility with hosts predating getToolsExpanded().
370
+ const bodyBudget =
371
+ this.uiCtx?.getToolsExpanded?.() === true
372
+ ? Infinity
373
+ : getMaxWidgetLines() - 1;
374
+ const draw: DrawContext = {
375
+ theme,
376
+ width,
377
+ truncate,
378
+ bound,
379
+ live,
380
+ showIds,
381
+ now: Date.now(),
382
+ evidence: this.evidence(),
383
+ };
384
+ const body =
385
+ getView() === "full"
386
+ ? this.fullBody(overlayState, plan, bodyBudget, draw)
387
+ : this.focusBody(overlayTasks, plan, bodyBudget, draw);
189
388
 
190
389
  const newlyDisplayedCompletedTaskIds = overlayTasks
191
390
  .filter(
@@ -198,22 +397,184 @@ export class TodoOverlay {
198
397
  for (const taskId of newlyDisplayedCompletedTaskIds) {
199
398
  this.completedTaskIdsPendingHide.add(taskId);
200
399
  }
400
+ return this.withTrailingSpacer([heading, ...body]);
401
+ }
201
402
 
202
- if (layout.hiddenCompleted === 0 && layout.truncatedTail === 0) {
203
- const last = lines.length - 1;
204
- lines[last] = lines[last].replace("├─", "└─");
205
- return this.withTrailingSpacer(lines);
206
- }
403
+ /** The whole dependency tree, budgeted by selectOverlayLayout (the `"full"` view). */
404
+ private fullBody(
405
+ overlayState: { tasks: Task[]; nextId: number },
406
+ plan: ReturnType<typeof planView>,
407
+ bodyBudget: number,
408
+ draw: DrawContext,
409
+ ): string[] {
410
+ const { theme, truncate } = draw;
411
+ const layout = selectOverlayLayout(overlayState, bodyBudget);
412
+ const overflow = layout.hiddenCompleted + layout.truncatedTail;
413
+ const spare = bodyBudget - layout.visible.length - Number(overflow > 0);
414
+ const lines = this.drawTasks(
415
+ layout.visible.map((task) => ({ task, row: plan.rows.get(task.id) })),
416
+ spare,
417
+ overflow === 0,
418
+ draw,
419
+ );
420
+ if (overflow === 0) return lines;
207
421
 
208
- const totalHidden = layout.hiddenCompleted + layout.truncatedTail;
209
422
  const overflowParts: string[] = [];
210
- if (layout.hiddenCompleted > 0) overflowParts.push(`${layout.hiddenCompleted} ${formatStatusLabel("completed")}`);
211
- if (layout.truncatedTail > 0) overflowParts.push(`${layout.truncatedTail} ${formatStatusLabel("pending")}`);
423
+ if (layout.hiddenCompleted > 0)
424
+ overflowParts.push(
425
+ `${layout.hiddenCompleted} ${formatStatusLabel("completed")}`,
426
+ );
427
+ if (layout.truncatedTail > 0)
428
+ overflowParts.push(
429
+ `${layout.truncatedTail} ${formatStatusLabel("pending")}`,
430
+ );
212
431
  const more = t("overlay.more", OVERLAY_MORE);
213
432
  const summary =
214
- overflowParts.length > 0 ? `+${totalHidden} ${more} (${overflowParts.join(", ")})` : `+${totalHidden} ${more}`;
215
- lines.push(truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", summary)}`));
216
- return this.withTrailingSpacer(lines);
433
+ overflowParts.length > 0
434
+ ? `+${overflow} ${more} (${overflowParts.join(", ")})`
435
+ : `+${overflow} ${more}`;
436
+ lines.push(
437
+ truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", summary)}`),
438
+ );
439
+ return lines;
440
+ }
441
+
442
+ /**
443
+ * The focus view (default): in-progress tasks with their runs, the next open
444
+ * tasks (two, or three when nothing is in progress), then this turn's completed
445
+ * rows if room is left, and one summary row counting whatever is hidden. Rows are
446
+ * flat, so every unfinished blocker goes to the `⛓` tail.
447
+ */
448
+ private focusBody(
449
+ overlayTasks: Task[],
450
+ plan: ReturnType<typeof planView>,
451
+ bodyBudget: number,
452
+ draw: DrawContext,
453
+ ): string[] {
454
+ const { theme, truncate } = draw;
455
+ const inProgress = plan.ordered.filter((t) => t.status === "in_progress");
456
+ const pending = plan.ordered.filter((t) => t.status === "pending");
457
+ const completed = overlayTasks.filter((t) => t.status === "completed");
458
+ const next = pending.slice(0, inProgress.length ? 2 : 3);
459
+ const total = inProgress.length + pending.length + completed.length;
460
+
461
+ // Task rows first, in priority order; runs take the spare rows in display order;
462
+ // completed rows get what is left. The summary row is reserved only when needed.
463
+ const fit = (slots: number) => {
464
+ const core = [...inProgress, ...next].slice(0, slots);
465
+ let spare = slots - core.length;
466
+ for (const task of core) {
467
+ const n = this.children(task, draw).length;
468
+ if (n <= spare) spare -= n;
469
+ }
470
+ const done = completed.slice(0, spare);
471
+ return { core, done, spare: slots - core.length - done.length };
472
+ };
473
+ let shown = fit(bodyBudget);
474
+ let summarized = shown.core.length + shown.done.length < total;
475
+ if (summarized) shown = fit(bodyBudget - 1);
476
+
477
+ const openIds = new Set(plan.ordered.map((t) => t.id));
478
+ const flat = (task: Task): PlanRow | undefined => {
479
+ const row = plan.rows.get(task.id);
480
+ return row
481
+ ? {
482
+ depth: 0,
483
+ graph: row.graph,
484
+ otherBlockers: (task.blockedBy ?? []).filter((id) => openIds.has(id)),
485
+ }
486
+ : undefined;
487
+ };
488
+ const lines = this.drawTasks(
489
+ [...shown.core, ...shown.done].map((task) => ({ task, row: flat(task) })),
490
+ shown.spare,
491
+ !summarized,
492
+ draw,
493
+ );
494
+ if (!summarized) return lines;
495
+
496
+ const isShown = new Set([...shown.core, ...shown.done]);
497
+ const hidden = (list: Task[]) => list.filter((t) => !isShown.has(t)).length;
498
+ const parts = (
499
+ [
500
+ [hidden(inProgress), "in_progress"],
501
+ [hidden(pending), "pending"],
502
+ [hidden(completed), "completed"],
503
+ ] as const
504
+ )
505
+ .filter(([n]) => n > 0)
506
+ .map(([n, status]) => `${n} ${formatStatusLabel(status)}`);
507
+ const summary = `+${parts.join(t("overlay.separator", OVERLAY_SEPARATOR))}`;
508
+ lines.push(
509
+ truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", summary)}`),
510
+ );
511
+ return lines;
512
+ }
513
+
514
+ /** Live run rows bound to a task (empty when the host gave no rows). */
515
+ private children(task: Task, draw: DrawContext): RunRow[] {
516
+ const { runs } = draw.bound.get(task.id) ?? history(undefined);
517
+ return runs.flatMap((r) => draw.live?.get(r.id) ?? []);
518
+ }
519
+
520
+ /**
521
+ * Draw task rows and, where `spare` rows remain, their run rows; a task whose
522
+ * runs do not fit shows `· N runs`. Ends the frame's claim bookkeeping. `closed`
523
+ * means no summary row follows, so the last task row takes `└─`.
524
+ */
525
+ private drawTasks(
526
+ entries: { task: Task; row?: PlanRow }[],
527
+ spare: number,
528
+ closed: boolean,
529
+ draw: DrawContext,
530
+ ): string[] {
531
+ const { theme, width, truncate, live, showIds, now, evidence } = draw;
532
+ const lines: string[] = [];
533
+ const drawn: string[] = [];
534
+ let ticking = false;
535
+ const marked = new Map<string, string>();
536
+ for (const [i, { task, row }] of entries.entries()) {
537
+ const { older } = draw.bound.get(task.id) ?? history(undefined);
538
+ const children = this.children(task, draw);
539
+ const fits = children.length <= spare;
540
+ const last = closed && i === entries.length - 1;
541
+ const display =
542
+ fits && children.some((r) => r.name === task.owner)
543
+ ? { ...task, owner: undefined }
544
+ : task;
545
+ const count = !fits
546
+ ? ` · ${children.length} ${t("run.count", "runs")}`
547
+ : "";
548
+ lines.push(
549
+ truncate(
550
+ `${theme.fg("dim", last ? "└─" : "├─")} ${formatPlanTaskLine(display, theme, showIds, row)}${count}${older && live ? ` +${older}` : ""}`,
551
+ ),
552
+ );
553
+ if (!fits) continue;
554
+ spare -= children.length;
555
+ for (const [j, r] of children.entries()) {
556
+ const indent = " ".repeat(row?.depth ?? 0);
557
+ const branch = `${last ? " " : "│"} ${indent}${j === children.length - 1 ? "└" : "├"} `;
558
+ // A run waiting for a reply stands out; idle and running rows stay dim. The tree stays dim.
559
+ const childLine =
560
+ runState(r) === "waiting"
561
+ ? theme.fg("dim", branch) + theme.fg("warning", runLine(r, now))
562
+ : theme.fg("dim", branch + runLine(r, now));
563
+ const whole = visibleWidth(childLine) <= width;
564
+ ticking = true;
565
+ // Only a row shown in full is claimed; a truncated one carries no marker.
566
+ if (whole && evidence === "screen") {
567
+ const line = childLine + this.marker(r.id);
568
+ marked.set(r.id, line);
569
+ lines.push(line);
570
+ } else {
571
+ lines.push(truncate(childLine));
572
+ if (whole && evidence === "inline") drawn.push(r.id);
573
+ }
574
+ }
575
+ }
576
+ this.finishFrame(drawn, ticking, marked);
577
+ return lines;
217
578
  }
218
579
 
219
580
  /**
@@ -230,6 +591,7 @@ export class TodoOverlay {
230
591
  }
231
592
 
232
593
  dispose(): void {
594
+ this.finishFrame([]);
233
595
  if (this.uiCtx) this.uiCtx.setWidget(WIDGET_KEY, undefined);
234
596
  this.widgetRegistered = false;
235
597
  this.tui = undefined;
package/src/todo.ts CHANGED
@@ -14,18 +14,15 @@
14
14
 
15
15
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
16
  import { loadConfig, validateGuidanceFields } from "./config.ts";
17
- import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./ledger/contract.ts";
18
- import { type GuardRegistry, runningGuard } from "./ledger/guards.ts";
17
+ import { ABORTED, type FinishCall, refuse } from "./ledger/finish-call.ts";
18
+ import { runningGuard } from "./ledger/guards.ts";
19
19
  import { readImport } from "./ledger/import-snapshot.ts";
20
- import { changedTasks, type NamespaceRegistry } from "./ledger/namespaces.ts";
21
20
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
22
21
  import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
23
- import { applyTaskMutation, type ApplyResult, changesState } from "./state/state-reducer.ts";
22
+ import { applyTaskMutation, type ApplyResult } from "./state/state-reducer.ts";
24
23
  import { withSessionLock } from "./state/session-lock.ts";
25
- import type { TaskState } from "./state/state.ts";
26
- import { commitState, getRenderState, getState, sid } from "./state/store.ts";
24
+ import { getRenderState, getState, sid } from "./state/store.ts";
27
25
  import { prepareTodoArguments } from "./tool/normalize-params.ts";
28
- import { buildToolResult } from "./tool/response-envelope.ts";
29
26
  import {
30
27
  COMMAND_NAME,
31
28
  ERR_REQUIRES_INTERACTIVE,
@@ -74,14 +71,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
74
71
  "Optional bookkeeping fields: points (effort, 0 to 10), anchor (the check that shows the task is done, e.g. a test command), and evidence (runs of checks, each {command, sha?, result: pass|fail, at?}). On update, points and anchor replace; evidence is appended, never replaced.",
75
72
  ];
76
73
 
77
- const ABORTED = "call aborted; nothing changed";
78
-
79
- /** An `isError` result for a refused call; the list is reported as it was. */
80
- function refuse(action: TaskAction, input: TaskMutationParams, state: TaskState, message: string) {
81
- return { ...buildToolResult(action, input, state, { kind: "error", message }), isError: true };
82
- }
83
-
84
- export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry): void {
74
+ export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall): void {
85
75
  const guidance = validateGuidanceFields(loadConfig().guidance);
86
76
  pi.registerTool({
87
77
  name: TOOL_NAME,
@@ -119,42 +109,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
119
109
  } else {
120
110
  result = applyTaskMutation(before, action, input);
121
111
  }
122
- const guardChange = {
123
- op: action === "import" ? "create" as const : action as GuardOp,
124
- params: input as Record<string, unknown>,
125
- before: before.tasks,
126
- after: result.state.tasks,
127
- sessionId,
128
- cwd: ctx.cwd,
129
- };
130
- if (!changesState(result.op)) {
131
- // A valid update that changes nothing still reaches the guards (flagged `noop`):
132
- // re-asserting a status is how an agent reports it after a reload, and guards may
133
- // track it. It writes no snapshot and emits no event.
134
- if (result.op.kind === "update") {
135
- const refusal = await guards.check({ ...guardChange, noop: true });
136
- if (refusal) return refuse(action, input, before, refusal);
137
- if (signal?.aborted) return refuse(action, input, before, ABORTED);
138
- }
139
- commitState(sessionId, result.state);
140
- return buildToolResult(action, input, result.state, result.op);
141
- }
142
- // Namespace owners, then change guards, see the change before it commits; a refusal
143
- // leaves state untouched.
144
- const refusal =
145
- namespaces.check(changedTasks(result.op, input, result.state)) ?? (await guards.check(guardChange));
146
- if (refusal) return refuse(action, input, before, refusal);
147
- if (signal?.aborted) return refuse(action, input, before, ABORTED);
148
- // Persist the snapshot as a custom entry on the calling session's branch, however the
149
- // tool was reached: a call made through another tool (`ctx.executeTool`, e.g. codemode)
150
- // never lands as a standalone `toolResult`, so its `details` alone would not survive
151
- // replay. Pi's own codemode persists its `store()` the same way.
152
- // The entry is written before the live state commits: if appending throws, the call
153
- // fails with the list unchanged, so live state never runs ahead of the branch.
154
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
155
- commitState(sessionId, result.state);
156
- pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
157
- return buildToolResult(action, input, result.state, result.op);
112
+ return finish(sessionId, ctx.cwd, action, input, before, result, signal);
158
113
  });
159
114
  },
160
115
 
@@ -86,7 +86,8 @@ export function formatPlanTaskLine(t: Task, theme: Theme, showId: boolean, row?:
86
86
  line += ` ${subject}`;
87
87
  if (t.owner) line += ` ${theme.fg("muted", `@${sanitizeTerminalText(t.owner)}`)}`;
88
88
  if (wait) line += ` ${theme.fg("muted", wait)}`;
89
- if (t.status === "in_progress" && t.activeForm) {
89
+ // An activeForm that only repeats the subject adds nothing.
90
+ if (t.status === "in_progress" && t.activeForm && t.activeForm.trim() !== t.subject.trim()) {
90
91
  line += ` ${theme.fg("muted", `(${sanitizeTerminalText(t.activeForm)})`)}`;
91
92
  }
92
93
  if (row?.graph) line += ` ${theme.fg("dim", row.graph)}`;