pi-better-background-tasks 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/goal-provider.ts +31 -16
  15. package/src/index.ts +6 -9
  16. package/src/managed-authority.ts +5 -3
  17. package/src/managed-client.ts +20 -7
  18. package/src/managed-frontend.ts +62 -17
  19. package/src/navigator-provider.ts +15 -5
  20. package/src/observed-wait-client.ts +10 -0
  21. package/src/observed-waits.ts +154 -30
  22. package/src/process-identity.ts +18 -2
  23. package/src/process.ts +3 -3
  24. package/src/registry.ts +53 -5
  25. package/src/runtime.ts +19 -9
  26. package/src/sandbox.ts +14 -11
  27. package/src/shared-callback-batcher.ts +11 -2
  28. package/src/shared-navigator-panels.ts +26 -4
  29. package/src/shared-navigator.ts +197 -14
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  31. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  32. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  33. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  34. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  35. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  36. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  37. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  38. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  39. package/src/shared-operation-coordinator/src/store.ts +34 -8
  40. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  41. package/src/shared-operation-coordinator/src/types.ts +5 -1
  42. package/src/shared-sandbox-core.ts +1 -1
  43. package/src/shared-work-client.mjs +150 -7
  44. package/src/supervisor/generated/process-identity.mjs +20 -2
  45. package/src/supervisor/generated/process.mjs +3 -3
  46. package/src/task-diagnostics.ts +1 -1
  47. package/src/tools.ts +41 -38
  48. package/src/types.ts +3 -1
  49. package/src/work-observation.ts +46 -19
package/src/runtime.ts CHANGED
@@ -27,7 +27,7 @@ import type {
27
27
  TerminalResult,
28
28
  } from "./types.js";
29
29
  import { observeTaskStallAttention } from "./stall-attention.js";
30
- import { isTerminalStatus } from "./types.js";
30
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
31
31
 
32
32
  export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
33
33
 
@@ -98,7 +98,7 @@ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
98
98
  /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
99
99
  export const DEFAULT_BLIND_CHECKS = 3;
100
100
  /** How long bg_task_watch waits for the first check before returning (#359). */
101
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
101
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.js";
102
102
  /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
103
103
  export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
104
104
  /**
@@ -110,7 +110,8 @@ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
110
110
  export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
111
 
112
112
  /** Each cached extension factory owns its scheduling and suspension state. */
113
- export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void }) {
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void },
114
+ sourceWork: (kind: string, id: string, work: () => unknown, dueAt?: number) => unknown = (_kind, _id, work) => work()) {
114
115
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
116
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
117
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -517,7 +518,8 @@ function scheduleRemoteSessionPoll(
517
518
  ): void {
518
519
  clearRemoteSessionTimer(id);
519
520
  if (scheduledWorkSuspended) return;
520
- const timer = setTimeout(() => void pollRemoteSession(pi, id, getActiveSession), delayMs);
521
+ const dueAt = Date.now() + delayMs;
522
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
521
523
  timer.unref();
522
524
  remoteSessionTimers.set(id, timer);
523
525
  }
@@ -735,6 +737,9 @@ function resumeRunningTask(
735
737
  scheduleLogRetention(pi, meta.id, getActiveSession);
736
738
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
737
739
  if (meta.kind === "command_watch") {
740
+ // Shared display refreshes can revisit an already supervised watch. They
741
+ // must not replace its captured interval with a new immediate poll.
742
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id)) return meta;
738
743
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
739
744
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
740
745
  : dependencies.watchPollRunner);
@@ -814,7 +819,8 @@ function scheduleHandoff(
814
819
  };
815
820
  const arm = () => {
816
821
  if (scheduledWorkSuspended) return;
817
- const timer = setTimeout(check, delayMs);
822
+ const dueAt = Date.now() + delayMs;
823
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended) check(); }, dueAt), delayMs);
818
824
  timer.unref();
819
825
  handoffTimers.set(id, timer);
820
826
  };
@@ -957,7 +963,8 @@ function scheduleWatch(
957
963
  ): void {
958
964
  clearWatchTimer(id);
959
965
  if (scheduledWorkSuspended) return;
960
- const timer = setTimeout(() => void pollWatch(pi, id, getActiveSession, runOnce), delayMs);
966
+ const dueAt = Date.now() + delayMs;
967
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
961
968
  timer.unref();
962
969
  watcherTimers.set(id, timer);
963
970
  }
