@abhishek944/pi-tasks 0.9.0 → 0.10.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/dist/ui/panel.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { stripVTControlCharacters } from "node:util";
2
2
  import { copyToClipboard } from "@earendil-works/pi-coding-agent";
3
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { sliceByColumn, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+ import { delegateLink, focusPane } from "../agents/links.js";
4
5
  import { formatWorksMarkdown } from "../markdown.js";
5
- import { openRepository } from "../open-repository.js";
6
+ import { openRepository, openSession } from "../open-repository.js";
7
+ import { taskOwner } from "../ownership.js";
6
8
  import { formatCompletion, taskCompletion, workCompletion } from "../progress.js";
7
9
  import { safeSingleLine } from "../text.js";
8
10
  const EMPTY_COMPONENT = { render: () => [], invalidate: () => { } };
@@ -18,13 +20,15 @@ export class TasksPanelHost {
18
20
  mode = "floating";
19
21
  minimized = false;
20
22
  cwd = "";
23
+ sessionId = "Session unavailable";
21
24
  constructor(state, git) {
22
25
  this.state = state;
23
26
  this.git = git;
24
27
  }
25
- attach(ui, cwd) {
28
+ attach(ui, cwd, sessionId) {
26
29
  this.hideCurrent();
27
30
  this.cwd = cwd;
31
+ this.sessionId = safeSingleLine(sessionId) || "Session unavailable";
28
32
  this.ui = ui;
29
33
  this.applyMode();
30
34
  }
@@ -62,7 +66,7 @@ export class TasksPanelHost {
62
66
  this.tui = tui;
63
67
  this.panel = new TasksPanel(tui, this.state, theme, "widget", this.minimized, (minimized) => {
64
68
  this.minimized = minimized;
65
- }, (message, type) => ui.notify(message, type), this.cwd, this.git);
69
+ }, (message, type) => ui.notify(message, type), this.cwd, this.git, this.sessionId);
66
70
  return this.panel;
67
71
  });
68
72
  return;
