@maxiaochao/pi-background-tasks 0.1.2 → 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 +8 -0
- package/README.md +24 -3
- package/TESTING.md +20 -2
- 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 +43 -8
- 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 +1 -1
- package/tests/fixtures/media-job.py +22 -0
- package/tests/fixtures/provider.ts +9 -2
- package/tests/media.mjs +54 -0
- package/tests/tui-smoke.py +1 -0
- package/tests/viewer.mjs +252 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-10-29 - v0.2.0
|
|
4
|
+
|
|
5
|
+
- Add live read-only Herdr task views, exact widget navigation and real two-task terminal media
|
|
6
|
+
- Re-record the real Pi/Herdr walkthrough with two live jobs, widget-row clicks focusing each pane, command headers, streaming progress, terminal results and automatic tab cleanup. Publish parent/task-pane screenshots, an animated GIF and the full WebM; use isolated offline fixtures without credentials.
|
|
7
|
+
- Inside Herdr, show each background task in a read-only pane of one per-session **Background tasks** tab: command header, live log via `tail -f`, and a final result line. Execution, logs, limits and notifications are unchanged.
|
|
8
|
+
- Open the tab without focus on the first start, reuse finished panes, and close the tab when no task runs, waiting while the user looks at it. Close it immediately on session shutdown, reload and replacement.
|
|
9
|
+
- Add `/bg watch <id>`, and in fullscreen mode a click on a widget task row, to reopen a closed pane and focus that task's pane. Closing a pane never cancels its task. Herdr subagent children and non-Herdr sessions open no view; Herdr failures warn once and leave tasks running.
|
|
10
|
+
|
|
3
11
|
## 2026-10-26 - v0.1.2
|
|
4
12
|
|
|
5
13
|
- restrict background tasks to model-only and use concise automatic-notification guidance
|
package/README.md
CHANGED
|
@@ -2,15 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
Run shell commands in the background, then notify the main agent when they finish. These are local processes, not subagents.
|
|
4
4
|
|
|
5
|
-

|
|
6
6
|
|
|
7
|
-

