pi-todo-ledger 0.6.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.
package/CONTRACT.md CHANGED
@@ -167,7 +167,11 @@ A match issues a normal guarded `update`: `owner` becomes the full `details.name
167
167
 
168
168
  `name` is verbatim; `id` is the child **run id** (`details.id`), not the parent's session id or a path-derived id.
169
169
  `pane` is the acknowledged `details.worktree.paneId` and is absent for ordinary launches.
170
- On another successful assignment the new record replaces the old one, so an old pane id does not carry forward.
170
+ The top-level fields always describe the latest assignment. An old pane id does not carry forward. For example, after a reviewer joins a worker on the same task, `owner` and `metadata.herdr.id` identify the reviewer.
171
+
172
+ New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
173
+
174
+ A successful `subagent_resume` appends its new run id when its acknowledged `sessionPath` matches a retained session path on exactly one non-deleted task in the calling session. An unknown or ambiguous path binds nothing.
171
175
  Other metadata stays intact; a refusal leaves the launch successful but adds the reason to its response.
172
176
  Manual `owner` updates (including `self`) are still allowed; the optional `herdr` record describes the last bound launch, not proof of a live pane or of the current owner's identity.
173
177
 
package/README.md CHANGED
@@ -49,7 +49,7 @@ Use `metadata.herdr.id` to resolve or message the worker by its run key.
49
49
  Use a name with `/boss send` only if it matches the name Straw Boss shows; a launch named `API worker` may appear there as `api-worker`.
50
50
  You can still set `owner` by hand.
51
51
 
52
- The panel and `/todos` indent each open task under its first unfinished blocker and show its owner as `@owner`.
52
+ `/todos` and the panel's full view indent each open task under its first unfinished blocker; the panel's default focus view lists tasks flat and names every unfinished blocker after the subject. Both show the owner as `@owner`.
53
53
  To mark a task as waiting for someone, set `metadata.waitsOn` to their name; to defer it until a particular time, set `metadata.until` to an ISO timestamp, e.g. `2027-01-15T09:00:00+08:00`.
54
54
  An open task shows `⏸` with the name or the future deadline in local time.
55
55
  These keys are display conventions: they neither schedule a wake-up nor change the task's `status` or the `todo/v1` contract.
@@ -110,18 +110,22 @@ Without one, the extension reads `rpiv-todo/config.json` from the same directori
110
110
  ```json
111
111
  {
112
112
  "maxWidgetLines": 8,
113
- "collapseKey": "alt+t"
113
+ "collapseKey": "alt+t",
114
+ "view": "full"
114
115
  }
115
116
  ```
116
117
 
117
118
  | Setting | What it does | Default |
118
119
  | --- | --- | --- |
119
- | `maxWidgetLines` | Content rows the panel may use, heading included. Minimum `3`. Pi's tool-output expansion mode shows all tasks. | `12` |
120
+ | `view` | `"focus"` lists the tasks in progress and the next open ones, and folds the rest into one summary row. `"full"` shows the whole dependency tree. | `"focus"` |
121
+ | `maxWidgetLines` | Content rows the panel may use, heading included. Minimum `3`. Pi's tool-output expansion mode lifts the limit. | `12` |
120
122
  | `collapseKey` | Key that collapses and expands the panel, in pi keybinding form (`alt+o`, `ctrl+shift+t`). `"off"` registers no shortcut. Needs `/reload` to rebind. | `"ctrl+shift+t"` |
121
123
  | `guidance` | Replaces the built-in instructions the extension gives the model about the todo list (`promptSnippet`, `promptGuidelines`). Needs `/reload`. | built-ins |
122
124
 
123
125
  More detail: [Configuration](docs/configuration.md), [`todo` tool reference](docs/tool-schema.md), [Panel and `/todos`](docs/overlay.md).
124
- The panel's text is localized when [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) is installed, and English otherwise.
126
+ The panel's text follows the locale chosen in [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) when it is installed.
127
+ Traditional Chinese needs `--locale zh-TW` or a `zh_TW` system locale, because the `/languages` picker offers only Simplified `zh`.
128
+ Without rpiv-i18n the panel is Traditional Chinese under a `zh_TW` or `zh_Hant` system locale and English otherwise; see [Localization](docs/overlay.md#localization).
125
129
 
126
130
  ## License
127
131
 
@@ -31,6 +31,7 @@ The extension never writes this file — you create and edit it yourself.
31
31
  {
32
32
  "maxWidgetLines": 8,
33
33
  "collapseKey": "alt+t",
34
+ "view": "full",
34
35
  "guidance": {
35
36
  "promptSnippet": "Use the `todo` tool to track multi-step work before starting it.",
36
37
  "promptGuidelines": [
@@ -41,10 +42,23 @@ The extension never writes this file — you create and edit it yourself.
41
42
  }
42
43
  ```
