@maxiaochao/pi-background-tasks 0.3.0 → 0.3.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 +7 -0
- package/README.md +6 -4
- package/TESTING.md +5 -3
- 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 +2 -2
- package/package.json +1 -1
- package/src/viewer.ts +22 -11
- package/tests/extension.mjs +2 -1
- package/tests/fixtures/provider.ts +8 -3
- package/tests/media.mjs +16 -0
- package/tests/notifications.mjs +2 -1
- package/tests/runtime.mjs +12 -0
- package/tests/viewer.mjs +91 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-11-05 - v0.3.1
|
|
4
|
+
|
|
5
|
+
- Use descriptive task views and clarify captured logs and automatic completion waiting
|
|
6
|
+
- Name Herdr tabs `BG · <task description>` and panes `<number> · <task description>`, following Herdr Subagents. Update the shared tab name on start/watch/completion, retain task numbers across pane reuse/reopening, and print the task name above the command so it is visible with one pane.
|
|
7
|
+
- Clarify in the command parameter that stdout/stderr are saved to a unique per-task log and the path is reported on completion.
|
|
8
|
+
- Tighten the start reminder: when nothing else remains, end the turn instead of sleeping, tailing logs or querying just to wait.
|
|
9
|
+
|
|
3
10
|
## 2026-11-03 - v0.3.0
|
|
4
11
|
|
|
5
12
|
- Report completion status and log paths for progressive inspection with bounded explicit output
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ The tool is fixed to `exposure: "model-only"`: the model calls it directly; Code
|
|
|
41
41
|
|
|
42
42
|
The tool declaration describes automatic completion notifications, concurrency and session lifetime. The action parameter explicitly permits `list` and `output` while tasks are still running. Each accepted start returns only its task data and this short, task-specific reminder:
|
|
43
43
|
|
|
44
|
-
> Completion is reported automatically. Continue other work or end the turn; do not
|
|
44
|
+
> Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.
|
|
45
45
|
|
|
46
46
|
The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
|
|
47
47
|
|
|
@@ -60,7 +60,7 @@ background_task({ action: "cancel", id: "<returned-task-id>" })
|
|
|
60
60
|
|
|
61
61
|
Start returns a running task's ID and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
|
|
62
62
|
|
|
63
|
-
- `command`: unchanged multi-line shell script; only for start.
|
|
63
|
+
- `command`: unchanged multi-line shell script; only for start. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.
|
|
64
64
|
- `description`: optional display label, shortened to 200 characters.
|
|
65
65
|
- `cwd`: optional directory, resolved relative to the current session directory.
|
|
66
66
|
- `timeout`: integer seconds, **1800 by default**, from 1 through 7200. Zero and unlimited mode are rejected.
|
|
@@ -86,10 +86,12 @@ A fixed widget **above the editor** shows each task's ID, status, elapsed time,
|
|
|
86
86
|
|
|
87
87
|
## Herdr task view
|
|
88
88
|
|
|
89
|
-
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one
|
|
89
|
+
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one per-session **BG · <task description>** tab:
|
|
90
90
|
|
|
91
91
|
- The tab is created on the first start without taking focus, and holds at most two panes, one per running task. A new task reuses the pane of a finished one.
|
|
92
|
-
-
|
|
92
|
+
- Like Herdr Subagents, the tab has a descriptive name and panes use numbered task names (`01 · Release build`, `02 · Unit tests`). Starting or watching a task updates the shared tab's name to that task's description. When one task ends, the tab names the remaining running task. Task numbers stay stable when panes are closed, reopened or reused.
|
|
93
|
+
- Each pane prints its numbered task name, the command (`$ ...`), cwd and runtime limit, then follows the task's captured log with `tail -f`. The task name remains visible even when the single-pane layout hides the pane label. Line output and `\r` progress updates appear live. When the task ends, the pane prints a result line such as `[failed · exit 4 · 6s]`.
|
|
94
|
+
- The view follows the tool's captured stdout/stderr, not files chosen by the command. Redirecting all output to another file leaves this log empty. No extra redirection is needed merely to inspect output later; use the reported log path. If an extra copy is required, `set -o pipefail; command 2>&1 | tee <unique-path>` preserves live output and command failures. The copy still counts toward the capture limit.
|
|
93
95
|
- The pane is a **viewer only**. The task runs through the same local backend as outside Herdr, with the same logs, limits, status and notifications. The command has no TTY, so tools that detect one may drop colour or animated progress bars.
|
|
94
96
|
- Closing a pane, or the whole tab, does not cancel the task. Clicking a task row in the widget (Pi 1.4+ fullscreen mode) or `/bg watch <id>` reopens the pane if needed and focuses that tab and pane; use `/bg cancel <id>` to stop the task.
|
|
95
97
|
- When no task runs any more, the tab closes. If the user is looking at it, it closes after focus moves to another tab. Session shutdown, reload and replacement close it immediately, together with the logs.
|
package/TESTING.md
CHANGED
|
@@ -28,6 +28,8 @@ Notification retry tests use the injected clock and session-idle interface. They
|
|
|
28
28
|
|
|
29
29
|
Load-test uses an isolated temporary agent directory, the production extension and an offline fixture provider. It does not access real provider credentials or alter the user's installed packages. From the workspace, `npm --prefix packages/background-tasks run load-test -- --toolkit` loads the complete toolkit directory through its manifest and verifies exactly one background-task tool; the root load-test runs this check too.
|
|
30
30
|
|
|
31
|
+
The deterministic registration test checks the approved per-task-log sentence in the `command` parameter description. The native offline-provider test verifies it is visible in the first model request, before starting a task. Viewer tests check single-task names, shared-tab renaming on start/watch/completion, stable task numbers when the left pane is closed and reopened, and pane reuse.
|
|
32
|
+
|
|
31
33
|
## Real Pi TUI
|
|
32
34
|
|
|
33
35
|
Requires Python 3 with the existing `pexpect` module; process fixtures use Bash, Python and `ps`. The current native-process/TUI suite is verified on Linux.
|
|
@@ -52,8 +54,8 @@ It relays the real PTY output, captures only the test window, then closes it. In
|
|
|
52
54
|
|
|
53
55
|
Run from a Pi or shell inside Herdr (`HERDR_ENV=1`). Start two real tasks through the production extension, for example one `printf 'tick %s\r'` loop that succeeds and one `sleep 6; exit 4` that fails. Check with `herdr tab list`, `herdr pane list` and `herdr pane read`:
|
|
54
56
|
|
|
55
|
-
- One unfocused **
|
|
56
|
-
- Each pane shows the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`).
|
|
57
|
+
- One unfocused **BG · <task description>** tab with two panes while both run. Starting or watching a task updates the tab name; each pane has a numbered task name.
|
|
58
|
+
- Each pane shows its task name above the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`). Check the name is visible with only one pane too.
|
|
57
59
|
- With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
|
|
58
60
|
- In a fullscreen Pi started in its own Herdr pane, an SGR click on each widget task row (`herdr pane send-text <pane> $'\e[<0;10;<row>M\e[<0;10;<row>m'`) focuses the tab and that task's pane (`herdr pane list`).
|
|
59
61
|
- No warning is shown, and the private log directory is removed after session shutdown.
|
|
@@ -74,7 +76,7 @@ git diff --check
|
|
|
74
76
|
|
|
75
77
|
The media command requires the real-TUI screenshot prerequisites above, Pillow, and GStreamer (`ximagesrc`, VP8/WebM encoding/decoding, and PNG encoding). Select the X11 window that already displays a working Herdr client with `HERDR_MEDIA_WINDOW_ID`; the GNOME desktop must be unlocked. The recorder checks the lock state before starting and at each screenshot; hidden windows can return stale pixels.
|
|
76
78
|
|
|
77
|
-
The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
|
|
79
|
+
The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs in sequence. It first verifies the single-pane tab name and visible task header, then adds the second task. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
|
|
78
80
|
|
|
79
81
|
The recorder captures the selected client window continuously, rejects uniform/blank screenshot centres, restores the original workspace/tab, and removes its own workspace. It never starts paid models or copies credentials. `result.json`, tool events and diagnostic frames are stored under `.cache/package-media/background-herdr`. The renderer publishes `docs/screenshot.png` (parent widget), `docs/task-panes.png` (actual task panes), `docs/demo.gif` (frames decoded from the recording), and the complete `docs/demo.webm`. No synthetic UI is drawn.
|
|
80
82
|
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/demo.webm
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
package/docs/task-panes.png
CHANGED
|
Binary file
|
|
@@ -9,7 +9,7 @@ import { HerdrViewer } from "../src/viewer.ts";
|
|
|
9
9
|
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
10
10
|
|
|
11
11
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
12
|
-
const startNotice = "Completion is reported automatically. Continue other work or end the turn; do not
|
|
12
|
+
const startNotice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
13
13
|
// Bound model-visible status text when many completions accumulate.
|
|
14
14
|
const NOTIFICATION_MAX_BYTES = 16 * 1024;
|
|
15
15
|
type Action = typeof actions[number];
|
|
@@ -23,7 +23,7 @@ interface Params {
|
|
|
23
23
|
}
|
|
24
24
|
const Parameters = Type.Object({
|
|
25
25
|
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task. list and output also work while tasks are running." }),
|
|
26
|
-
command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed." })),
|
|
26
|
+
command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion." })),
|
|
27
27
|
description: Type.Optional(Type.String({ description: "Short display label for start" })),
|
|
28
28
|
cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
|
|
29
29
|
timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 7200, description: "Runtime limit for start, in seconds: default 1800 (30 minutes), maximum 7200 (2 hours); no unlimited mode" })),
|
package/package.json
CHANGED
package/src/viewer.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { existsSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { stripVTControlCharacters } from "node:util";
|
|
4
|
-
import { errorText, type TaskSnapshot } from "./background-tasks.ts";
|
|
4
|
+
import { errorText, summary, type TaskSnapshot } from "./background-tasks.ts";
|
|
5
5
|
import { isMissing, type HerdrCall } from "./herdr.ts";
|
|
6
6
|
import { duration } from "./widget.ts";
|
|
7
7
|
|
|
8
|
-
export const TAB_LABEL = "Background tasks";
|
|
9
8
|
const UNFOCUS_POLL_MS = 1000;
|
|
10
9
|
|
|
11
10
|
// Runs inside the pane's own shell. It only reads files; the task itself runs elsewhere.
|
|
@@ -34,6 +33,7 @@ interface Options {
|
|
|
34
33
|
|
|
35
34
|
function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
|
|
36
35
|
function clean(text: string): string { return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); }
|
|
36
|
+
function tabLabel(task: TaskSnapshot): string { return summary(`BG · ${task.description}`, 80); }
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
39
|
* Shows background task logs in one Herdr tab per session. Display only: every failure
|
|
@@ -41,7 +41,7 @@ function clean(text: string): string { return stripVTControlCharacters(text).rep
|
|
|
41
41
|
*/
|
|
42
42
|
export class HerdrViewer {
|
|
43
43
|
private readonly options: Options;
|
|
44
|
-
private readonly commands = new Map<string, string>();
|
|
44
|
+
private readonly commands = new Map<string, { text: string; order: number }>();
|
|
45
45
|
private tab?: string;
|
|
46
46
|
private panes: Pane[] = [];
|
|
47
47
|
private chain: Promise<unknown> = Promise.resolve();
|
|
@@ -58,7 +58,7 @@ export class HerdrViewer {
|
|
|
58
58
|
|
|
59
59
|
/** Opens a pane for a newly started task without taking focus. */
|
|
60
60
|
show(task: TaskSnapshot, command: string): Promise<void> {
|
|
61
|
-
this.commands.set(task.id, command);
|
|
61
|
+
this.commands.set(task.id, { text: command, order: this.commands.size + 1 });
|
|
62
62
|
return this.enqueue(async () => { await this.open(task, false); });
|
|
63
63
|
}
|
|
64
64
|
|
|
@@ -66,7 +66,9 @@ export class HerdrViewer {
|
|
|
66
66
|
watch(task: TaskSnapshot): Promise<string> {
|
|
67
67
|
return this.enqueue(async () => {
|
|
68
68
|
await this.prune();
|
|
69
|
-
const
|
|
69
|
+
const existing = this.panes.find((entry) => entry.task === task.id);
|
|
70
|
+
const pane = existing ?? await this.open(task, false);
|
|
71
|
+
if (existing) await this.options.call(["tab", "rename", this.tab!, tabLabel(task)]);
|
|
70
72
|
await this.options.call(["tab", "focus", this.tab!]);
|
|
71
73
|
// Panes are split left to right; Herdr focuses a pane through its neighbour.
|
|
72
74
|
const index = this.panes.indexOf(pane);
|
|
@@ -82,6 +84,12 @@ export class HerdrViewer {
|
|
|
82
84
|
if (this.disposed) return;
|
|
83
85
|
try { this.writeDone(task); }
|
|
84
86
|
catch (error) { this.report(error); }
|
|
87
|
+
void this.enqueue(async () => {
|
|
88
|
+
const remaining = this.options.tasks().find((task) => task.status === "running");
|
|
89
|
+
if (!this.tab || !remaining) return;
|
|
90
|
+
try { await this.options.call(["tab", "rename", this.tab, tabLabel(remaining)]); }
|
|
91
|
+
catch (error) { if (!isMissing(error)) throw error; }
|
|
92
|
+
});
|
|
85
93
|
this.closeWhenIdle();
|
|
86
94
|
}
|
|
87
95
|
|
|
@@ -119,7 +127,7 @@ export class HerdrViewer {
|
|
|
119
127
|
let pane = this.panes.find((entry) => !running.has(entry.task));
|
|
120
128
|
try {
|
|
121
129
|
if (!this.tab) {
|
|
122
|
-
const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label",
|
|
130
|
+
const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label", tabLabel(task), "--no-focus"]);
|
|
123
131
|
this.tab = created.tab?.tab_id;
|
|
124
132
|
const root = created.root_pane?.pane_id;
|
|
125
133
|
if (!this.tab || !root) throw new Error("herdr tab create omitted the tab or pane id");
|
|
@@ -127,14 +135,17 @@ export class HerdrViewer {
|
|
|
127
135
|
this.panes = [pane];
|
|
128
136
|
} else if (pane) {
|
|
129
137
|
pane.task = task.id;
|
|
138
|
+
await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
|
|
130
139
|
} else {
|
|
131
140
|
const split = await this.options.call(["pane", "split", this.panes.at(-1)!.id, "--direction", "right", "--cwd", task.cwd, "--no-focus"]);
|
|
132
141
|
if (!split.pane?.pane_id) throw new Error("herdr pane split omitted the pane id");
|
|
133
142
|
pane = { id: split.pane.pane_id, task: task.id };
|
|
134
143
|
this.panes.push(pane);
|
|
144
|
+
await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
await this.options.call(["pane", "
|
|
146
|
+
const label = summary(`${String(this.commands.get(task.id)!.order).padStart(2, "0")} · ${task.description}`, 80);
|
|
147
|
+
await this.options.call(["pane", "rename", pane.id, label]);
|
|
148
|
+
await this.options.call(["pane", "run", pane.id, this.viewCommand(task, label)]);
|
|
138
149
|
return pane;
|
|
139
150
|
} catch (error) {
|
|
140
151
|
// The user may close a pane or the whole tab; drop stale handles and retry once.
|
|
@@ -158,13 +169,13 @@ export class HerdrViewer {
|
|
|
158
169
|
await this.options.call(["tab", "close", tab]).catch(() => {});
|
|
159
170
|
}
|
|
160
171
|
|
|
161
|
-
private viewCommand(task: TaskSnapshot): string {
|
|
172
|
+
private viewCommand(task: TaskSnapshot, label: string): string {
|
|
162
173
|
const directory = dirname(task.log_path);
|
|
163
174
|
const script = join(directory, "view.sh");
|
|
164
175
|
const header = join(directory, `${task.id}.header`);
|
|
165
176
|
if (!existsSync(script)) writeFileSync(script, VIEW_SCRIPT, { mode: 0o600 });
|
|
166
|
-
const lines = clean(this.commands.get(task.id)
|
|
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 });
|
|
177
|
+
const lines = clean(this.commands.get(task.id)!.text).split("\n");
|
|
178
|
+
writeFileSync(header, `${label}\n${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
|
|
168
179
|
if (task.status !== "running") this.writeDone(task);
|
|
169
180
|
// The leading space keeps the line out of shell history where HISTCONTROL allows it.
|
|
170
181
|
return ` sh ${[script, task.log_path, this.donePath(task), header].map(quote).join(" ")}`;
|
package/tests/extension.mjs
CHANGED
|
@@ -465,6 +465,7 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
465
465
|
assert.equal(h.tool.exposure, "model-only");
|
|
466
466
|
assert.match(h.tool.description, /up to two concurrent background shell tasks/);
|
|
467
467
|
assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
|
|
468
|
+
assert.equal(h.tool.parameters.properties.command.description, "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.");
|
|
468
469
|
assert.ok(h.tool.description.length < 500);
|
|
469
470
|
assert.equal(h.tool.promptGuidelines, undefined);
|
|
470
471
|
assert.ok(h.tool.outputSchema);
|
|
@@ -482,7 +483,7 @@ test("start keeps only task-specific guidance while the declaration describes li
|
|
|
482
483
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
483
484
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
484
485
|
const { task } = started.structuredContent;
|
|
485
|
-
const notice = "Completion is reported automatically. Continue other work or end the turn; do not
|
|
486
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
486
487
|
assert.equal(task.status, "running");
|
|
487
488
|
assert.ok(started.content[0].text.includes(notice));
|
|
488
489
|
assert.ok(!started.content[0].text.includes(task.log_path));
|
|
@@ -19,16 +19,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
19
19
|
queueMicrotask(() => {
|
|
20
20
|
const last = context.messages.at(-1) as any;
|
|
21
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("
|
|
22
|
+
const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("background demo job"));
|
|
23
23
|
const tools = getCurrentTools(context.messages);
|
|
24
24
|
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
25
|
-
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description
|
|
25
|
+
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description,
|
|
26
|
+
backgroundCommandDescription: tools.find((tool) => tool.name === "background_task")?.parameters?.properties?.command?.description });
|
|
26
27
|
const calls: { name: string; arguments: any }[] = [];
|
|
27
28
|
const call = (args: any) => calls.push({ name: "background_task", arguments: args });
|
|
28
29
|
if (last?.role !== "toolResult") {
|
|
29
30
|
if (text.includes("Start two background demo jobs")) {
|
|
30
31
|
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
31
32
|
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
33
|
+
} else if (text.includes("Start one background demo job")) {
|
|
34
|
+
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
35
|
+
} else if (text.includes("Start the second background demo job")) {
|
|
36
|
+
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
32
37
|
} else if (text.includes("SMOKE_START")) {
|
|
33
38
|
call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
|
|
34
39
|
call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
|
|
@@ -61,7 +66,7 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
|
61
66
|
} else {
|
|
62
67
|
const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with /bg." : "BACKGROUND_NOTIFICATION_RECEIVED")
|
|
63
68
|
: 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
|
|
69
|
+
? `${tasks.size === 1 ? "One demo job is" : "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
70
|
: "Main agent is ready; accepted background tasks keep running.";
|
|
66
71
|
message.content.push({ type: "text", text: reply });
|
|
67
72
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
package/tests/media.mjs
CHANGED
|
@@ -52,3 +52,19 @@ test("offline media provider issues exactly two direct background starts, then r
|
|
|
52
52
|
assert.equal(next.filter((event) => event.type === "toolcall_end").length, 0);
|
|
53
53
|
assert.match(next.find((event) => event.type === "text_end").content, /Click a task row/);
|
|
54
54
|
});
|
|
55
|
+
|
|
56
|
+
for (const [prompt, kind] of [
|
|
57
|
+
["Start one background demo job: build progress.", "build"],
|
|
58
|
+
["Start the second background demo job: a test suite.", "tests"],
|
|
59
|
+
]) {
|
|
60
|
+
test(`offline media provider can start the ${kind} job separately for single-pane verification`, async () => {
|
|
61
|
+
let provider;
|
|
62
|
+
register({ registerProvider(_name, value) { provider = value; }, on() {} });
|
|
63
|
+
const events = [];
|
|
64
|
+
for await (const event of provider.streamSimple({ api: "bg-fixture", provider: "bg-fixture", id: "deterministic" }, { messages: [{ role: "user", content: prompt }] })) events.push(event);
|
|
65
|
+
const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
|
|
66
|
+
assert.equal(calls.length, 1);
|
|
67
|
+
assert.equal(calls[0].name, "background_task");
|
|
68
|
+
assert.equal(calls[0].arguments.command, `python3 demo-job.py ${kind}`);
|
|
69
|
+
});
|
|
70
|
+
}
|
package/tests/notifications.mjs
CHANGED
|
@@ -22,10 +22,11 @@ test("native model receives distinct declaration and start guidance without Code
|
|
|
22
22
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
23
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
24
|
assert.equal(started.isError, false);
|
|
25
|
-
const notice = "Completion is reported automatically. Continue other work or end the turn; do not
|
|
25
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
26
26
|
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
27
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
28
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
|
+
assert.match(requests[0].backgroundCommandDescription, /Stdout\/stderr are saved to a unique per-task log; its path is reported on completion\./);
|
|
29
30
|
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
30
31
|
assert.match(requests[0].backgroundDescription, /session changes, reload, or exit/);
|
|
31
32
|
assert.ok(!requests[0].backgroundDescription.includes(notice));
|
package/tests/runtime.mjs
CHANGED
|
@@ -7,10 +7,22 @@ import { pathToFileURL } from "node:url";
|
|
|
7
7
|
|
|
8
8
|
// npm prepends workspace .bin paths, which may contain an older development Pi.
|
|
9
9
|
const hostPath = (process.env.PATH ?? "").split(delimiter).filter((entry) => !entry.endsWith("node_modules/.bin")).join(delimiter);
|
|
10
|
+
// The managed installer's launcher is a shell script outside the Pi package. Like
|
|
11
|
+
// that launcher, read install/current-version on each run so Pi updates need no change.
|
|
12
|
+
function managedPiModules(launcher) {
|
|
13
|
+
const install = join(dirname(launcher), "..", "install");
|
|
14
|
+
try {
|
|
15
|
+
const version = readFileSync(join(install, "current-version"), "utf8").trim();
|
|
16
|
+
const modules = join(install, "releases", version, "node_modules");
|
|
17
|
+
return existsSync(join(modules, "@earendil-works", "pi-coding-agent", "package.json")) ? modules : undefined;
|
|
18
|
+
} catch { return undefined; }
|
|
19
|
+
}
|
|
10
20
|
const binary = process.env.PI_TEST_BINARY || execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", env: { ...process.env, PATH: hostPath } }).trim();
|
|
11
21
|
let root = dirname(realpathSync(binary));
|
|
12
22
|
while (!existsSync(join(root, "package.json")) || JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name !== "@earendil-works/pi-coding-agent") {
|
|
13
23
|
const parent = dirname(root);
|
|
24
|
+
const managed = parent === root ? managedPiModules(realpathSync(binary)) : undefined;
|
|
25
|
+
if (managed) { root = join(managed, "@earendil-works", "pi-coding-agent"); break; }
|
|
14
26
|
if (parent === root) throw new Error(`Cannot locate Pi runtime next to ${binary}`);
|
|
15
27
|
root = parent;
|
|
16
28
|
}
|
package/tests/viewer.mjs
CHANGED
|
@@ -24,12 +24,13 @@ function fakeHerdr() {
|
|
|
24
24
|
const [noun, verb, id] = args;
|
|
25
25
|
if (noun === "tab" && verb === "create") {
|
|
26
26
|
const tab = `w:t${++next}`, pane = `w:p${++next}`;
|
|
27
|
-
tabs.set(tab,
|
|
27
|
+
tabs.set(tab, { label: args[args.indexOf("--label") + 1] });
|
|
28
28
|
panes.set(pane, { tab, runs: [] });
|
|
29
29
|
return { tab: { tab_id: tab }, root_pane: { pane_id: pane } };
|
|
30
30
|
}
|
|
31
31
|
if (noun === "tab") {
|
|
32
32
|
if (!tabs.has(id)) throw missing("tab", id);
|
|
33
|
+
if (verb === "rename") tabs.get(id).label = args[3];
|
|
33
34
|
if (verb === "close") {
|
|
34
35
|
tabs.delete(id);
|
|
35
36
|
for (const [pane, value] of panes) if (value.tab === id) panes.delete(pane);
|
|
@@ -37,6 +38,7 @@ function fakeHerdr() {
|
|
|
37
38
|
return { tab: { tab_id: id, focused: state.focused } };
|
|
38
39
|
}
|
|
39
40
|
if (!panes.has(id)) throw missing("pane", id);
|
|
41
|
+
if (verb === "rename") panes.get(id).label = args[3];
|
|
40
42
|
if (verb === "split") {
|
|
41
43
|
const pane = `w:p${++next}`;
|
|
42
44
|
panes.set(pane, { tab: panes.get(id).tab, runs: [] });
|
|
@@ -73,7 +75,7 @@ function harness(env = { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w" }) {
|
|
|
73
75
|
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, herdr: herdr.call, env, sleep: () => flush() });
|
|
74
76
|
return {
|
|
75
77
|
...f, herdr, handlers, commands, notices, widgets, ctx,
|
|
76
|
-
start: async (command) => (await tool.execute(command, { action: "start", command })).structuredContent.task,
|
|
78
|
+
start: async (command, description) => (await tool.execute(command, { action: "start", command, description })).structuredContent.task,
|
|
77
79
|
begin: () => handlers.get("session_start")({}, ctx),
|
|
78
80
|
async close() {
|
|
79
81
|
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
@@ -86,6 +88,69 @@ function harness(env = { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w" }) {
|
|
|
86
88
|
|
|
87
89
|
async function settle() { for (let i = 0; i < 20; i++) await flush(); }
|
|
88
90
|
|
|
91
|
+
test("a single task names its tab, pane and visible header; watch and pane reuse update the names", async () => {
|
|
92
|
+
const h = harness();
|
|
93
|
+
try {
|
|
94
|
+
await h.begin();
|
|
95
|
+
const first = await h.start("make release", "Release build");
|
|
96
|
+
await settle();
|
|
97
|
+
const [tab] = h.herdr.tabs.keys();
|
|
98
|
+
const [left] = h.herdr.panes.keys();
|
|
99
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Release build");
|
|
100
|
+
assert.equal(h.herdr.panes.get(left).label, "01 · Release build");
|
|
101
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · Release build\n\$ make release\n/);
|
|
102
|
+
|
|
103
|
+
await h.start("make test", "Unit tests");
|
|
104
|
+
await settle();
|
|
105
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
106
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Unit tests");
|
|
107
|
+
assert.equal([...h.herdr.panes.values()][1].label, "02 · Unit tests");
|
|
108
|
+
await h.commands.get("bg").handler(`watch ${first.id}`, h.ctx);
|
|
109
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Release build");
|
|
110
|
+
assert.equal(h.herdr.panes.get(left).runs.length, 1, "watch must not restart an existing viewer");
|
|
111
|
+
|
|
112
|
+
h.calls[0].resolve();
|
|
113
|
+
await settle();
|
|
114
|
+
const third = await h.start("make lint", "Lint");
|
|
115
|
+
await settle();
|
|
116
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Lint");
|
|
117
|
+
assert.equal(h.herdr.panes.get(left).label, "03 · Lint");
|
|
118
|
+
assert.match(readFileSync(third.log_path.replace(/\.log$/, ".header"), "utf8"), /^03 · Lint\n\$ make lint\n/);
|
|
119
|
+
assert.equal(h.herdr.panes.size, 2);
|
|
120
|
+
} finally { await h.close(); }
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("task numbers survive closing the left pane and reopening it beside another task", async () => {
|
|
124
|
+
const h = harness();
|
|
125
|
+
try {
|
|
126
|
+
await h.begin();
|
|
127
|
+
const first = await h.start("make build", "Build");
|
|
128
|
+
await h.start("make test", "Tests");
|
|
129
|
+
await settle();
|
|
130
|
+
const [left] = h.herdr.panes.keys();
|
|
131
|
+
h.herdr.closePane(left);
|
|
132
|
+
await h.commands.get("bg").handler(`watch ${first.id}`, h.ctx);
|
|
133
|
+
assert.deepEqual([...h.herdr.panes.values()].map((pane) => pane.label), ["02 · Tests", "01 · Build"]);
|
|
134
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · Build\n/);
|
|
135
|
+
} finally { await h.close(); }
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("when the named task finishes, the tab names the remaining running task", async () => {
|
|
139
|
+
const h = harness();
|
|
140
|
+
try {
|
|
141
|
+
await h.begin();
|
|
142
|
+
await h.start("make build", "Build");
|
|
143
|
+
await h.start("make test", "Tests");
|
|
144
|
+
await settle();
|
|
145
|
+
const [tab] = h.herdr.tabs.keys();
|
|
146
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Tests");
|
|
147
|
+
h.calls[1].resolve();
|
|
148
|
+
await settle();
|
|
149
|
+
assert.equal(h.herdr.tabs.get(tab).label, "BG · Build");
|
|
150
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
151
|
+
} finally { await h.close(); }
|
|
152
|
+
});
|
|
153
|
+
|
|
89
154
|
test("two tasks share one unfocused tab, one pane each; the pane shows the command, then the log", async () => {
|
|
90
155
|
const h = harness();
|
|
91
156
|
try {
|
|
@@ -101,7 +166,7 @@ test("two tasks share one unfocused tab, one pane each; the pane shows the comma
|
|
|
101
166
|
const runs = [...h.herdr.panes.values()].map((pane) => pane.runs.at(-1));
|
|
102
167
|
assert.ok(runs[0].includes(first.log_path) && runs[1].includes(second.log_path));
|
|
103
168
|
assert.doesNotMatch(runs.join("\n"), /make test|printf/, "the command text is never passed as shell syntax");
|
|
104
|
-
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"),
|
|
169
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · printf 'a\\n'; sleep 1\n\$ printf 'a\\n'; sleep 1\n# bg-.* · cwd .* · timeout 30m\n/);
|
|
105
170
|
} finally { await h.close(); }
|
|
106
171
|
});
|
|
107
172
|
|
|
@@ -156,6 +221,8 @@ test("closing a pane keeps the task running; /bg watch reopens and focuses it",
|
|
|
156
221
|
assert.equal(h.herdr.tabs.size, 1);
|
|
157
222
|
assert.equal(h.herdr.panes.size, 1);
|
|
158
223
|
assert.ok([...h.herdr.panes.values()][0].runs.at(-1).includes(task.log_path));
|
|
224
|
+
assert.equal([...h.herdr.tabs.values()][0].label, "BG · one");
|
|
225
|
+
assert.equal([...h.herdr.panes.values()][0].label, "01 · one");
|
|
159
226
|
assert.ok(h.herdr.calls.some((args) => args[0] === "tab" && args[1] === "focus"));
|
|
160
227
|
assert.deepEqual(h.notices, []);
|
|
161
228
|
} finally { await h.close(); }
|
|
@@ -190,6 +257,27 @@ test("clicking a widget task row opens its view and focuses the tab; other click
|
|
|
190
257
|
} finally { await h.close(); }
|
|
191
258
|
});
|
|
192
259
|
|
|
260
|
+
test("completion after the user closes the tab does not consume the warning for real Herdr failures", async () => {
|
|
261
|
+
const h = harness();
|
|
262
|
+
try {
|
|
263
|
+
await h.begin();
|
|
264
|
+
await h.start("one");
|
|
265
|
+
await h.start("two");
|
|
266
|
+
await settle();
|
|
267
|
+
const [tab] = h.herdr.tabs.keys();
|
|
268
|
+
await h.herdr.call(["tab", "close", tab]);
|
|
269
|
+
h.calls[0].resolve();
|
|
270
|
+
await settle();
|
|
271
|
+
assert.deepEqual(h.notices, [], "closing a view is not a Herdr failure");
|
|
272
|
+
assert.equal(h.calls[1].signal.aborted, false);
|
|
273
|
+
h.herdr.state.fail = () => true;
|
|
274
|
+
await h.start("three");
|
|
275
|
+
await settle();
|
|
276
|
+
assert.equal(h.notices.length, 1, "a later real failure still warns");
|
|
277
|
+
assert.equal(h.notices[0].level, "warning");
|
|
278
|
+
} finally { await h.close(); }
|
|
279
|
+
});
|
|
280
|
+
|
|
193
281
|
test("Herdr failures warn once and never affect tasks", async () => {
|
|
194
282
|
const h = harness();
|
|
195
283
|
try {
|