@@ -1260,7 +1267,8 @@ function scheduleProcessTimeout(
1260
1267
  clearProcessTimeout(id);
1261
1268
  if (scheduledWorkSuspended) return;
1262
1269
  const delay = Math.max(0, deadlineAt - Date.now());
1263
- const timer = setTimeout(() => void timeoutProcess(pi, id, getActiveSession), delay);
1270
+ const dueAt = deadlineAt;
1271
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1264
1272
  timer.unref();
1265
1273
  processTimeoutTimers.set(id, timer);
1266
1274
  }
@@ -1459,7 +1467,9 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1459
1467
  function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1460
1468
  stopLogRetention(id);
1461
1469
  if (scheduledWorkSuspended) return;
1462
- const timer = setInterval(() => {
1470
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1471
+ const timer = setInterval(() => { const due = dueAt; dueAt = Date.now() + LOG_RETENTION_CHECK_MS; return sourceWork("log-retention", id, () => {
1472
+ if (scheduledWorkSuspended) return;
1463
1473
  const meta = readMeta(id);
1464
1474
  if (!meta || meta.status !== "running") {
1465
1475
  stopLogRetention(id);
@@ -1467,7 +1477,7 @@ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: A
1467
1477
  }
1468
1478
  if (meta.kind === "process") enforceLogRetention(meta);
1469
1479
  if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1470
- }, LOG_RETENTION_CHECK_MS);
1480
+ }, due); }, LOG_RETENTION_CHECK_MS);
1471
1481
  timer.unref();
1472
1482
  logRetentionTimers.set(id, timer);
1473
1483
  }
package/src/sandbox.ts CHANGED
@@ -214,7 +214,7 @@ export interface ForegroundSandboxPolicy {
214
214
  readonly denyWrite: readonly string[];
215
215
  /** Human-readable evidence for why `state` is what it is. */
216
216
  readonly reason: string;
217
- readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
217
+ readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean; processAccess?: "off" | "read" }>;
218
218
  readonly policySource?: "background" | "main-legacy";
219
219
  }
220
220
 
@@ -320,6 +320,7 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
320
320
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
321
321
  outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
322
322
  storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess as "off" | "read" }),
323
324
  ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
324
325
  ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
325
326
  });
