pi-suite 0.3.6 → 0.3.8

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 (43) hide show
  1. package/package.json +1 -1
  2. package/src/agents/child.ts +9 -3
  3. package/src/agents/history.ts +3 -3
  4. package/src/agents/index.ts +22 -21
  5. package/src/agents/manager.ts +40 -12
  6. package/src/agents/records.ts +4 -2
  7. package/src/agents/runner.ts +12 -3
  8. package/src/agents/runtime.ts +1 -1
  9. package/src/agents/schedules/menu.ts +1 -1
  10. package/src/agents/types.ts +2 -1
  11. package/src/agents/ui/runs.ts +34 -14
  12. package/src/agents/viewer.ts +69 -43
  13. package/src/agents/workflow/index.ts +32 -9
  14. package/src/agents/workflow/manager.ts +18 -6
  15. package/src/agents/workflow/ui/menu.ts +2 -2
  16. package/src/jobs/index.ts +49 -36
  17. package/src/jobs/manager-record.ts +2 -2
  18. package/src/jobs/manager.ts +30 -12
  19. package/src/jobs/monitors/runtime.ts +41 -27
  20. package/src/jobs/store.ts +49 -10
  21. package/src/jobs/tools.ts +2 -2
  22. package/src/jobs/types.ts +2 -0
  23. package/src/jobs/viewer/metadata.ts +6 -0
  24. package/src/jobs/viewer.ts +30 -25
  25. package/src/runtime/branch.ts +14 -0
  26. package/src/runtime/cleanup/command.ts +116 -0
  27. package/src/runtime/cleanup/locations.ts +91 -0
  28. package/src/runtime/cleanup/occupancy.ts +117 -0
  29. package/src/runtime/cleanup/paths.ts +44 -0
  30. package/src/runtime/cleanup/quarantine.ts +162 -0
  31. package/src/runtime/cleanup/scan.ts +297 -0
  32. package/src/runtime/cleanup/session-use.ts +62 -0
  33. package/src/runtime/cleanup/sessions.ts +119 -0
  34. package/src/runtime/json-store.ts +6 -0
  35. package/src/runtime/owner.ts +1 -1
  36. package/src/runtime/settings/index.ts +9 -1
  37. package/src/runtime/suite.ts +43 -1
  38. package/src/tasks/store.ts +18 -1
  39. package/src/tasks/viewer.ts +14 -12
  40. package/src/ui/actions.ts +1 -1
  41. package/src/ui/browser.ts +95 -43
  42. package/src/ui/scroll.ts +5 -1
  43. package/src/ui/ticker.ts +2 -2
@@ -12,13 +12,15 @@ import { editAgentModel } from './model-editor.ts';
12
12
  import type { SuiteConfig } from '../runtime/config.ts';
13
13
  import type { ScrollView } from '../ui/scroll.ts';
14
14
  import { jobActions, type ViewerDeps } from '../jobs/viewer.ts';
15
+ import { timedJob } from '../jobs/viewer/metadata.ts';
15
16
  import { isActive as jobActive } from '../jobs/state.ts';
16
17
  import { ViewerNavigation } from '../ui/viewer/navigation.ts';
17
18
  import { agentInformation } from '../ui/viewer/agent-information.ts';
18
19
  import { WORKING_INTERVAL_MS, workingLine } from '../ui/working.ts';
20
+ import { PresentationTicker } from '../ui/ticker.ts';
19
21
  import { agentDetails } from './viewer-info.ts';
20
22
  import { showDetails } from '../ui/details.ts';
21
- import { displayName as jobName, jobCompactStatus, jobLabel, jobStatus } from '../jobs/index.ts';
23
+ import { displayName as jobName, jobCompactStatus, jobStatus } from '../jobs/index.ts';
22
24
  import { browse, browseState, compareActivity } from '../ui/browser.ts';
23
25
  import { jobDetailView } from '../jobs/query.ts';
24
26
  import type { JobSummary } from '../jobs/types.ts';