|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
[Watch the full recording (WebM)](docs/demo.webm).
|
|
12
|
+
|
|
13
|
+
The recording uses an offline fixture provider to start two real local demo jobs: an in-place build counter and a streaming test log. It captures the production extension in a real Pi TUI and a temporary Herdr workspace, including clicks on both widget rows, the exact pane focus, success/failure results, and automatic tab cleanup. No paid model or user credentials are used.
|
|
8
14
|
|
|
9
15
|
## Why
|
|
10
16
|
|
|
11
17
|
A command such as `sleep 60; python3 ...` can spend most of its time waiting to check a build log. A normal Bash call keeps waiting for that command. This package returns a task ID immediately so the main agent can do other work.
|
|
12
18
|
|
|
13
|
-
It uses Pi's public `createLocalBashOperations()` backend for shell execution and process-group cancellation. It adds session ownership, bounded logs, status, and completion messages. It neither replaces Bash nor starts another model
|
|
19
|
+
It uses Pi's public `createLocalBashOperations()` backend for shell execution and process-group cancellation. It adds session ownership, bounded logs, status, and completion messages. It neither replaces Bash nor starts another model. Inside Herdr, it also opens a read-only pane per task so the user can watch the command and its live output; the command still runs locally, not in that pane.
|
|
14
20
|
|
|
15
21
|
Completion delivery follows [oh-my-pi's yield-queue approach](https://github.com/can1357/oh-my-pi/blob/3a2758b68f7c8e6bdf22c3a76b86c8675e5e0c9e/packages/coding-agent/src/session/yield-queue.ts): retain results, combine them at a safe boundary, and filter consumed results before delivery. This package uses Pi's public extension API, not patched host code; a local idle retry covers busy operations that expose no final agent boundary.
|
|
16
22
|
|
|
@@ -69,12 +75,27 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
|
|
|
69
75
|
/bg list
|
|
70
76
|
/bg output <returned-task-id>
|
|
71
77
|
/bg cancel <returned-task-id>
|
|
78
|
+
/bg watch <returned-task-id>
|
|
72
79
|
```
|
|
73
80
|
|
|
74
81
|
The commands inspect the same jobs without asking a model to perform the operation. Start a command through the agent tool; there is no second shell parser in `/bg`.
|
|
75
82
|
|
|
76
83
|
A fixed widget **above the editor** shows each task's ID, status, elapsed time, runtime limit and description. It coexists with Scheduler, Todo, and Herdr widgets. Finished rows remain for five seconds; hiding a row does not delete its record. RPC gets a compact active count; non-interactive tools work without the widget.
|
|
77
84
|
|
|
85
|
+
## Herdr task view
|
|
86
|
+
|
|
87
|
+
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one **Background tasks** tab:
|
|
88
|
+
|
|
89
|
+
- 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.
|
|
90
|
+
- Each pane prints the command (`$ ...`), cwd and runtime limit, then follows the task's captured log with `tail -f`. Line output and `\r` progress updates appear live. When the task ends, the pane prints a result line such as `[failed · exit 4 · 6s]`.
|
|
91
|
+
- 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.
|
|
92
|
+
- 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.
|
|
93
|
+
- 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.
|
|
94
|
+
- Herdr subagent children (`PI_HERDR_SUBAGENTS_CHILD=1`) open no view; their tasks remain visible in the child's own widget. RPC and print modes open no view either.
|
|
95
|
+
- A failed Herdr call shows one warning. Tasks keep running and the widget stays current.
|
|
96
|
+
|
|
97
|
+
There is no setting to turn the view off.
|
|
98
|
+
|
|
78
99
|
Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
|
|
79
100
|
|
|
80
101
|
- While the main agent is busy, completions are combined into one message after the current tool batch returns, before the next model request. This includes waiting for a synchronous Herdr subagent; it does not cancel or interrupt that subagent.
|
package/TESTING.md
CHANGED
|
@@ -14,6 +14,8 @@ Tests use Node's built-in test runner. They resolve host peers from the installe
|
|
|
14
14
|
- `output.mjs`: compares both output views with the real host Bash tool. Covers line/byte limits, long lines, empty output, missing final newline, UTF-8 split across chunks, invalid UTF-8 and logs larger than 1 MiB.
|
|
15
15
|
- `processes.mjs`: the native backend, a multi-line Python log check, non-blocking concurrency, PID-observed process-tree cleanup, silent busy-loop timeout and the default 32 MiB disk limit.
|
|
16
16
|
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, command parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, no output in notifications, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks fixed `model-only` exposure and the concise English startup guidance in both return paths and the tool description; verifies 24-hour retention after an interrupt, output consumption while stopped, custom-wake isolation and restoration of automatic delivery by a new user-message run.
|
|
17
|
+
- `viewer.mjs`: the Herdr task view with an in-memory Herdr CLI. One unfocused tab with one pane per running task, command header and log paths passed as arguments (never command text as shell syntax), result line, pane reuse, tab closing after the last task and after focus moves away, user-closed panes not cancelling tasks, `/bg watch` and widget-row clicks reopening and focusing the right pane, one warning for Herdr failures, immediate close on shutdown, and no Herdr calls outside Herdr or in subagent children. Also runs the real view script against a log file. `extension.mjs` and `tui-smoke.py` run without Herdr so their widget assertions stay independent of the host terminal.
|
|
18
|
+
- `media.mjs`: actual demo Python jobs stream in-place/line output and exit with 0/3 only after explicit release files; the offline provider issues exactly two direct starts, then returns without polling. This tests the fixtures used by the real recorder, not an invented screen.
|
|
17
19
|
- `notifications.mjs`: isolated real Pi with model-issued background calls, default one-at-a-time queues and an offline provider. Sequential blocking fixtures hold one native tool batch open across two waves of actual failing shell jobs. The blocking fixture runs directly or through native Codemode, but background calls always come from the model. The next model request gets one merged notification for four completions, excluding zero, one or two first-wave terminal outputs read directly by the model before the boundary; no extra requests follow the final report. Complete pending-batch consumption remains covered by the deterministic extension tests. Also verifies that the model receives the English guidance without a Codemode suffix, and that native Codemode cannot discover or call `background_task`. The blocking tool is a fixture, not a real Herdr child. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
|
|
18
20
|
- `compaction.mjs`: isolated native Pi SDK sessions call `session.compact()`, the same manual-compaction entry point used by `/compact` and RPC. Real shell jobs exit during a held offline summary request. Covers successful native compaction, a provider summary error and `abortCompaction()` cancellation; each must retain the pending completion while busy and automatically deliver it once afterward, without another user prompt. Checks actual compaction lifecycle/events, saved compaction entries, completion timestamps/logs and exactly one automatic conversation request. Uses real timers and native `isIdle`/`isCompacting`, not injected busy state or replacement compaction results; no paid model call or TUI keyboard invocation of `/compact`. `BG_TEST_EXTENSION` also supports a negative-control extension.
|
|
19
21
|
- `interruptions.mjs`: isolated native Pi SDK sessions call the real `session.abort()` while a foreground tool is held. A real shell finishes before or after the interrupt; terminal timestamps verify the ordering. Native `agent_settled.aborted` must confirm the stop; no completion may start another model request. A new user prompt sees the retained completion in its first request, reads the real failed task's output, and finishes without duplicate delivery or extension errors. A third case starts actual manual compaction while the foreground tool is held: Pi itself interrupts the active agent, which must stay stopped even after compaction and background completion. The public abort event has no reason field, so the extension preserves this native interruption rather than guessing its source. `BG_TEST_EXTENSION` supports a negative control without interrupt suppression.
|
|
@@ -44,12 +46,22 @@ gnome-terminal.real --wait --window --title='Pi Background Tasks Smoke' --geomet
|
|
|
44
46
|
|
|
45
47
|
It relays the real PTY output, captures only the test window, then closes it. Inspect the running, completed and history screenshots; check the widget has disappeared in the last one. Provider decisions are fixtures; tool execution, shell jobs, queues, TUI and cleanup are real.
|
|
46
48
|
|
|
49
|
+
## Real Herdr view
|
|
50
|
+
|
|
51
|
+
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`:
|
|
52
|
+
|
|
53
|
+
- One unfocused **Background tasks** tab with two panes while both run.
|
|
54
|
+
- Each pane shows the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`).
|
|
55
|
+
- With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
|
|
56
|
+
- 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`).
|
|
57
|
+
- No warning is shown, and the private log directory is removed after session shutdown.
|
|
58
|
+
|
|
47
59
|
For the original delayed-check scenario, also run one 60-second sleep + Python heredoc check against temporary build log/exit files. The normal regression uses a one-second delay to keep the suite short.
|
|
48
60
|
|
|
49
61
|
## Media and workspace checks
|
|
50
62
|
|
|
51
63
|
```bash
|
|
52
|
-
node scripts/capture-package-media.mjs background-tasks
|
|
64
|
+
HERDR_MEDIA_WINDOW_ID=<visible-herdr-window-id> node scripts/capture-package-media.mjs background-tasks
|
|
53
65
|
node tests/package-layout.mjs
|
|
54
66
|
node tests/release-check.mjs
|
|
55
67
|
npm test
|
|
@@ -58,6 +70,12 @@ npm pack --dry-run
|
|
|
58
70
|
git diff --check
|
|
59
71
|
```
|
|
60
72
|
|
|
61
|
-
The media command requires the real-TUI screenshot prerequisites above,
|
|
73
|
+
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.
|
|
74
|
+
|
|
75
|
+
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.
|
|
76
|
+
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
Inspect both screenshots, the GIF and actual video playback through `docs/package-media-gallery.html` with Chrome. Check the click transitions and final parent view, not only media decoding. The root tarball must include all four media files under `packages/background-tasks/docs/`; the root default loadout must enable its extension exactly once. The standalone tarball remains independently loadable.
|
|
62
80
|
|
|
63
81
|
Record actual checks and any missing prerequisites in `docs/verification.md`. A missing GUI, skipped browser check or unavailable Pi does not count as a successful end-to-end verification.
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/demo.webm
ADDED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
|
Binary file
|
|
@@ -4,6 +4,8 @@ import { Text } from "@earendil-works/pi-tui";
|
|
|
4
4
|
import { stripVTControlCharacters } from "node:util";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import { BackgroundTasks, errorText, summary, systemClock, type Clock, type TaskSnapshot } from "../src/background-tasks.ts";
|
|
7
|
+
import { cliHerdr, type HerdrCall } from "../src/herdr.ts";
|
|
8
|
+
import { HerdrViewer } from "../src/viewer.ts";
|
|
7
9
|
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
8
10
|
|
|
9
11
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
@@ -51,14 +53,20 @@ function validate(params: Params): void {
|
|
|
51
53
|
function formatTask(task: TaskSnapshot): string {
|
|
52
54
|
return `${task.id} · ${task.status} · ${duration(task.elapsed_seconds)} / ${duration(task.timeout)}${task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`} · ${JSON.stringify(task.description)}`;
|
|
53
55
|
}
|
|
54
|
-
function parseCommand(input: string): Params {
|
|
56
|
+
function parseCommand(input: string): Params | { action: "watch"; id: string } {
|
|
55
57
|
const parts = input.trim().split(/\s+/).filter(Boolean);
|
|
56
58
|
if (parts.length === 0 || (parts.length === 1 && parts[0] === "list")) return { action: "list" };
|
|
57
|
-
if (parts.length === 2 && (parts[0] === "output" || parts[0] === "cancel")) return { action: parts[0], id: parts[1] };
|
|
58
|
-
throw new Error("usage: /bg [list | output <id> | cancel <id>]");
|
|
59
|
+
if (parts.length === 2 && (parts[0] === "output" || parts[0] === "cancel" || parts[0] === "watch")) return { action: parts[0], id: parts[1] };
|
|
60
|
+
throw new Error("usage: /bg [list | output <id> | cancel <id> | watch <id>]");
|
|
59
61
|
}
|
|
60
62
|
|
|
61
|
-
|
|
63
|
+
/** Herdr panes are a view for the user's own Pi session; subagent children keep only their widget. */
|
|
64
|
+
function herdrWorkspace(env: NodeJS.ProcessEnv): string | undefined {
|
|
65
|
+
if (env.HERDR_ENV !== "1" || env.PI_HERDR_SUBAGENTS_CHILD === "1") return;
|
|
66
|
+
return env.HERDR_WORKSPACE_ID?.trim() || undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string; herdr?: HerdrCall; env?: NodeJS.ProcessEnv; sleep?: (ms: number) => Promise<void> } = {}) {
|
|
62
70
|
const clock = dependencies.clock ?? systemClock;
|
|
63
71
|
let manager: BackgroundTasks | undefined;
|
|
64
72
|
let context: ExtensionContext | undefined;
|
|
@@ -69,6 +77,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
69
77
|
let interrupted = false;
|
|
70
78
|
const pending = new Map<string, TaskSnapshot>();
|
|
71
79
|
let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
|
|
80
|
+
let viewer: HerdrViewer | undefined;
|
|
72
81
|
|
|
73
82
|
const clearNotificationTimer = () => {
|
|
74
83
|
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
@@ -136,6 +145,11 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
136
145
|
if (!event.aborted && completedNormally) scheduleNotification();
|
|
137
146
|
});
|
|
138
147
|
|
|
148
|
+
const watch = (id: string) => {
|
|
149
|
+
const current = context;
|
|
150
|
+
if (!manager || !viewer || !current) return;
|
|
151
|
+
viewer.watch(manager.get(id)).catch((error) => current.ui.notify(`Cannot show task ${id}: ${errorText(error)}`, "error"));
|
|
152
|
+
};
|
|
139
153
|
const clearTimer = () => {
|
|
140
154
|
if (timer !== undefined) clock.clearTimeout(timer);
|
|
141
155
|
timer = undefined;
|
|
@@ -162,7 +176,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
162
176
|
mounted.tui.requestRender();
|
|
163
177
|
} else {
|
|
164
178
|
context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
|
|
165
|
-
const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme);
|
|
179
|
+
const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, viewer ? watch : undefined);
|
|
166
180
|
mounted = { widget, tui };
|
|
167
181
|
return widget;
|
|
168
182
|
}, { placement: "aboveEditor" });
|
|
@@ -176,8 +190,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
176
190
|
generation++;
|
|
177
191
|
const previous = manager;
|
|
178
192
|
const previousContext = context;
|
|
193
|
+
const previousViewer = viewer;
|
|
179
194
|
manager = undefined;
|
|
180
195
|
context = undefined;
|
|
196
|
+
viewer = undefined;
|
|
181
197
|
clearTimer();
|
|
182
198
|
clearNotificationTimer();
|
|
183
199
|
pending.clear();
|
|
@@ -189,17 +205,27 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
189
205
|
if (previousContext.mode === "tui") previousContext.ui.setWidget(WIDGET_KEY, undefined);
|
|
190
206
|
}
|
|
191
207
|
mounted = undefined;
|
|
192
|
-
} finally {
|
|
208
|
+
} finally {
|
|
209
|
+
// Cancel tasks first and synchronously; closing the view tab must not delay that.
|
|
210
|
+
await Promise.all([previous?.shutdown(), previousViewer?.dispose()]);
|
|
211
|
+
}
|
|
193
212
|
};
|
|
194
213
|
pi.on("session_start", async (_event, ctx) => {
|
|
195
214
|
await dispose();
|
|
196
215
|
context = ctx;
|
|
197
216
|
const epoch = generation;
|
|
217
|
+
const workspaceId = ctx.mode === "tui" && ctx.hasUI ? herdrWorkspace(dependencies.env ?? process.env) : undefined;
|
|
218
|
+
viewer = workspaceId ? new HerdrViewer({
|
|
219
|
+
call: dependencies.herdr ?? cliHerdr(), workspaceId, sleep: dependencies.sleep,
|
|
220
|
+
tasks: () => manager?.list().tasks ?? [],
|
|
221
|
+
warn: (message) => { if (generation === epoch) ctx.ui.notify(message, "warning"); },
|
|
222
|
+
}) : undefined;
|
|
198
223
|
manager = new BackgroundTasks({
|
|
199
224
|
operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
|
|
200
225
|
onChange() { if (generation === epoch) refresh(); },
|
|
201
226
|
onComplete(task) {
|
|
202
227
|
if (generation !== epoch || !context) return;
|
|
228
|
+
viewer?.finished(task);
|
|
203
229
|
pending.set(task.id, task);
|
|
204
230
|
scheduleNotification();
|
|
205
231
|
},
|
|
@@ -212,6 +238,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
212
238
|
if (!manager) throw new Error("Background tasks session is not ready");
|
|
213
239
|
if (params.action === "start") {
|
|
214
240
|
const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
|
|
241
|
+
void viewer?.show(task, params.command!);
|
|
215
242
|
return {
|
|
216
243
|
text: `Started ${formatTask(task)}\n${startGuidance}\nLog: ${task.log_path}\nAt most 2 tasks run at once. Tasks stop on session changes, reload, or exit; captured logs are then removed.`,
|
|
217
244
|
data: { action: params.action, task, guidance: startGuidance }, details: { action: params.action, task }, isError: false,
|
|
@@ -270,10 +297,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
270
297
|
},
|
|
271
298
|
});
|
|
272
299
|
pi.registerCommand("bg", {
|
|
273
|
-
description: "List background shell tasks, read output,
|
|
300
|
+
description: "List background shell tasks, read output, cancel a task, or watch it in Herdr",
|
|
274
301
|
handler: async (args, ctx) => {
|
|
275
302
|
try {
|
|
276
|
-
const
|
|
303
|
+
const params = parseCommand(args);
|
|
304
|
+
if (params.action === "watch") {
|
|
305
|
+
if (!manager) throw new Error("Background tasks session is not ready");
|
|
306
|
+
const task = manager.get(params.id);
|
|
307
|
+
if (!viewer) throw new Error("/bg watch needs this Pi session to run inside Herdr");
|
|
308
|
+
await viewer.watch(task);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const result = await perform(params, ctx.cwd);
|
|
277
312
|
pi.sendMessage({ customType: "background-task-inspect", content: result.text, display: true, details: result.details }, { triggerTurn: false });
|
|
278
313
|
} catch (error) { ctx.ui.notify(errorText(error), "error"); }
|
|
279
314
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Session-scoped background shell tasks with completion notifications for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"typebox": "*"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
|
-
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs tests/notifications.mjs tests/compaction.mjs tests/interruptions.mjs",
|
|
37
|
+
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs tests/notifications.mjs tests/compaction.mjs tests/interruptions.mjs tests/viewer.mjs tests/media.mjs",
|
|
38
38
|
"load-test": "node --experimental-strip-types tests/load.mjs"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
package/src/herdr.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/** One Herdr CLI call: arguments in, parsed `result` object out. */
|
|
4
|
+
export type HerdrCall = (args: string[]) => Promise<Record<string, any>>;
|
|
5
|
+
|
|
6
|
+
export class HerdrError extends Error {
|
|
7
|
+
readonly code?: string;
|
|
8
|
+
constructor(message: string, code?: string) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "HerdrError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isMissing(error: unknown): boolean {
|
|
16
|
+
return error instanceof HerdrError && /^(tab|pane)_not_found$/.test(error.code ?? "");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Spawns the Herdr CLI without a shell. A hung call fails after `timeoutMs`. */
|
|
20
|
+
export function cliHerdr(binary = "herdr", timeoutMs = 10_000): HerdrCall {
|
|
21
|
+
return (args) => new Promise((resolve, reject) => {
|
|
22
|
+
let stdout = "";
|
|
23
|
+
let stderr = "";
|
|
24
|
+
const child = spawn(binary, args, { stdio: ["ignore", "pipe", "pipe"], shell: false, signal: AbortSignal.timeout(timeoutMs) });
|
|
25
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
26
|
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
27
|
+
child.once("error", (error) => reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${error.message}`)));
|
|
28
|
+
child.once("close", (code) => {
|
|
29
|
+
let parsed: { result?: Record<string, any>; error?: { code?: string; message?: string } } | undefined;
|
|
30
|
+
try { parsed = JSON.parse(stdout); } catch { /* Reported below. */ }
|
|
31
|
+
if (code === 0 && parsed?.result) return resolve(parsed.result);
|
|
32
|
+
// Some commands, such as `pane run`, succeed without printing a response.
|
|
33
|
+
if (code === 0 && !stdout.trim()) return resolve({});
|
|
34
|
+
const detail = parsed?.error?.message ?? (stderr.trim() || stdout.trim() || `exit code ${code}`);
|
|
35
|
+
reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${detail}`, parsed?.error?.code));
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
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; },
|
|
@@ -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)
|
|
@@ -19,13 +19,17 @@ 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("Start two background demo jobs"));
|
|
22
23
|
const tools = getCurrentTools(context.messages);
|
|
23
24
|
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
24
25
|
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description });
|
|
25
26
|
const calls: { name: string; arguments: any }[] = [];
|
|
26
27
|
const call = (args: any) => calls.push({ name: "background_task", arguments: args });
|
|
27
28
|
if (last?.role !== "toolResult") {
|
|
28
|
-
if (text.includes("
|
|
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")) {
|
|
29
33
|
call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
|
|
30
34
|
call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
|
|
31
35
|
call({ action: "start", command: "printf third" });
|
|
@@ -55,7 +59,10 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
|
55
59
|
stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
|
|
56
60
|
}
|
|
57
61
|
} else {
|
|
58
|
-
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.";
|
|
59
66
|
message.content.push({ type: "text", text: reply });
|
|
60
67
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
|
61
68
|
stream.push({ type: "text_delta", contentIndex: 0, delta: reply, partial: message });
|
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
|
+
});
|
package/tests/tui-smoke.py
CHANGED
|
@@ -28,6 +28,7 @@ render = os.environ.get('BG_SMOKE_RENDER') == '1'
|
|
|
28
28
|
capture = os.environ.get('BG_SMOKE_CAPTURE') == '1'
|
|
29
29
|
env = dict(os.environ, PI_CODING_AGENT_DIR=str(work), PI_OFFLINE='1', BG_SMOKE_EVENTS=str(events_path), TERM='xterm-256color', COLORTERM='truecolor')
|
|
30
30
|
env.pop('PI_HERDR_SUBAGENTS_CHILD', None)
|
|
31
|
+
env.pop('HERDR_ENV', None) # Keep this smoke run's widget-only path; Herdr views are covered by viewer.mjs.
|
|
31
32
|
(work / 'settings.json').write_text(json.dumps({'quietStartup': True}))
|
|
32
33
|
args = ['--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session', '--offline',
|
|
33
34
|
'-e', 'builtin:codemode', '-e', str(PKG / 'extensions/background-tasks.ts'),
|
package/tests/viewer.mjs
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import register from "../extensions/background-tasks.ts";
|
|
9
|
+
import { HerdrError } from "../src/herdr.ts";
|
|
10
|
+
import { VIEW_SCRIPT } from "../src/viewer.ts";
|
|
11
|
+
import { fixture, flush } from "./helpers.mjs";
|
|
12
|
+
|
|
13
|
+
/** In-memory Herdr: records CLI calls and models tabs, panes and focus. */
|
|
14
|
+
function fakeHerdr() {
|
|
15
|
+
const calls = [];
|
|
16
|
+
const tabs = new Map();
|
|
17
|
+
const panes = new Map();
|
|
18
|
+
let next = 0;
|
|
19
|
+
const state = { focused: false, fail: undefined };
|
|
20
|
+
const missing = (kind, id) => new HerdrError(`${kind} ${id} not found`, `${kind}_not_found`);
|
|
21
|
+
const call = async (args) => {
|
|
22
|
+
calls.push(args);
|
|
23
|
+
if (state.fail?.(args)) throw new Error(`herdr ${args.join(" ")} failed`);
|
|
24
|
+
const [noun, verb, id] = args;
|
|
25
|
+
if (noun === "tab" && verb === "create") {
|
|
26
|
+
const tab = `w:t${++next}`, pane = `w:p${++next}`;
|
|
27
|
+
tabs.set(tab, true);
|
|
28
|
+
panes.set(pane, { tab, runs: [] });
|
|
29
|
+
return { tab: { tab_id: tab }, root_pane: { pane_id: pane } };
|
|
30
|
+
}
|
|
31
|
+
if (noun === "tab") {
|
|
32
|
+
if (!tabs.has(id)) throw missing("tab", id);
|
|
33
|
+
if (verb === "close") {
|
|
34
|
+
tabs.delete(id);
|
|
35
|
+
for (const [pane, value] of panes) if (value.tab === id) panes.delete(pane);
|
|
36
|
+
}
|
|
37
|
+
return { tab: { tab_id: id, focused: state.focused } };
|
|
38
|
+
}
|
|
39
|
+
if (!panes.has(id)) throw missing("pane", id);
|
|
40
|
+
if (verb === "split") {
|
|
41
|
+
const pane = `w:p${++next}`;
|
|
42
|
+
panes.set(pane, { tab: panes.get(id).tab, runs: [] });
|
|
43
|
+
return { pane: { pane_id: pane } };
|
|
44
|
+
}
|
|
45
|
+
if (verb === "run") panes.get(id).runs.push(args[3]);
|
|
46
|
+
return { pane: { pane_id: id } };
|
|
47
|
+
};
|
|
48
|
+
return { call, calls, tabs, panes, state, closePane: (id) => panes.delete(id) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function harness(env = { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w" }) {
|
|
52
|
+
const f = fixture();
|
|
53
|
+
const herdr = fakeHerdr();
|
|
54
|
+
const handlers = new Map();
|
|
55
|
+
const commands = new Map();
|
|
56
|
+
const notices = [];
|
|
57
|
+
const widgets = new Map();
|
|
58
|
+
let tool;
|
|
59
|
+
const theme = { fg: (_color, text) => text, bold: (text) => text };
|
|
60
|
+
const ctx = {
|
|
61
|
+
cwd: f.root, mode: "tui", hasUI: true, isIdle: () => true,
|
|
62
|
+
ui: {
|
|
63
|
+
setWidget(key, factory) { if (factory) widgets.set(key, factory({ requestRender() {} }, theme)); else widgets.delete(key); },
|
|
64
|
+
setStatus() {}, notify(message, level) { notices.push({ message, level }); },
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
const pi = {
|
|
68
|
+
on(name, handler) { handlers.set(name, handler); },
|
|
69
|
+
registerTool(value) { tool = value; },
|
|
70
|
+
registerCommand(name, value) { commands.set(name, value); },
|
|
71
|
+
sendMessage() {},
|
|
72
|
+
};
|
|
73
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, herdr: herdr.call, env, sleep: () => flush() });
|
|
74
|
+
return {
|
|
75
|
+
...f, herdr, handlers, commands, notices, widgets, ctx,
|
|
76
|
+
start: async (command) => (await tool.execute(command, { action: "start", command })).structuredContent.task,
|
|
77
|
+
begin: () => handlers.get("session_start")({}, ctx),
|
|
78
|
+
async close() {
|
|
79
|
+
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
80
|
+
for (const call of f.calls) call.resolve();
|
|
81
|
+
await closing;
|
|
82
|
+
await f.close();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function settle() { for (let i = 0; i < 20; i++) await flush(); }
|
|
88
|
+
|
|
89
|
+
test("two tasks share one unfocused tab, one pane each; the pane shows the command, then the log", async () => {
|
|
90
|
+
const h = harness();
|
|
91
|
+
try {
|
|
92
|
+
await h.begin();
|
|
93
|
+
const first = await h.start("printf 'a\\n'; sleep 1");
|
|
94
|
+
const second = await h.start("make test");
|
|
95
|
+
await settle();
|
|
96
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
97
|
+
assert.equal(h.herdr.panes.size, 2);
|
|
98
|
+
const create = h.herdr.calls.find((args) => args[0] === "tab" && args[1] === "create");
|
|
99
|
+
assert.ok(create.includes("--no-focus"));
|
|
100
|
+
assert.ok(h.herdr.calls.filter((args) => args[1] === "split").every((args) => args.includes("--no-focus")));
|
|
101
|
+
const runs = [...h.herdr.panes.values()].map((pane) => pane.runs.at(-1));
|
|
102
|
+
assert.ok(runs[0].includes(first.log_path) && runs[1].includes(second.log_path));
|
|
103
|
+
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"), /^\$ printf 'a\\n'; sleep 1\n# bg-.* · cwd .* · timeout 30m\n/);
|
|
105
|
+
} finally { await h.close(); }
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("a finished task's pane shows the result, is reused, and the tab closes once nothing runs", async () => {
|
|
109
|
+
const h = harness();
|
|
110
|
+
try {
|
|
111
|
+
await h.begin();
|
|
112
|
+
const first = await h.start("one");
|
|
113
|
+
await h.start("two");
|
|
114
|
+
await settle();
|
|
115
|
+
h.calls[0].resolve(3);
|
|
116
|
+
await settle();
|
|
117
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".done"), "utf8"), /\[failed · exit 3 · 0s\]/);
|
|
118
|
+
assert.equal(h.herdr.tabs.size, 1, "the tab stays while a task still runs");
|
|
119
|
+
const third = await h.start("three");
|
|
120
|
+
await settle();
|
|
121
|
+
assert.equal(h.herdr.panes.size, 2, "the finished task's pane is reused");
|
|
122
|
+
assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(third.log_path)));
|
|
123
|
+
h.calls[1].resolve();
|
|
124
|
+
h.calls[2].resolve();
|
|
125
|
+
await settle();
|
|
126
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
127
|
+
} finally { await h.close(); }
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("the tab waits while the user looks at it, then closes after focus moves away", async () => {
|
|
131
|
+
const h = harness();
|
|
132
|
+
try {
|
|
133
|
+
await h.begin();
|
|
134
|
+
await h.start("one");
|
|
135
|
+
await settle();
|
|
136
|
+
h.herdr.state.focused = true;
|
|
137
|
+
h.calls[0].resolve();
|
|
138
|
+
await settle();
|
|
139
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
140
|
+
h.herdr.state.focused = false;
|
|
141
|
+
await settle();
|
|
142
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
143
|
+
} finally { await h.close(); }
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("closing a pane keeps the task running; /bg watch reopens and focuses it", async () => {
|
|
147
|
+
const h = harness();
|
|
148
|
+
try {
|
|
149
|
+
await h.begin();
|
|
150
|
+
const task = await h.start("one");
|
|
151
|
+
await settle();
|
|
152
|
+
h.herdr.closePane([...h.herdr.panes.keys()][0]);
|
|
153
|
+
assert.equal(h.calls[0].signal.aborted, false);
|
|
154
|
+
await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
|
|
155
|
+
await settle();
|
|
156
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
157
|
+
assert.equal(h.herdr.panes.size, 1);
|
|
158
|
+
assert.ok([...h.herdr.panes.values()][0].runs.at(-1).includes(task.log_path));
|
|
159
|
+
assert.ok(h.herdr.calls.some((args) => args[0] === "tab" && args[1] === "focus"));
|
|
160
|
+
assert.deepEqual(h.notices, []);
|
|
161
|
+
} finally { await h.close(); }
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("clicking a widget task row opens its view and focuses the tab; other clicks do nothing", async () => {
|
|
165
|
+
const h = harness();
|
|
166
|
+
try {
|
|
167
|
+
await h.begin();
|
|
168
|
+
await h.start("one");
|
|
169
|
+
const second = await h.start("two");
|
|
170
|
+
await settle();
|
|
171
|
+
h.herdr.closePane([...h.herdr.panes.keys()][1]);
|
|
172
|
+
const widget = h.widgets.get("background-tasks");
|
|
173
|
+
const lines = widget.render(120);
|
|
174
|
+
assert.match(lines[2], new RegExp(second.id));
|
|
175
|
+
const click = (y, extra = {}) => widget.handleMouse({ type: "click", button: "left", x: 4, y, screenX: 4, screenY: y, width: 120, height: lines.length, shift: false, alt: false, ctrl: false, ...extra });
|
|
176
|
+
assert.equal(click(0), undefined, "the title row is not a task");
|
|
177
|
+
assert.equal(click(2, { button: "right" }), undefined);
|
|
178
|
+
const before = h.herdr.calls.length;
|
|
179
|
+
assert.deepEqual(click(2), { handled: true, render: false });
|
|
180
|
+
await settle();
|
|
181
|
+
assert.ok(h.herdr.calls.length > before);
|
|
182
|
+
assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(second.log_path)), "the closed pane was reopened");
|
|
183
|
+
const [first] = h.herdr.panes.keys();
|
|
184
|
+
assert.deepEqual(h.herdr.calls.at(-2).slice(0, 2), ["tab", "focus"]);
|
|
185
|
+
assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", first, "--direction", "right"], "the reopened right pane gets focus");
|
|
186
|
+
click(1);
|
|
187
|
+
await settle();
|
|
188
|
+
const [, right] = h.herdr.panes.keys();
|
|
189
|
+
assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", right, "--direction", "left"], "the left pane gets focus");
|
|
190
|
+
} finally { await h.close(); }
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("Herdr failures warn once and never affect tasks", async () => {
|
|
194
|
+
const h = harness();
|
|
195
|
+
try {
|
|
196
|
+
await h.begin();
|
|
197
|
+
h.herdr.state.fail = () => true;
|
|
198
|
+
await h.start("one");
|
|
199
|
+
await h.start("two");
|
|
200
|
+
await settle();
|
|
201
|
+
assert.equal(h.notices.length, 1);
|
|
202
|
+
assert.equal(h.notices[0].level, "warning");
|
|
203
|
+
assert.ok(h.calls.every((call) => !call.signal.aborted), "tasks keep running");
|
|
204
|
+
h.calls[0].resolve();
|
|
205
|
+
h.calls[1].resolve();
|
|
206
|
+
await settle();
|
|
207
|
+
assert.equal(h.notices.length, 1, "the warning is shown once");
|
|
208
|
+
} finally { await h.close(); }
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test("session shutdown closes the tab immediately", async () => {
|
|
212
|
+
const h = harness();
|
|
213
|
+
await h.begin();
|
|
214
|
+
await h.start("one");
|
|
215
|
+
await settle();
|
|
216
|
+
h.herdr.state.focused = true;
|
|
217
|
+
await h.close();
|
|
218
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
for (const [label, env] of [
|
|
222
|
+
["outside Herdr", {}],
|
|
223
|
+
["in a Herdr subagent child", { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w", PI_HERDR_SUBAGENTS_CHILD: "1" }],
|
|
224
|
+
]) {
|
|
225
|
+
test(`${label}, no Herdr call is made and /bg watch explains why`, async () => {
|
|
226
|
+
const h = harness(env);
|
|
227
|
+
try {
|
|
228
|
+
await h.begin();
|
|
229
|
+
const task = await h.start("one");
|
|
230
|
+
await settle();
|
|
231
|
+
await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
|
|
232
|
+
const widget = h.widgets.get("background-tasks");
|
|
233
|
+
widget.render(120);
|
|
234
|
+
assert.equal(widget.handleMouse({ type: "click", button: "left", x: 4, y: 1, width: 120, height: 2 }), undefined, "rows are not clickable without a view");
|
|
235
|
+
assert.deepEqual(h.herdr.calls, []);
|
|
236
|
+
assert.match(h.notices[0].message, /inside Herdr/);
|
|
237
|
+
} finally { await h.close(); }
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
test("the view script follows a real log, then prints the result line", async () => {
|
|
242
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-bg-view-"));
|
|
243
|
+
try {
|
|
244
|
+
const [log, done, header, script] = ["t.log", "t.done", "t.header", "view.sh"].map((name) => join(dir, name));
|
|
245
|
+
writeFileSync(log, "line 1\nline 2\n");
|
|
246
|
+
writeFileSync(header, "$ echo hi\n");
|
|
247
|
+
writeFileSync(script, VIEW_SCRIPT);
|
|
248
|
+
setTimeout(() => writeFileSync(done, "\n[succeeded · exit 0 · 1s]\n"), 300);
|
|
249
|
+
const { stdout: output } = await promisify(execFile)("sh", [script, log, done, header], { encoding: "utf8", timeout: 10000 });
|
|
250
|
+
assert.match(output, /\$ echo hi\nline 1\nline 2\n\n\[succeeded · exit 0 · 1s\]\n$/);
|
|
251
|
+
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
252
|
+
});
|