43
44
 
45
+ ## `view`
46
+
47
+ **Default `"focus"`.** How the overlay lays out the list.
48
+
49
+ - `"focus"` shows the tasks in progress with their worker runs, the next two
50
+ open tasks (three when nothing is in progress), and one summary row for the
51
+ rest, such as `+1 in progress, 5 pending, 2 completed`.
52
+ - `"full"` shows the whole dependency tree, as releases up to 0.6.0 did.
53
+ - Any other value, or none, means `"focus"`.
54
+ - Read fresh on every render, like `maxWidgetLines`, so no `/reload`.
55
+
56
+ [overlay.md](./overlay.md#focus-view) describes both layouts.
57
+
44
58
  ## `maxWidgetLines`
45
59
 
46
60
  **Default `12`.** The content-row budget for the overlay — the heading row and,
47
- on overflow, the `+N more` summary row both count against it. Only the trailing
61
+ on overflow, the summary row both count against it. Only the trailing
48
62
  blank spacer sits outside the budget, so `12` renders up to 13 terminal rows.
49
63
 
50
64
  - Floor of `3`. A number below `3` falls back to the default.
@@ -52,8 +66,9 @@ blank spacer sits outside the budget, so `12` renders up to 13 terminal rows.
52
66
  - No ceiling.
53
67
  - Read fresh on every render, so a change takes effect on the next repaint —
54
68
  no `/reload`.
55
- - Pi's tool-output expansion mode (`ctrl+o` by default) temporarily overrides
56
- this budget and shows every task; collapsing restores the configured budget.
69
+ - Pi's tool-output expansion mode (`ctrl+o` by default) temporarily lifts
70
+ this budget; collapsing restores it. In the full view that shows every task.
71
+ The focus view keeps its selection and only stops cutting rows for space.
57
72
 
58
73
  ## `collapseKey`
59
74
 
package/docs/overlay.md CHANGED
@@ -21,8 +21,35 @@ and taking the last saved snapshot, which replaces the whole list
21
21
  (last-write-wins). See [tool-schema.md](./tool-schema.md#persistence) for where
22
22
  snapshots are saved.
23
23
 
24
+ ## Focus view
25
+
26
+ The panel opens in the focus view. It shows what is being worked on and what comes next, and folds the rest into one row:
27
+
28
+ ```text
29
+ ● Todos (0/8)
30
+ ├─ ◐ #8 執行等待
31
+ │ └ fixture-test · astra · 執行中 6s
32
+ ├─ ○ #1 檢查畫面
33
+ ├─ ○ #2 確認版面
34
+ └─ +5 待處理
35
+ ```
36
+
37
+ Rows come in this order, until the row budget runs out:
38
+
39
+ 1. the heading;
40
+ 2. every task in progress, each followed by its run rows;
41
+ 3. the next two open tasks in display order, or the next three when nothing is in progress;
42
+ 4. completed tasks from the current turn, only if rows are left after the run rows;
43
+ 5. one summary row counting the hidden tasks in progress, pending, and completed, in that order, such as `+1 in progress, 5 pending, 2 completed` (`+1 進行中、5 待處理、2 已完成` in zh-TW). Zero counts are left out, and with nothing hidden there is no summary row.
44
+
45
+ `maxWidgetLines` is a hard cap here too: tasks in progress that do not fit are counted in the summary, and run rows that do not fit fold into `· N runs`.
46
+ Rows are flat, so the `⛓` tail lists every unfinished blocker of a task; `⏸`, owners, and the other marks are the same as in the full view.
47
+ Pi's tool-output expansion mode lifts the row cap but keeps this selection. Set `"view": "full"` (see [configuration.md](./configuration.md#view)) for the tree below, or use `/todos` to see everything once.
48
+
24
49
  ## Anatomy of a row
25
50
 
51
+ The full view (`"view": "full"`) draws the whole dependency tree:
52
+
26
53
  ```text
27
54
  ● Todos (0/5) · fan-out/fan-in
28
55
  ├─ ◐ #1 Scope @Ari
@@ -38,7 +65,7 @@ snapshots are saved.
38
65
  - **Glyphs** — `○` pending, `◐` in_progress, `✓` completed, `✗` deleted.
39
66
  Completed and deleted subjects render dim and struck through.
40
67
  - **activeForm** — appended dim in parentheses, only while the task is
41
- `in_progress`.
68
+ `in_progress` and only when it differs from the subject (ignoring leading and trailing spaces).
42
69
  - **Waiting** — `⏸` replaces the open-task glyph when `metadata.waitsOn` names a party or `metadata.until` is an ISO time in the future. The row shows the party, the local deadline, or both. An elapsed deadline no longer marks a task as waiting.
43
70
  - **Owner** — `@owner` follows the subject in muted text.
44
71
  - **Dependencies** — open rows nest under the first unfinished `blockedBy` id; siblings are visited in id order. Other unfinished blockers appear in the `⛓ #1,#2` tail. If another prerequisite interrupts a branch, `↳ #N` names the parent the row returns to.
@@ -49,10 +76,31 @@ snapshots are saved.
49
76
 
50
77
  Rows longer than the terminal width are truncated with `…`.
51
78
 
79
+ ## Worker runs under a task
80
+
81
+ When pi-herdr-agents is loaded, each task lists its live bound runs (`metadata.herdr.runs`) under its row: name, short model, state, and time in that state.
82
+ A run that is not working keeps its one row and gains a mark before its name:
83
+
84
+ - `◇ … · idle 3m` (zh-TW `閒置`), dim: its turn ended, or a persistent specialist sits between tasks (Maestro lifecycle `waiting`).
85
+ - `? … · waiting 42s` (zh-TW `等待回覆`), in the warning color: the pane shows a dialog, approval, or question (Maestro lifecycle `blocked`).
86
+
87
+ Starting and working runs carry no mark; other lifecycle kinds show their state word only.
88
+ A pending cancel replaces the state with `cancelling` or `cancel unconfirmed` and drops the mark.
89
+ Run rows count against the row budget; a task whose runs do not fit shows `· N runs` instead.
90
+
91
+ The panel asks the Subagents widget to hide a run only once it knows the run's row reached the screen:
92
+
93
+ - In Pi's inline renderer every widget line is written, so a row drawn on two frames in a row counts.
94
+ - Pi's fullscreen layout can clip the panel after it is drawn. Each run row there ends in an invisible marker unique to the panel and run: an escape sequence shaped like OSC 8 with an `id` parameter and no URI. Pi counts it as zero width, and terminals drop it (Ghostty and Herdr discard it as an invalid OSC 8), so it neither shows nor opens a link. Right after Pi paints a frame, the panel looks in `getScreenLines()` for a line that starts with the exact row it drew, marker included. A row the layout cut off is absent, and a row under a popup, a search highlight, or a selection no longer matches, so in both cases its run stays in the Subagents widget. A changed claim triggers one more frame, so the Subagents widget catches up one frame later.
95
+ - A renderer that offers neither gives no evidence, and the Subagents widget keeps every run.
96
+
97
+ Collapsing the panel, or the run leaving the panel, returns the run to the Subagents widget.
98
+
52
99
  ## Overflow
53
100
 
54
101
  The content-row budget is `maxWidgetLines` (default `12`), and the heading counts
55
- against it. When there are more tasks than fit:
102
+ against it. The focus view applies it as described [above](#focus-view). In the
103
+ full view, when there are more tasks than fit:
56
104
 
57
105
  1. one row is reserved for the summary line;
58
106
  2. completed tasks are dropped first, newest first — the oldest completed rows
@@ -61,8 +109,8 @@ against it. When there are more tasks than fit:
61
109
  truncated;
62
110
  4. the last row becomes `+N more (X completed, Y pending)`.
63
111
 
64
- Use Pi's tool-output expansion shortcut (`ctrl+o` by default) to expand the
65
- widget and show every task. Collapsing Pi's tool output reapplies the configured
112
+ In the full view, Pi's tool-output expansion shortcut (`ctrl+o` by default)
113
+ expands the widget to show every task. Collapsing Pi's tool output reapplies the configured
66
114
  row budget. Unfinished work is therefore the last thing to disappear in the
67
115
  compact view. See [configuration.md](./configuration.md#maxwidgetlines) for the
68
116
  budget's floor and reload semantics.
@@ -107,18 +155,28 @@ tasks. Tombstoned tasks are never listed.
107
155
 
108
156
  ## Localization
109
157
 
110
- The overlay heading, the `+N more` summary, the collapse hint, the `/todos`
158
+ The overlay heading, both summary rows, the collapse hint, the `/todos`
111
159
  section headers, and the status words all localize through
112
160
  [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n)
113
161
  when that package is installed. Bundled locales: `de`, `en`, `es`, `fr`, `pt`,
114
- `pt-BR`, `ru`, `uk`, `zh`.
162
+ `pt-BR`, `ru`, `uk`, `zh` (Simplified), and `zh-TW` (Traditional).
163
+
164
+ The `/languages` picker has no Traditional Chinese entry; its `中文 (zh)` is
165
+ Simplified. An explicit choice always wins, and the system locale is only the
166
+ default. To get Traditional Chinese, use one of:
167
+
168
+ - `pi --locale zh-TW`;
169
+ - `{ "locale": "zh-TW" }` in rpiv-i18n's `locale.json` (see its README for the path);
170
+ - **System default** in `/languages`, with `LC_ALL`, `LC_MESSAGES`, or `LANG` set to
171
+ a `zh_TW` or `zh_Hant` locale such as `zh_TW.UTF-8`.
115
172
 
116
173
  LLM-facing output — the tool response envelope, reducer error messages, and the
117
174
  schema descriptions — stays English by design.
118
175
 
119
176
  The SDK is a soft optional peer, loaded through a dynamic import at module init.
120
- When it is absent, every call site returns its inline English literal and the
121
- extension stays online: no warning, no crash. Install it at any time with
177
+ When it is absent, the panel is Traditional Chinese under a `zh_TW` or `zh_Hant`
178
+ system locale and English otherwise, and the extension stays online: no warning,
179
+ no crash. Install it at any time with
122
180
  `pi install npm:@juicesharp/rpiv-i18n` and restart the session. To add or
123
181
  override a translation, drop a `locales/<code>.json` file mirroring `en.json` —
124
182
  see the `@juicesharp/rpiv-i18n` README's "Contributing translations" section.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/config.ts CHANGED
@@ -39,6 +39,24 @@ export function configCandidates(): string[] {
39
39
  return [CONFIG_NAME, LEGACY_CONFIG_NAME].flatMap((name) => dirs.map((dir) => join(dir, name, "config.json")));
40
40
  }
41
41
 
42
+ /**
43
+ * The locale rpiv-i18n's `/languages` picker saved, read the way rpiv-config reads it:
44
+ * the `$XDG_CONFIG_HOME` file wins when it exists, else `~/.config/rpiv-i18n/locale.json`.
45
+ */
46
+ export function savedLocale(): string | undefined {
47
+ for (const dir of configDirs()) {
48
+ const path = join(dir, "rpiv-i18n", "locale.json");
49
+ if (!existsSync(path)) continue;
50
+ try {
51
+ const locale = (JSON.parse(readFileSync(path, "utf-8")) as { locale?: unknown } | null)?.locale;
52
+ return typeof locale === "string" && locale ? locale : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+
42
60
  /** Parse a JSON config file; `{}` for malformed JSON or a non-object value (with a warning). */
43
61
  function readJsonObject(path: string): Record<string, unknown> {
44
62
  try {
@@ -84,6 +102,19 @@ interface TodoConfig {
84
102
  * entirely. Validation happens in `resolveCollapseKey`, not at load.
85
103
  */
86
104
  collapseKey?: string;
105
+ /** Panel layout: `"focus"` (default) or `"full"`. Validated in `getView`. */
106
+ view?: unknown;
107
+ }
108
+
109
+ /** Panel layout: the compact focus view, or the whole dependency tree. */
110
+ export type OverlayView = "focus" | "full";
111
+
112
+ /** Default panel layout when `view` is missing or not one of the two names. */
113
+ export const DEFAULT_VIEW: OverlayView = "focus";
114
+
115
+ /** Panel layout, read fresh on every render like getMaxWidgetLines(); anything but `"full"` is focus. */
116
+ export function getView(): OverlayView {
117
+ return loadConfig().view === "full" ? "full" : DEFAULT_VIEW;
87
118
  }
88
119
 
89
120
  /** Default content-row budget when the config is missing/invalid — the prior
package/src/index.ts CHANGED
@@ -169,7 +169,7 @@ export default function (
169
169
  const { TodoOverlay } = await loadTodoOverlay();
170
170
  if (generation !== lifecycleGeneration || !uiCtx) return;
171
171
 
172
- todoOverlay ??= new TodoOverlay();
172
+ todoOverlay ??= new TodoOverlay(p => pi.events.emit('pi-herdr-agents:run-rows:v1', p));
173
173
  todoOverlay.setUICtx(uiCtx);
174
174
  if (resetCompletedDisplayState) todoOverlay.resetCompletedDisplayState();
175
175
  todoOverlay.update();
@@ -6,6 +6,8 @@ import { sanitizeTerminalText } from "../tool/sanitize.ts";
6
6
  import type { FinishCall } from "./finish-call.ts";
7
7
  import { runningGuard } from "./guards.ts";
8
8
 
9
+ import { bindRun, history } from "./herdr-runs.ts";
10
+
9
11
  const uid = /^t_[a-z2-7]{10}$/;
10
12
  const local = /^([a-f0-9]{8})#([1-9]\d*)$/i;
11
13
  const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
@@ -35,7 +37,8 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
35
37
  // A blocked call need not produce a result. Drop any leftover captures at the turn boundary.
36
38
  pi.on("agent_end", (_event, ctx) => { pending.delete(sid(ctx)); });
37
39
  pi.on("tool_result", async (event, ctx) => {
38
- if (event.toolName !== "subagent") return;
40
+ const resume = event.toolName === "subagent_resume";
41
+ if (!resume && event.toolName !== "subagent") return;
39
42
  const session = sid(ctx);
40
43
  const calls = pending.get(session);
41
44
  const capture = calls?.get(event.toolCallId);
@@ -44,11 +47,13 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
44
47
  const d = event.details;
45
48
  if (event.isError || !record(d) || d.status !== "started" || !nonblank(d.name) || !nonblank(d.id)) return;
46
49
  const item = d.item;
47
- if (typeof item !== "string" || item !== event.input.item) return;
50
+ const path = resume ? event.input.sessionPath : d.sessionFile;
51
+ if (resume ? (!nonblank(path) || path !== d.sessionPath) : (typeof item !== "string" || item !== event.input.item)) return;
48
52
  const pinned = capture?.item === item ? capture : undefined;
49
- if (!pinned && !uid.test(item)) return;
53
+ if (!resume && !pinned && !(typeof item === 'string' && uid.test(item))) return;
50
54
  const pane = record(d.worktree) ? d.worktree.paneId : undefined;
51
- const herdr = { name: d.name, id: d.id, ...(nonblank(pane) ? { pane } : {}) };
55
+ const agent = d.agent ?? event.input.agent;
56
+ const run = { name: d.name, id: d.id, ...(nonblank(path) ? {session:path} : {}), ...(nonblank(agent) ? {agent} : {}), ...(nonblank(pane) ? { pane } : {}) };
52
57
  const warn = (why: string) => ({
53
58
  content: [...event.content, { type: "text" as const, text: `Todo owner binding: ${sanitizeTerminalText(why)}` }],
54
59
  structuredContent: event.structuredContent,
@@ -58,10 +63,13 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
58
63
  return await withSessionLock(session, async () => {
59
64
  const before = getState(session);
60
65
  if (pinned && !pinned.uid && listGeneration(session) !== pinned.generation) return;
61
- const task = pinned && !pinned.uid
66
+ const matches = resume ? before.tasks.filter(t => t.status !== 'deleted' && history(t.metadata?.herdr).runs.some(r => r.session === path)) : [];
67
+ if (resume && matches.length !== 1) return;
68
+ const task = resume ? matches[0] : pinned && !pinned.uid
62
69
  ? before.tasks.find(t => t.id === pinned.id && !t.uid)
63
70
  : before.tasks.find(t => t.uid === (pinned?.uid ?? item));
64
71
  if (!task || task.status === "deleted") return;
72
+ const herdr = bindRun(task.metadata?.herdr, run);
65
73
  const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr } };
66
74
  const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params));
67
75
  if (result.details.error) return warn(result.details.error);
@@ -0,0 +1,44 @@
1
+ export interface BoundRun {
2
+ id: string;
3
+ name: string;
4
+ pane?: string;
5
+ session?: string;
6
+ agent?: string;
7
+ }
8
+ export function history(value: unknown): { runs: BoundRun[]; older: number } {
9
+ if (!value || typeof value !== "object") return { runs: [], older: 0 };
10
+ const h = value as Record<string, unknown>;
11
+ const valid = (Array.isArray(h.runs) ? h.runs : [h]).filter(
12
+ (r): r is BoundRun =>
13
+ r && typeof r.id === "string" && typeof r.name === "string",
14
+ );
15
+ // Imported or hand-edited metadata may repeat an id: keep its last record, in its last position.
16
+ const seen = new Set<string>();
17
+ const unique: BoundRun[] = [];
18
+ for (let i = valid.length - 1; i >= 0; i--) {
19
+ if (seen.has(valid[i].id)) continue;
20
+ seen.add(valid[i].id);
21
+ unique.push(valid[i]);
22
+ }
23
+ unique.reverse();
24
+ const stored =
25
+ typeof h.older === "number" && Number.isSafeInteger(h.older) && h.older > 0
26
+ ? h.older
27
+ : 0;
28
+ return {
29
+ runs: unique.slice(-6),
30
+ older: stored + Math.max(0, unique.length - 6),
31
+ };
32
+ }
33
+ export function bindRun(previous: unknown, newest: BoundRun) {
34
+ const { runs, older } = history(previous);
35
+ const next = [...runs.filter((r) => r.id !== newest.id), newest];
36
+ const dropped = older + Math.max(0, next.length - 6);
37
+ return {
38
+ name: newest.name,
39
+ id: newest.id,
40
+ ...(newest.pane ? { pane: newest.pane } : {}),
41
+ runs: next.slice(-6),
42
+ ...(dropped ? { older: dropped } : {}),
43
+ };
44
+ }
@@ -8,6 +8,7 @@
8
8
  "overlay.more": "more",
9
9
  "overlay.expandHint": "{key} to expand",
10
10
  "overlay.collapsed": "collapsed",
11
+ "overlay.separator": ", ",
11
12
 
12
13
  "command.no_todos": "No todos yet. Ask the agent to add some!",
13
14
  "command.requires_interactive": "/todos requires interactive mode",
@@ -0,0 +1,33 @@
1
+ {
2
+ "status.pending": "待處理",
3
+ "status.in_progress": "進行中",
4
+ "status.completed": "已完成",
5
+ "status.deleted": "已刪除",
6
+ "overlay.heading": "Todos",
7
+ "overlay.more": "項未顯示",
8
+ "overlay.expandHint": "按 {key} 展開",
9
+ "overlay.collapsed": "已收合",
10
+ "overlay.separator": "、",
11
+ "command.no_todos": "目前沒有待辦事項。",
12
+ "command.requires_interactive": "/todos 需要互動模式",
13
+ "command.section.pending": "── 待處理 ──",
14
+ "command.section.in_progress": "── 進行中 ──",
15
+ "command.section.completed": "── 已完成 ──",
16
+ "wait.party": "等",
17
+ "wait.until": "等到",
18
+ "run.count": "個工作階段",
19
+ "run.cancel.requested": "取消中",
20
+ "run.cancel.unconfirmed": "取消未確認",
21
+ "run.tool.thread_wait": "等 thread",
22
+ "run.active.reviewer": "審查中",
23
+ "run.kind.active": "執行中",
24
+ "run.kind.running": "執行中",
25
+ "run.kind.starting": "啟動中",
26
+ "run.state.idle": "閒置",
27
+ "run.state.waiting": "等待回覆",
28
+ "run.kind.interrupted": "已中斷",
29
+ "run.kind.stalled": "停滯",
30
+ "run.kind.finalizing": "收尾中",
31
+ "run.kind.completed": "已完成",
32
+ "run.kind.failed": "失敗"
33
+ }
@@ -10,6 +10,7 @@
10
10
  "overlay.more": "更多",
11
11
  "overlay.expandHint": "按 {key} 展开",
12
12
  "overlay.collapsed": "已折叠",
13
+ "overlay.separator": "、",
13
14
 
14
15
  "command.no_todos": "暂无任务。可以让 agent 添加一些!",
15
16
  "command.requires_interactive": "/todos 需要交互模式",
@@ -5,9 +5,10 @@
5
5
  *
6
6
  * - `t(key, fallback)` is `scope("pi-todo-ledger")` if the SDK is
7
7
  * installed (live `/languages` updates propagate). If the SDK is missing
8
- * (standalone install without rpiv-i18n), `t` is an identity passthrough
9
- * that returns the inline English fallback at every call site, so the
10
- * extension stays online with English UI.
8
+ * (standalone install without rpiv-i18n), `t` returns the inline English
9
+ * fallback at every call site, so the extension stays online with English UI.
10
+ * - Traditional Chinese (`locales/zh-TW.json`) is served here, not by the SDK,
11
+ * whose picker lists only `zh`: see `renderLocale()` for when it applies.
11
12
  * - `formatStatusLabel(status)` resolves a TaskStatus to its locale-aware
12
13
  * label via the canonical `status.*` namespace, with the English literal
13
14
  * as fallback so nothing renders blank if the namespace isn't registered.
@@ -19,6 +20,8 @@
19
20
  * `const X = formatStatusLabel(...)`.
20
21
  */
21
22
 
23
+ import { readFileSync } from 'node:fs';
24
+ import { savedLocale } from "../config.ts";
22
25
  import type { TaskStatus } from "../tool/types.ts";
23
26
 
24
27
  export const I18N_NAMESPACE = "pi-todo-ledger";
@@ -38,6 +41,7 @@ type I18nSDK = { scope: (namespace: string) => ScopeFn };
38
41
  // Top-level await is required so a synchronous `t(...)` call from any
39
42
  // downstream module sees the resolved scope; ESM module loading awaits this
40
43
  // before evaluating any importer.
44
+ const traditional: Record<string,string> = JSON.parse(readFileSync(new URL('../locales/zh-TW.json', import.meta.url), 'utf8'));
41
45
  let scopeImpl: ScopeFn;
42
46
  try {
43
47
  const sdk = (await import(I18N_SDK)) as I18nSDK;
@@ -46,7 +50,51 @@ try {
46
50
  scopeImpl = (_key, fallback) => fallback;
47
51
  }
48
52
 
49
- export const t: ScopeFn = scopeImpl;
53
+ const TRADITIONAL = /^zh[-_](?:TW|Hant)(?:[-_.@]|$)/i;
54
+
55
+ // The SDK republishes this plain-data snapshot on every locale change, a /languages pick included.
56
+ const SDK_STATE = Symbol.for("rpiv-i18n");
57
+ type SdkState = { readonly locale?: string } | undefined;
58
+
59
+ /** The `--locale` value Pi was started with (`--locale x` or `--locale=x`). */
60
+ function flagLocale(argv = process.argv): string | undefined {
61
+ for (const [i, arg] of argv.entries()) {
62
+ if (arg.startsWith("--locale=")) return arg.slice(9) || undefined;
63
+ if (arg === "--locale" && argv[i + 1] && !argv[i + 1].startsWith("-")) return argv[i + 1];
64
+ }
65
+ return undefined;
66
+ }
67
+
68
+ let seenState: SdkState | null = null;
69
+ let chosen: string | undefined;
70
+ /** The user's explicit choice (`--locale`, then the saved /languages pick), re-read when the SDK applies a locale. */
71
+ function explicitLocale(state: SdkState): string | undefined {
72
+ if (state !== seenState) {
73
+ seenState = state;
74
+ chosen = flagLocale() ?? savedLocale();
75
+ }
76
+ return chosen;
77
+ }
78
+
79
+ /**
80
+ * The locale to render in. An explicit choice wins as given: `zh` stays Simplified and `zh-TW`
81
+ * is Traditional. Without one, the system locale is the default, read in POSIX order
82
+ * (`LC_ALL`, then `LC_MESSAGES`, then `LANG`). The SDK reads `LANG` first and drops the
83
+ * region, so a Traditional system locale decides here; any other keeps the SDK's code.
84
+ */
85
+ export function renderLocale(): string {
86
+ const sys = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '';
87
+ const state = (globalThis as { [k: symbol]: SdkState })[SDK_STATE];
88
+ const locale = state?.locale;
89
+ if (!locale) return sys;
90
+ if (explicitLocale(state) !== undefined) return locale;
91
+ return TRADITIONAL.test(sys) ? sys : locale;
92
+ }
93
+
94
+ export const t: ScopeFn = (key, fallback) => {
95
+ if (TRADITIONAL.test(renderLocale())) return traditional[key] ?? fallback;
96
+ return scopeImpl(key, fallback);
97
+ };
50
98
 
51
99
  const STATUS_LABEL_PENDING = "pending";
52
100
  const STATUS_LABEL_IN_PROGRESS = "in progress";
@@ -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;
@@ -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)}`;
@@ -0,0 +1,120 @@
1
+ import { t } from "../state/i18n-bridge.ts";
2
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
3
+ export interface RunRow {
4
+ id: string;
5
+ name: string;
6
+ agent?: string;
7
+ model?: string;
8
+ startedAt: number;
9
+ phase: { kind: string; label?: string; since?: number };
10
+ cancel?: string;
11
+ }
12
+ export interface Probe {
13
+ claim?: { by: string; ids: string[] };
14
+ rows?: { version: 1; rows: RunRow[] };
15
+ }
16
+ export type Query = (probe: Probe) => void;
17
+ export function liveRows(query?: Query) {
18
+ const p: Probe = {};
19
+ try {
20
+ query?.(p);
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ if (p.rows?.version !== 1 || !Array.isArray(p.rows.rows)) return undefined;
25
+ return new Map(
26
+ p.rows.rows
27
+ .filter(
28
+ (r) =>
29
+ r &&
30
+ typeof r.id === "string" &&
31
+ typeof r.name === "string" &&
32
+ typeof r.phase?.kind === "string" &&
33
+ Number.isFinite(r.startedAt),
34
+ )
35
+ .map((r) => [r.id, r]),
36
+ );
37
+ }
38
+ export function shortModel(model: string) {
39
+ const base = model.split("/").at(-1) ?? model;
40
+ return (
41
+ base
42
+ .split(/[-_:]/)
43
+ .filter(
44
+ (x) => x && !/^(?:claude|gpt|openai|anthropic|\d[\d.]*)$/i.test(x),
45
+ )
46
+ .join("-") || base
47
+ );
48
+ }
49
+ /**
50
+ * What a run row says about its subagent, from Maestro's `projectLifecycle` kind:
51
+ * Herdr `working` is `active`; Herdr `done` or `idle` after work (the turn ended, or a
52
+ * persistent specialist sits between tasks) is `waiting`, shown as idle; Herdr `blocked`
53
+ * (a dialog, approval or question in the pane) is `blocked`, shown as waiting for a reply.
54
+ * Other kinds (interrupted, stalled, finalizing, ...) and unknown ones keep the plain row.
55
+ */
56
+ export type RunState = "running" | "idle" | "waiting";
57
+ const STATES: Record<string, RunState> = {
58
+ starting: "running",
59
+ running: "running",
60
+ active: "running",
61
+ waiting: "idle",
62
+ blocked: "waiting",
63
+ };
64
+ /** Single-cell marks distinct from the task glyphs (○ ◐ ✓ ✗ ⏸); running rows carry none. */
65
+ const MARKS: Partial<Record<RunState, string>> = { idle: "◇", waiting: "?" };
66
+ function pendingCancel(row: RunRow) {
67
+ return row.cancel === "requested" || row.cancel === "unconfirmed"
68
+ ? `cancel.${row.cancel}`
69
+ : undefined;
70
+ }
71
+ /** The row's state, or undefined when a pending cancel leads or the kind is not mapped. */
72
+ export function runState(row: RunRow): RunState | undefined {
73
+ if (pendingCancel(row)) return undefined;
74
+ return Object.hasOwn(STATES, row.phase.kind) ? STATES[row.phase.kind] : undefined;
75
+ }
76
+ const words: Record<string, string> = {
77
+ "cancel.requested": "cancelling",
78
+ "cancel.unconfirmed": "cancel unconfirmed",
79
+ "tool.thread_wait": "waiting for thread",
80
+ "active.reviewer": "reviewing",
81
+ "kind.active": "running",
82
+ "state.idle": "idle",
83
+ "state.waiting": "waiting",
84
+ };
85
+ export function runLine(row: RunRow, now: number) {
86
+ const { kind, label, since } = row.phase;
87
+ // A pending cancel outranks the lifecycle: the host hides its own warning for claimed rows.
88
+ const cancel = pendingCancel(row);
89
+ const state = runState(row);
90
+ const keys = [
91
+ cancel,
92
+ state && state !== "running" && `state.${state}`,
93
+ label && `tool.${label}`,
94
+ kind === "active" && row.agent && `active.${row.agent}`,
95
+ `kind.${kind}`,
96
+ ];
97
+ const word =
98
+ keys
99
+ .filter(Boolean)
100
+ .map((k) => t(`run.${k}`, words[String(k)] ?? ""))
101
+ .find(Boolean) || kind;
102
+ const s = Math.max(
103
+ 0,
104
+ Math.floor(
105
+ (now - (Number.isFinite(since) ? since! : row.startedAt)) / 1000,
106
+ ),
107
+ );
108
+ const time =
109
+ s < 60
110
+ ? `${s}s`
111
+ : s < 3600
112
+ ? `${Math.floor(s / 60)}m`
113
+ : `${Math.floor(s / 3600)}h${String(Math.floor(s / 60) % 60).padStart(2, "0")}m`;
114
+ return sanitizeTerminalText(
115
+ (state && MARKS[state] ? `${MARKS[state]} ` : "") +
116
+ [row.name, row.model && shortModel(row.model), `${word} ${time}`]
117
+ .filter(Boolean)
118
+ .join(" · "),
119
+ );
120
+ }
@@ -1,3 +1,4 @@
1
+ import { t } from '../state/i18n-bridge.ts';
1
2
  import { sanitizeTerminalText } from "../tool/sanitize.ts";
2
3
  import type { Task } from "../tool/types.ts";
3
4
 
@@ -20,7 +21,7 @@ export function waitingLabel(task: Task): string {
20
21
  const party = typeof who === "string" ? sanitizeTerminalText(who).trim() : "";
21
22
  const until = task.metadata?.until;
22
23
  const time = typeof until === "string" && isoDateTime.test(until) ? Date.parse(until) : NaN;
23
- return [party && `waits ${party}`, time > Date.now() && `until ${localTime.format(time)}`].filter(Boolean).join(" · ");
24
+ return [party && `${t('wait.party','waits')} ${party}`, time > Date.now() && `${t('wait.until','until')} ${localTime.format(time)}`].filter(Boolean).join(" · ");
24
25
  }
25
26
 
26
27
  export function resultSuffix(task: Task): string {