@@ -71,7 +75,7 @@ export class TasksPanelHost {
71
75
  this.tui = tui;
72
76
  this.panel = new TasksPanel(tui, this.state, theme, "floating", this.minimized, (minimized) => {
73
77
  this.minimized = minimized;
74
- }, (message, type) => ui.notify(message, type), this.cwd, this.git);
78
+ }, (message, type) => ui.notify(message, type), this.cwd, this.git, this.sessionId);
75
79
  this.handle = tui.showOverlay(this.panel, {
76
80
  anchor: "top-right",
77
81
  width: "42%",
@@ -108,18 +112,22 @@ class TasksPanel {
108
112
  notify;
109
113
  cwd;
110
114
  git;
115
+ sessionId;
111
116
  scrollOffset = 0;
112
117
  pageSize = 1;
113
118
  contentLength = 0;
114
119
  followTail = true;
115
120
  copying = false;
116
121
  opening = false;
122
+ openingDelegate = false;
123
+ delegateHits = [];
117
124
  disposed = false;
118
125
  unsubscribeGit;
119
126
  copyHitRegion;
120
127
  openHitRegion;
128
+ sessionHitRegion;
121
129
  toggleHitRegion;
122
- constructor(tui, state, theme, placement, minimized, onMinimizedChange, notify, cwd, git) {
130
+ constructor(tui, state, theme, placement, minimized, onMinimizedChange, notify, cwd, git, sessionId) {
123
131
  this.tui = tui;
124
132
  this.state = state;
125
133
  this.theme = theme;
@@ -129,8 +137,10 @@ class TasksPanel {
129
137
  this.notify = notify;
130
138
  this.cwd = cwd;
131
139
  this.git = git;
140
+ this.sessionId = sessionId;
132
141
  }
133
142
  render(width) {
143
+ this.delegateHits = [];
134
144
  if (this.placement === "widget")
135
145
  this.setVisible(width >= 38);
136
146
  if (width < 38)
@@ -140,7 +150,7 @@ class TasksPanel {
140
150
  const innerWidth = boxWidth - 2;
141
151
  const leftPad = this.placement === "widget" ? " ".repeat(Math.max(0, width - boxWidth)) : "";
142
152
  if (this.minimized) {
143
- const header = this.renderHeader("Works", innerWidth, leftPad.length);
153
+ const header = this.renderHeader(innerWidth, leftPad.length);
144
154
  return [
145
155
  gitBorder(innerWidth, this.theme, this.git.getSnapshot()),
146
156
  frame(header, innerWidth, this.theme),
@@ -149,14 +159,18 @@ class TasksPanel {
149
159
  }
150
160
  const contentWidth = innerWidth - PROGRESS_COLUMN_WIDTH;
151
161
  const content = [];
162
+ const delegateRows = new Map();
152
163
  if (works.length === 0)
153
164
  content.push(progressColumn(this.theme.fg("muted", "No works yet."), null, innerWidth, this.theme));
154
165
  for (const work of works) {
155
166
  const completed = work.tasks.filter((todo) => todo.status === "completed").length;
156
- const summary = workSummaryLine(work.status, work.workName, `${completed}/${work.tasks.length}`, contentWidth, this.theme);
167
+ const summary = workSummaryLine(work.status, work.workName, `${completed}/${work.tasks.length}`, contentWidth, this.theme, work.workId);
157
168
  content.push(progressColumn(summary, workCompletion(work), innerWidth, this.theme));
158
169
  for (const todo of work.tasks) {
159
- const label = ` ${todoIcon(todo.status, this.theme)} ${this.theme.fg(todo.status === "completed" ? "muted" : "text", safeSingleLine(todo.taskName))}`;
170
+ const agent = delegateLink(todo.taskInfo);
171
+ const lead = ` ${todoIcon(todo.status, this.theme)} ${recordId(todo.taskId, this.theme)} `;
172
+ const label = `${lead}${ownerBadge(todo.taskInfo, this.theme, Boolean(agent))} ${this.theme.fg(todo.status === "completed" ? "muted" : "text", safeSingleLine(todo.taskName))}`;
173
+ delegateRows.set(content.length, { agent, start: visibleWidth(lead) });
160
174
  content.push(progressColumn(label, taskCompletion(todo), innerWidth, this.theme));
161
175
  }
162
176
  }
@@ -174,15 +188,20 @@ class TasksPanel {
174
188
  this.clampScrollOffset();
175
189
  }
176
190
  const shown = content.slice(this.scrollOffset, this.scrollOffset + this.pageSize);
191
+ shown.forEach((line, index) => {
192
+ const row = delegateRows.get(this.scrollOffset + index);
193
+ if (!row)
194
+ return;
195
+ const hit = delegateHitRegion(row.agent, row.start, line, 3 + index, leftPad.length);
196
+ if (hit)
197
+ this.delegateHits.push(hit);
198
+ });
177
199
  const hasOverflow = content.length > this.pageSize;
178
200
  const range = `${this.scrollOffset + 1}–${this.scrollOffset + shown.length}/${content.length}`;
179
- let title = "Works";
180
- if (this.placement === "floating" && hasOverflow) {
181
- title += this.tui.mode === "fullscreen"
182
- ? ` · ${range}`
183
- : ` · ${range} · latest · /works for all`;
184
- }
185
- const header = this.renderHeader(title, innerWidth, leftPad.length);
201
+ const suffix = this.placement === "floating" && hasOverflow
202
+ ? this.tui.mode === "fullscreen" ? ` · ${range}` : ` · ${range} · latest · /works for all`
203
+ : "";
204
+ const header = this.renderHeader(innerWidth, leftPad.length, suffix);
186
205
  const lines = [
187
206
  gitBorder(innerWidth, this.theme, this.git.getSnapshot()),
188
207
  frame(header, innerWidth, this.theme),
@@ -195,7 +214,23 @@ class TasksPanel {
195
214
  handleMouse(event) {
196
215
  if (this.disposed)
197
216
  return undefined;
198
- if (event.type === "click" && event.button === "left" && event.y === 1) {
217
+ if (event.type === "press" && event.button === "left") {
218
+ const delegateHit = this.delegateHits.some((region) => event.y === region.y && this.isHit(event.x, region));
219
+ const headerHit = event.y === 1 && [this.copyHitRegion, this.sessionHitRegion, this.openHitRegion, this.toggleHitRegion].some((region) => this.isHit(event.x, region));
220
+ // Own the gesture so Pi does not turn repeated control clicks into text selection.
221
+ if (delegateHit || headerHit)
222
+ return { handled: true };
223
+ }
224
+ // Legacy mouse releases omit the button; Pi still normalizes the gesture as a click.
225
+ const primaryClick = event.type === "click" && (event.button === "left" || event.button === "none");
226
+ if (primaryClick) {
227
+ const hit = this.delegateHits.find((region) => event.y === region.y && this.isHit(event.x, region));
228
+ if (hit) {
229
+ void this.openLinkedDelegate(hit.link);
230
+ return { handled: true, render: true };
231
+ }
232
+ }
233
+ if (primaryClick && event.y === 1) {
199
234
  if (this.isHit(event.x, this.toggleHitRegion)) {
200
235
  this.setMinimized(!this.minimized);
201
236
  return { handled: true, render: true };
@@ -204,6 +239,10 @@ class TasksPanel {
204
239
  void this.copyAllAsMarkdown();
205
240
  return { handled: true, render: true };
206
241
  }
242
+ if (this.isHit(event.x, this.sessionHitRegion)) {
243
+ void this.openInCursor(true);
244
+ return { handled: true, render: true };
245
+ }
207
246
  if (this.isHit(event.x, this.openHitRegion)) {
208
247
  void this.openInCursor();
209
248
  return { handled: true, render: true };
@@ -239,43 +278,66 @@ class TasksPanel {
239
278
  this.onMinimizedChange(minimized);
240
279
  this.tui.requestRender();
241
280
  }
242
- renderHeader(titleText, width, leftPadWidth) {
243
- const title = this.theme.fg("accent", this.theme.bold(titleText));
281
+ renderHeader(width, leftPadWidth, suffix = "") {
244
282
  const copyAction = this.copying
245
283
  ? this.theme.fg("dim", "[Copying…]")
246
284
  : this.theme.fg("accent", this.theme.bold("[Copy]"));
247
- const openAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.bold("[Open]"));
248
- const toggleLabel = this.minimized ? "[Maximize]" : "[Minimize]";
285
+ const sessionAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.underline(this.theme.bold("[Open session]")));
286
+ const openAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.underline(this.theme.bold("[Open]")));
287
+ const fixedWidth = visibleWidth(copyAction) + visibleWidth(sessionAction) + visibleWidth(openAction) + 3;
288
+ const fullToggle = this.minimized ? "[Maximize]" : "[Minimize]";
289
+ const toggleLabel = fixedWidth + visibleWidth(fullToggle) <= width ? fullToggle : this.minimized ? "[+]" : "[-]";
249
290
  const toggleAction = this.theme.fg("accent", this.theme.bold(toggleLabel));
250
- const actionsWidth = visibleWidth(copyAction) + 1 + visibleWidth(openAction) + 1 + visibleWidth(toggleAction);
291
+ const actionsWidth = fixedWidth + visibleWidth(toggleAction);
251
292
  const titleWidth = Math.max(0, width - actionsWidth - 1);
252
- const shownTitle = truncateToWidth(title, titleWidth, "");
253
- const gap = " ".repeat(Math.max(1, width - visibleWidth(shownTitle) - actionsWidth));
254
- const copyStart = leftPadWidth + 1 + visibleWidth(shownTitle) + gap.length;
293
+ const context = truncateToWidth(this.theme.fg("dim", suffix.replace(/^\s*·\s*/, "")), titleWidth, "…");
294
+ const gap = " ".repeat(Math.max(0, width - visibleWidth(context) - actionsWidth));
295
+ const copyStart = leftPadWidth + 1 + visibleWidth(context) + gap.length;
255
296
  this.copyHitRegion = { start: copyStart, end: copyStart + visibleWidth(copyAction) };
256
- const openStart = this.copyHitRegion.end + 1;
297
+ const sessionStart = this.copyHitRegion.end + 1;
298
+ this.sessionHitRegion = { start: sessionStart, end: sessionStart + visibleWidth(sessionAction) };
299
+ const openStart = this.sessionHitRegion.end + 1;
257
300
  this.openHitRegion = { start: openStart, end: openStart + visibleWidth(openAction) };
258
301
  const toggleStart = this.openHitRegion.end + 1;
259
302
  this.toggleHitRegion = { start: toggleStart, end: toggleStart + visibleWidth(toggleAction) };
260
- return `${shownTitle}${gap}${copyAction} ${openAction} ${toggleAction}`;
303
+ return `${context}${gap}${copyAction} ${sessionAction} ${openAction} ${toggleAction}`;
261
304
  }
262
305
  isHit(x, region) {
263
306
  return region !== undefined && x >= region.start && x < region.end;
264
307
  }
265
- async openInCursor() {
308
+ async openLinkedDelegate(link) {
309
+ if (this.openingDelegate)
310
+ return;
311
+ this.openingDelegate = true;
312
+ try {
313
+ await focusPane(link.paneId, this.cwd);
314
+ }
315
+ catch (error) {
316
+ const reason = error instanceof Error ? safeSingleLine(error.message) : "Unknown error.";
317
+ if (!this.disposed)
318
+ this.notify(`Could not open delegate. ${reason}`, "error");
319
+ }
320
+ finally {
321
+ this.openingDelegate = false;
322
+ }
323
+ }
324
+ async openInCursor(session = false) {
266
325
  if (this.opening)
267
326
  return;
268
327
  this.opening = true;
269
328
  this.tui.requestRender();
270
329
  try {
271
- await openRepository(this.cwd);
330
+ if (session)
331
+ await openSession(this.cwd, this.sessionId);
332
+ else
333
+ await openRepository(this.cwd);
272
334
  if (!this.disposed)
273
- this.notify("Opened repository in Cursor.", "info");
335
+ this.notify(session ? "Opened session artifacts in Cursor." : "Opened repository in Cursor.", "info");
274
336
  }
275
337
  catch (error) {
276
338
  const reason = error instanceof Error ? ` ${safeSingleLine(error.message)}` : "";
277
339
  if (!this.disposed)
278
- this.notify(`Could not open Cursor. Check that cursor is installed on PATH.${reason}`, "error");
340
+ this.notify(session ? `Could not open session artifacts in Cursor.${reason}` : `Could not open Cursor. Check that cursor is installed on PATH.${reason}`, "error");
279
341
  }
280
342
  finally {
281
343
  this.opening = false;
@@ -321,9 +383,22 @@ class TasksPanel {
321
383
  return Math.max(0, this.contentLength - this.pageSize);
322
384
  }
323
385
  }
324
- export function progressName(name, completion, width) {
386
+ export function recordId(id, theme) {
387
+ return theme.fg(id.startsWith("W") ? "accent" : "syntaxType", `[${safeSingleLine(id)}]`);
388
+ }
389
+ export function ownerBadge(taskInfo, theme, linked = false) {
390
+ const owner = taskOwner(taskInfo);
391
+ const label = owner === "delegate" && linked ? theme.underline(`[${owner}]`) : `[${owner}]`;
392
+ return theme.fg(owner === "self" ? "success" : owner === "delegate" ? "warning" : "muted", label);
393
+ }
394
+ export function delegateHitRegion(link, start, line, y, leftPad = 0) {
395
+ if (!link || stripVTControlCharacters(sliceByColumn(line, start, 10)) !== "[delegate]")
396
+ return undefined;
397
+ return { start: leftPad + 1 + start, end: leftPad + 1 + start + 10, y, link };
398
+ }
399
+ export function progressName(name, completion, width, prefix = "") {
325
400
  const suffix = ` · ${formatCompletion(completion)}`;
326
- return `${truncateToWidth(safeSingleLine(name), Math.max(0, width - visibleWidth(suffix)), "…")}${suffix}`;
401
+ return `${truncateToWidth(`${prefix}${safeSingleLine(name)}`, Math.max(0, width - visibleWidth(suffix)), "…")}${suffix}`;
327
402
  }
328
403
  function progressColumn(content, completion, width, theme) {
329
404
  const contentWidth = width - PROGRESS_COLUMN_WIDTH;
@@ -332,10 +407,10 @@ function progressColumn(content, completion, width, theme) {
332
407
  const value = theme.fg(completion === null ? "muted" : "accent", formatCompletion(completion).padStart(PROGRESS_VALUE_WIDTH));
333
408
  return `${left}${padding}${theme.fg("border", " │ ")}${value}`;
334
409
  }
335
- function workSummaryLine(status, name, count, width, theme) {
410
+ function workSummaryLine(status, name, count, width, theme, workId) {
336
411
  const right = theme.fg("dim", count);
337
412
  const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
338
- const left = `${workIcon(status, theme)} ${theme.fg("text", safeSingleLine(name))}`;
413
+ const left = `${workIcon(status, theme)} ${recordId(workId, theme)} ${theme.fg("text", safeSingleLine(name))}`;
339
414
  const shownLeft = truncateToWidth(left, leftWidth, "…");
340
415
  const gap = " ".repeat(Math.max(1, width - visibleWidth(shownLeft) - visibleWidth(right)));
341
416
  return `${shownLeft}${gap}${right}`;
@@ -21,6 +21,8 @@ export declare class WorksDashboard implements Component, Focusable {
21
21
  private messageColor;
22
22
  private copying;
23
23
  private opening;
24
+ private openingDelegate;
25
+ private delegateHits;
24
26
  private minimized;
25
27
  private readonly unsubscribeGit;
26
28
  private openHitRegion;
@@ -43,6 +45,7 @@ export declare class WorksDashboard implements Component, Focusable {
43
45
  private renderHeader;
44
46
  private toggleMinimized;
45
47
  private isHit;
48
+ private openLinkedDelegate;
46
49
  private openInCursor;
47
50
  private copyAllAsMarkdown;
48
51
  private renderFooter;
@@ -1,10 +1,11 @@
1
1
  import { copyToClipboard } from "@earendil-works/pi-coding-agent";
2
2
  import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
3
+ import { delegateLink, focusPane } from "../agents/links.js";
3
4
  import { formatWorksMarkdown } from "../markdown.js";
4
5
  import { openRepository } from "../open-repository.js";
5
6
  import { formatCompletion, taskCompletion, workCompletion } from "../progress.js";
6
7
  import { safeMultiline, safeSingleLine } from "../text.js";
7
- import { border, frame, gitBorder, progressName, rule, todoIcon, workIcon } from "./panel.js";
8
+ import { border, delegateHitRegion, frame, gitBorder, ownerBadge, progressName, recordId, rule, todoIcon, workIcon } from "./panel.js";
8
9
  const CHROME_LINES = 8;
9
10
  export class WorksDashboard {
10
11
  tui;
@@ -25,6 +26,8 @@ export class WorksDashboard {
25
26
  messageColor = "warning";
26
27
  copying = false;
27
28
  opening = false;
29
+ openingDelegate = false;
30
+ delegateHits = [];
28
31
  minimized = false;
29
32
  unsubscribeGit;
30
33
  openHitRegion;
@@ -49,6 +52,7 @@ export class WorksDashboard {
49
52
  this.refreshTimer.unref?.();
50
53
  }
51
54
  render(width) {
55
+ this.delegateHits = [];
52
56
  const dialogWidth = Math.max(1, width);
53
57
  const innerWidth = Math.max(1, dialogWidth - 2);
54
58
  const works = this.state.listWorks();
@@ -74,9 +78,16 @@ export class WorksDashboard {
74
78
  const listHeight = Math.max(0, bodyHeight - details.length);
75
79
  if (listHeight > 0)
76
80
  this.keepSelectionVisible(items, listHeight);
77
- const rows = items.slice(this.scrollOffset, this.scrollOffset + listHeight).map((item) => this.renderRow(item, innerWidth));
81
+ const rows = items.slice(this.scrollOffset, this.scrollOffset + listHeight).map((item, index) => this.renderRow(item, innerWidth, 4 + index));
78
82
  while (rows.length < listHeight)
79
83
  rows.push("");
84
+ const selected = items.find((item) => item.key === this.selectedKey);
85
+ if (selected?.kind === "todo" && details[1] !== undefined) {
86
+ const start = visibleWidth(`${recordId(selected.todo.taskId, this.theme)} `);
87
+ const hit = delegateHitRegion(delegateLink(selected.todo.taskInfo), start, details[1], 5 + listHeight);
88
+ if (hit)
89
+ this.delegateHits.push(hit);
90
+ }
80
91
  return [
81
92
  gitBorder(innerWidth, this.theme, this.git.getSnapshot()),
82
93
  frame(header, innerWidth, this.theme),
@@ -113,6 +124,18 @@ export class WorksDashboard {
113
124
  }
114
125
  if (this.minimized)
115
126
  return;
127
+ if (matchesKey(data, "d")) {
128
+ const selected = items.find((item) => item.key === this.selectedKey);
129
+ const link = selected?.kind === "todo" ? delegateLink(selected.todo.taskInfo) : undefined;
130
+ if (link)
131
+ void this.openLinkedDelegate(link);
132
+ else {
133
+ this.message = "Select a delegated task with a Herdr pane link. Navigation requires Herdr.";
134
+ this.messageColor = "warning";
135
+ this.tui.requestRender();
136
+ }
137
+ return;
138
+ }
116
139
  this.messageColor = "warning";
117
140
  if (this.keybindings.matches(data, "tui.select.up")) {
118
141
  this.select(items, index - 1);
@@ -136,7 +159,24 @@ export class WorksDashboard {
136
159
  this.tui.requestRender();
137
160
  }
138
161
  handleMouse(event) {
139
- if (this.disposed || event.type !== "click" || event.button !== "left" || event.y !== 1)
162
+ if (this.disposed)
163
+ return undefined;
164
+ if (event.type === "press" && event.button === "left") {
165
+ const delegateHit = this.delegateHits.some((region) => event.y === region.y && this.isHit(event.x, region));
166
+ const headerHit = event.y === 1 && [this.copyHitRegion, this.openHitRegion, this.toggleHitRegion].some((region) => this.isHit(event.x, region));
167
+ // Own the gesture so Pi does not turn repeated control clicks into text selection.
168
+ if (delegateHit || headerHit)
169
+ return { handled: true };
170
+ }
171
+ // Legacy mouse releases omit the button; Pi still normalizes the gesture as a click.
172
+ if (event.type !== "click" || (event.button !== "left" && event.button !== "none"))
173
+ return undefined;
174
+ const hit = this.delegateHits.find((region) => event.y === region.y && this.isHit(event.x, region));
175
+ if (hit) {
176
+ void this.openLinkedDelegate(hit.link);
177
+ return { handled: true, focus: true, render: true };
178
+ }
179
+ if (event.y !== 1)
140
180
  return undefined;
141
181
  if (this.isHit(event.x, this.toggleHitRegion)) {
142
182
  this.toggleMinimized();
@@ -189,18 +229,23 @@ export class WorksDashboard {
189
229
  this.scrollOffset = index - height + 1;
190
230
  this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, Math.max(0, items.length - height)));
191
231
  }
192
- renderRow(item, width) {
232
+ renderRow(item, width, y) {
193
233
  const selected = item.key === this.selectedKey;
194
234
  const prefix = selected ? this.theme.fg("accent", "▶ ") : " ";
195
235
  if (item.kind === "work") {
196
236
  const done = item.work.tasks.filter((todo) => todo.status === "completed").length;
197
- const metadata = this.theme.fg("dim", `${item.work.workId} · ${item.work.status} · ${done}/${item.work.tasks.length}`);
237
+ const metadata = this.theme.fg("dim", `${item.work.status} · ${done}/${item.work.tasks.length}`);
198
238
  const nameWidth = width - visibleWidth(prefix) - 3 - visibleWidth(metadata);
199
- return truncateToWidth(`${prefix}${workIcon(item.work.status, this.theme)} ${this.theme.bold(progressName(item.work.workName, workCompletion(item.work), nameWidth))} ${metadata}`, width, "");
239
+ return truncateToWidth(`${prefix}${workIcon(item.work.status, this.theme)} ${this.theme.bold(progressName(item.work.workName, workCompletion(item.work), nameWidth, `${recordId(item.work.workId, this.theme)} `))} ${metadata}`, width, "");
200
240
  }
201
- const metadata = this.theme.fg("dim", `${item.todo.taskId} · ${item.todo.status}`);
241
+ const metadata = this.theme.fg("dim", item.todo.status);
202
242
  const nameWidth = width - visibleWidth(prefix) - 5 - visibleWidth(metadata);
203
- return truncateToWidth(`${prefix} ${todoIcon(item.todo.status, this.theme)} ${progressName(item.todo.taskName, taskCompletion(item.todo), nameWidth)} ${metadata}`, width, "");
243
+ const line = truncateToWidth(`${prefix} ${todoIcon(item.todo.status, this.theme)} ${progressName(item.todo.taskName, taskCompletion(item.todo), nameWidth, `${recordId(item.todo.taskId, this.theme)} ${ownerBadge(item.todo.taskInfo, this.theme, Boolean(delegateLink(item.todo.taskInfo)))} `)} ${metadata}`, width, "");
244
+ const start = visibleWidth(`${prefix} ${todoIcon(item.todo.status, this.theme)} ${recordId(item.todo.taskId, this.theme)} `);
245
+ const hit = delegateHitRegion(delegateLink(item.todo.taskInfo), start, line, y);
246
+ if (hit)
247
+ this.delegateHits.push(hit);
248
+ return line;
204
249
  }
205
250
  renderDetails(items, width, budget) {
206
251
  if (!this.detailsVisible || budget === 0)
@@ -210,21 +255,23 @@ export class WorksDashboard {
210
255
  return [this.theme.fg("muted", "No works or todos in this session.")].slice(0, budget);
211
256
  let heading;
212
257
  if (item.kind === "work") {
213
- const lead = `${item.work.workId} · `;
258
+ const lead = `${recordId(item.work.workId, this.theme)} `;
214
259
  const tail = ` · ${item.work.status}`;
215
260
  heading = `${lead}${progressName(item.work.workName, workCompletion(item.work), width - visibleWidth(lead + tail))}${tail}`;
216
261
  }
217
262
  else {
218
263
  const taskName = safeSingleLine(item.todo.taskName);
264
+ const taskLead = `${recordId(item.todo.taskId, this.theme)} ${ownerBadge(item.todo.taskInfo, this.theme, Boolean(delegateLink(item.todo.taskInfo)))} `;
219
265
  const workName = safeSingleLine(item.work.workName);
220
266
  const taskProgress = formatCompletion(taskCompletion(item.todo));
221
267
  const workProgress = formatCompletion(workCompletion(item.work));
222
- const fixed = `${item.todo.taskId} · · ${taskProgress} · ${item.todo.status} · ${item.todo.workId} · ${workProgress}`;
268
+ const workId = recordId(item.todo.workId, this.theme);
269
+ const fixed = `${taskLead} · ${taskProgress} · ${item.todo.status} · ${workId} · ${workProgress}`;
223
270
  const available = Math.max(0, width - visibleWidth(fixed));
224
271
  const taskWidth = Math.min(visibleWidth(taskName), available - Math.min(visibleWidth(workName), Math.floor(available / 2)));
225
272
  const shownTask = truncateToWidth(taskName, taskWidth, "…");
226
273
  const shownWork = truncateToWidth(workName, available - taskWidth, "…");
227
- heading = `${item.todo.taskId} · ${shownTask} · ${taskProgress} · ${item.todo.status} · ${item.todo.workId} ${shownWork} · ${workProgress}`;
274
+ heading = `${taskLead}${shownTask} · ${taskProgress} · ${item.todo.status} · ${workId} ${shownWork} · ${workProgress}`;
228
275
  }
229
276
  const info = item.kind === "work" ? item.work.workInfo : item.todo.taskInfo;
230
277
  const infoLines = safeMultiline(info).flatMap((line) => wrapTextWithAnsi(this.theme.fg("dim", line || " "), width));
@@ -248,7 +295,7 @@ export class WorksDashboard {
248
295
  const copyAction = this.copying
249
296
  ? this.theme.fg("dim", "[Copying…]")
250
297
  : this.theme.fg("accent", this.theme.bold("[C Copy]"));
251
- const openAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.bold("[O Open]"));
298
+ const openAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.underline(this.theme.bold("[O Open]")));
252
299
  const toggleLabel = this.minimized ? "[M Maximize]" : "[M Minimize]";
253
300
  const toggleAction = this.theme.fg("accent", this.theme.bold(toggleLabel));
254
301
  const actionsWidth = visibleWidth(copyAction) + 1 + visibleWidth(openAction) + 1 + visibleWidth(toggleAction);
@@ -274,6 +321,31 @@ export class WorksDashboard {
274
321
  isHit(x, region) {
275
322
  return region !== undefined && x >= region.start && x < region.end;
276
323
  }
324
+ async openLinkedDelegate(link) {
325
+ if (this.openingDelegate)
326
+ return;
327
+ this.openingDelegate = true;
328
+ this.message = "Opening delegated agent in Herdr…";
329
+ this.messageColor = "warning";
330
+ this.tui.requestRender();
331
+ try {
332
+ await focusPane(link.paneId, this.cwd);
333
+ this.message = "Opened delegated agent in Herdr.";
334
+ this.messageColor = "success";
335
+ }
336
+ catch (error) {
337
+ const reason = error instanceof Error ? safeSingleLine(error.message) : "Unknown error.";
338
+ this.message = `Could not open delegate. ${reason}`;
339
+ this.messageColor = "error";
340
+ if (!this.disposed)
341
+ this.notify(this.message, "error");
342
+ }
343
+ finally {
344
+ this.openingDelegate = false;
345
+ if (!this.disposed)
346
+ this.tui.requestRender();
347
+ }
348
+ }
277
349
  async openInCursor() {
278
350
  if (this.opening)
279
351
  return;
@@ -325,7 +397,7 @@ export class WorksDashboard {
325
397
  }
326
398
  }
327
399
  renderFooter(width) {
328
- const text = "C copy all · O open Cursor · M minimize · configured ↑/↓ select · PgUp/PgDn scroll details · confirm toggles · cancel closes";
400
+ const text = "C copy all · O open Cursor · D open delegate · M minimize · configured ↑/↓ select · PgUp/PgDn scroll details · confirm toggles · cancel closes";
329
401
  return truncateToWidth(this.theme.fg("muted", text), width, "");
330
402
  }
331
403
  }
package/docs/REFERENCE.md CHANGED
@@ -44,19 +44,31 @@ Replay normalizes legacy `planned` and `pending` statuses to `active` in both cr
44
44
 
45
45
  When all tracking tools are active, the extension adds hidden per-turn guidance for every normal request that starts or continues work. Pi finds or creates work, synchronizes todos, marks the current todo active before the attempt, and updates statuses afterward. Tracking is not skipped merely because the request looks small.
46
46
 
47
+ The guidance also requires every delegated subagent, at every depth, to create or resume its own session-local Work and Todos before assigned work, maintain a real `workId` and an active `taskId`, and return its IDs with results. Parent assignment IDs are recorded as context, not used to mutate another session's records. Worker prompts must carry this requirement, including stopping delegated execution if tracking tools or IDs are unavailable. This is instruction-only, not a tool-call gate or automatic tracking repair.
48
+
47
49
  The guidance is not added when the tracking tools have been removed from the active tool set. Pi Ask removes them during `/ask`. Pi BTW executes its side conversation outside the main conversation. The guidance also explicitly forbids changing works, todos, loops, or monitors during either mode.
48
50
 
51
+ ### Shared workflow contract
52
+
53
+ The guidance directs every tracked Work, including worker-local Works, through the globally installed `implement` skill. Reuse an active skill rather than recursively invoking it. Specialized skill permissions remain authoritative; planning, research, and review do not gain implementation authority. Missing `implement`, tracking tools, valid session identity, or real IDs blocks execution. Reading instructions, obtaining identity, and establishing records are startup steps, not assigned execution. Plain conversation and side-thread exceptions remain unchanged.
54
+
55
+ The agent obtains its full session identity from `PI_SESSION_ID` in its own shell-tool command, not from a parent prompt or Herdr pane/name. Require `[A-Za-z0-9][A-Za-z0-9_-]*` and actual Work/Task IDs. Hosts without session-environment support must report the identity blocker rather than guess. Root artifacts use repository-relative `var/<sessionId>/<workId>/<taskId>/`; delegated artifacts append `<childSessionId>/<childWorkId>/<childTaskId>/` beneath the exact canonical parent task directory, recursively. Resolved destinations, including symlinks, must remain inside repository `var/`. Paths and parent IDs go in existing `taskInfo` and handoff context; each worker returns its own IDs and canonical path. Do not migrate legacy artifacts implicitly or overwrite files after branch navigation solely because numeric IDs match. `implement` owns the detailed path/ownership contract, including incompatible specialized helper handling.
56
+
57
+ Each task starts its existing `taskInfo` with `owner: self` or `owner: delegate` plus a reason, preserving that declaration in later updates. Delegation requires a bounded outcome, isolated ownership, ready inputs and verified prerequisites, useful parallelism or expertise that exceeds coordination costs, owning-skill permission, and available tracking/monitoring. Small or tightly coupled changes stay with one owner by default. Reassess on scope changes and apply the rule at every permitted delegation depth; parents retain integration and verification responsibility. Herdr retains lifecycle and monitor ownership. Worker root panes use only the parent's delegated Task ID as their name (`T34`, without brackets or descriptions), updated when a different parent Todo is assigned. This label is distinct from worker-local IDs and may repeat across parent sessions; returned resource IDs remain authoritative for lifecycle commands. No file-count, agent-count, or depth threshold is imposed.
58
+
59
+ This is model guidance only. No new schema fields, path-creation code, tool-call gate, cross-session mutation, session-ID API dependency, or automatic skill installer is added. Guidance still depends on all tracking tools being active as described above.
60
+
49
61
  ## Auto-continuation
50
62
 
51
63
  Auto-continuation is optional and requires Pi 1.2.0 or newer. Configure `pi-tasks.autoContinue` in Pi's `settings.json`; the extension reads `pi.getSettings()` so trusted project settings override global settings. `enabled` defaults to `false`; `maxContinuations` is optional. Omission means no continuation limit; if supplied, it must be a positive safe integer. Explicit `null` is invalid. Invalid configuration disables the flow and reports a warning. Hosts without the new settings API keep normal task tracking with no automatic continuation.
52
64
 
53
- A fresh accepted main interactive/RPC run arms a new continuation epoch. Input is provisional until the run starts, so handled/rejected prompts cannot arm it. Extension/custom starts do not arm or reset it. Steering/follow-up messages queued inside an already-running activity do not themselves reset the cap. Session start/reload, tree navigation, and shutdown disarm it until fresh user input. Aborted or failed activity also suspends it. `agent_settled.aborted` covers aborts that skip the actionable boundary. Tracking tools must be active; side conversations must not start continuation.
65
+ A fresh accepted main interactive/RPC run arms a new continuation epoch. Input is provisional until the run starts, so handled/rejected prompts cannot arm it. Extension/custom starts do not arm or reset it. Steering/follow-up messages queued inside an already-running activity do not themselves reset the cap. Session start/reload, tree navigation, and shutdown disarm it until fresh user input. Explicitly aborted activity also suspends it; failed activity does not. `agent_settled.aborted` covers aborts that skip the actionable boundary. Tracking tools must be active; side conversations must not start continuation.
54
66
 
55
- The synchronous `agent_before_settle` handler runs after native retries, compaction, and queued work. It requires a completed outcome, a non-aborted signal, no pending messages in either the boundary preview or runtime queue, and no continuation already requested by an earlier handler. Pi is still busy at this actionable boundary, so it does not require `ctx.isIdle()`. Instead it appends one custom-message draft and requests one native continuation; Pi owns committing it and honoring cancellation. No detached prompt, timer, background worker, or polling loop is created.
67
+ The synchronous `agent_before_settle` handler runs after native retries, compaction, and queued work. It accepts completed or error outcomes and requires a non-aborted signal, no pending messages in either the boundary preview or runtime queue, and no continuation already requested by an earlier handler. Pi is still busy at this actionable boundary, so it does not require `ctx.isIdle()`. Instead it appends one custom-message draft and requests one native continuation; Pi owns committing it and honoring cancellation. No detached prompt, timer, background worker, or polling loop is created.
56
68
 
57
- Active works and todos on the current branch require continuation. Completed, blocked, and cancelled records are settled. A settled parent does not hide an unfinished child. The prompt includes a bounded preview of IDs, names and statuses, and directs the agent to list tools for full details. No records means no continuation. The extension never mutates statuses, verifies work independently, or treats a blocker label as proof of an actual dependency.
69
+ Any work or todo on the current branch whose status is not blocked, completed, or cancelled requires continuation. This includes active records and legacy planned/pending records, which replay normalizes to active. Completed, blocked, and cancelled records are settled. A settled parent does not hide an unfinished child. The prompt includes a bounded preview of IDs, names and statuses, and directs the agent to list tools for full details. No records means no continuation. The extension never mutates statuses, verifies work independently, or treats a blocker label as proof of an actual dependency.
58
70
 
59
- When `maxContinuations` is supplied, at most that many extra continuations are requested per fresh accepted main user run. The next unfinished boundary warns once and suspends continuation; a fresh user prompt resets the cap. With no limit supplied, continuation can consume tokens indefinitely while unfinished records remain, until interrupted, failed, disabled or otherwise suspended. This is not a cost cap or a cap on native tool/retry requests, and another extension may independently request work. Settings changes take effect when Pi reloads effective settings, normally through `/reload`.
71
+ When `maxContinuations` is supplied, at most that many extra continuations are requested per fresh accepted main user run. The next unfinished boundary warns once and suspends continuation; a fresh user prompt resets the cap. With no limit supplied, continuation can consume tokens indefinitely while unfinished records remain, until explicitly interrupted, disabled or otherwise suspended, including during repeated provider failures. This is not a cost cap or a cap on native tool/retry requests, and another extension may independently request work. Settings changes take effect when Pi reloads effective settings, normally through `/reload`.
60
72
 
61
73
  ## Repository status and Cursor
62
74
 
@@ -66,8 +78,24 @@ The implementation is informed by [pi-powerline-footer's cache behavior](https:/
66
78
 
67
79
  Open appears between Copy and Minimize/Maximize. It executes `cursor` with the separate argument `.` in the active session working directory, without a shell. The executable must be on PATH; errors are shown instead of silently failing. `/works-panel open` supplies a command path, and `/works` uses `o`. Open is also available outside Git repositories.
68
80
 
81
+ ### Ownership display
82
+
83
+ `taskOwner(taskInfo)` interprets explicit line-start `owner: self` or `owner: delegate` declarations case-insensitively. A trailing sentence/reason is allowed, but incidental prose and longer enum-like tokens such as `self-managed` do not count. Missing/invalid decisions or conflicting valid declarations return `unassigned`; repeated identical declarations remain unambiguous. Compact floating/widget panel rows, dashboard rows, and todo detail headings share this interpretation and show `[taskId] [self/delegate] Task name` (or `[unassigned]`). The existing `taskInfo` is the sole source; no persistence fields, tool parameters, migrations, or task-name edits are introduced. Progress reservations, status/count logic, and full details remain unchanged.
84
+
85
+ ### Delegate navigation
86
+
87
+ Agent tools are thin, bounded, shell-free Herdr CLI wrappers using actual paneId values. No separate agent handle, private registry, process/session validation, startup receipt, recovery/reconnection or acquisition framework is implemented. Panes are assumed not to be repurposed. Structured CLI errors are reported even with exit code zero, and partial creation failures report the handles already obtained without automatic retry/cleanup.
88
+
89
+ AgentCreate creates a dedicated unfocused tab, starts Pi with the supplied model flags and calls the existing MonitorCreate through ctx.executeTool with onSignal and optional onDone unchanged. It returns paneId/tabId/monitorId, assignmentSent:false and the prepared assignment. The AI must confirm MonitorList shows subscription ready before explicit AgentSend. Follow-up sends do not replace the monitor. AgentClose calls MonitorStop with the supplied monitorId, then closes the supplied pane; callers must use only resources they created. AgentList returns the CLI inventory, including unrelated agents. No subprocess runs during rendering.
90
+
91
+ AgentCreate stores herdr-pane and herdr-monitor lines in existing taskInfo; task tools persist and restore these details. TodoUpdate preserves existing link lines for delegate-to-delegate detail edits unless explicit replacement metadata is supplied, so ordinary progress/status descriptions do not silently disable navigation. Changing ownership, explicit `herdr-pane: none`, or AgentClose can unlink. delegateLink interprets an unambiguous valid pane ID for owner:delegate inside Herdr. AgentClose removes matching delegate links. No task schema change or automatic task completion is introduced. The onSignal/onDone callbacks remain entirely owned by pi-loop-monitor; onDone means its process ended, not that worker work is complete.
92
+
93
+ Delegate navigation and AgentFocus first focus the pane, then explicitly activate the tab returned by Herdr; pane-focus success alone does not guarantee that the visible client switched tabs.
94
+
95
+ Linked `[delegate]` badges and Cursor Open controls are underlined. Fullscreen mouse regions use ANSI-aware visible columns and only include complete visible badges after clipping and scrolling. Floating/widget rows, dashboard rows and todo detail headings support clicks; hidden/minimized/offscreen badges have no regions. In `/works`, `d` opens the selected task's delegate, and `/works-panel delegate T<number>` provides a command path in regular mode. Outside Herdr or without a pane link, ownership stays informational and is not underlined. Unavailable CLI, stale/closed targets and other navigation failures produce visible errors.
96
+
69
97
  ## Interfaces
70
98
 
71
- The compact panel defaults to a non-capturing floating overlay anchored at the top-right. It shows work and todo names, status icons, completion counts, and a visible row range when content exceeds the terminal-aware viewport. It hides on terminals narrower than 90 columns or shorter than 18 rows. In fullscreen TUI mode, its title-bar Copy action exports every work and nested todo as Markdown, while Minimize collapses the panel to a restorable title bar that keeps Copy, Open, and Maximize available. `/works-panel minimize` and `/works-panel maximize` provide a keyboard-command path and preserve the collapsed state when switching between floating and widget layouts. Overflow starts at the newest rows and follows newly added tail rows until the user scrolls upward. Mouse-wheel events over the expanded floating panel scroll it directly without taking keyboard focus; regular terminal mode shows the newest rows and uses `/works` for complete browsing and copying. Because Pi treats any persistent overlay as active, the floating mode can block display-mode changes. `/works-panel widget` switches to a right-aligned widget above the editor, renders all rows, and retains the title actions, while `/works-panel off` hides it.
99
+ The compact panel defaults to a non-capturing floating overlay anchored at the top-right. Its header hides the session ID and places an underlined Open session action immediately after Copy, including minimized/widget layouts. The action uses the Pi session-context identity to locate the matching direct/nested artifact directory under repository var and opens it via the existing shell-free Cursor launcher. If absent, the standard var/sessionId directory is created on activation; ambiguous matches or unsafe identity fail visibly. No lookup or process launch occurs during rendering. /works-panel open-session supplies a keyboard-command path. Existing repository Open remains separate. On narrow headers, Minimize/Maximize shorten to [-]/[+] to preserve every action and its hit region; overflow hints use remaining space. It prefixes work and todo names with bracketed IDs (`[W1] Name`, `[T1] [self] Name`), alongside status icons, completion counts, and a visible row range when content exceeds the terminal-aware viewport. It hides on terminals narrower than 90 columns or shorter than 18 rows. In fullscreen TUI mode, its title-bar Copy action exports every work and nested todo as Markdown, while Minimize collapses the panel to a restorable title bar that keeps Copy, Open, and Maximize available. `/works-panel minimize` and `/works-panel maximize` provide a keyboard-command path and preserve the collapsed state when switching between floating and widget layouts. Overflow starts at the newest rows and follows newly added tail rows until the user scrolls upward. Mouse-wheel events over the expanded floating panel scroll it directly without taking keyboard focus; regular terminal mode shows the newest rows and uses `/works` for complete browsing and copying. Because Pi treats any persistent overlay as active, the floating mode can block display-mode changes. `/works-panel widget` switches to a right-aligned widget above the editor, renders all rows, and retains the title actions, while `/works-panel off` hides it.
72
100
 
73
- `/works` opens a top-centered detailed overlay. Its top-right Copy action uses `c` to copy every work and nested todo to the system clipboard as Markdown. Its Open action uses `o` to open the current directory in Cursor. Its Minimize action uses `m` to collapse the overlay to a framed top bar containing live total work and todo counts, Copy, Open, and a Maximize action; activating Maximize restores the full dashboard. In fullscreen TUI mode, Copy, Open, and Minimize/Maximize also respond to left clicks. Configured selection keys choose records, configured Page Up and Page Down keys scroll long details, the configured confirmation key toggles details, and the configured cancel key closes it.
101
+ `/works` opens a top-centered detailed overlay. List rows and detail headings use the same bracketed ID and ownership prefixes; list metadata no longer repeats the ID after the name. The dashboard title remains unchanged. Stored names remain unchanged. Its top-right Copy action uses `c` to copy every work and nested todo to the system clipboard as Markdown. Its Open action uses `o` to open the current directory in Cursor. Its Minimize action uses `m` to collapse the overlay to a framed top bar containing live total work and todo counts, Copy, Open, and a Maximize action; activating Maximize restores the full dashboard. In fullscreen TUI mode, Copy, Open, and Minimize/Maximize also respond to left clicks. Configured selection keys choose records, configured Page Up and Page Down keys scroll long details, the configured confirmation key toggles details, and the configured cancel key closes it.