@maxiaochao/pi-background-tasks 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +144 -2
- package/TESTING.md +63 -0
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/extensions/background-tasks.ts +280 -0
- package/package.json +41 -4
- package/src/background-tasks.ts +240 -0
- package/src/output.ts +128 -0
- package/src/widget.ts +54 -0
- package/tests/compaction.mjs +167 -0
- package/tests/extension.mjs +492 -0
- package/tests/fixtures/notifications.ts +77 -0
- package/tests/fixtures/provider.ts +73 -0
- package/tests/helpers.mjs +55 -0
- package/tests/interruptions.mjs +140 -0
- package/tests/load.mjs +28 -0
- package/tests/notifications.mjs +80 -0
- package/tests/output.mjs +55 -0
- package/tests/processes.mjs +96 -0
- package/tests/runtime.mjs +30 -0
- package/tests/tasks.mjs +201 -0
- package/tests/tui-smoke.py +199 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { stripVTControlCharacters } from "node:util";
|
|
6
|
+
import type { BashOperations } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { TaskLog, type LogWrite, type OutputView } from "./output.ts";
|
|
8
|
+
|
|
9
|
+
export interface Clock {
|
|
10
|
+
now(): number;
|
|
11
|
+
setTimeout(callback: () => void, delay: number): unknown;
|
|
12
|
+
clearTimeout(handle: unknown): void;
|
|
13
|
+
}
|
|
14
|
+
export const systemClock: Clock = {
|
|
15
|
+
now: () => Date.now(),
|
|
16
|
+
setTimeout: (callback, delay) => setTimeout(callback, delay),
|
|
17
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
18
|
+
};
|
|
19
|
+
export type TaskStatus = "running" | "succeeded" | "failed" | "cancelled" | "timed_out" | "output_limit";
|
|
20
|
+
export interface TaskSnapshot {
|
|
21
|
+
id: string;
|
|
22
|
+
status: TaskStatus;
|
|
23
|
+
description: string;
|
|
24
|
+
cwd: string;
|
|
25
|
+
started_at: number;
|
|
26
|
+
ended_at?: number;
|
|
27
|
+
timeout: number;
|
|
28
|
+
elapsed_seconds: number;
|
|
29
|
+
log_path: string;
|
|
30
|
+
bytes: number;
|
|
31
|
+
capture_complete: boolean;
|
|
32
|
+
exit_code?: number;
|
|
33
|
+
reason?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface StartParams {
|
|
36
|
+
command: string;
|
|
37
|
+
description?: string;
|
|
38
|
+
cwd?: string;
|
|
39
|
+
timeout?: number;
|
|
40
|
+
}
|
|
41
|
+
interface Task {
|
|
42
|
+
data: TaskSnapshot;
|
|
43
|
+
log: TaskLog;
|
|
44
|
+
controller: AbortController;
|
|
45
|
+
timer?: unknown;
|
|
46
|
+
done: Promise<void>;
|
|
47
|
+
stop?: Exclude<TaskStatus, "running" | "succeeded">;
|
|
48
|
+
captureLost: boolean;
|
|
49
|
+
}
|
|
50
|
+
export interface TaskList {
|
|
51
|
+
tasks: TaskSnapshot[];
|
|
52
|
+
running: number;
|
|
53
|
+
total: number;
|
|
54
|
+
omitted: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function summary(text: string, max = 200): string {
|
|
58
|
+
return Array.from(stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f\uFFF9-\uFFFB]/g, " ").trim()).slice(0, max).join("");
|
|
59
|
+
}
|
|
60
|
+
export function errorText(error: unknown): string {
|
|
61
|
+
return summary(error instanceof Error ? error.message : String(error), 500);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Session-owned jobs; tool calls only transfer control, never own the job signal. */
|
|
65
|
+
export class BackgroundTasks {
|
|
66
|
+
private readonly operations: BashOperations;
|
|
67
|
+
readonly clock: Clock;
|
|
68
|
+
private readonly onComplete: (task: TaskSnapshot) => void;
|
|
69
|
+
private readonly onChange: () => void;
|
|
70
|
+
private readonly logRoot: string;
|
|
71
|
+
private readonly logWrite?: LogWrite;
|
|
72
|
+
private readonly taskBytes: number;
|
|
73
|
+
private readonly sessionBytes: number;
|
|
74
|
+
private readonly tasks = new Map<string, Task>();
|
|
75
|
+
private directory?: string;
|
|
76
|
+
private bytes = 0;
|
|
77
|
+
private closed = false;
|
|
78
|
+
private shutdownPromise?: Promise<void>;
|
|
79
|
+
|
|
80
|
+
constructor(options: {
|
|
81
|
+
operations: BashOperations;
|
|
82
|
+
clock?: Clock;
|
|
83
|
+
onComplete?: (task: TaskSnapshot) => void;
|
|
84
|
+
onChange?: () => void;
|
|
85
|
+
logRoot?: string;
|
|
86
|
+
logWrite?: LogWrite;
|
|
87
|
+
limits?: { taskBytes: number; sessionBytes: number };
|
|
88
|
+
}) {
|
|
89
|
+
this.operations = options.operations;
|
|
90
|
+
this.clock = options.clock ?? systemClock;
|
|
91
|
+
this.onComplete = options.onComplete ?? (() => {});
|
|
92
|
+
this.onChange = options.onChange ?? (() => {});
|
|
93
|
+
this.logRoot = options.logRoot ?? tmpdir();
|
|
94
|
+
this.logWrite = options.logWrite;
|
|
95
|
+
this.taskBytes = options.limits?.taskBytes ?? 32 * 1024 * 1024;
|
|
96
|
+
this.sessionBytes = options.limits?.sessionBytes ?? 256 * 1024 * 1024;
|
|
97
|
+
if (this.taskBytes <= 0 || this.sessionBytes <= 0) throw new Error("Log limits must be positive");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
start(params: StartParams, sessionCwd: string): TaskSnapshot {
|
|
101
|
+
if (this.closed) throw new Error("Background tasks session is closed");
|
|
102
|
+
if (typeof params.command !== "string" || !params.command.trim()) throw new Error("start requires a non-empty command");
|
|
103
|
+
const timeout = params.timeout === undefined ? 1800 : params.timeout;
|
|
104
|
+
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 7200) throw new Error("timeout must be an integer from 1 to 7200 seconds (default 1800)");
|
|
105
|
+
if (params.description !== undefined && typeof params.description !== "string") throw new Error("description must be a string");
|
|
106
|
+
if (params.cwd !== undefined && (typeof params.cwd !== "string" || !params.cwd.trim())) throw new Error("cwd must be a non-empty directory path");
|
|
107
|
+
const cwd = resolve(sessionCwd, params.cwd ?? ".");
|
|
108
|
+
try {
|
|
109
|
+
if (!statSync(cwd).isDirectory()) throw new Error("not a directory");
|
|
110
|
+
} catch (error) { throw new Error(`Invalid working directory: ${errorText(error)}`); }
|
|
111
|
+
if (this.running() >= 2) throw new Error("At most two background tasks may be running; cancel one or wait for completion");
|
|
112
|
+
if (this.bytes >= this.sessionBytes) throw new Error("Session log budget exhausted; start a new session to reset it");
|
|
113
|
+
this.directory ??= mkdtempSync(join(this.logRoot, "pi-background-tasks-"));
|
|
114
|
+
let id: string;
|
|
115
|
+
do { id = `bg-${randomUUID().replace(/-/g, "").slice(0, 12)}`; } while (this.tasks.has(id));
|
|
116
|
+
const log = new TaskLog(join(this.directory, `${id}.log`), this.logWrite);
|
|
117
|
+
const task: Task = {
|
|
118
|
+
data: {
|
|
119
|
+
id, status: "running", description: summary(params.description || params.command.split("\n", 1)[0]), cwd,
|
|
120
|
+
started_at: this.clock.now(), timeout, elapsed_seconds: 0, log_path: log.path,
|
|
121
|
+
bytes: 0, capture_complete: false,
|
|
122
|
+
},
|
|
123
|
+
log, controller: new AbortController(), done: Promise.resolve(), captureLost: false,
|
|
124
|
+
};
|
|
125
|
+
// This path is synchronous: reserve the slot before any execution can await.
|
|
126
|
+
this.tasks.set(id, task);
|
|
127
|
+
task.timer = this.clock.setTimeout(() => this.stop(task, "timed_out", `Runtime limit of ${timeout} seconds reached`), timeout * 1000);
|
|
128
|
+
const accepted = this.snapshot(task);
|
|
129
|
+
task.done = this.run(task, params.command);
|
|
130
|
+
this.changed();
|
|
131
|
+
return accepted;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
get(id: string): TaskSnapshot { return this.snapshot(this.find(id)); }
|
|
135
|
+
|
|
136
|
+
list(): TaskList {
|
|
137
|
+
const all = [...this.tasks.values()];
|
|
138
|
+
const active = all.filter((task) => task.data.status === "running");
|
|
139
|
+
const ended = all.filter((task) => task.data.status !== "running").reverse().slice(0, 20);
|
|
140
|
+
return { tasks: [...active, ...ended].map((task) => this.snapshot(task)), running: active.length, total: all.length, omitted: all.length - active.length - ended.length };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
output(id: string): TaskSnapshot & OutputView {
|
|
144
|
+
const task = this.find(id);
|
|
145
|
+
try { return { ...this.snapshot(task), ...task.log.read() }; }
|
|
146
|
+
catch (error) {
|
|
147
|
+
this.captureFailure(task, `Cannot read task log: ${errorText(error)}`);
|
|
148
|
+
throw new Error(`Cannot read task log: ${errorText(error)}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async cancel(id: string): Promise<TaskSnapshot> {
|
|
153
|
+
const task = this.find(id);
|
|
154
|
+
this.stop(task, "cancelled", "Cancelled by request");
|
|
155
|
+
await task.done;
|
|
156
|
+
return this.snapshot(task);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
shutdown(): Promise<void> {
|
|
160
|
+
if (this.shutdownPromise) return this.shutdownPromise;
|
|
161
|
+
this.closed = true;
|
|
162
|
+
for (const task of this.tasks.values()) this.stop(task, "cancelled", "Session closed");
|
|
163
|
+
this.shutdownPromise = Promise.all([...this.tasks.values()].map((task) => task.done)).then(() => {
|
|
164
|
+
if (this.directory) rmSync(this.directory, { recursive: true, force: true });
|
|
165
|
+
});
|
|
166
|
+
return this.shutdownPromise;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private async run(task: Task, command: string): Promise<void> {
|
|
170
|
+
try {
|
|
171
|
+
const { exitCode } = await this.operations.exec(command, task.data.cwd, {
|
|
172
|
+
signal: task.controller.signal,
|
|
173
|
+
onData: (data) => this.append(task, data),
|
|
174
|
+
});
|
|
175
|
+
if (exitCode !== null) task.data.exit_code = exitCode;
|
|
176
|
+
if (!task.stop && exitCode !== 0) this.stop(task, "failed", `Command exited with ${exitCode === null ? "no exit code" : `code ${exitCode}`}`);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
this.stop(task, "failed", errorText(error));
|
|
179
|
+
} finally {
|
|
180
|
+
if (task.timer !== undefined) this.clock.clearTimeout(task.timer);
|
|
181
|
+
task.timer = undefined;
|
|
182
|
+
try { task.log.finish(); }
|
|
183
|
+
catch (error) {
|
|
184
|
+
this.captureFailure(task, `Cannot close task log: ${errorText(error)}`);
|
|
185
|
+
}
|
|
186
|
+
task.data.status = task.stop ?? "succeeded";
|
|
187
|
+
task.data.ended_at = this.clock.now();
|
|
188
|
+
task.data.capture_complete = !task.captureLost;
|
|
189
|
+
this.changed();
|
|
190
|
+
if (!this.closed) {
|
|
191
|
+
try { this.onComplete(this.snapshot(task)); }
|
|
192
|
+
catch (error) { console.error(`Background completion notification failed: ${errorText(error)}`); }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private append(task: Task, data: Buffer): void {
|
|
198
|
+
if (task.captureLost || task.data.status !== "running" || data.length === 0) return;
|
|
199
|
+
const remaining = Math.max(0, Math.min(this.taskBytes - task.log.bytes, this.sessionBytes - this.bytes));
|
|
200
|
+
const before = task.log.bytes;
|
|
201
|
+
try { if (remaining > 0) task.log.append(data.subarray(0, remaining)); }
|
|
202
|
+
catch (error) {
|
|
203
|
+
this.captureFailure(task, `Cannot write task log: ${errorText(error)}`);
|
|
204
|
+
} finally { this.bytes += task.log.bytes - before; }
|
|
205
|
+
if (data.length >= remaining) {
|
|
206
|
+
task.captureLost = true;
|
|
207
|
+
this.stop(task, "output_limit", `Log output limit reached (task ${this.taskBytes} bytes; session ${this.sessionBytes} bytes)`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private captureFailure(task: Task, reason: string): void {
|
|
212
|
+
task.captureLost = true;
|
|
213
|
+
if (task.stop || task.data.status !== "running") {
|
|
214
|
+
task.data.reason = summary(`${task.data.reason ? `${task.data.reason}; ` : ""}${reason}`, 500);
|
|
215
|
+
}
|
|
216
|
+
this.stop(task, "failed", reason);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private stop(task: Task, status: NonNullable<Task["stop"]>, reason: string): void {
|
|
220
|
+
if (task.data.status !== "running" || task.stop) return;
|
|
221
|
+
task.stop = status;
|
|
222
|
+
task.data.reason = summary(reason, 500);
|
|
223
|
+
task.controller.abort();
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private running(): number { return [...this.tasks.values()].filter((task) => task.data.status === "running").length; }
|
|
227
|
+
private find(id: string): Task {
|
|
228
|
+
const task = this.tasks.get(id);
|
|
229
|
+
if (!task) throw new Error("Unknown background task ID in this session");
|
|
230
|
+
return task;
|
|
231
|
+
}
|
|
232
|
+
private snapshot(task: Task): TaskSnapshot {
|
|
233
|
+
return { ...task.data, capture_complete: task.data.capture_complete && !task.captureLost, bytes: task.log.bytes, elapsed_seconds: Math.max(0, ((task.data.ended_at ?? this.clock.now()) - task.data.started_at) / 1000) };
|
|
234
|
+
}
|
|
235
|
+
private changed(): void {
|
|
236
|
+
if (this.closed) return;
|
|
237
|
+
try { this.onChange(); }
|
|
238
|
+
catch (error) { console.error(`Background task display failed: ${errorText(error)}`); }
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/output.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync, writeSync } from "node:fs";
|
|
2
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
const PROGRAM_BYTES = 1024 * 1024;
|
|
5
|
+
export type LogWrite = (fd: number, data: Buffer) => number;
|
|
6
|
+
|
|
7
|
+
export interface OutputView {
|
|
8
|
+
text: string;
|
|
9
|
+
output: string;
|
|
10
|
+
truncated: boolean;
|
|
11
|
+
truncation: TruncationResult;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Owns one log. Reads are range-limited even when the on-disk log is large. */
|
|
15
|
+
export class TaskLog {
|
|
16
|
+
readonly path: string;
|
|
17
|
+
bytes = 0;
|
|
18
|
+
private fd: number;
|
|
19
|
+
private closed = false;
|
|
20
|
+
private readonly write: LogWrite;
|
|
21
|
+
private decoder = new TextDecoder();
|
|
22
|
+
private decodedBytes = 0;
|
|
23
|
+
private lines = 0;
|
|
24
|
+
private openLine = false;
|
|
25
|
+
private lastLineBytes = 0;
|
|
26
|
+
|
|
27
|
+
constructor(path: string, write: LogWrite = (fd, data) => writeSync(fd, data)) {
|
|
28
|
+
this.path = path;
|
|
29
|
+
this.write = write;
|
|
30
|
+
this.fd = openSync(path, "wx", 0o600);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
append(data: Buffer): void {
|
|
34
|
+
if (this.closed) throw new Error("Log is closed");
|
|
35
|
+
let offset = 0;
|
|
36
|
+
while (offset < data.length) {
|
|
37
|
+
const remaining = data.subarray(offset);
|
|
38
|
+
const count = this.write(this.fd, remaining);
|
|
39
|
+
if (!Number.isInteger(count) || count <= 0 || count > remaining.length) throw new Error("Log write made invalid progress");
|
|
40
|
+
this.bytes += count;
|
|
41
|
+
this.countText(this.decoder.decode(remaining.subarray(0, count), { stream: true }));
|
|
42
|
+
offset += count;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
finish(): void {
|
|
47
|
+
if (this.closed) return;
|
|
48
|
+
this.closed = true;
|
|
49
|
+
try { this.countText(this.decoder.decode()); }
|
|
50
|
+
finally { closeSync(this.fd); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
read(): OutputView {
|
|
54
|
+
const fd = openSync(this.path, "r");
|
|
55
|
+
try {
|
|
56
|
+
// Keep a bounded working window comparable to Bash's rolling tail. This
|
|
57
|
+
// preserves an oversized last line that ends with a newline before trimming.
|
|
58
|
+
const start = Math.max(0, this.bytes - DEFAULT_MAX_BYTES * 4 - 4);
|
|
59
|
+
const tail = this.range(fd, start, this.bytes - start);
|
|
60
|
+
let first = 0;
|
|
61
|
+
while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
|
|
62
|
+
let snapshot = new TextDecoder().decode(tail.subarray(first), { stream: !this.closed });
|
|
63
|
+
if (start > 0) {
|
|
64
|
+
const previous = this.range(fd, start - 1, 1)[0];
|
|
65
|
+
if (first > 0 || previous !== 0x0a) {
|
|
66
|
+
const newline = snapshot.indexOf("\n");
|
|
67
|
+
if (newline !== -1) snapshot = snapshot.slice(newline + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const truncation = truncateTail(snapshot);
|
|
71
|
+
const totalLines = this.lines + (this.openLine ? 1 : 0);
|
|
72
|
+
truncation.truncated = totalLines > DEFAULT_MAX_LINES || this.decodedBytes > DEFAULT_MAX_BYTES;
|
|
73
|
+
truncation.truncatedBy = truncation.truncated
|
|
74
|
+
? (truncation.truncatedBy ?? (this.decodedBytes > DEFAULT_MAX_BYTES ? "bytes" : "lines")) : null;
|
|
75
|
+
truncation.totalLines = totalLines;
|
|
76
|
+
truncation.totalBytes = this.decodedBytes;
|
|
77
|
+
let text = truncation.content || "(no output)";
|
|
78
|
+
if (truncation.truncated) {
|
|
79
|
+
const end = totalLines;
|
|
80
|
+
const begin = end - truncation.outputLines + 1;
|
|
81
|
+
const detail = truncation.lastLinePartial
|
|
82
|
+
? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.lastLineBytes)})`
|
|
83
|
+
: `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(DEFAULT_MAX_BYTES)} limit)` : ""}`;
|
|
84
|
+
text += `\n\n[Showing ${detail}. Full output: ${this.path}]`;
|
|
85
|
+
}
|
|
86
|
+
const program = this.readProgram(fd);
|
|
87
|
+
return { text, output: program.content, truncated: program.truncated, truncation };
|
|
88
|
+
} finally { closeSync(fd); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private readProgram(fd: number): { content: string; truncated: boolean } {
|
|
92
|
+
if (this.bytes <= PROGRAM_BYTES) {
|
|
93
|
+
return { content: new TextDecoder().decode(this.range(fd, 0, this.bytes), { stream: !this.closed }), truncated: false };
|
|
94
|
+
}
|
|
95
|
+
const half = PROGRAM_BYTES / 2;
|
|
96
|
+
const head = this.range(fd, 0, half);
|
|
97
|
+
const tail = this.range(fd, this.bytes - half, half);
|
|
98
|
+
const headText = new TextDecoder().decode(head, { stream: true });
|
|
99
|
+
let first = 0;
|
|
100
|
+
while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
|
|
101
|
+
const tailText = new TextDecoder().decode(tail.subarray(first), { stream: !this.closed });
|
|
102
|
+
return { content: `${headText}\n\n[... ${this.bytes - PROGRAM_BYTES} bytes omitted ...]\n\n${tailText}`, truncated: true };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private range(fd: number, position: number, length: number): Buffer {
|
|
106
|
+
const data = Buffer.alloc(length);
|
|
107
|
+
let offset = 0;
|
|
108
|
+
while (offset < length) {
|
|
109
|
+
const count = readSync(fd, data, offset, length - offset, position + offset);
|
|
110
|
+
if (count === 0) throw new Error("Log changed unexpectedly while reading");
|
|
111
|
+
offset += count;
|
|
112
|
+
}
|
|
113
|
+
return data;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private countText(text: string): void {
|
|
117
|
+
this.decodedBytes += Buffer.byteLength(text);
|
|
118
|
+
const last = text.lastIndexOf("\n");
|
|
119
|
+
if (last === -1) {
|
|
120
|
+
if (text.length) this.openLine = true;
|
|
121
|
+
this.lastLineBytes += Buffer.byteLength(text);
|
|
122
|
+
} else {
|
|
123
|
+
for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) this.lines++;
|
|
124
|
+
this.lastLineBytes = Buffer.byteLength(text.slice(last + 1));
|
|
125
|
+
this.openLine = last < text.length - 1;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
package/src/widget.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { Clock, TaskSnapshot } from "./background-tasks.ts";
|
|
4
|
+
|
|
5
|
+
export const WIDGET_KEY = "background-tasks";
|
|
6
|
+
export const FINISHED_VISIBLE_MS = 5000;
|
|
7
|
+
|
|
8
|
+
export function visibleTasks(tasks: TaskSnapshot[], now: number): TaskSnapshot[] {
|
|
9
|
+
return tasks.filter((task) => task.status === "running" || (task.ended_at !== undefined && now < task.ended_at + FINISHED_VISIBLE_MS));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function duration(seconds: number): string {
|
|
13
|
+
const value = Math.max(0, Math.floor(seconds));
|
|
14
|
+
if (value >= 3600) return `${Math.floor(value / 3600)}h${value % 3600 ? ` ${Math.floor(value % 3600 / 60)}m` : ""}`;
|
|
15
|
+
if (value >= 60) return `${Math.floor(value / 60)}m${value % 60 ? ` ${value % 60}s` : ""}`;
|
|
16
|
+
return `${value}s`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class BackgroundWidget {
|
|
20
|
+
private lines?: string[];
|
|
21
|
+
private width?: number;
|
|
22
|
+
private readonly getTasks: () => TaskSnapshot[];
|
|
23
|
+
private readonly clock: Clock;
|
|
24
|
+
private readonly theme: Theme;
|
|
25
|
+
|
|
26
|
+
constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme) {
|
|
27
|
+
this.getTasks = getTasks;
|
|
28
|
+
this.clock = clock;
|
|
29
|
+
this.theme = theme;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
render(width: number): string[] {
|
|
33
|
+
if (this.lines && this.width === width) return this.lines;
|
|
34
|
+
const tasks = visibleTasks(this.getTasks(), this.clock.now());
|
|
35
|
+
const active = tasks.filter((task) => task.status === "running").length;
|
|
36
|
+
const { theme } = this;
|
|
37
|
+
this.lines = [
|
|
38
|
+
truncateToWidth(theme.fg("accent", `Background tasks ${active}/2`), width),
|
|
39
|
+
...tasks.map((task) => {
|
|
40
|
+
const color = task.status === "running" ? "accent" : task.status === "succeeded" ? "success" : task.status === "cancelled" ? "muted" : "error";
|
|
41
|
+
const marker = task.status === "running" ? "●" : task.status === "succeeded" ? "✓" : task.status === "cancelled" ? "○" : "✗";
|
|
42
|
+
const elapsed = ((task.ended_at ?? this.clock.now()) - task.started_at) / 1000;
|
|
43
|
+
return truncateToWidth(` ${theme.fg(color, marker)} ${theme.fg("accent", task.id)} · ${duration(elapsed)} / ${duration(task.timeout)} · ${theme.fg(color, task.status)} · ${theme.fg("text", task.description)}`, width);
|
|
44
|
+
}),
|
|
45
|
+
];
|
|
46
|
+
this.width = width;
|
|
47
|
+
return this.lines;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
invalidate(): void {
|
|
51
|
+
this.lines = undefined;
|
|
52
|
+
this.width = undefined;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import "./runtime.mjs";
|
|
9
|
+
|
|
10
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
|
|
11
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
12
|
+
const { default: register } = await import(process.env.BG_TEST_EXTENSION
|
|
13
|
+
? pathToFileURL(process.env.BG_TEST_EXTENSION).href : new URL("../extensions/background-tasks.ts", import.meta.url).href);
|
|
14
|
+
|
|
15
|
+
async function waitFor(check, label) {
|
|
16
|
+
for (let i = 0; i < 1000; i++) {
|
|
17
|
+
if (check()) return;
|
|
18
|
+
await delay(10);
|
|
19
|
+
}
|
|
20
|
+
throw new Error(`Timed out waiting for ${label}`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
for (const outcome of ["success", "failure", "cancel"]) {
|
|
24
|
+
test(`real Pi manual compaction ${outcome} delivers a job completed during summarization once, without another user prompt`, { timeout: 20000 }, async (t) => {
|
|
25
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-compact-"));
|
|
26
|
+
const release = join(directory, "release");
|
|
27
|
+
const exited = join(directory, "exited");
|
|
28
|
+
const finishSummary = Promise.withResolvers();
|
|
29
|
+
const requests = [], lifecycle = [], events = [], errors = [];
|
|
30
|
+
let session, startedTask;
|
|
31
|
+
try {
|
|
32
|
+
const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
|
|
33
|
+
modelRuntime.registerProvider("bg-compaction", {
|
|
34
|
+
name: "Offline real-compaction fixture", baseUrl: "http://127.0.0.1:1", api: "bg-compaction", apiKey: "fixture-not-a-secret",
|
|
35
|
+
models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
36
|
+
streamSimple(model, context, options) {
|
|
37
|
+
const stream = createAssistantMessageEventStream();
|
|
38
|
+
const compacting = session.isCompacting;
|
|
39
|
+
requests.push({ compacting, messages: context.messages });
|
|
40
|
+
void (async () => {
|
|
41
|
+
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: "stop",
|
|
42
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
43
|
+
try {
|
|
44
|
+
if (compacting) {
|
|
45
|
+
assert.ok(options.signal, "native summarization supplies its cancellation signal");
|
|
46
|
+
writeFileSync(release, "release background shell\n");
|
|
47
|
+
const aborted = () => finishSummary.resolve();
|
|
48
|
+
options.signal.addEventListener("abort", aborted, { once: true });
|
|
49
|
+
try { await finishSummary.promise; }
|
|
50
|
+
finally { options.signal.removeEventListener("abort", aborted); }
|
|
51
|
+
if (options.signal.aborted) {
|
|
52
|
+
message.stopReason = "aborted";
|
|
53
|
+
message.errorMessage = "Fixture summary aborted";
|
|
54
|
+
} else if (outcome === "failure") {
|
|
55
|
+
message.stopReason = "error";
|
|
56
|
+
message.errorMessage = "Fixture summary failure";
|
|
57
|
+
} else message.content.push({ type: "text", text: "## Goal\nVerify compaction delivery.\n## Progress\nA background shell remains owned by this session." });
|
|
58
|
+
} else {
|
|
59
|
+
const last = context.messages.at(-1);
|
|
60
|
+
const text = typeof last.content === "string" ? last.content : last.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
61
|
+
if (last.role === "user" && text.includes("START_COMPACTION_JOB")) {
|
|
62
|
+
message.stopReason = "toolUse";
|
|
63
|
+
message.content.push({ type: "toolCall", id: "compaction-start", name: "background_task", arguments: {
|
|
64
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'finished during compaction\\n'; printf done > exited; exit 7", description: "Finishes during native compaction", timeout: 10,
|
|
65
|
+
} });
|
|
66
|
+
} else message.content.push({ type: "text", text: text.includes("[Background task finished]") ? "COMPLETION_ACK" : "JOB_ACCEPTED" });
|
|
67
|
+
}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
message.stopReason = "error";
|
|
70
|
+
message.errorMessage = String(error);
|
|
71
|
+
}
|
|
72
|
+
stream.push({ type: "start", partial: message });
|
|
73
|
+
if (["error", "aborted"].includes(message.stopReason)) stream.push({ type: "error", reason: message.stopReason, error: message });
|
|
74
|
+
else stream.push({ type: "done", reason: message.stopReason, message });
|
|
75
|
+
})();
|
|
76
|
+
return stream;
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false, keepRecentTokens: 128 }, retry: { enabled: false }, cacheWarming: "off" });
|
|
80
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
81
|
+
cwd: directory, agentDir: directory, settingsManager,
|
|
82
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
83
|
+
extensionFactories: [register, (pi) => {
|
|
84
|
+
for (const type of ["session_before_compact", "session_compact", "session_compact_failed"]) pi.on(type, (event, ctx) => {
|
|
85
|
+
lifecycle.push({ type, reason: event.reason, aborted: event.aborted, fromExtension: event.fromExtension, idle: ctx.isIdle() });
|
|
86
|
+
});
|
|
87
|
+
}],
|
|
88
|
+
});
|
|
89
|
+
await resourceLoader.reload();
|
|
90
|
+
const created = await createAgentSession({ cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-compaction", "deterministic"), thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task"] });
|
|
91
|
+
session = created.session;
|
|
92
|
+
assert.deepEqual(created.extensionsResult.errors, []);
|
|
93
|
+
session.extensionRunner.onError((error) => errors.push(error));
|
|
94
|
+
session.subscribe((event) => {
|
|
95
|
+
events.push({ ...event, observedAt: Date.now() });
|
|
96
|
+
if (event.type === "tool_execution_end" && event.toolName === "background_task") startedTask = event.result.structuredContent.task;
|
|
97
|
+
});
|
|
98
|
+
await session.bindExtensions({});
|
|
99
|
+
await session.prompt("Earlier context to summarize: " + "background verification history ".repeat(200));
|
|
100
|
+
await session.prompt("START_COMPACTION_JOB");
|
|
101
|
+
assert.equal(startedTask?.status, "running");
|
|
102
|
+
assert.equal(session.isIdle, true);
|
|
103
|
+
const notifications = () => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
104
|
+
const conversationRequests = () => requests.filter((request) => !request.compacting);
|
|
105
|
+
const before = conversationRequests().length;
|
|
106
|
+
// This is the same public manual-compaction entry point used by /compact and RPC.
|
|
107
|
+
const compacting = session.compact("COMPACTION_DELIVERY_FIXTURE").then((value) => ({ value }), (error) => ({ error }));
|
|
108
|
+
await waitFor(() => lifecycle.some((event) => event.type === "session_before_compact"), "native compaction start");
|
|
109
|
+
await waitFor(() => requests.some((request) => request.compacting), "native summarizer request");
|
|
110
|
+
await waitFor(() => existsSync(exited), "real background shell exit marker");
|
|
111
|
+
await delay(1250); // Let the real first retry run while native compaction is still busy.
|
|
112
|
+
assert.equal(session.isCompacting, true);
|
|
113
|
+
assert.equal(session.isIdle, false);
|
|
114
|
+
assert.equal(notifications().length, 0, "completion cannot interrupt native compaction");
|
|
115
|
+
assert.equal(conversationRequests().length, before, "busy retries must not start another conversation request");
|
|
116
|
+
if (outcome === "cancel") session.abortCompaction();
|
|
117
|
+
else finishSummary.resolve();
|
|
118
|
+
const result = await compacting;
|
|
119
|
+
if (outcome === "success") {
|
|
120
|
+
assert.equal(result.error, undefined);
|
|
121
|
+
assert.match(result.value.summary, /Verify compaction delivery/);
|
|
122
|
+
} else {
|
|
123
|
+
assert.ok(result.error, "native compaction must reject on failure or cancellation");
|
|
124
|
+
if (outcome === "failure") assert.match(result.error.message, /Fixture summary failure/);
|
|
125
|
+
}
|
|
126
|
+
assert.equal(session.isCompacting, false);
|
|
127
|
+
assert.deepEqual(lifecycle.map((event) => event.type), ["session_before_compact", outcome === "success" ? "session_compact" : "session_compact_failed"]);
|
|
128
|
+
assert.ok(lifecycle.every((event) => event.reason === "manual"));
|
|
129
|
+
assert.equal(lifecycle[1].fromExtension, false, "the fixture must not supply a replacement compaction result");
|
|
130
|
+
if (outcome !== "success") assert.equal(lifecycle[1].aborted, outcome === "cancel");
|
|
131
|
+
await waitFor(() => notifications().length > 0, "automatic completion delivery after compaction");
|
|
132
|
+
await session.waitForIdle();
|
|
133
|
+
await delay(50);
|
|
134
|
+
assert.equal(notifications().length, 1);
|
|
135
|
+
assert.equal(conversationRequests().length, before + 1, "no user prompt is submitted after compact()");
|
|
136
|
+
const notification = notifications()[0];
|
|
137
|
+
const task = notification.details.tasks[0];
|
|
138
|
+
assert.equal(task.id, startedTask.id);
|
|
139
|
+
assert.equal(task.status, "failed");
|
|
140
|
+
assert.equal(task.exit_code, 7);
|
|
141
|
+
assert.match(readFileSync(task.log_path, "utf8"), /finished during compaction/);
|
|
142
|
+
const start = events.find((event) => event.type === "compaction_start");
|
|
143
|
+
const end = events.find((event) => event.type === "compaction_end");
|
|
144
|
+
assert.ok(start && end, "native compaction lifecycle must actually run");
|
|
145
|
+
assert.ok(task.ended_at >= start.observedAt && task.ended_at <= end.observedAt, "the actual task completed during compaction, not beforehand");
|
|
146
|
+
assert.equal(end.aborted, outcome === "cancel");
|
|
147
|
+
assert.equal(session.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, outcome === "success" ? 1 : 0);
|
|
148
|
+
assert.equal(session.getLastAssistantText(), "COMPLETION_ACK");
|
|
149
|
+
assert.deepEqual(errors, []);
|
|
150
|
+
t.diagnostic(JSON.stringify({
|
|
151
|
+
outcome, lifecycle, taskCompletedDuringCompaction: true,
|
|
152
|
+
summaryRequests: requests.filter((request) => request.compacting).length,
|
|
153
|
+
automaticConversationRequests: conversationRequests().length - before,
|
|
154
|
+
completionEntries: notifications().length,
|
|
155
|
+
}));
|
|
156
|
+
} finally {
|
|
157
|
+
finishSummary.resolve();
|
|
158
|
+
if (session) {
|
|
159
|
+
session.abortCompaction();
|
|
160
|
+
await session.abort();
|
|
161
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
162
|
+
session.dispose();
|
|
163
|
+
}
|
|
164
|
+
rmSync(directory, { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|