@@ -343,16 +344,18 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
343
344
  try {
344
345
  const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
345
346
  const hasBackground = published && Object.hasOwn(published, "background");
346
- const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
347
- if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
348
- const access = (value: unknown): unknown => {
349
- if (!value || typeof value !== "object") return undefined;
350
- return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
351
- };
352
- mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
353
- mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
354
- if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
355
- if (policy) { mirror.policy = policy; mirror.error = undefined; }
347
+ const main = readPolicy(data);
348
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
349
+ if (hasBackground && (!main || !policy)) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
350
+ if (!policy || !main) return;
351
+ const isOff = (scope: ForegroundSandboxPolicy) => scope.state === "disabled" || scope.state === "inactive";
352
+ const allowsRead = (scope: ForegroundSandboxPolicy) => scope.permissions !== undefined &&
353
+ (isOff(scope) || scope.permissions.processAccess === "read");
354
+ mirror.mainConfined = !isOff(main);
355
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
356
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
357
+ mirror.policy = policy;
358
+ mirror.error = undefined;
356
359
  } catch (error) {
357
360
  mirror.error = error as Error;
358
361
  mirror.processAccess = "off";
@@ -210,6 +210,8 @@ export interface CallbackBatcher {
210
210
  toolEnded(toolCallId: string): Promise<boolean>;
211
211
  deliverUrgent(event: UrgentCallbackEvent): boolean | Promise<boolean>;
212
212
  cancel(): void;
213
+ /** Await already-started handoffs after the owner has cancelled scheduling. */
214
+ settled(): Promise<void>;
213
215
  pendingCount(): number;
214
216
  }
215
217
 
@@ -568,6 +570,7 @@ export function createCallbackBatcher(
568
570
  const pending = new Map<string, PendingEvent>();
569
571
  const inFlight = new Set<string>();
570
572
  const urgentInFlight = new Set<string>();
573
+ const urgentSettlements = new Set<Promise<boolean>>();
571
574
  const handedOff = new Map<string, number>();
572
575
  const activeTools = new Set<string>();
573
576
  let sequence = 0;
@@ -750,10 +753,12 @@ export function createCallbackBatcher(
750
753
  { deliverAs: "followUp", triggerTurn: true },
751
754
  );
752
755
  if (isPromiseLike(handoff)) {
753
- return Promise.resolve(handoff).then(
756
+ const settlement = Promise.resolve(handoff).then(
754
757
  () => acknowledge(),
755
758
  () => false,
756
- ).finally(() => urgentInFlight.delete(key));
759
+ ).finally(() => { urgentInFlight.delete(key); urgentSettlements.delete(settlement); });
760
+ urgentSettlements.add(settlement);
761
+ return settlement;
757
762
  }
758
763
  const acknowledged = acknowledge();
759
764
  urgentInFlight.delete(key);
@@ -800,6 +805,10 @@ export function createCallbackBatcher(
800
805
  return pending.size > 0 ? api.flush() : true;
801
806
  },
802
807
  deliverUrgent,
808
+ async settled() {
809
+ await flushPromise;
810
+ await Promise.all([...urgentSettlements]);
811
+ },
803
812
  cancel() {
804
813
  cancelTimer();
805
814
  pending.clear();
@@ -9,7 +9,8 @@ export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
9
9
  export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
10
10
  type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
11
11
  type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
12
- export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
12
+ export type NavigatorPanelLayout = { availableRows(): number };
13
+ export type NavigatorPanelFactory = (tui: TUI, theme: Theme, layout: NavigatorPanelLayout) => PanelComponent;
13
14
  type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
14
15
  type Preference = { version: 1; sticky: boolean };
15
16
  type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
@@ -23,6 +24,8 @@ type State = {
23
24
  mounted: boolean;
24
25
  tui?: TUI | undefined;
25
26
  theme?: Theme | undefined;
27
+ host?: Component | undefined;
28
+ availableRows?: number | undefined;
26
29
  anchor?: string | undefined;
27
30
  pendingAnchor: boolean;
28
31
  generation: number;
@@ -61,14 +64,30 @@ function orderedPanels(s: State): Panel[] {
61
64
  }
62
65
  function buildPanels(s: State): void {
63
66
  if (!s.tui || !s.theme) return;
64
- for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
67
+ for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme, { availableRows: () => s.availableRows ?? Infinity });
68
+ }
69
+ // Count the editor, footer and other siblings following the host in regular mode.
70
+ // Never render ancestors here: they contain this host and would recurse.
71
+ function rowsAfter(root: object, target: Component, width: number): number | undefined {
72
+ if (root === target) return 0;
73
+ const children = (root as Component & { children?: Component[] }).children;
74
+ if (!children) return undefined;
75
+ for (let i = children.length - 1; i >= 0; i--) {
76
+ const after = rowsAfter(children[i]!, target, width);
77
+ if (after !== undefined) return after + children.slice(i + 1).reduce((sum, child) => sum + child.render(width).length, 0);
78
+ }
79
+ return undefined;
65
80
  }
66
81
  function renderPanels(s: State, width: number): string[] {
67
82
  buildPanels(s);
68
83
  const lines: string[] = [];
69
84
  s.ranges = [];
85
+ const after = s.sticky && s.tui && s.host ? rowsAfter(s.tui, s.host, width) : undefined;
86
+ const height = s.tui?.terminal?.rows;
87
+ const budget = after !== undefined && height ? Math.max(0, height - after) : Infinity;
70
88
  for (const panel of orderedPanels(s)) {
71
89
  if (!panel.component) continue;
90
+ s.availableRows = Math.max(0, budget - lines.length);
72
91
  const rendered = panel.component.render(width);
73
92
  s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
74
93
  lines.push(...rendered);
@@ -115,6 +134,7 @@ function clearHost(s: State): void {
115
134
  disposePanels(s);
116
135
  s.mounted = false;
117
136
  s.tui = undefined;
137
+ s.host = undefined;
118
138
  s.theme = undefined;
119
139
  }
120
140
  function adoptContext(s: State, ctx: ExtensionContext): void {
@@ -134,7 +154,7 @@ function mountHost(s: State): void {
134
154
  s.tui = tui;
135
155
  s.theme = theme;
136
156
  buildPanels(s);
137
- return {
157
+ const host: PanelComponent = {
138
158
  render(width: number) {
139
159
  const lines = renderPanels(s, width);
140
160
  if (s.sticky) return lines;
@@ -147,6 +167,8 @@ function mountHost(s: State): void {
147
167
  },
148
168
  dispose() { disposePanels(s); s.mounted = false; },
149
169
  };
170
+ s.host = host;
171
+ return host;
150
172
  }, { placement: "aboveEditor" });
151
173
  }
152
174
  function changeSticky(value: string, ctx: ExtensionContext): void {
@@ -247,4 +269,4 @@ export function __resetNavigatorPanelsForTests(): void {
247
269
  s.anchor = undefined;
248
270
  s.sticky = true;
249
271
  s.control = undefined;
250
- }
272
+ }
@@ -1,19 +1,41 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth } from "@earendil-works/pi-tui";
3
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
3
4
  import type { Component } from "@earendil-works/pi-tui";
4
5
  import { createRenderScheduler, type RenderScheduler } from "./shared-render-scheduler.ts";
5
- import { setNavigatorPanel } from "./shared-navigator-panels.ts";
6
+ import { setNavigatorPanel, type NavigatorPanelLayout } from "./shared-navigator-panels.ts";
6
7
 
7
8
  export default function navigatorExtension(): void {
8
9
  // Internal shared package. Pi may scan its symlink in the extension directory
9
10
  // for sibling relative imports; loading it directly should be harmless.
10
11
  }
11
12
 
13
+ export type NavigatorView = "tree" | "flatten";
14
+ export function getNavigatorView(): NavigatorView { return state().view ?? "flatten"; }
15
+ export function loadNavigatorView(): void {
16
+ const value = readHarnessSetting("navigatorView");
17
+ state().view = value === "tree" ? "tree" : "flatten";
18
+ }
19
+ export function setNavigatorView(value: string): void {
20
+ if (value !== "tree" && value !== "flatten") throw new Error("View must be tree or flatten.");
21
+ updateHarnessSetting("navigatorView", () => value);
22
+ state().view = value;
23
+ refreshBackgroundWorkNavigator();
24
+ }
25
+
12
26
  export type BackgroundWorkStatusTone = "running" | "success" | "failed" | "warning" | "muted";
13
27
 
14
28
  export type BackgroundWorkRow = {
15
29
  providerId: string;
16
30
  id: string;
31
+ /** Stable worker conversation identity, independent of execution attempts. */
32
+ agentId?: string;
33
+ parentAgentId?: string;
34
+ readOnly?: boolean;
35
+ treeDepth?: number;
36
+ lastChild?: boolean;
37
+
38
+ ownerGroupLabel?: string;
17
39
  name?: string;
18
40
  model?: string;
19
41
  effort?: string;
@@ -70,9 +92,65 @@ export type BackgroundWorkProvider = {
70
92
  close(id: string): BackgroundWorkCloseOutcome;
71
93
  /** Return true when this detail handled the key. The navigator refreshes the sheet. */
72
94
  handleDetailInput?(id: string, data: string): boolean;
95
+ /** An explicit navigator interaction may attach a deferred work subscription. */
96
+ onOpen?(): void;
73
97
  onVisibleChanged?(notify: () => void): () => void;
74
98
  };
75
99
 
100
+ /** UI time is independent of worker time; repeated refreshes never renew it. */
101
+ export function createTerminalRowRetention(retentionMs = 30_000) {
102
+ const held = new Map<string, { row: BackgroundWorkRow; until: number }>();
103
+ const dismissed = new Set<string>();
104
+ return {
105
+ clear() { held.clear(); dismissed.clear(); },
106
+ dismiss(id: string) { held.delete(id); dismissed.add(id); },
107
+ merge(rows: BackgroundWorkRow[], now: number): BackgroundWorkRow[] {
108
+ const result: BackgroundWorkRow[] = [];
109
+ const present = new Set(rows.map(row => row.id));
110
+ for (const id of dismissed) if (!present.has(id)) dismissed.delete(id);
111
+ for (const row of rows) {
112
+ if (dismissed.has(row.id)) continue;
113
+ const terminal = ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status);
114
+ if (!terminal) { held.delete(row.id); result.push(row); continue; }
115
+ let entry = held.get(row.id);
116
+ if (!entry) { entry = {row, until: now + retentionMs}; held.set(row.id, entry); }
117
+ entry.row = {...row, expiresAt: entry.until};
118
+ if (now < entry.until) result.push(entry.row);
119
+ }
120
+ for (const [id, entry] of held) {
121
+ if (present.has(id)) continue;
122
+ if (now < entry.until) result.push(entry.row);
123
+ else held.delete(id);
124
+ }
125
+ return result;
126
+ },
127
+ };
128
+ }
129
+
130
+ /** A frontend-only diagnostic, never an execution record or authority to retry. */
131
+ export async function observeNavigatorLaunch<T>(ctx: ExtensionContext, providerId: string, key: string, name: string, launch: () => Promise<T>): Promise<T> {
132
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
133
+ const report = (error: unknown) => {
134
+ const s = state();
135
+ if (!isNavigatorUiAvailable(s.uiCtx) || s.observationScope !== scope) return;
136
+ const id = `launch-error-${key}`;
137
+ const primary = error instanceof Error ? error.message : String(error);
138
+ const failures = s.launchFailures ??= new Map();
139
+ const identity = rowKey(providerId, id);
140
+ failures.set(identity, {providerId, id, name, status: "failed", statusTone: "failed", kind: "launch-error", elapsed: "", primary,
141
+ secondary: "Launch failed or was not confirmed; inspect before retrying.", sortStartedAt: Date.now()});
142
+ // Diagnostics are session-local and bounded, including expired tombstones.
143
+ if (failures.size > 128) failures.delete(failures.keys().next().value!);
144
+ refreshBackgroundWorkNavigator();
145
+ };
146
+ try {
147
+ const result = await launch();
148
+ const response = result as {isError?: boolean; content?: {type: string; text?: string}[]};
149
+ if (response?.isError) report(response.content?.filter(item => item.type === "text").map(item => item.text).join("\n") || "Launch request failed");
150
+ return result;
151
+ } catch (error) { report(error); throw error; }
152
+ }
153
+
76
154
  type HostDeps = {
77
155
  createDefaultEditor: (tui: unknown, theme: unknown, keybindings: unknown) => unknown;
78
156
  isOpenTrigger: (data: string) => boolean;
@@ -83,6 +161,10 @@ type HostDeps = {
83
161
 
84
162
  type NavigatorState = {
85
163
  providers: Map<string, BackgroundWorkProvider>;
164
+ view?: NavigatorView;
165
+ terminalRows?: Map<string, ReturnType<typeof createTerminalRowRetention>>;
166
+ launchFailures?: Map<string, BackgroundWorkRow>;
167
+ observationScope?: string;
86
168
  registrationTokens?: Map<string, symbol>;
87
169
  unsubscribers: Map<string, () => void>;
88
170
  uiCtx?: ExtensionContext;
@@ -202,6 +284,10 @@ export function applyCloseConfirmFooter(ui: { setStatus(key: string, value: stri
202
284
  export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostDeps, owner?: symbol): void {
203
285
  if (!isNavigatorUiAvailable(ctx)) return;
204
286
  const s = state();
287
+ if (s.view === undefined) { try { loadNavigatorView(); } catch { s.view = "flatten"; } }
288
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
289
+ if (s.observationScope !== scope) { s.terminalRows?.clear(); s.launchFailures?.clear(); }
290
+ s.observationScope = scope;
205
291
  s.uiCtx = ctx;
206
292
  s.uiOwner = owner;
207
293
  s.deps = {
@@ -239,6 +325,9 @@ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext, owner?: s
239
325
  stopMainListWidget();
240
326
  const activeCtx = ctx ?? s.uiCtx;
241
327
  s.uiCtx = undefined;
328
+ s.terminalRows?.clear();
329
+ s.launchFailures?.clear();
330
+ s.observationScope = undefined;
242
331
  s.uiOwner = undefined;
243
332
  if (activeCtx && isNavigatorUiAvailable(activeCtx)) {
244
333
  try { setNavigatorPanel(activeCtx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
@@ -328,7 +417,7 @@ function refreshMainListWidget(): void {
328
417
  }
329
418
  if (!s.mainListWidgetInstalled) {
330
419
  try {
331
- setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown) => createMainListWidget(tui, theme, deps), { placement: "aboveEditor" });
420
+ setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown, layout) => createMainListWidget(tui, theme, deps, layout), { placement: "aboveEditor" });
332
421
  s.mainListWidgetInstalled = true;
333
422
  } catch { /* ignore */ }
334
423
  }
@@ -406,7 +495,7 @@ function createPointerNavigation(targetAt: (event: WidgetMouseEvent) => string |
406
495
  };
407
496
  }
408
497
 
409
- function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps): MainListWidget {
498
+ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps, panelLayout: NavigatorPanelLayout = { availableRows: () => Infinity }): MainListWidget {
410
499
  const requestRender = () => tui.requestRender?.();
411
500
  state().mainListRequestRender = requestRender;
412
501
  // navigatorId per rendered line, so a pointer row resolves by structure, never by row text.
@@ -439,8 +528,23 @@ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, d
439
528
  if (hint) { layout.lines.push(deps.truncate(` ${hint}`, renderWidth(width))); layout.owners.push(undefined); }
440
529
  lineWidth = renderWidth(width);
441
530
  // The leading gap line belongs to the widget too, so its slot stays ownerless.
531
+ let rawLines = ["", ...layout.lines];
442
532
  lineOwners = [undefined, ...layout.owners];
443
- const lines = ["", ...layout.lines].map((line, index) =>
533
+ const budget = Math.max(0, Math.floor(panelLayout.availableRows()));
534
+ if (rawLines.length > budget) {
535
+ const selected = state().mainListFocused ? lineOwners.indexOf(state().mainListSelectedId) : -1;
536
+ const count = Math.max(0, budget - 1);
537
+ const start = selected >= 0 ? Math.max(0, Math.min(selected - Math.floor(count / 2), rawLines.length - count)) : 2;
538
+ rawLines = rawLines.slice(start, start + count);
539
+ lineOwners = lineOwners.slice(start, start + count);
540
+ const visible = new Set(lineOwners.filter(Boolean));
541
+ if (budget > 0) {
542
+ const hidden = rows.length - visible.size;
543
+ rawLines.push(deps.truncate(hidden ? ` +${hidden} tasks` : ` ${rows.length} tasks`, renderWidth(width)));
544
+ lineOwners.push(undefined);
545
+ }
546
+ }
547
+ const lines = rawLines.map((line, index) =>
444
548
  pointer.hovered && lineOwners[index] === pointer.hovered ? highlightPointerTarget(theme, line, lineWidth) : line);
445
549
  state().lastMainListLines = lines;
446
550
  return lines;
@@ -483,10 +587,14 @@ function listRows(now = Date.now()): InternalRow[] {
483
587
  for (const provider of providers()) {
484
588
  let providerRows: BackgroundWorkRow[] = [];
485
589
  try { providerRows = provider.listRows(now) ?? []; } catch { providerRows = []; }
590
+ providerRows = [...providerRows, ...[...(state().launchFailures?.values() ?? [])].filter(row => row.providerId === provider.id)];
591
+ const retention = state().terminalRows ??= new Map();
592
+ if (!retention.has(provider.id)) retention.set(provider.id, createTerminalRowRetention());
593
+ if (isNavigatorUiAvailable(state().uiCtx)) providerRows = retention.get(provider.id)!.merge(providerRows, now);
486
594
  const orderedProviderRows = [...providerRows].sort((a, b) => b.sortStartedAt - a.sortStartedAt || rowDisplayName(a).localeCompare(rowDisplayName(b)));
487
595
  let showSection = orderedProviderRows.length > 0 || provider.parentRow !== undefined;
488
596
  try { showSection = provider.showSection?.(orderedProviderRows, now) ?? showSection; } catch { showSection = false; }
489
- if (!showSection) continue;
597
+ if (!showSection && !(getNavigatorView() === "tree" && provider.parentRow)) continue;
490
598
  let parentRow: BackgroundWorkRow | null = null;
491
599
  try { parentRow = provider.parentRow?.(now) ?? null; } catch { parentRow = null; }
492
600
  if (parentRow) {
@@ -501,7 +609,48 @@ function listRows(now = Date.now()): InternalRow[] {
501
609
  rows.push({ ...row, navigatorId: rowKey(provider.id, row.id), providerLabel: provider.label });
502
610
  }
503
611
  }
504
- return rows;
612
+ const conversations = mergeAgentAttempts(rows);
613
+ return getNavigatorView() === "tree" ? treeRows(conversations) : conversations;
614
+ }
615
+
616
+ /** A resumed execution is still the same agent in either layout. */
617
+ export function mergeAgentAttempts<T extends BackgroundWorkRow>(rows: T[]): T[] {
618
+ const latest = new Map<string, T>();
619
+ for (const row of rows) {
620
+ if (row.providerId !== "subagents" || !row.agentId) continue;
621
+ const previous = latest.get(row.agentId);
622
+ if (!previous || row.sortStartedAt > previous.sortStartedAt
623
+ || (row.sortStartedAt === previous.sortStartedAt && row.id > previous.id)) latest.set(row.agentId, row);
624
+ }
625
+ return rows.filter(row => row.providerId !== "subagents" || !row.agentId || latest.get(row.agentId) === row);
626
+ }
627
+
628
+ /** Two levels only: agents are peers, tasks attach by captured conversation. */
629
+ export function treeRows<T extends BackgroundWorkRow>(rows: T[]): T[] {
630
+ const agents = new Map<string, T>();
631
+ for (const row of rows.filter(row => row.providerId === "subagents")) {
632
+ const key = row.agentId ?? row.id;
633
+ const prior = agents.get(key);
634
+ if (!prior || row.sortStartedAt > prior.sortStartedAt) agents.set(key, row);
635
+ }
636
+ const tasks = rows.filter(row => row.providerId !== "subagents");
637
+ const ordered = [...agents.entries()].sort(([a], [b]) => a === "main" ? -1 : b === "main" ? 1 : 0);
638
+ const result: T[] = [], attached = new Set<T>();
639
+ for (const [key, agent] of ordered) {
640
+ const children = tasks.filter(row => (row.parentAgentId ?? "main") === key);
641
+ result.push({...agent, treeDepth: 0});
642
+ children.forEach((row, i) => { result.push({...row, treeDepth: 1, lastChild: i === children.length - 1}); attached.add(row); });
643
+ }
644
+ // Never hide live work when its owner's observation has not arrived yet.
645
+ const missing = new Map<string, T[]>();
646
+ for (const row of tasks) if (!attached.has(row)) {
647
+ const key = row.parentAgentId ?? "main";
648
+ missing.set(key, [...(missing.get(key) ?? []), row]);
649
+ }
650
+ for (const [key, children] of missing) children.forEach((row, i) => result.push({...row,
651
+ treeDepth: 1, lastChild: i === children.length - 1,
652
+ ownerGroupLabel: i === 0 ? (key === "main" ? "Main" : `Agent ${key} · not running`) : undefined}));
653
+ return result;
505
654
  }
506
655
 
507
656
  function rowDisplayName(row: Pick<BackgroundWorkRow, "name" | "id">): string {
@@ -582,6 +731,15 @@ function buildMainListLayout(
582
731
  lines.push(line);
583
732
  owners.push(owner);
584
733
  };
734
+ if (getNavigatorView() === "tree") {
735
+ push(providerGroupLabel("work", fg));
736
+ for (const row of rows) {
737
+ if (row.ownerGroupLabel) push(` ${dim(row.ownerGroupLabel, fg)}`);
738
+ push(formatMainListRow(row, options.focused === true && row.navigatorId === options.selectedId, fg, width), row.navigatorId);
739
+ }
740
+ push(""); push(shortcutsLine(options.focused === true, fg));
741
+ return {lines: lines.map(line => safeTruncate(line, width, truncate)), owners};
742
+ }
585
743
  const grouped = new Map<string, InternalRow[]>();
586
744
  for (const row of rows) {
587
745
  const existing = grouped.get(row.providerLabel) ?? [];
@@ -606,8 +764,9 @@ function buildMainListLayout(
606
764
  }
607
765
 
608
766
  function shortcutsLine(focused: boolean, fg: (color: string, value: string) => string): string {
767
+ const selected = state().mainListRows?.find(row => row.navigatorId === state().mainListSelectedId);
609
768
  const keys = focused
610
- ? "↑↓ switch · Enter detail · x stop · Esc unfocus"
769
+ ? `↑↓ switch · Enter detail${selected?.readOnly || selected?.parentRow ? "" : " · x stop"} · Esc unfocus`
611
770
  : "← work navigator";
612
771
  return dim(keys, fg);
613
772
  }
@@ -618,7 +777,7 @@ function providerGroupLabel(label: string, fg: (color: string, value: string) =>
618
777
  }
619
778
 
620
779
  function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: string, value: string) => string, width: number): string {
621
- const prefix = selected ? fg("accent", "› ") : " ";
780
+ const prefix = (selected ? fg("accent", "› ") : " ") + (row.treeDepth === 1 ? dim(` ${row.lastChild ? "└─" : "├─"} `, fg) : "");
622
781
  const name = row.name || row.id;
623
782
  const indicator = statusIndicator(row);
624
783
  const status = fg(indicator.color, indicator.glyph);
@@ -648,17 +807,21 @@ function statusGlyph(row: InternalRow): string {
648
807
  function statusIndicator(row: InternalRow, now = Date.now()): { glyph: string; color: string } {
649
808
  void now;
650
809
  if (row.statusTone !== "running") return { glyph: statusGlyph(row), color: toneColor(row.statusTone, row.status) };
651
- return { glyph: RUNNING_DOT_GLYPH, color: "accent" };
810
+ const glyph = row.treeDepth === 1 && row.providerId === "background-tasks" ? ">_" : RUNNING_DOT_GLYPH;
811
+ return { glyph, color: "accent" };
652
812
  }
653
813
 
654
814
  function mainListSignature(rows: InternalRow[], options: { selectedId?: string; focused?: boolean; closeHint?: string | null } = {}): string {
655
815
  return JSON.stringify({
816
+ view: getNavigatorView(),
656
817
  focused: options.focused === true,
657
818
  closeHint: options.closeHint ?? null,
658
819
  selectedId: options.focused === true ? options.selectedId ?? null : null,
659
820
  rows: rows.map((row) => ({
660
821
  navigatorId: row.navigatorId,
661
822
  providerLabel: row.providerLabel,
823
+ parentAgentId: row.parentAgentId,
824
+ agentId: row.agentId,
662
825
  parentRow: row.parentRow === true,
663
826
  providerId: row.providerId,
664
827
  id: row.id,
@@ -684,6 +847,9 @@ function stableFacts(facts: string[] | undefined): string[] {
684
847
  }
685
848
 
686
849
  function rowSummary(row: InternalRow): string {
850
+ if (getNavigatorView() === "tree" && row.providerId === "background-tasks") {
851
+ return [singleLine(row.status).replaceAll("_", " "), ...(row.facts ?? []).map(singleLine)].join(" · ");
852
+ }
687
853
  if (row.providerId === "subagents") {
688
854
  const attention = row.facts?.map(singleLine).filter(Boolean);
689
855
  if (attention?.length) return `${singleLine(row.status)} · ${attention.join(" · ")}`;
@@ -736,20 +902,33 @@ function prepareDetail(navigatorId: string, options?: {logTailLines?: number}):
736
902
 
737
903
  function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLines?: number }): BackgroundWorkDetail | null {
738
904
  const { providerId, id } = splitRowKey(navigatorId);
905
+ const failed = state().launchFailures?.get(navigatorId);
906
+ if (failed) return {providerId, id, title: failed.name ?? "Launch failed", status: "failed", statusTone: "failed", metadata: [], evidence: {label: "Launch error", text: failed.primary}};
739
907
  const provider = state().providers.get(providerId);
740
908
  if (!provider) return null;
741
909
  try { return provider.detail(id, now, options); } catch { return null; }
742
910
  }
743
911
 
744
912
  function closeFor(row: InternalRow): BackgroundWorkCloseOutcome {
745
- if (row.parentRow) return { action: "not-closable", providerId: row.providerId, id: row.id };
913
+ if (row.parentRow || row.readOnly) return { action: "not-closable", providerId: row.providerId, id: row.id };
746
914
  const provider = state().providers.get(row.providerId);
915
+ if (state().launchFailures?.delete(row.navigatorId)) {
916
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
917
+ return {action: "dismissed", providerId: row.providerId, id: row.id};
918
+ }
747
919
  if (!provider) return { action: "missing", providerId: row.providerId, id: row.id };
748
- try { return provider.close(row.id); } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
920
+ try {
921
+ const outcome = provider.close(row.id);
922
+ if (["dismissed", "stopped-and-dismissed"].includes(outcome.action)
923
+ || outcome.action === "requested" && ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status)) {
924
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
925
+ }
926
+ return outcome;
927
+ } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
749
928
  }
750
929
 
751
930
  function closeHintFor(row: InternalRow | undefined): string | null {
752
- if (!row || row.parentRow) return null;
931
+ if (!row || row.parentRow || row.readOnly) return null;
753
932
  const provider = state().providers.get(row.providerId);
754
933
  if (!provider) return null;
755
934
  try { return `${provider.armCloseLabel(row)} ${row.name || row.id}`; } catch { return null; }
@@ -807,6 +986,9 @@ function wrapEditor(inner: any, deps: HostDeps): unknown {
807
986
 
808
987
  function handleMainListInput(data: string, deps: HostDeps): boolean {
809
988
  const s = state();
989
+ if (!s.mainListFocused && deps.isOpenTrigger(data)) {
990
+ for (const provider of s.providers.values()) provider.onOpen?.();
991
+ }
810
992
  const rows = listRows();
811
993
  if (rows.length === 0) {
812
994
  // Every row is gone, but an overlay that lost focus may still be mounted: Esc still closes it.
@@ -876,7 +1058,7 @@ function dismissOverlay(): void {
876
1058
 
877
1059
  function handleMainListCloseKey(): void {
878
1060
  const row = selectedMainListRow();
879
- if (!row || row.parentRow) return;
1061
+ if (!row || row.parentRow || row.readOnly) return;
880
1062
  const s = state();
881
1063
  const now = Date.now();
882
1064
  const arm = s.mainListCloseArm;
@@ -917,6 +1099,7 @@ function openNavigator(): void {
917
1099
  const ctx = s.uiCtx;
918
1100
  const deps = s.deps;
919
1101
  if (!ctx || !deps || !isNavigatorUiAvailable(ctx)) return;
1102
+ for (const provider of s.providers.values()) provider.onOpen?.();
920
1103
  const rows = listRows();
921
1104
  if (rows.length === 0) return;
922
1105
  const selectedId = selectedMainListRow()?.navigatorId ?? rows[0]!.navigatorId;
@@ -1113,7 +1296,7 @@ function createOverlayComponent(
1113
1296
 
1114
1297
  function handleCloseKey(): void {
1115
1298
  const row = selectedRow();
1116
- if (!row || row.parentRow) return;
1299
+ if (!row || row.parentRow || row.readOnly) return;
1117
1300
  const now = Date.now();
1118
1301
  if (closeArm?.id === row.navigatorId && now >= closeArm.armedAt && now < closeArm.armedAt + CLOSE_ARM_MS) {
1119
1302
  clearCloseArm();