@maxiaochao/pi-background-tasks 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +33 -21
- package/TESTING.md +23 -5
- package/docs/demo.gif +0 -0
- package/docs/demo.webm +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/task-panes.png +0 -0
- package/extensions/background-tasks.ts +47 -11
- package/package.json +2 -2
- package/src/herdr.ts +38 -0
- package/src/viewer.ts +201 -0
- package/src/widget.ts +15 -2
- package/tests/extension.mjs +5 -4
- package/tests/fixtures/media-job.py +22 -0
- package/tests/fixtures/notifications.ts +46 -36
- package/tests/fixtures/provider.ts +43 -21
- package/tests/media.mjs +54 -0
- package/tests/notifications.mjs +48 -22
- package/tests/tui-smoke.py +11 -4
- package/tests/viewer.mjs +252 -0
package/src/viewer.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { errorText, type TaskSnapshot } from "./background-tasks.ts";
|
|
5
|
+
import { isMissing, type HerdrCall } from "./herdr.ts";
|
|
6
|
+
import { duration } from "./widget.ts";
|
|
7
|
+
|
|
8
|
+
export const TAB_LABEL = "Background tasks";
|
|
9
|
+
const UNFOCUS_POLL_MS = 1000;
|
|
10
|
+
|
|
11
|
+
// Runs inside the pane's own shell. It only reads files; the task itself runs elsewhere.
|
|
12
|
+
// Arguments are file paths, so the user's command text never becomes shell syntax here.
|
|
13
|
+
export const VIEW_SCRIPT = `printf '\\033[2J\\033[3J\\033[H'
|
|
14
|
+
cat "$3"
|
|
15
|
+
tail -n +1 -f "$1" &
|
|
16
|
+
tail_pid=$!
|
|
17
|
+
while [ ! -e "$2" ]; do sleep 0.5; done
|
|
18
|
+
sleep 1
|
|
19
|
+
kill "$tail_pid" 2>/dev/null
|
|
20
|
+
wait "$tail_pid" 2>/dev/null
|
|
21
|
+
cat "$2"
|
|
22
|
+
`;
|
|
23
|
+
|
|
24
|
+
interface Pane { id: string; task: string }
|
|
25
|
+
interface Options {
|
|
26
|
+
call: HerdrCall;
|
|
27
|
+
workspaceId: string;
|
|
28
|
+
/** Current tasks, used to free panes and decide when the tab can close. */
|
|
29
|
+
tasks: () => TaskSnapshot[];
|
|
30
|
+
warn: (message: string) => void;
|
|
31
|
+
/** Delay between focus checks while the user is looking at a finished tab. */
|
|
32
|
+
sleep?: (ms: number) => Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
|
|
36
|
+
function clean(text: string): string { return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); }
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Shows background task logs in one Herdr tab per session. Display only: every failure
|
|
40
|
+
* is reported once and never affects task execution or status.
|
|
41
|
+
*/
|
|
42
|
+
export class HerdrViewer {
|
|
43
|
+
private readonly options: Options;
|
|
44
|
+
private readonly commands = new Map<string, string>();
|
|
45
|
+
private tab?: string;
|
|
46
|
+
private panes: Pane[] = [];
|
|
47
|
+
private chain: Promise<unknown> = Promise.resolve();
|
|
48
|
+
private closing = false;
|
|
49
|
+
private disposed = false;
|
|
50
|
+
private warned = false;
|
|
51
|
+
|
|
52
|
+
private readonly sleep: (ms: number) => Promise<void>;
|
|
53
|
+
|
|
54
|
+
constructor(options: Options) {
|
|
55
|
+
this.options = options;
|
|
56
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms).unref()));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Opens a pane for a newly started task without taking focus. */
|
|
60
|
+
show(task: TaskSnapshot, command: string): Promise<void> {
|
|
61
|
+
this.commands.set(task.id, command);
|
|
62
|
+
return this.enqueue(async () => { await this.open(task, false); });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Reopens a task's pane on user request, then focuses its tab and pane. */
|
|
66
|
+
watch(task: TaskSnapshot): Promise<string> {
|
|
67
|
+
return this.enqueue(async () => {
|
|
68
|
+
await this.prune();
|
|
69
|
+
const pane = this.panes.find((entry) => entry.task === task.id) ?? await this.open(task, false);
|
|
70
|
+
await this.options.call(["tab", "focus", this.tab!]);
|
|
71
|
+
// Panes are split left to right; Herdr focuses a pane through its neighbour.
|
|
72
|
+
const index = this.panes.indexOf(pane);
|
|
73
|
+
if (index > 0) await this.options.call(["pane", "focus", "--pane", this.panes[index - 1].id, "--direction", "right"]);
|
|
74
|
+
else if (this.panes.length > 1) await this.options.call(["pane", "focus", "--pane", this.panes[1].id, "--direction", "left"]);
|
|
75
|
+
this.closeWhenIdle();
|
|
76
|
+
return pane.id;
|
|
77
|
+
}, true);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Writes the result line into the task's pane, then closes the tab once nothing runs. */
|
|
81
|
+
finished(task: TaskSnapshot): void {
|
|
82
|
+
if (this.disposed) return;
|
|
83
|
+
try { this.writeDone(task); }
|
|
84
|
+
catch (error) { this.report(error); }
|
|
85
|
+
this.closeWhenIdle();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Closes the tab immediately, for session shutdown, reload and replacement. */
|
|
89
|
+
async dispose(): Promise<void> {
|
|
90
|
+
this.disposed = true;
|
|
91
|
+
await this.chain.catch(() => {});
|
|
92
|
+
const tab = this.tab;
|
|
93
|
+
this.tab = undefined;
|
|
94
|
+
this.panes = [];
|
|
95
|
+
if (tab) await this.options.call(["tab", "close", tab]).catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private enqueue<T>(step: () => Promise<T>, rethrow = false): Promise<T> {
|
|
99
|
+
const run = this.chain.then(() => {
|
|
100
|
+
if (this.disposed) throw new Error("Background tasks session is closed");
|
|
101
|
+
return step();
|
|
102
|
+
});
|
|
103
|
+
this.chain = run.catch(() => {});
|
|
104
|
+
return rethrow ? run : run.catch((error) => { this.report(error); return undefined as T; });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private report(error: unknown): void {
|
|
108
|
+
if (this.disposed || this.warned) return;
|
|
109
|
+
this.warned = true;
|
|
110
|
+
this.options.warn(`Herdr task view unavailable; tasks keep running and the widget stays current. ${errorText(error)}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private running(): Set<string> {
|
|
114
|
+
return new Set(this.options.tasks().filter((task) => task.status === "running").map((task) => task.id));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private async open(task: TaskSnapshot, retried: boolean): Promise<Pane> {
|
|
118
|
+
const running = this.running();
|
|
119
|
+
let pane = this.panes.find((entry) => !running.has(entry.task));
|
|
120
|
+
try {
|
|
121
|
+
if (!this.tab) {
|
|
122
|
+
const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label", TAB_LABEL, "--no-focus"]);
|
|
123
|
+
this.tab = created.tab?.tab_id;
|
|
124
|
+
const root = created.root_pane?.pane_id;
|
|
125
|
+
if (!this.tab || !root) throw new Error("herdr tab create omitted the tab or pane id");
|
|
126
|
+
pane = { id: root, task: task.id };
|
|
127
|
+
this.panes = [pane];
|
|
128
|
+
} else if (pane) {
|
|
129
|
+
pane.task = task.id;
|
|
130
|
+
} else {
|
|
131
|
+
const split = await this.options.call(["pane", "split", this.panes.at(-1)!.id, "--direction", "right", "--cwd", task.cwd, "--no-focus"]);
|
|
132
|
+
if (!split.pane?.pane_id) throw new Error("herdr pane split omitted the pane id");
|
|
133
|
+
pane = { id: split.pane.pane_id, task: task.id };
|
|
134
|
+
this.panes.push(pane);
|
|
135
|
+
}
|
|
136
|
+
await this.options.call(["pane", "rename", pane.id, `${task.id} · ${task.description}`.slice(0, 80)]);
|
|
137
|
+
await this.options.call(["pane", "run", pane.id, this.viewCommand(task)]);
|
|
138
|
+
return pane;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// The user may close a pane or the whole tab; drop stale handles and retry once.
|
|
141
|
+
if (retried || !isMissing(error)) throw error;
|
|
142
|
+
await this.prune();
|
|
143
|
+
return this.open(task, true);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Forgets panes the user closed. Without any of our panes, the tab is gone or closed. */
|
|
148
|
+
private async prune(): Promise<void> {
|
|
149
|
+
const alive: Pane[] = [];
|
|
150
|
+
for (const pane of this.panes) {
|
|
151
|
+
try { await this.options.call(["pane", "get", pane.id]); alive.push(pane); }
|
|
152
|
+
catch (error) { if (!isMissing(error)) throw error; }
|
|
153
|
+
}
|
|
154
|
+
this.panes = alive;
|
|
155
|
+
if (alive.length > 0 || !this.tab) return;
|
|
156
|
+
const tab = this.tab;
|
|
157
|
+
this.tab = undefined;
|
|
158
|
+
await this.options.call(["tab", "close", tab]).catch(() => {});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private viewCommand(task: TaskSnapshot): string {
|
|
162
|
+
const directory = dirname(task.log_path);
|
|
163
|
+
const script = join(directory, "view.sh");
|
|
164
|
+
const header = join(directory, `${task.id}.header`);
|
|
165
|
+
if (!existsSync(script)) writeFileSync(script, VIEW_SCRIPT, { mode: 0o600 });
|
|
166
|
+
const lines = clean(this.commands.get(task.id) ?? task.description).split("\n");
|
|
167
|
+
writeFileSync(header, `${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
|
|
168
|
+
if (task.status !== "running") this.writeDone(task);
|
|
169
|
+
// The leading space keeps the line out of shell history where HISTCONTROL allows it.
|
|
170
|
+
return ` sh ${[script, task.log_path, this.donePath(task), header].map(quote).join(" ")}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private donePath(task: TaskSnapshot): string { return join(dirname(task.log_path), `${task.id}.done`); }
|
|
174
|
+
|
|
175
|
+
private writeDone(task: TaskSnapshot): void {
|
|
176
|
+
const exit = task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`;
|
|
177
|
+
const reason = task.reason ? `\n${clean(task.reason)}` : "";
|
|
178
|
+
writeFileSync(this.donePath(task), `\n[${task.status}${exit} · ${duration(task.elapsed_seconds)}]${reason}\n`, { mode: 0o600 });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Closes the tab after the last task ends; waits while the user is looking at it. */
|
|
182
|
+
private closeWhenIdle(): void {
|
|
183
|
+
if (this.closing || this.disposed) return;
|
|
184
|
+
this.closing = true;
|
|
185
|
+
const check = (): Promise<void> => this.enqueue(async (): Promise<"wait" | "done"> => {
|
|
186
|
+
if (!this.tab || this.running().size > 0) return "done";
|
|
187
|
+
const tab = this.tab;
|
|
188
|
+
try {
|
|
189
|
+
const info = await this.options.call(["tab", "get", tab]);
|
|
190
|
+
if (info.tab?.focused) return "wait";
|
|
191
|
+
await this.options.call(["tab", "close", tab]);
|
|
192
|
+
} catch (error) { if (!isMissing(error)) throw error; }
|
|
193
|
+
this.tab = undefined;
|
|
194
|
+
this.panes = [];
|
|
195
|
+
return "done";
|
|
196
|
+
}).then((state) => {
|
|
197
|
+
if (state === "wait" && !this.disposed) return this.sleep(UNFOCUS_POLL_MS).then(check);
|
|
198
|
+
});
|
|
199
|
+
void check().finally(() => { this.closing = false; });
|
|
200
|
+
}
|
|
201
|
+
}
|
package/src/widget.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { truncateToWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
import { truncateToWidth, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
3
3
|
import type { Clock, TaskSnapshot } from "./background-tasks.ts";
|
|
4
4
|
|
|
5
5
|
export const WIDGET_KEY = "background-tasks";
|
|
@@ -22,11 +22,23 @@ export class BackgroundWidget {
|
|
|
22
22
|
private readonly getTasks: () => TaskSnapshot[];
|
|
23
23
|
private readonly clock: Clock;
|
|
24
24
|
private readonly theme: Theme;
|
|
25
|
+
private readonly onSelect?: (id: string) => void;
|
|
26
|
+
private rows: string[] = [];
|
|
25
27
|
|
|
26
|
-
|
|
28
|
+
/** With `onSelect`, a primary click on a task row selects it (fullscreen mode only). */
|
|
29
|
+
constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, onSelect?: (id: string) => void) {
|
|
27
30
|
this.getTasks = getTasks;
|
|
28
31
|
this.clock = clock;
|
|
29
32
|
this.theme = theme;
|
|
33
|
+
this.onSelect = onSelect;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
37
|
+
if (!this.onSelect || event.type !== "click" || event.button !== "left") return;
|
|
38
|
+
const id = this.rows[event.y - 1];
|
|
39
|
+
if (!id) return;
|
|
40
|
+
this.onSelect(id);
|
|
41
|
+
return { handled: true, render: false };
|
|
30
42
|
}
|
|
31
43
|
|
|
32
44
|
render(width: number): string[] {
|
|
@@ -34,6 +46,7 @@ export class BackgroundWidget {
|
|
|
34
46
|
const tasks = visibleTasks(this.getTasks(), this.clock.now());
|
|
35
47
|
const active = tasks.filter((task) => task.status === "running").length;
|
|
36
48
|
const { theme } = this;
|
|
49
|
+
this.rows = tasks.map((task) => task.id);
|
|
37
50
|
this.lines = [
|
|
38
51
|
truncateToWidth(theme.fg("accent", `Background tasks ${active}/2`), width),
|
|
39
52
|
...tasks.map((task) => {
|
package/tests/extension.mjs
CHANGED
|
@@ -35,7 +35,7 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
35
35
|
registerCommand(name, value) { commands.set(name, value); },
|
|
36
36
|
sendMessage(message, options) { messages.push({ message, options }); },
|
|
37
37
|
};
|
|
38
|
-
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
|
|
38
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, env: {} });
|
|
39
39
|
return {
|
|
40
40
|
...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
|
|
41
41
|
setIdle(value) { idle = value; },
|
|
@@ -325,6 +325,7 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
325
325
|
const h = harness();
|
|
326
326
|
try {
|
|
327
327
|
assert.equal(h.tool.name, "background_task");
|
|
328
|
+
assert.equal(h.tool.exposure, "model-only");
|
|
328
329
|
assert.match(h.tool.description, /return task IDs immediately/);
|
|
329
330
|
assert.ok(h.tool.description.length < 500);
|
|
330
331
|
assert.equal(h.tool.promptGuidelines, undefined);
|
|
@@ -344,9 +345,9 @@ test("start provides non-blocking next steps in both model text and structured r
|
|
|
344
345
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
345
346
|
const { task, guidance } = started.structuredContent;
|
|
346
347
|
assert.equal(task.status, "running");
|
|
347
|
-
assert.equal(guidance, "
|
|
348
|
-
assert.ok(started.content[0].text.includes(guidance), "
|
|
349
|
-
assert.ok(h.tool.description.includes(guidance), "
|
|
348
|
+
assert.equal(guidance, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
|
|
349
|
+
assert.ok(started.content[0].text.includes(guidance), "the start result must include the guidance");
|
|
350
|
+
assert.ok(h.tool.description.includes(guidance), "the tool description must include the same guidance");
|
|
350
351
|
assert.equal(h.tool.outputSchema.properties.guidance.type, "string");
|
|
351
352
|
assert.equal(h.tool.outputSchema.required?.includes("guidance") ?? false, false);
|
|
352
353
|
const list = await h.tool.execute("list", { action: "list" });
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Real demo jobs. Explicit release files control completion for screen recording."""
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
kind = sys.argv[1]
|
|
8
|
+
if kind not in ("build", "tests"):
|
|
9
|
+
raise SystemExit("expected build or tests")
|
|
10
|
+
|
|
11
|
+
print(f"Starting {kind} demo job (real local process)", flush=True)
|
|
12
|
+
count = 0
|
|
13
|
+
while not Path(f"release-{kind}").exists():
|
|
14
|
+
count += 1
|
|
15
|
+
if kind == "build":
|
|
16
|
+
print(f"\rCompiling module {count:03d} ...", end="", flush=True)
|
|
17
|
+
else:
|
|
18
|
+
print(f"test_{count:03d} ... passed", flush=True)
|
|
19
|
+
time.sleep(0.5) # Output cadence only; completion is controlled by the release file.
|
|
20
|
+
|
|
21
|
+
print("\nBUILD SUCCESSFUL" if kind == "build" else "TEST SUITE COMPLETE: one demo failure", flush=True)
|
|
22
|
+
raise SystemExit(0 if kind == "build" else 3)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
import { appendFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
// Sequential fixture tools hold one native batch open; background calls remain model-issued.
|
|
2
|
+
import { appendFileSync, existsSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
5
5
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
@@ -8,32 +8,40 @@ import { Type } from "typebox";
|
|
|
8
8
|
|
|
9
9
|
export default function (pi: ExtensionAPI) {
|
|
10
10
|
const record = (entry: unknown) => appendFileSync(process.env.BG_NOTIFICATION_EVENTS!, JSON.stringify(entry) + "\n");
|
|
11
|
+
const tasks = new Map<string, any>();
|
|
12
|
+
const consumed: string[] = [];
|
|
13
|
+
let finished = false;
|
|
11
14
|
pi.registerTool({
|
|
12
15
|
name: "synchronous_subagent_fixture", label: "Synchronous subagent fixture",
|
|
13
|
-
description: "Wait for
|
|
14
|
-
parameters: Type.Object({
|
|
15
|
-
async execute(_id, {
|
|
16
|
-
record({ event: "waiting" });
|
|
17
|
-
writeFileSync(join(ctx.cwd,
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
if (
|
|
23
|
-
|
|
16
|
+
description: "Wait for two real shell jobs while holding one synchronous tool call open.",
|
|
17
|
+
parameters: Type.Object({ wave: Type.Number() }), executionMode: "sequential",
|
|
18
|
+
async execute(_id, { wave }, _signal, _update, ctx) {
|
|
19
|
+
record({ event: "waiting", wave });
|
|
20
|
+
writeFileSync(join(ctx.cwd, `release-${wave}`), "ready");
|
|
21
|
+
for (let i = 0; i < 1000; i++) {
|
|
22
|
+
if ([0, 1].every((job) => existsSync(join(ctx.cwd, `exited-${wave}-${job}`)))) {
|
|
23
|
+
// Exit markers precede process exit. Let the native shell backend settle.
|
|
24
|
+
await delay(100);
|
|
25
|
+
if (wave === 1) finished = true;
|
|
26
|
+
return { content: [{ type: "text", text: "Synchronous subagent returned; shell wave finished." }], details: undefined };
|
|
24
27
|
}
|
|
25
|
-
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
for (let i = 0; i < 2; i++) await ctx.executeTool("background_task", {
|
|
29
|
-
action: "start", command: "printf 'second wave\\n'; exit 7", description: `second wave ${i}`, timeout: 10,
|
|
30
|
-
});
|
|
31
|
-
const tasks = await wait();
|
|
32
|
-
for (const task of tasks.slice(0, reads)) await ctx.executeTool("background_task", { action: "output", id: task.id });
|
|
33
|
-
record({ event: "returned", tasks, consumed: tasks.slice(0, reads).map((task: any) => task.id) });
|
|
34
|
-
return { content: [{ type: "text", text: "Synchronous subagent returned; final build report is ready." }], details: undefined };
|
|
28
|
+
await delay(5);
|
|
29
|
+
}
|
|
30
|
+
throw new Error("Fixture shell jobs did not finish");
|
|
35
31
|
},
|
|
36
32
|
});
|
|
33
|
+
pi.on("tool_execution_end", (event) => {
|
|
34
|
+
if (event.toolName !== "background_task") return;
|
|
35
|
+
const data = event.result.structuredContent as any;
|
|
36
|
+
if (data?.task) tasks.set(data.task.id, data.task);
|
|
37
|
+
if (data?.action === "output" && data.task.status !== "running") consumed.push(data.task.id);
|
|
38
|
+
});
|
|
39
|
+
pi.on("context", () => {
|
|
40
|
+
if (finished) {
|
|
41
|
+
record({ event: "returned", tasks: [...tasks.values()], consumed });
|
|
42
|
+
finished = false;
|
|
43
|
+
}
|
|
44
|
+
});
|
|
37
45
|
let requests = 0;
|
|
38
46
|
pi.registerProvider("bg-notifications", {
|
|
39
47
|
name: "Offline notification fixture", baseUrl: "http://127.0.0.1:1", api: "bg-notifications", apiKey: "fixture-not-a-secret",
|
|
@@ -43,21 +51,23 @@ export default function (pi: ExtensionAPI) {
|
|
|
43
51
|
queueMicrotask(() => {
|
|
44
52
|
requests++;
|
|
45
53
|
record({ event: "request", number: requests, messages: context.messages });
|
|
46
|
-
const
|
|
47
|
-
const toolTurn = requests === 1 || (direct && requests === 2);
|
|
48
|
-
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: toolTurn ? "toolUse" : "stop",
|
|
54
|
+
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: requests <= 2 ? "toolUse" : "stop",
|
|
49
55
|
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
50
56
|
stream.push({ type: "start", partial: message });
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
message.content.push({ type: "toolCall", id: "
|
|
57
|
+
if (requests <= 2) {
|
|
58
|
+
// First start a pair to obtain IDs. The second native batch waits, starts
|
|
59
|
+
// another pair, waits again, and reads selected outputs before its boundary.
|
|
60
|
+
const wave = requests - 1;
|
|
61
|
+
if (requests === 2) message.content.push({ type: "toolCall", id: "wait-first-wave", name: "synchronous_subagent_fixture", arguments: { wave: 0 } });
|
|
62
|
+
for (let i = 0; i < 2; i++) message.content.push({ type: "toolCall", id: `start-${wave}-${i}`, name: "background_task", arguments: {
|
|
63
|
+
action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'wave ${wave}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
|
|
64
|
+
} });
|
|
65
|
+
if (requests === 2) {
|
|
66
|
+
if (process.env.BG_NOTIFICATION_MODE === "codemode") message.content.push({ type: "toolCall", id: "wait-second-wave", name: "codemode", arguments: { code: "text(await tools.synchronous_subagent_fixture({ wave: 1 }));" } });
|
|
67
|
+
else message.content.push({ type: "toolCall", id: "wait-second-wave", name: "synchronous_subagent_fixture", arguments: { wave: 1 } });
|
|
68
|
+
// Only first-wave IDs are known to the model before this batch returns.
|
|
69
|
+
const reads = Number(process.env.BG_NOTIFICATION_READS);
|
|
70
|
+
for (const task of [...tasks.values()].slice(0, reads)) message.content.push({ type: "toolCall", id: `read-${task.id}`, name: "background_task", arguments: { action: "output", id: task.id } });
|
|
61
71
|
}
|
|
62
72
|
for (let i = 0; i < message.content.length; i++) {
|
|
63
73
|
stream.push({ type: "toolcall_start", contentIndex: i, partial: message });
|
|
@@ -8,6 +8,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
8
8
|
if (process.env.BG_SMOKE_EVENTS) appendFileSync(process.env.BG_SMOKE_EVENTS, JSON.stringify(entry) + "\n");
|
|
9
9
|
};
|
|
10
10
|
let sequence = 0;
|
|
11
|
+
const tasks = new Map<string, any>();
|
|
11
12
|
const observedNotifications = new Set<string>();
|
|
12
13
|
pi.registerProvider("bg-fixture", {
|
|
13
14
|
name: "Offline background-task fixture", baseUrl: "http://127.0.0.1:1", api: "bg-fixture",
|
|
@@ -18,34 +19,50 @@ export default function (pi: ExtensionAPI) {
|
|
|
18
19
|
queueMicrotask(() => {
|
|
19
20
|
const last = context.messages.at(-1) as any;
|
|
20
21
|
const text = typeof last?.content === "string" ? last.content : (last?.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n");
|
|
22
|
+
const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("Start two background demo jobs"));
|
|
21
23
|
const tools = getCurrentTools(context.messages);
|
|
22
24
|
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
23
25
|
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description });
|
|
24
|
-
|
|
26
|
+
const calls: { name: string; arguments: any }[] = [];
|
|
27
|
+
const call = (args: any) => calls.push({ name: "background_task", arguments: args });
|
|
25
28
|
if (last?.role !== "toolResult") {
|
|
26
|
-
if (text.includes("
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
else if (text.includes("
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
else if (text.includes("SMOKE_LONG"))
|
|
38
|
-
|
|
29
|
+
if (text.includes("Start two background demo jobs")) {
|
|
30
|
+
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
31
|
+
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
32
|
+
} else if (text.includes("SMOKE_START")) {
|
|
33
|
+
call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
|
|
34
|
+
call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
|
|
35
|
+
call({ action: "start", command: "printf third" });
|
|
36
|
+
} else if (text.includes("SMOKE_CANCEL")) {
|
|
37
|
+
call({ action: "cancel", id: tasks.get("Cancel this task").id });
|
|
38
|
+
} else if (text.includes("SMOKE_OUTPUT")) {
|
|
39
|
+
call({ action: "output", id: tasks.get("Release build").id });
|
|
40
|
+
} else if (text.includes("SMOKE_LONG")) {
|
|
41
|
+
call({ action: "start", command: "echo $$ > shell.pid; sleep 300 & echo $! > child.pid; wait", description: "Lifecycle cleanup check", timeout: 300 });
|
|
42
|
+
} else if (text.includes("SMOKE_GUIDANCE")) {
|
|
43
|
+
call({ action: "start", command: "sleep 300", description: "Guidance check", timeout: 300 });
|
|
44
|
+
} else if (text.includes("SMOKE_EXPOSURE")) {
|
|
45
|
+
calls.push({ name: "codemode", arguments: { code: `
|
|
46
|
+
text({ discovered: ALL_TOOLS.some(t => t.name === "background_task"), available: "background_task" in tools });
|
|
47
|
+
try { await tools.background_task({ action: "start", command: "touch should-not-exist" }); text("UNEXPECTED_SUCCESS"); }
|
|
48
|
+
catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
49
|
+
}
|
|
39
50
|
}
|
|
40
|
-
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason:
|
|
51
|
+
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: calls.length ? "toolUse" : "stop",
|
|
41
52
|
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
42
53
|
stream.push({ type: "start", partial: message });
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
54
|
+
if (calls.length) {
|
|
55
|
+
for (const call of calls) {
|
|
56
|
+
const index = message.content.length;
|
|
57
|
+
message.content.push({ type: "toolCall", id: `fixture-${++sequence}`, ...call });
|
|
58
|
+
stream.push({ type: "toolcall_start", contentIndex: index, partial: message });
|
|
59
|
+
stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
|
|
60
|
+
}
|
|
47
61
|
} else {
|
|
48
|
-
const reply = text.includes("[Background task finished]") ?
|
|
62
|
+
const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with /bg." : "BACKGROUND_NOTIFICATION_RECEIVED")
|
|
63
|
+
: media
|
|
64
|
+
? "Both demo jobs are running. Click a task row below to open its live Herdr pane; closing the pane does not stop the job."
|
|
65
|
+
: "Main agent is ready; accepted background tasks keep running.";
|
|
49
66
|
message.content.push({ type: "text", text: reply });
|
|
50
67
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
|
51
68
|
stream.push({ type: "text_delta", contentIndex: 0, delta: reply, partial: message });
|
|
@@ -60,7 +77,12 @@ text({ status: result.task.status, output: result.output });`;
|
|
|
60
77
|
record({ event: "loaded", tools: pi.getAllTools().map((tool) => tool.name) });
|
|
61
78
|
if (ctx.hasUI) ctx.ui.setTitle("Pi Background Tasks Smoke");
|
|
62
79
|
});
|
|
63
|
-
pi.on("
|
|
80
|
+
pi.on("agent_settled", () => record({ event: "settled" }));
|
|
81
|
+
pi.on("tool_execution_end", (event) => {
|
|
82
|
+
const data = event.result.structuredContent as any;
|
|
83
|
+
if (event.toolName === "background_task" && data?.action === "start" && data.task) tasks.set(data.task.description, data.task);
|
|
84
|
+
record({ event: "tool_end", name: event.toolName, isError: event.isError, result: event.result });
|
|
85
|
+
});
|
|
64
86
|
pi.on("context", (_event, ctx) => {
|
|
65
87
|
// Both boundary entries and idle messages are persisted before the provider request.
|
|
66
88
|
// Key by entry ID so two actual notifications for the same tasks remain observable.
|
package/tests/media.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import register from "./fixtures/provider.ts";
|
|
9
|
+
|
|
10
|
+
for (const [kind, marker, code] of [["build", "Compiling module", 0], ["tests", "test_001", 3]]) {
|
|
11
|
+
test(`media ${kind} job streams real output and exits only after its release file`, async () => {
|
|
12
|
+
const root = mkdtempSync(join(tmpdir(), "pi-bg-media-job-"));
|
|
13
|
+
const child = spawn("python3", [fileURLToPath(new URL("./fixtures/media-job.py", import.meta.url)), kind], {
|
|
14
|
+
cwd: root, stdio: ["ignore", "pipe", "pipe"], signal: AbortSignal.timeout(5000),
|
|
15
|
+
});
|
|
16
|
+
let output = "";
|
|
17
|
+
let error = "";
|
|
18
|
+
try {
|
|
19
|
+
const exited = new Promise((resolve, reject) => {
|
|
20
|
+
child.once("error", reject);
|
|
21
|
+
child.stdout.on("data", (data) => {
|
|
22
|
+
output += data.toString();
|
|
23
|
+
if (output.includes(marker)) writeFileSync(join(root, `release-${kind}`), "release");
|
|
24
|
+
});
|
|
25
|
+
child.stderr.on("data", (data) => { error += data.toString(); });
|
|
26
|
+
child.once("close", (exitCode) => resolve(exitCode));
|
|
27
|
+
});
|
|
28
|
+
assert.equal(await exited, code, error);
|
|
29
|
+
assert.ok(output.includes(marker));
|
|
30
|
+
assert.match(output, kind === "build" ? /\rCompiling module.*BUILD SUCCESSFUL/s : /test_001.*one demo failure/s);
|
|
31
|
+
} finally {
|
|
32
|
+
child.kill("SIGKILL");
|
|
33
|
+
rmSync(root, { recursive: true, force: true });
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("offline media provider issues exactly two direct background starts, then returns while they run", async () => {
|
|
39
|
+
let provider;
|
|
40
|
+
register({ registerProvider(_name, value) { provider = value; }, on() {} });
|
|
41
|
+
const user = { role: "user", content: "Start two background demo jobs: build progress and a test suite." };
|
|
42
|
+
const model = { api: "bg-fixture", provider: "bg-fixture", id: "deterministic" };
|
|
43
|
+
const events = [];
|
|
44
|
+
for await (const event of provider.streamSimple(model, { messages: [user] })) events.push(event);
|
|
45
|
+
const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
|
|
46
|
+
assert.deepEqual(calls.map((call) => [call.name, call.arguments.command, call.arguments.description]), [
|
|
47
|
+
["background_task", "python3 demo-job.py build", "Build progress"],
|
|
48
|
+
["background_task", "python3 demo-job.py tests", "Test suite"],
|
|
49
|
+
]);
|
|
50
|
+
const next = [];
|
|
51
|
+
for await (const event of provider.streamSimple(model, { messages: [user, { role: "toolResult", toolCallId: calls[1].id, toolName: "background_task", content: [{ type: "text", text: "Started" }] }] })) next.push(event);
|
|
52
|
+
assert.equal(next.filter((event) => event.type === "toolcall_end").length, 0);
|
|
53
|
+
assert.match(next.find((event) => event.type === "text_end").content, /Click a task row/);
|
|
54
|
+
});
|