@@ -30,22 +32,24 @@ export async function showAgentJobs(ctx: ExtensionContext, deps: AgentJobViewer,
30
32
  try { for (; !navigation.closed;) {
31
33
  // Creator ancestry selects the entire execution subtree, including jobs left by
32
34
  // collected children. Task references and another run of this agent do not confer ownership.
33
- const current = () => deps.viewer.jobs.createdBy([runId]).filter(jobActive);
34
- if (!current().length) { ctx.ui.notify('No active jobs for this run'); return; }
35
- let displayed = new Map<string, JobSummary>();
35
+ const current = () => deps.viewer.jobs.createdBy([runId], jobActive);
36
+ const initial = current();
37
+ if (!initial.length) { ctx.ui.notify('No active jobs for this run'); return; }
38
+ let first: JobSummary[] | undefined = initial, displayed = new Map<string, JobSummary>(), measuredAt = performance.now();
36
39
  const selected = await browse(ctx, deps.viewer.dock, { title: 'Subagents', page: 'Jobs', scope: 'Run subtree', state: viewState, navigation,
37
40
  selection: item => ({name: jobName(displayed.get(item.value)!)}),
38
41
  layout: {truncatePrimary: ({item, maxWidth, theme}) => {
39
- const job = displayed.get(item.value)!;
42
+ const job = timedJob(displayed.get(item.value)!, measuredAt);
40
43
  return executionRow(jobName(job), jobStatus(job), jobCompactStatus(job), maxWidth, theme);
41
44
  }},
42
- subscribe: refresh => deps.viewer.jobs.control().subscribe(refresh), ticking: () => current().length > 0,
45
+ subscribe: refresh => deps.viewer.jobs.control().subscribe(refresh), ticking: () => displayed.size > 0,
43
46
  // Index the item snapshot once: native layout must not rescan creator ancestry per row.
44
47
  items: () => {
45
- const items = current().sort((a, b) => compareActivity(a, b, jobActive));
48
+ const items = (first ?? current()).sort((a, b) => compareActivity(a, b, jobActive));
49
+ first = undefined; measuredAt = performance.now();
46
50
  displayed = new Map(items.map(job => [job.id, job]));
47
- return items.map(job => ({ value: job.id, status: job.state, label: jobName(job), display: jobLabel(job),
48
- search: `${job.id} ${jobName(job)} ${job.state} ${job.command} ${job.cwd}`, details: () => jobDetailView(job, true) }));
51
+ return items.map(job => ({ value: job.id, label: jobName(job),
52
+ search: `${job.id} ${jobName(job)} ${job.state} ${job.command} ${job.cwd}`, details: () => jobDetailView(timedJob(job, measuredAt), true) }));
49
53
  },
50
54
  });
51
55
  if (selected === undefined) return;
@@ -55,12 +59,13 @@ export async function showAgentJobs(ctx: ExtensionContext, deps: AgentJobViewer,
55
59
  } } finally { release(); }
56
60
  }
57
61
 
58
- export function agentControls(ctx: ExtensionContext, agents: Pick<AgentsModule, 'manager' | 'scope'>, id: string, runId: string, readonly: boolean) {
59
- const get = () => agents.manager.get(id, runId);
62
+ export function agentControls(ctx: ExtensionContext, agents: Pick<AgentsModule, 'manager' | 'scope'>, id: string, runId: () => string, readonly: boolean) {
63
+ const get = () => agents.manager.get(id, runId());
60
64
  const canStop = () => { const run = get().run; return Boolean(!readonly && run && !run.settled && active(run.record.state) && run.record.state !== 'stopping'); };
61
65
  const canMessage = () => {
66
+ if (readonly) return false;
62
67
  const { record, run } = get(), scope = agents.scope(ctx);
63
- if (readonly || agents.manager.get(id).record.runId !== runId) return false;
68
+ if (agents.manager.get(id).record.runId !== record.runId) return false;
64
69
  if (!run || run.settled) return !active(record.state) && !agents.manager.isStopping(id) && agents.manager.visible(record, scope);
65
70
  // The public state can still say running while the SDK session is closing.
66
71
  if (!active(run.record.state) || run.record.state === 'queued' || run.record.state === 'stopping') return false;
@@ -70,15 +75,15 @@ export function agentControls(ctx: ExtensionContext, agents: Pick<AgentsModule,
70
75
  }
71
76
 
72
77
  export function agentMessage(ctx: ExtensionContext, agents: Pick<AgentsModule, 'manager' | 'scope' | 'admitSend'>, id: string, runId: string,
73
- readonly: boolean, config: () => SuiteConfig, sent?: () => void): InlineRequest {
74
- const {get, canMessage} = agentControls(ctx, agents, id, runId, readonly);
78
+ readonly: boolean, config: () => SuiteConfig, sent?: (result: Awaited<ReturnType<AgentsModule['manager']['send']>>) => void): InlineRequest {
79
+ const {get, canMessage} = agentControls(ctx, agents, id, () => runId, readonly);
75
80
  const {record, run} = get();
76
81
  const prompt = run?.question ? 'Answer parent question: ' : active(record.state) ? `Message ${record.name}: ` : `Resume ${record.name}: `;
77
82
  return {multiline: true, prompt, submit: async message => {
78
83
  // The composer can outlive a run; never send an old reader's input to its successor.
79
84
  if (!canMessage()) throw new Error('This run no longer accepts messages');
80
85
  const result = await agents.admitSend(id).send(id, message, agents.scope(ctx), config());
81
- sent?.();
86
+ sent?.(result);
82
87
  return `${record.name}: ${result.action}`;
83
88
  }};
84
89
  }
@@ -98,28 +103,45 @@ export const showAgent = (...args: Parameters<typeof readAgent>): Promise<void>
98
103
  withReadingScreen(args[0], () => readAgent(...args));
99
104
 
100
105
  async function readAgent(ctx: ExtensionContext, agents: Pick<AgentsModule, 'manager' | 'scope' | 'renderer' | 'customRendererLookup' | 'admitSend'>, dock: Dock, id: string, runId: string, config: () => SuiteConfig, readonly = false, jobs?: AgentJobViewer, navigation = new ViewerNavigation()): Promise<void> {
101
- const release = agents.manager.retain(runId);
106
+ const { manager } = agents;
107
+ // Only a reader opened on the latest run follows successors; history stays pinned.
108
+ const follow = manager.get(id).record.runId === runId;
109
+ let release = manager.retain(runId);
102
110
  let content: Transcript | undefined, reader: ScrollView | undefined;
103
- const { get, canStop, canMessage } = agentControls(ctx, agents, id, runId, readonly);
111
+ let revision: ReturnType<typeof transcript> = [], transcriptError: string | undefined;
112
+ const { get, canStop, canMessage } = agentControls(ctx, agents, id, () => runId, readonly);
113
+ const syncRun = () => {
114
+ if (!follow) return;
115
+ const latest = manager.get(id).record.runId;
116
+ if (latest === runId) return;
117
+ const releaseNext = manager.retain(latest);
118
+ release(); release = releaseNext; runId = latest;
119
+ transcriptError = undefined;
120
+ };
121
+ const suiteLookup = agents.customRendererLookup();
122
+ // Look up the current child lazily: a successor may still be binding its extensions.
123
+ const lookup = {
124
+ getMessageRenderer: (type: string) => (get().run?.customRenderers ?? suiteLookup).getMessageRenderer(type),
125
+ getEntryRenderer: (type: string) => (get().run?.customRenderers ?? suiteLookup).getEntryRenderer(type),
126
+ };
127
+ let refresh: (() => void) | undefined;
128
+ // Keep the run lease current even while a nested page owns the screen.
129
+ const unsubscribe = manager.subscribe(() => { syncRun(); refresh?.(); });
130
+ // A busy owner reused across reloads may still deliver partial output on the lifecycle channel.
131
+ const unsubscribeOutput = manager.subscribeOutput?.(output => { if (output === runId) refresh?.(); });
104
132
  try { for (; !navigation.closed;) {
105
- const { run } = get();
106
- const suiteLookup = agents.customRendererLookup();
107
- // A reader can open while the child is still binding its extensions.
108
- const lookup = {
109
- getMessageRenderer: (type: string) => (run?.customRenderers ?? suiteLookup).getMessageRenderer(type),
110
- getEntryRenderer: (type: string) => (run?.customRenderers ?? suiteLookup).getEntryRenderer(type),
111
- };
133
+ syncRun();
112
134
  dock.setDetail(true);
113
135
  let action: 'model' | 'stop' | 'jobs' | 'details' | undefined;
114
136
  try {
115
137
  await openReading<void>(ctx, (tui, theme, keys, done) => {
116
- content ??= new Transcript(tui, get().record.cwd, name => run?.renderers?.get(name) ?? agents.renderer(name), { theme, ...lookup });
117
- content.setEntries(transcript(get().record, get().run));
118
- const view = new DetailsView(tui, () => '', content, done, [
119
- { key: 'm', label: 'Message', available: canMessage, input: () => agentMessage(ctx, agents, id, runId, readonly, config) },
138
+ const body = content ??= new Transcript(tui, get().record.cwd, name => get().run?.renderers?.get(name) ?? agents.renderer(name), { theme, ...lookup });
139
+ const view = new DetailsView(tui, () => '', body, done, [
140
+ { key: 'm', label: 'Message', available: canMessage, input: () => agentMessage(ctx, agents, id, runId, readonly, config,
141
+ ({action}) => { if (action === 'resumed') view.reader.follow(); }) },
120
142
  { key: 'd', label: 'Details', run: () => { action = 'details'; done(); } },
121
- { key: 'o', label: 'Tools', run: () => { content!.toggleTools(); view.invalidate(); } },
122
- { key: 'h', label: 'Thinking', run: () => { content!.toggleThinking(); view.invalidate(); } },
143
+ { key: 'o', label: 'Tools', run: () => { body.toggleTools(); view.invalidate(); } },
144
+ { key: 'h', label: 'Thinking', run: () => { body.toggleThinking(); view.invalidate(); } },
123
145
  { key: 'j', label: 'Jobs', available: () => jobs !== undefined, run: () => { action = 'jobs'; done(); } },
124
146
  { key: 'c', label: 'Model / thinking', available: () => !readonly, run: () => { action = 'model'; done(); } },
125
147
  { label: 'Background', key: 'b', available: () => !readonly && agents.manager.canSendToBackground(id, runId), run: () => { agents.manager.sendToBackground(id, runId); } },
@@ -128,27 +150,31 @@ async function readAgent(ctx: ExtensionContext, agents: Pick<AgentsModule, 'mana
128
150
  bottom: width => agentInformation(get().record, Boolean(get().run?.question), readonly, view.reader, width, theme),
129
151
  status: () => ['starting', 'running'].includes(get().record.state) ? workingLine(theme) : undefined});
130
152
  if (!reader) view.reader.follow();
131
- view.reader.setContent(content);
132
153
  reader = view.reader;
133
- let revision = transcript(get().record, get().run);
134
- const refresh = () => {
135
- const { record, run } = get(), entries = transcript(record, run);
154
+ const clock = new PresentationTicker(() => true, () => tui.requestRender(), WORKING_INTERVAL_MS);
155
+ refresh = () => {
156
+ const { record, run } = get();
157
+ let entries: ReturnType<typeof transcript> | undefined;
158
+ try { entries = transcript(record, run); transcriptError = undefined; }
159
+ catch (error) {
160
+ // An unreadable saved transcript must not break synchronous manager notifications.
161
+ const message = error instanceof Error ? error.message : String(error);
162
+ if (transcriptError !== message) ctx.ui.notify(message, 'error');
163
+ transcriptError = message;
164
+ }
136
165
  // Several tools can stream concurrently. Compare every immutable entry identity,
137
166
  // since an unchanged last tool result says nothing about an earlier live tail.
138
- if (entries.length !== revision.length || entries.some((entry, index) => entry !== revision[index])) {
167
+ if (entries && (entries.length !== revision.length || entries.some((entry, index) => entry !== revision[index]))) {
139
168
  revision = entries;
140
169
  view.reader.markNewOutput();
141
- content!.setEntries(entries); view.reader.setContent(content!);
170
+ body.setEntries(entries); view.reader.setContent(body);
142
171
  }
172
+ clock.update(active(record.state));
143
173
  tui.requestRender();
144
174
  };
145
- const unsubscribe = agents.manager.subscribe(refresh);
146
- const clock = active(get().record.state) ? setInterval(() => {
147
- if (!active(get().record.state)) clearInterval(clock);
148
- tui.requestRender();
149
- }, WORKING_INTERVAL_MS).unref() : undefined;
175
+ refresh();
150
176
  const dispose = view.dispose.bind(view);
151
- return Object.assign(view, { dispose: () => {dispose(); unsubscribe(); clearInterval(clock);} });
177
+ return Object.assign(view, { dispose: () => {refresh = undefined; clock.stop(); dispose();} });
152
178
  });
153
179
  } finally { dock.setDetail(false); }
154
180
  if (!action || navigation.closed) return;
@@ -158,5 +184,5 @@ async function readAgent(ctx: ExtensionContext, agents: Pick<AgentsModule, 'mana
158
184
  if (action === 'details') await showDetails(ctx, dock, 'Subagents ▸ Details', agentDetails(get().record, {readonly, canMessage: canMessage(), canStop: canStop()}), 'text', navigation);
159
185
  else if (action !== 'stop' || canStop()) await performAgentAction(action, ctx, agents, id, runId, readonly, config, jobs, navigation);
160
186
  } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error'); }
161
- } } finally { release(); }
187
+ } } finally { unsubscribe(); unsubscribeOutput?.(); release(); }
162
188
  }
@@ -29,13 +29,14 @@ export class WorkflowsModule implements Waitable {
29
29
  readonly stale?: string;
30
30
  private warned = false;
31
31
  private unsubscribe?: () => void;
32
+ private activity = new Map<string, OwnedWorkflowTask>();
32
33
  private queued = new Set<string>();
33
34
  private saved = new Map<string, string>();
34
35
  constructor(private pi: ExtensionAPI, private binding: SessionBinding, private notices: Notifications,
35
36
  private dock: Dock, private agents: AgentsModule, manager?: WorkflowManager) {
36
37
  if (manager) { this.manager = manager; this.stale = agents.stale; }
37
38
  else ({ owner: this.manager, stale: this.stale } = workflowRuntime({ owner: agents.manager, stale: agents.stale }));
38
- dock.register('workflows', { title: 'Workflows', rows: () => this.list().filter(task => !this.manager.settled(task.id)).map(task => ({
39
+ dock.register('workflows', { title: 'Workflows', rows: () => [...this.activity.values()].map(task => ({
39
40
  id: task.id, text: `${task.id} ${task.workflowName ?? 'workflow'}`, priority: 60,
40
41
  suffix: `${task.status} · ${task.doneCount}/${task.agentCount}`,
41
42
  })) });
@@ -46,7 +47,9 @@ export class WorkflowsModule implements Waitable {
46
47
  }
47
48
  list(): OwnedWorkflowTask[] {
48
49
  const current = this.binding.current;
49
- return current ? [...this.manager.tasks.values()].filter(task => this.manager.visible(task, this.agents.scope(current.ctx))) : [];
50
+ if (!current) return [];
51
+ const scope = this.agents.scope(current.ctx);
52
+ return [...this.manager.tasks.values()].filter(task => this.manager.visible(task, scope));
50
53
  }
51
54
  bind(): void {
52
55
  this.detach();
@@ -57,16 +60,23 @@ export class WorkflowsModule implements Waitable {
57
60
  }
58
61
  const entries = workflowEntries(current.ctx.sessionManager.getBranch()); this.manager.restore(entries);
59
62
  for (const entry of entries) this.saved.set(entry.id, `${entry.status}:${entry.endTime ?? ''}:${entry.notified}:${entry.error ?? ''}`);
60
- this.unsubscribe = this.manager.subscribe(() => this.refresh()); this.refresh();
63
+ this.unsubscribe = this.subscribeDisplay(id => {
64
+ if (id === undefined) this.refresh();
65
+ else if (this.activity.has(id)) this.dock.invalidate();
66
+ });
67
+ this.refresh();
61
68
  }
62
69
  detach(): void {
63
70
  this.unsubscribe?.(); this.unsubscribe = undefined;
64
71
  if (this.binding.current) for (const id of this.queued) this.notices.cancel(this.binding.current.sessionId, `workflow:${id}:result`);
65
- this.queued.clear(); this.saved.clear(); this.dock.invalidate();
72
+ this.queued.clear(); this.saved.clear(); this.activity.clear(); this.dock.invalidate();
66
73
  }
67
74
  private refresh(): void {
68
75
  const current = this.binding.current; if (!current) return;
69
- for (const task of this.list()) {
76
+ const tasks = this.list();
77
+ // Dock painting and progress use only the active snapshot; rebind refreshes branch membership.
78
+ this.activity = new Map(tasks.filter(task => !this.manager.settled(task.id)).map(task => [task.id, task]));
79
+ for (const task of tasks) {
70
80
  // A status may change while result files are still being flushed. Parent history
71
81
  // must announce completion only after the execution owner has settled it.
72
82
  if (!workflowActive(task) && !this.manager.settled(task.id)) continue;
@@ -75,8 +85,8 @@ export class WorkflowsModule implements Waitable {
75
85
  this.saved.set(task.id, revision); this.pi.appendEntry(WORKFLOW_ENTRY_TYPE, this.manager.snapshot(task));
76
86
  }
77
87
  }
78
- for (const item of this.unread()) {
79
- if (this.queued.has(item.id)) continue;
88
+ for (const item of this.unreadTasks(tasks)) {
89
+ if (this.queued.has(item.id) || this.manager.get(item.id).notified) continue;
80
90
  this.queued.add(item.id);
81
91
  this.notices.enqueue(current.sessionId, `workflow:${item.id}:result`, item.summary, () => this.consume(item),
82
92
  'event', resultView(this.manager.get(item.id)));
@@ -86,10 +96,23 @@ export class WorkflowsModule implements Waitable {
86
96
  settlement(id: string): Settlement {
87
97
  const task = this.manager.get(id), current = this.binding.current;
88
98
  if (!current || !this.manager.visible(task, this.agents.scope(current.ctx))) throw new Error(`Workflow ${id} is not visible on this branch. Wait from the session branch that started it.`);
89
- return {id, state: task.status, settled: this.manager.settled(id), summary: `${workflowSummary(task, true)}\n${resultBody(task)}`};
99
+ return this.describe(task);
90
100
  }
91
- unread(): Settlement[] { return this.list().filter(task => this.manager.settled(task.id) && !task.notified).map(task => this.settlement(task.id)); }
101
+ private describe(task: OwnedWorkflowTask): Settlement {
102
+ return {id: task.id, state: task.status, settled: this.manager.settled(task.id), summary: `${workflowSummary(task, true)}\n${resultBody(task)}`};
103
+ }
104
+ private unreadTasks(tasks: OwnedWorkflowTask[]): Settlement[] {
105
+ return tasks.filter(task => this.manager.settled(task.id) && !task.notified).map(task => this.describe(task));
106
+ }
107
+ unread(): Settlement[] { return this.unreadTasks(this.list()); }
92
108
  subscribe(listener: () => void): () => void { return this.manager.subscribe(listener); }
109
+ subscribeDisplay(listener: (id?: string) => void): () => void {
110
+ const lifecycle = this.subscribe(() => listener());
111
+ // An occupied pre-upgrade owner sends both kinds of update on its original channel.
112
+ const progress = this.manager.subscribeProgress?.(listener);
113
+ return () => { lifecycle(); progress?.(); };
114
+ }
115
+ hasActive(): boolean { return this.activity.size > 0; }
93
116
  consume(item: Settlement): void {
94
117
  if (!item.settled) return;
95
118
  const task = this.manager.get(item.id); task.notified = true;
@@ -11,6 +11,7 @@ import { captureParent } from '../parent.ts';
11
11
  import { agentRuntime } from '../runtime.ts';
12
12
  import { WORKFLOW_OWNER } from '../registry.ts';
13
13
  import { acquireOwner, existingOwner, type OwnerHandle } from '../../runtime/owner.ts';
14
+ import { branchIds } from '../../runtime/branch.ts';
14
15
  import type { AgentManager } from '../manager.ts';
15
16
  import { appendJournal, readJournal } from './journal.ts';
16
17
  import { taskFromEntry, workflowEntryData, type OwnedWorkflowTask, type WorkflowEntryData } from './entry.ts';
@@ -25,12 +26,18 @@ export class WorkflowManager {
25
26
  readonly tasks = new Map<string, OwnedWorkflowTask>();
26
27
  private runs = new Map<string, {done: Promise<void>; store: WorkflowStore; settled: boolean}>();
27
28
  private listeners = new Set<() => void>();
29
+ private progressListeners = new Set<(id: string) => void>();
28
30
  private runtime?: Promise<typeof import('./runtime/run.ts')>;
29
- private starting = 0;
31
+ private starting = new Map<string, string>();
30
32
  closed = false;
31
33
  constructor(readonly agents: AgentManager, private jobs: () => JobManager) {}
32
34
  subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); }
33
35
  changed = (): void => { for (const listener of [...this.listeners]) listener(); };
36
+ subscribeProgress(listener: (id: string) => void): () => void {
37
+ this.progressListeners.add(listener); return () => this.progressListeners.delete(listener);
38
+ }
39
+ /** Cosmetic updates must not wake waiters or run the session persistence pass. */
40
+ progressChanged(id: string): void { for (const listener of [...this.progressListeners]) listener(id); }
34
41
  get(id: string): OwnedWorkflowTask {
35
42
  const task = this.tasks.get(id);
36
43
  if (!task) throw new ToolError('NOT_FOUND', `No workflow ${id}. Use a wf_ ID from this branch.`, id);
@@ -39,7 +46,7 @@ export class WorkflowManager {
39
46
  jobManager(): JobManager { return this.jobs(); }
40
47
  visible(task: OwnedWorkflowTask, scope: ParentScope): boolean {
41
48
  return !scope.run && task.ownerSessionId === scope.ctx.sessionManager.getSessionId()
42
- && (task.anchorEntryId === null || scope.ctx.sessionManager.getBranch().some(entry => entry.id === task.anchorEntryId));
49
+ && (task.anchorEntryId === null || branchIds(scope.ctx.sessionManager).has(task.anchorEntryId));
43
50
  }
44
51
  restore(entries: WorkflowEntryData[]): void {
45
52
  for (const entry of entries) {
@@ -73,9 +80,9 @@ export class WorkflowManager {
73
80
  {cwd: scope.ctx.cwd, ...scope.owner!, recordPath: files.recordPath, resultPath: files.resultPath, notified: false, children: [] as OwnedWorkflowTask['children']});
74
81
  if (replay?.truncated) updateWorkflowProgressBatch(task, [{type: 'workflow_log', message: 'Resume journal has an incomplete final append; only its complete prefix is available.'}]);
75
82
  const store = new WorkflowStore(workflowEntryData(task));
76
- this.starting++;
83
+ this.starting.set(id, task.ownerSessionId);
77
84
  try { await store.save(workflowEntryData(task)); }
78
- finally { this.starting--; }
85
+ finally { this.starting.delete(id); }
79
86
  // Quit can race the initial disk write, before a Worker has been admitted.
80
87
  if (this.closed || this.agents.closed) throw new ToolError('CLOSING', 'Pi quit before the workflow could launch. Start it after reopening Pi.');
81
88
  this.tasks.set(id, task);
@@ -91,7 +98,7 @@ export class WorkflowManager {
91
98
  onMeta: meta => { task.meta = meta; task.workflowName = meta.name; },
92
99
  journal: {entries: task.replay, append: entry => appendJournal(task.journalPath!, entry)},
93
100
  onControl: control => { task.control = control; },
94
- onProgress: entries => { updateWorkflowProgressBatch(task, entries); this.changed(); }});
101
+ onProgress: entries => { updateWorkflowProgressBatch(task, entries); this.progressChanged(task.id); }});
95
102
  await host.close();
96
103
  completeWorkflowTask(task, result);
97
104
  } catch (error) {
@@ -132,9 +139,14 @@ export class WorkflowManager {
132
139
  if (requested) task.abortController.abort();
133
140
  await this.finished(id); return requested;
134
141
  }
142
+ cleanupOwners(): Set<string> {
143
+ const ids = new Set(this.starting.values());
144
+ for (const [id, run] of this.runs) if (!run.settled) ids.add(this.get(id).ownerSessionId);
145
+ return ids;
146
+ }
135
147
  /** Keep the owner through initial admission and the final result write, as well as Worker execution. */
136
148
  busy(): boolean {
137
- if (this.starting) return true;
149
+ if (this.starting.size) return true;
138
150
  for (const run of this.runs.values()) if (!run.settled) return true;
139
151
  return false;
140
152
  }
@@ -55,7 +55,7 @@ export async function showWorkflow(ctx: ExtensionContext, deps: Deps, task: Owne
55
55
  const view = new DetailsView(tui, () => `Subagents ▸ Workflow · ${workflowSummary(task)}`, progress, done,
56
56
  actions.map(item => ({...item, run: () => { action = item.label; done(); }})), reader, theme, {navigation, keys});
57
57
  view.reader.setContent(progress); reader = view.reader;
58
- const off = deps.workflows.manager.subscribe(() => { progress.invalidate(); tui.requestRender(); });
58
+ const off = deps.workflows.subscribeDisplay(id => { if (id === undefined || id === task.id) { progress.invalidate(); tui.requestRender(); } });
59
59
  const timer = setInterval(() => { if (workflowActive(task)) tui.requestRender(); }, 1000); timer.unref();
60
60
  const dispose = view.dispose.bind(view);
61
61
  return Object.assign(view, {dispose() { dispose(); off(); clearInterval(timer); }});
@@ -108,7 +108,7 @@ export async function showWorkflows(ctx: ExtensionContext, deps: Deps, page: Wor
108
108
  items: () => [{value: 'runs', label: 'Runs'}, {value: 'saved', label: 'Saved'}],
109
109
  select: (value, done) => { const previous = states[Number(saved)]; saved = value === 'saved'; page.saved = saved;
110
110
  states[Number(saved)].focus = previous.focus; changed = true; done(); } }],
111
- subscribe: refresh => deps.workflows.subscribe(refresh), ticking: () => !saved && deps.workflows.list().some(workflowActive),
111
+ subscribe: refresh => saved ? () => {} : deps.workflows.subscribeDisplay(() => refresh()), refreshOnTick: true, ticking: () => !saved && deps.workflows.hasActive(),
112
112
  items: () => saved ? names.map(name => ({value: name, label: name, details: () => {
113
113
  const source = sources.get(name)!;
114
114
  return {rows: [source.ok ? source.script : [part(source.message, 'error')]]};
package/src/jobs/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import { getAgentDir } from '@earendil-works/pi-coding-agent';
3
3
  import type { SessionBinding } from '../runtime/binding.ts';
4
+ import { branchIds } from '../runtime/branch.ts';
4
5
  import type { NotificationDetails, Notifications, NotificationView } from '../runtime/notifications.ts';
5
6
  import type { Settlement, Waitable } from '../runtime/wait.ts';
6
7
  import type { StatusPublisher } from '../ui/status.ts';
@@ -16,7 +17,7 @@ import { isWorkflowGate, type JobSummary, type Workspace } from './types.ts';
16
17
  import type { MonitorEvent } from './monitors/runtime.ts';
17
18
  import type { HandsFreeUpdate } from './monitors/hands-free.ts';
18
19
  import type { JobControl } from './control.ts';
19
- import { listJobs, selectJobRows, type ListQuery, type ListRow, type SessionScope } from './query.ts';
20
+ import { listJobs, selectJobRows, type ListQuery, type ListRow, type ListScope, type SessionScope } from './query.ts';
20
21
 
21
22
  export { displayName } from './launch/name.ts';
22
23
  function seconds(ms: number | undefined): string { return ms === undefined ? '' : `${(ms / 1000).toFixed(1)}s`; }
@@ -40,9 +41,6 @@ export function jobCompactStatus(job: JobSummary): DisplayField[][] {
40
41
  return job.cleanup.state === 'pending' || job.cleanup.state === 'unconfirmed'
41
42
  ? [[state, {text: ' · ', tone: 'dim'}, warning], [warning]] : [[state]];
42
43
  }
43
- export function jobLabel(job: JobSummary): DisplayField[] {
44
- return [{text: displayName(job)}, {text: ' · ', tone: 'dim'}, ...jobStatus(job)];
45
- }
46
44
  /** First line of every job result: `job_3fa1c2d0 completed · exit 0 · 12.4s · pipe`. */
47
45
  export function summaryLine(job: JobSummary): string {
48
46
  const parts = [`${job.id} ${job.state}`];
@@ -99,7 +97,8 @@ export class JobsModule implements Waitable {
99
97
  readonly prefix = 'job_';
100
98
  private handle?: RuntimeHandle;
101
99
  private unsubscribe?: () => void;
102
- private readonly ticker = new PresentationTicker(() => this.status.detailsVisible('jobs'), () => this.publishActivities());
100
+ private activityJobs: JobSummary[] = [];
101
+ private readonly ticker = new PresentationTicker(() => this.status.detailsVisible('jobs'), () => this.publishActivities(true));
103
102
  private queued = new Set<string>();
104
103
  /** Monitor event count already handed to Notifications per job; a higher count re-enqueues. */
105
104
  private queuedEvents = new Map<string, number>();
@@ -119,10 +118,16 @@ export class JobsModule implements Waitable {
119
118
  if (handle.mode === 'unavailable') throw new ToolError('RUNTIME_UNAVAILABLE', handle.reason);
120
119
  return handle.mode === 'active' ? handle.manager : handle.control.jobs;
121
120
  }
122
- createdBy(runIds: string[]): JobSummary[] {
121
+ createdBy(runIds: string[], matches?: (job: JobSummary) => boolean): JobSummary[] {
123
122
  const handle = this.runtime();
124
- if (handle.mode === 'active') return handle.manager.createdBy(runIds);
125
- if (handle.mode === 'restricted' && handle.control.version !== 1) return handle.control.jobs.createdBy(runIds);
123
+ if (handle.mode === 'active') {
124
+ const jobs = handle.manager.createdBy(runIds, matches);
125
+ return matches ? jobs.filter(matches) : jobs;
126
+ }
127
+ if (handle.mode === 'restricted' && handle.control.version !== 1) {
128
+ const jobs = handle.control.jobs.createdBy(runIds);
129
+ return matches ? jobs.filter(matches) : jobs;
130
+ }
126
131
  throw new ToolError('RUNTIME_UNAVAILABLE', handle.mode === 'unavailable' ? handle.reason
127
132
  : 'The older jobs runtime (control bridge v1) cannot list jobs created by agent runs; reading history and stopping jobs still work. Restart Pi to upgrade');
128
133
  }
@@ -133,33 +138,43 @@ export class JobsModule implements Waitable {
133
138
  throw new ToolError('RUNTIME_UNAVAILABLE', handle.mode === 'unavailable' ? handle.reason
134
139
  : `The older jobs runtime (control bridge v${handle.control.version}) cannot list every job of this session; use job_list with scope "workspace". Reading history and stopping jobs still work`);
135
140
  }
136
- private sessionScope(ctx: ExtensionContext, restricted = false): SessionScope {
137
- const sessionId = ctx.sessionManager.getSessionId(), branch = new Set(ctx.sessionManager.getBranch().map(entry => entry.id));
141
+ private sessionScope(ctx: ExtensionContext, restricted = false, matches?: (job: JobSummary) => boolean): SessionScope {
142
+ const sessionId = ctx.sessionManager.getSessionId(), branch = branchIds(ctx.sessionManager);
138
143
  const roots = new Set(restricted ? [] : this.creatorRoots());
139
- return {jobs: () => [...(restricted ? this.control().activeIds(sessionId).map(id => this.control().peek(id)) : this.sessionJobs(sessionId)),
140
- ...(roots.size ? this.createdBy([...roots]) : [])], visible: job => !isWorkflowGate(job) && (job.ownerSessionId === sessionId
144
+ const visible = (job: JobSummary) => !isWorkflowGate(job) && (job.ownerSessionId === sessionId
141
145
  && (job.anchorEntryId === null || branch.has(job.anchorEntryId)) || !!job.creator
142
- && [job.creator.runId, ...job.creator.ancestors].some(runId => roots.has(runId)))};
146
+ && [job.creator.runId, ...job.creator.ancestors].some(runId => roots.has(runId)));
147
+ const select = matches && ((job: JobSummary) => visible(job) && matches(job));
148
+ return {visible, jobs: () => {
149
+ const handle = this.handle;
150
+ const jobs = handle?.mode === 'active' ? [...handle.manager.sessionJobs(sessionId, select),
151
+ ...(roots.size ? handle.manager.createdBy([...roots], select) : [])]
152
+ : [...(restricted ? this.control().activeIds(sessionId).map(id => this.control().peek(id)) : this.sessionJobs(sessionId)),
153
+ ...(roots.size ? this.createdBy([...roots]) : [])];
154
+ // A process owner retained across reload can still have the unfiltered query implementation.
155
+ return select ? jobs.filter(select) : jobs;
156
+ }};
143
157
  }
144
158
  list(workspace: Workspace, query: Omit<ListQuery, 'sessionId'>, ctx: ExtensionContext) {
145
159
  return listJobs(this.control(), workspace, {...query, sessionId: ctx.sessionManager.getSessionId()},
146
160
  query.scope === 'session' ? this.sessionScope(ctx) : undefined);
147
161
  }
148
- /** Browsing updates owned metadata in memory; timer ticks never reread every history file. */
149
- browseRows(rows: ListRow[], query: Pick<ListQuery, 'scope' | 'state'>, ctx: ExtensionContext): ListRow[] {
162
+ /** Storage is a browser snapshot; only manager changes merge new owned records. */
163
+ browseRows(rows: { job: JobSummary; live: boolean }[], scope: ListScope, ctx: ExtensionContext): ListRow[] {
150
164
  const current = this.sessionScope(ctx);
165
+ const control = this.control();
151
166
  const loaded = rows.flatMap(row => {
152
167
  if (!row.live) return [row];
153
- try { return [{ ...row, job: this.control().peek(row.job.id) }]; }
168
+ if (scope === 'session') return []; // SessionScope supplies every visible owned job, including this one.
169
+ try { return [{ ...row, job: control.peek(row.job.id) }]; }
154
170
  catch (error) {
155
- // A settled job can be cleared by another command while this browser is open.
156
- // Owners survive reload, so match the public error code across module instances.
157
- if (error instanceof Error && 'code' in error && error.code === 'NOT_FOUND') return [];
171
+ // Another caller can clear a settled job while the browser is open.
172
+ if (error instanceof Error && 'code' in error && (error.code === 'NOT_FOUND' || error.code === 'HISTORY_READ_ONLY')) return [];
158
173
  throw error;
159
174
  }
160
175
  });
161
- if (query.scope === 'workspace') for (const job of current.jobs()) loaded.push({ job, live: true, unsettled: false });
162
- return selectJobRows(loaded, { ...query, sessionId: ctx.sessionManager.getSessionId() }, current);
176
+ if (scope === 'workspace') for (const job of current.jobs()) loaded.push({ job, live: true });
177
+ return selectJobRows(loaded, { scope, state: 'all', sessionId: ctx.sessionManager.getSessionId() }, current);
163
178
  }
164
179
  get executionAvailable(): boolean { return this.runtime().mode === 'active'; }
165
180
  bind(): void {
@@ -173,7 +188,7 @@ export class JobsModule implements Waitable {
173
188
  }
174
189
  detach(): void {
175
190
  this.unsubscribe?.(); this.unsubscribe = undefined;
176
- this.ticker.stop();
191
+ this.ticker.stop(); this.activityJobs = [];
177
192
  const current = this.binding.current;
178
193
  if (current) {
179
194
  for (const id of this.queued) this.notifications.cancel(current.sessionId, `job:${id}`);
@@ -210,22 +225,20 @@ export class JobsModule implements Waitable {
210
225
  private visible(job: JobSummary): boolean {
211
226
  const current = this.binding.current!;
212
227
  // A job started on another branch reports only after the user returns to that branch.
213
- return !isWorkflowGate(job) && job.ownerSessionId === current.sessionId && (job.anchorEntryId === null || current.ctx.sessionManager.getBranch().some(entry => entry.id === job.anchorEntryId));
228
+ return !isWorkflowGate(job) && job.ownerSessionId === current.sessionId && (job.anchorEntryId === null || branchIds(current.ctx.sessionManager).has(job.anchorEntryId));
214
229
  }
215
- /** Timer ticks project owned metadata only; notifications stay on the manager change path. */
216
- private publishActivities(): void {
230
+ /** Reuse the scoped candidates on the clock; reading elapsed time does not rediscover ownership. */
231
+ private publishActivities(tick = false): void {
217
232
  const handle = this.handle!;
218
- const scope = this.sessionScope(this.binding.current!.ctx, handle.mode === 'restricted' && handle.control.version < 3);
219
- const jobs = [...new Map(scope.jobs().filter(scope.visible).map(job => [job.id, job])).values()];
220
- const activeIds = jobs.filter(isActive).map(job => job.id);
221
- this.status.setActivities('jobs', activeIds, jobs.flatMap(job => {
222
- const cleanup = job.cleanup.state === 'pending' || job.cleanup.state === 'unconfirmed';
223
- const failed = (job.state === 'failed' || job.state === 'timed_out') && !job.notified;
224
- if (!isActive(job) && !cleanup && !failed) return [];
225
- return [{ id: job.id, text: displayName(job), suffix: jobStatus(job), compactSuffixes: jobCompactStatus(job),
226
- priority: cleanup ? 100 : failed ? 80 : job.state === 'stopping' ? 75 : 20 }];
227
- }));
228
- this.ticker.update(activeIds.length > 0);
233
+ if (!tick) {
234
+ // Keep the Dock in sync with the active count, independent of notification delivery.
235
+ const scope = this.sessionScope(this.binding.current!.ctx, handle.mode === 'restricted' && handle.control.version < 3, isActive);
236
+ this.activityJobs = [...new Map(scope.jobs().map(job => [job.id, job])).values()];
237
+ }
238
+ const jobs = tick ? this.activityJobs.map(job => this.control().peek(job.id)).filter(isActive) : this.activityJobs;
239
+ this.status.setActivities('jobs', jobs.map(job => job.id), jobs.map(job => ({ id: job.id, text: displayName(job), suffix: jobStatus(job), compactSuffixes: jobCompactStatus(job),
240
+ priority: job.cleanup.state === 'pending' || job.cleanup.state === 'unconfirmed' ? 100 : job.state === 'stopping' ? 75 : 20 })));
241
+ this.ticker.update(jobs.length > 0);
229
242
  }
230
243
  private sendQuiet(requestId: string, { text, view }: JobNotice): void {
231
244
  // Keep the next-turn string payload and delivery mode; only attach display details.
@@ -5,12 +5,12 @@ import type { JobSummary, StopResult } from './types.ts';
5
5
 
6
6
  /** In-process lifecycle state, separate from the persisted and displayable job summary. */
7
7
  export type Owned = {
8
- job: JobSummary; run?: Tracked; launched: boolean; ready: PromiseWithResolvers<void>;
8
+ job: JobSummary; cleanupOwner?: string; run?: Tracked; launched: boolean; ready: PromiseWithResolvers<void>;
9
9
  settlement?: Promise<void>;
10
10
  stopPromise?: Promise<StopResult>; stopDone?: boolean; cleanupSettled?: boolean;
11
11
  stopDeadline?: number; stopController?: AbortController; stopTimer?: NodeJS.Timeout;
12
12
  timeoutTimer?: NodeJS.Timeout;
13
- saveQueue: Promise<void>; dirty?: boolean; saveAttempts?: number; retryAt?: number; persistenceError?: string;
13
+ saveQueue: Promise<void>; dirty?: boolean; saving?: boolean; saveAttempts?: number; retryAt?: number; persistenceError?: string;
14
14
  deleting?: boolean;
15
15
  inputQueue: Promise<void>;
16
16
  /** Set while the user types in the terminal view; model input is refused until control returns. */