pi-suite 0.3.7 → 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 (42) 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 +33 -13
  12. package/src/agents/viewer.ts +17 -11
  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
@@ -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. */
@@ -35,6 +35,7 @@ export class JobManager {
35
35
  readonly runtimeId: string;
36
36
  private store: JobStore;
37
37
  private jobs = new Map<string, Owned>();
38
+ private admissions = new Set<Pick<StartRequest, 'ownerSessionId' | 'cleanupOwner'>>();
38
39
  private listeners = new Set<() => void>();
39
40
  private stoppingCreators = new Set<string>();
40
41
  /** Jobs whose automatic wake was paused by Esc; their results arrive with the next user turn. */
@@ -73,7 +74,7 @@ export class JobManager {
73
74
  if (item.deleting) return item.saveQueue;
74
75
  item.saveQueue = item.saveQueue.then(async () => {
75
76
  if (!item.dirty) return;
76
- item.dirty = false;
77
+ item.dirty = false; item.saving = true;
77
78
  try {
78
79
  await this.store.save(item.job);
79
80
  item.persistenceError = undefined; item.saveAttempts = 0; item.retryAt = undefined;
@@ -81,7 +82,7 @@ export class JobManager {
81
82
  item.dirty = true; item.persistenceError = String(error);
82
83
  item.saveAttempts = (item.saveAttempts ?? 0) + 1;
83
84
  item.retryAt = Date.now() + Math.min(30000, 1000 * 2 ** Math.min(item.saveAttempts - 1, 5));
84
- }
85
+ } finally { item.saving = false; }
85
86
  }).finally(() => this.changed());
86
87
  return item.saveQueue;
87
88
  }
@@ -98,10 +99,15 @@ export class JobManager {
98
99
  throw new ToolError('INVALID_ARGS', 'command must be 1-32768 characters, name at most 80, timeoutMs 1-86400000');
99
100
  }
100
101
  this.admit(signal);
101
- const workspace = await resolveWorkspace(request.cwd);
102
- if (await this.store.workspaceBytes(workspace) >= LIMITS.workspaceBytes) {
103
- throw new ToolError('WORKSPACE_CAPACITY', 'Workspace job history reached 1 GiB; ask the user to delete finished jobs in /jobs');
104
- }
102
+ const admission = {ownerSessionId: request.ownerSessionId, cleanupOwner: request.cleanupOwner};
103
+ this.admissions.add(admission);
104
+ let workspace;
105
+ try {
106
+ workspace = await resolveWorkspace(request.cwd);
107
+ if (await this.store.workspaceBytes(workspace) >= LIMITS.workspaceBytes) {
108
+ throw new ToolError('WORKSPACE_CAPACITY', 'Workspace job history reached 1 GiB; ask the user to delete finished jobs in /jobs');
109
+ }
110
+ } finally { this.admissions.delete(admission); }
105
111
  this.admit(signal);
106
112
  const id = this.store.allocate(workspace);
107
113
  const job: JobSummary = {
@@ -116,7 +122,7 @@ export class JobManager {
116
122
  ...(request.timeoutMs ? { timeoutMs: request.timeoutMs } : {}), exitCode: null,
117
123
  cleanup: { state: 'not_required', scope: [], rootExited: false },
118
124
  };
119
- const item: Owned = { job, launched: false, ready: Promise.withResolvers(), saveQueue: Promise.resolve(), inputQueue: Promise.resolve(), pendingEvents: [] };
125
+ const item: Owned = { job, cleanupOwner: request.cleanupOwner, launched: false, ready: Promise.withResolvers(), saveQueue: Promise.resolve(), inputQueue: Promise.resolve(), pendingEvents: [] };
120
126
  // Registered before any await so a concurrent creator stop or quit includes this job.
121
127
  this.jobs.set(id, item);
122
128
  if (this.creatorStopping(request.creator)) job.stopReason = 'agent';
@@ -296,10 +302,14 @@ export class JobManager {
296
302
  [job.creator.runId, ...job.creator.ancestors].some(runId => roots.has(runId)));
297
303
  }
298
304
  /** Complete creation scope across workspaces and notification owners, without pagination. */
299
- createdBy(runIds: string[]): JobSummary[] { return this.createdItems(runIds).map(item => this.view(item)); }
305
+ createdBy(runIds: string[], matches?: (job: JobSummary) => boolean): JobSummary[] {
306
+ return this.createdItems(runIds).flatMap(item => !matches || matches(item.job) ? [this.view(item)] : []);
307
+ }
300
308
  /** Session ownership spans working directories; branch visibility belongs to JobsModule. */
301
- sessionJobs(sessionId: string): JobSummary[] {
302
- return [...this.jobs.values()].filter(item => item.job.ownerSessionId === sessionId).map(item => this.view(item));
309
+ sessionJobs(sessionId: string, matches?: (job: JobSummary) => boolean): JobSummary[] {
310
+ const jobs: JobSummary[] = [];
311
+ for (const item of this.jobs.values()) if (item.job.ownerSessionId === sessionId && (!matches || matches(item.job))) jobs.push(this.view(item));
312
+ return jobs;
303
313
  }
304
314
  /** Stop every job created by these agent runs or their descendants, including detached ones. */
305
315
  async stopCreatedBy(runIds: string[]): Promise<StopResult[]> {
@@ -490,7 +500,15 @@ export class JobManager {
490
500
  try { this.store.saveSync(job); } catch {}
491
501
  }
492
502
  }
493
- hasOccupancy(): boolean {
494
- return [...this.jobs.values()].some(item => item.deleting || !item.launched || item.dirty || isActive(item.job));
503
+ *cleanupOwners(): IterableIterator<string> {
504
+ for (const admission of this.admissions) {
505
+ yield admission.ownerSessionId;
506
+ if (admission.cleanupOwner) yield admission.cleanupOwner;
507
+ }
508
+ for (const item of this.jobs.values()) if (item.deleting || !item.launched || item.dirty || item.saving || isActive(item.job)) {
509
+ yield item.job.ownerSessionId;
510
+ if (item.cleanupOwner) yield item.cleanupOwner;
511
+ }
495
512
  }
513
+ hasOccupancy(): boolean { return !this.cleanupOwners().next().done; }
496
514
  }
@@ -5,6 +5,7 @@
5
5
  import { spawn } from 'node:child_process';
6
6
  import { open } from 'node:fs/promises';
7
7
  import { StringDecoder } from 'node:string_decoder';
8
+ import { setImmediate as yieldToLoop } from 'node:timers/promises';
8
9
  import { normalizeVisibleText } from '../terminal/visible-text.ts';
9
10
  import { sanitizeText } from '../../runtime/text.ts';
10
11
  import type { ResolvedShellConfig } from '../terminal/shell.ts';
@@ -17,8 +18,9 @@ export type MonitorEvent = {
17
18
  detectorError?: string;
18
19
  };
19
20
  type Candidate = Omit<MonitorEvent, 'eventId' | 'at'>;
20
- type Source = { path: string; stream: MonitorEvent['stream']; pty: boolean; offset: number; decoder: StringDecoder; partial: string };
21
+ type Source = { path: string; stream: MonitorEvent['stream']; pty: boolean; offset: number; decoder: StringDecoder; partial: string[]; tail: string };
21
22
  const TAIL_MS = 250;
23
+ const READ_BYTES = 128 * 1024;
22
24
 
23
25
  function summarizeDiff(previous: string, current: string): string {
24
26
  if (!previous) return `Output changed: now has content (${current.length} chars)`;
@@ -79,7 +81,7 @@ export class JobMonitor {
79
81
  this.timer.unref();
80
82
  }
81
83
  static sources(entries: { path: string; stream: MonitorEvent['stream'] }[], pty: boolean): Source[] {
82
- return entries.map(entry => ({ ...entry, pty, offset: 0, decoder: new StringDecoder('utf8'), partial: '' }));
84
+ return entries.map(entry => ({ ...entry, pty, offset: 0, decoder: new StringDecoder('utf8'), partial: [], tail: '' }));
83
85
  }
84
86
 
85
87
  private tick(final = false): Promise<void> {
@@ -89,41 +91,53 @@ export class JobMonitor {
89
91
  private async readNew(final: boolean): Promise<void> {
90
92
  for (const source of this.sources) {
91
93
  const file = await open(source.path, 'r');
92
- let text = '';
93
94
  try {
95
+ // Drain only the size observed at the start of this tick; a busy writer
96
+ // cannot monopolize it. Each read bounds the synchronous framing/matching work.
94
97
  const { size } = await file.stat();
95
- if (size > source.offset) {
96
- const buffer = Buffer.alloc(size - source.offset);
97
- const { bytesRead } = await file.read(buffer, 0, buffer.length, source.offset);
98
+ const buffer = Buffer.allocUnsafe(Math.min(READ_BYTES, Math.max(0, size - source.offset)));
99
+ while (source.offset < size) {
100
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - source.offset), source.offset);
101
+ if (!bytesRead) break;
98
102
  source.offset += bytesRead;
99
- text = source.decoder.write(buffer.subarray(0, bytesRead));
103
+ this.accept(source, source.decoder.write(buffer.subarray(0, bytesRead)), false);
104
+ if (source.offset < size) await yieldToLoop();
100
105
  }
101
106
  } finally { await file.close(); }
102
- if (final) text += source.decoder.end();
103
- this.accept(source, text, final);
107
+ if (final) this.accept(source, source.decoder.end(), true);
104
108
  }
105
109
  }
106
110
  private accept(source: Source, text: string, final: boolean): void {
107
- if (this.config.strategy === 'poll-diff') {
108
- // Keep incomplete markers/output across disk reads. A stop in the middle of an iteration
109
- // must not turn its partial output into a spurious final change.
110
- const samples = (source.partial + text).split(POLL_BOUNDARY);
111
- source.partial = final ? '' : samples.pop()!;
112
- if (final) samples.pop();
113
- for (const raw of samples) {
114
- const sample = raw.split(/\r?\n/).map(line =>
115
- (source.pty ? normalizeVisibleText(line) : sanitizeText(line)).trimEnd()).filter(Boolean).join('\n');
116
- this.pollSample(sample, source.stream);
117
- }
111
+ const polling = this.config.strategy === 'poll-diff';
112
+ const separator = polling ? POLL_BOUNDARY : '\n';
113
+ const input = source.tail + text;
114
+ let start = 0;
115
+ for (let end = input.indexOf(separator); end >= 0; end = input.indexOf(separator, start)) {
116
+ if (source.partial.length) source.partial.push(input.slice(start, end));
117
+ const frame = source.partial.length ? source.partial.join('') : input.slice(start, end);
118
+ source.partial.length = 0;
119
+ this.frame(source, !polling && frame.endsWith('\r') ? frame.slice(0, -1) : frame, polling);
120
+ start = end + separator.length;
121
+ }
122
+ const remaining = input.slice(start);
123
+ if (final) {
124
+ // A partial poll iteration is not a sample. A non-terminated stream line is.
125
+ if (!polling) this.frame(source, source.partial.join('') + remaining, false);
126
+ source.partial.length = 0; source.tail = '';
118
127
  return;
119
128
  }
120
- const lines = (source.partial + text).split(/\r?\n/);
121
- source.partial = final ? '' : lines.pop()!;
122
- for (const raw of lines) {
123
- // PTY lines replay CR overwrites to the final visible text; pipe lines drop control bytes.
124
- const line = (source.pty ? normalizeVisibleText(raw) : sanitizeText(raw)).trimEnd();
125
- if (!line) continue;
126
- this.match(line, line, source.stream);
129
+ // Only the suffix that could contain half a delimiter is searched again.
130
+ // Store the remaining fragments rather than repeatedly joining a long line/sample.
131
+ const tailLength = Math.min(remaining.length, separator.length - 1);
132
+ if (remaining.length > tailLength) source.partial.push(remaining.slice(0, remaining.length - tailLength));
133
+ source.tail = tailLength ? remaining.slice(-tailLength) : '';
134
+ }
135
+ private frame(source: Source, raw: string, polling: boolean): void {
136
+ const visible = (line: string) => (source.pty ? normalizeVisibleText(line) : sanitizeText(line)).trimEnd();
137
+ if (polling) this.pollSample(raw.split(/\r?\n/).map(visible).filter(Boolean).join('\n'), source.stream);
138
+ else {
139
+ const line = visible(raw);
140
+ if (line) this.match(line, line, source.stream);
127
141
  }
128
142
  }
129
143
  private pollSample(sample: string, stream: MonitorEvent['stream']): void {