@maxiaochao/pi-background-tasks 0.3.1 → 0.4.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 +15 -0
- package/README.md +18 -34
- package/TESTING.md +16 -22
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/shell-list.png +0 -0
- package/extensions/background-tasks.ts +51 -69
- package/package.json +2 -2
- package/src/background-tasks.ts +5 -0
- package/src/panel.ts +167 -0
- package/src/widget.ts +41 -32
- package/tests/extension.mjs +96 -27
- package/tests/fixtures/provider.ts +3 -3
- package/tests/fixtures/terminal.py +52 -0
- package/tests/load.mjs +1 -0
- package/tests/media.mjs +2 -2
- package/tests/panel.mjs +164 -0
- package/tests/tui-smoke.py +10 -4
- package/docs/demo.webm +0 -0
- package/docs/task-panes.png +0 -0
- package/src/herdr.ts +0 -38
- package/src/viewer.ts +0 -212
- package/tests/viewer.mjs +0 -340
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-11-16 - v0.4.1
|
|
4
|
+
|
|
5
|
+
- Fix bottom-footer shell controls and hide the footer during task inspection
|
|
6
|
+
- Move the clickable shell count to the bottom footer status row, beside editor status when present; preserve Pi's native path, usage and model rendering.
|
|
7
|
+
- Hide the entire footer while the shell list or details panel is open, and restore it on close.
|
|
8
|
+
- Verify bottom-row placement and clean panels with real Chrome clicks, both with and without Codex Edit. Keep capture browsers isolated from existing browser sessions.
|
|
9
|
+
|
|
10
|
+
## 2026-11-13 - v0.4.0
|
|
11
|
+
|
|
12
|
+
- Replace Herdr task views and /bg commands with a local shell counter and details panel
|
|
13
|
+
- Show `1 shell` / `N shells` below the editor. Click or press Alt+J to open local shell details or a selectable list. Align Status, Runtime and Command; refresh a bounded Output tail every second.
|
|
14
|
+
- Support arrows, Enter, Escape, Space and `x` to inspect, return, dismiss and stop without a model call. Keep finished history accessible with Alt+J.
|
|
15
|
+
- Remove all `/bg` commands and Herdr tab/pane creation, log-following processes, focus and cleanup code. Task execution, timeouts, log budgets and completion delivery stay local and unchanged.
|
|
16
|
+
- Replace the retired Herdr suite/media flow with deterministic panel tests and real Pi PTY interaction in Chrome.
|
|
17
|
+
|
|
3
18
|
## 2026-11-05 - v0.3.1
|
|
4
19
|
|
|
5
20
|
- Use descriptive task views and clarify captured logs and automatic completion waiting
|
package/README.md
CHANGED
|
@@ -2,21 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
Run shell commands in the background, then notify the main agent of completion and the captured log location. These are local processes, not subagents.
|
|
4
4
|
|
|
5
|
-

|
|
6
6
|
|
|
7
|
-

|
|
8
8
|
|
|
9
|
-

|
|
10
10
|
|
|
11
|
-
|
|
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.
|
|
11
|
+
The frames come from the production extension in a real Pi PTY, displayed in Chrome with xterm.js. An offline fixture starts two actual local jobs; real browser clicks and keyboard events exercise the UI. No paid model or user credentials are used.
|
|
14
12
|
|
|
15
13
|
## Why
|
|
16
14
|
|
|
17
15
|
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.
|
|
18
16
|
|
|
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.
|
|
17
|
+
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. The shell counter and local details panel follow the compact interaction shown in the supplied reference screenshots. No terminal multiplexer is required.
|
|
20
18
|
|
|
21
19
|
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. Prompt timing is informed by [OMP’s background-start notice](https://github.com/can1357/oh-my-pi/blob/256b3211bca7458391866a8bcc9369902664be55/packages/tui/src/tools/bash.ts#L36-L48), but delivery is deliberately different: this package sends status and log paths only, not OMP-style automatic command-output injection. Agents inspect captured logs progressively when needed.
|
|
22
20
|
|
|
@@ -29,7 +27,7 @@ pi install npm:@maxiaochao/pi-background-tasks
|
|
|
29
27
|
pi update npm:@maxiaochao/pi-background-tasks
|
|
30
28
|
```
|
|
31
29
|
|
|
32
|
-
The complete `@maxiaochao/pi-toolkit` package **bundles and enables Background Tasks by default**. Choose either the toolkit or this standalone package; do not install both, because the tool and
|
|
30
|
+
The complete `@maxiaochao/pi-toolkit` package **bundles and enables Background Tasks by default**. Choose either the toolkit or this standalone package; do not install both, because the tool and shortcut would be registered twice.
|
|
33
31
|
|
|
34
32
|
## Agent tool
|
|
35
33
|
|
|
@@ -51,7 +49,7 @@ Inspect a running or finished task whenever its output is needed; no completion
|
|
|
51
49
|
background_task({ action: "output", id: "<returned-task-id>" })
|
|
52
50
|
```
|
|
53
51
|
|
|
54
|
-
Use `list` to inspect task status at any time, including while tasks are running. These are agent-callable
|
|
52
|
+
Use `list` to inspect task status at any time, including while tasks are running. These actions are agent-callable. Query on demand rather than repeatedly checking just to wait. After completion, use the reported log path to search relevant terms or read selected ranges; avoid loading the entire log by default. The tool also supports cancellation:
|
|
55
53
|
|
|
56
54
|
```text
|
|
57
55
|
background_task({ action: "list" })
|
|
@@ -72,33 +70,19 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
|
|
|
72
70
|
|
|
73
71
|
## User controls and status
|
|
74
72
|
|
|
75
|
-
|
|
76
|
-
/bg
|
|
77
|
-
/bg list
|
|
78
|
-
/bg output <returned-task-id>
|
|
79
|
-
/bg cancel <returned-task-id>
|
|
80
|
-
/bg watch <returned-task-id>
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
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`.
|
|
84
|
-
|
|
85
|
-
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.
|
|
73
|
+
A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status row**, beside `editor: apply_patch` or other extension statuses. Without another status, it occupies that row alone. The existing native path, usage and model rows stay unchanged. Click the count in fullscreen mode, or press **Alt+J** in either terminal mode. One active task opens **Shell details** directly; multiple tasks open **Background**. With no active tasks, Alt+J still opens retained history.
|
|
86
74
|
|
|
87
|
-
|
|
75
|
+
- **List:** ↑/↓ selects a shell, Enter opens its details, and clicking a task row opens that task. Running tasks appear first, followed by **Earlier in this session**. At most eight task rows are visible; selection scrolls the retained history (latest 20 finished tasks).
|
|
76
|
+
- **Details:** `Status:`, `Runtime:` and `Command:` share a fixed value column. Long commands wrap for up to three lines with an ellipsis. **Output:** shows the last ten captured lines, clipped to the current width, refreshed every second. Empty output says `No output available`; truncated tails show the log path for further inspection. Finished tasks also show their exit code, reason and incomplete-capture warning when applicable.
|
|
77
|
+
- **Controls:** ← returns to the list. Esc closes either view; Enter or Space also closes details. `x` stops only the selected running shell. While either panel is open, the entire footer is hidden: path, usage, model, extension statuses and shell count. Closing restores the current footer and leaves the task running. Inspecting output in the panel does not add model messages or consume a pending completion reminder.
|
|
78
|
+
- **Counter:** recently finished tasks add `N done` for five seconds. Hiding the counter does not delete history. RPC receives an active count; print/JSON mode has no UI timer.
|
|
79
|
+
- **No `/bg` commands or Herdr integration:** the extension creates no tabs, panes or log-following processes, including when Pi itself runs inside Herdr. Task execution always uses the same local backend.
|
|
88
80
|
|
|
89
|
-
|
|
81
|
+
The preview is intentionally bounded, not a full log viewer. Use the retained log path for earlier output or long lines. Commands have no TTY, so TTY-only colour and progress rendering may be absent. Other extensions' widgets remain intact.
|
|
90
82
|
|
|
91
|
-
-
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
98
|
-
- 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.
|
|
99
|
-
- A failed Herdr call shows one warning. Tasks keep running and the widget stays current.
|
|
83
|
+
The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter. Extensions that also replace the entire footer are therefore not composable: a replacement present at startup produces an explicit extension error, and one installed later can replace this footer. Use the built-in footer with `setStatus()` extensions such as Codex Edit. A host-provided composable/clickable status API would remove this constraint.
|
|
100
84
|
|
|
101
|
-
|
|
85
|
+
## Completion delivery
|
|
102
86
|
|
|
103
87
|
Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
|
|
104
88
|
|
|
@@ -106,7 +90,7 @@ Completion, failure, cancellation, timeout and output-limit termination update t
|
|
|
106
90
|
- While idle, pending completions are combined on the next event-loop tick and wake the main agent once. Oversized metadata batches remain pending for later safe boundaries rather than being dropped. Jobs that finish after that batch can produce another notification. Pi's global steering/follow-up queue settings are unchanged.
|
|
107
91
|
- If another operation such as manual compaction keeps the session busy without an agent boundary, one local timer retries after 1, 2, 4, 8, 16, then 30 seconds, staying at 30 seconds thereafter. There is no retry-count limit or expiry that discards unread results. This does not call a model or poll shell output.
|
|
108
92
|
- Normal tool/settlement boundaries still deliver immediately, without waiting for the retry timer. Without a boundary, an idle session can wait up to the current retry interval (at most 30 seconds, subject to native timer delays). Once a batch is delivered or fully consumed, the next batch starts with an immediate check and fresh backoff.
|
|
109
|
-
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks. A running snapshot, `list`, a failed log read, or a user
|
|
93
|
+
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks. A running snapshot, `list`, a failed log read, or a user panel inspection does not consume the main agent's reminder. Consumption does not mean the task passed validation.
|
|
110
94
|
- Aborted/error boundaries do not request continuation or replay a previously scheduled wake. An error does not suppress later completions.
|
|
111
95
|
- A user interrupt keeps the agent stopped: accepted jobs still run, but even later completions cannot restart it. Unread results remain queryable and are handed to the next user-message run before its first model request. Another extension's custom wake does not release this interrupt state; a new user-message run or session replacement does. This adds no notification pause switch.
|
|
112
96
|
- Cancelling manual compaction is separate from interrupting the agent. Pending completions still wake an otherwise-idle session after compaction succeeds, fails or is cancelled.
|
|
@@ -152,7 +136,7 @@ The tool description is compact. This package adds no `promptGuidelines` or extr
|
|
|
152
136
|
## Lifetime and scope
|
|
153
137
|
|
|
154
138
|
- Exit, new/resumed/forked sessions and reload terminate active tasks, remove the widget and timers, and delete this package's captured logs. Commands' own files are left alone. History is not restored.
|
|
155
|
-
- Aborting the main agent's current turn does not cancel an accepted job, but its completion cannot automatically restart the interrupted agent. Use cancel or
|
|
139
|
+
- Aborting the main agent's current turn does not cancel an accepted job, but its completion cannot automatically restart the interrupted agent. Use the tool’s cancel action or `x` in the panel to stop the job itself.
|
|
156
140
|
- Cancellation and runtime limits stop the native shell process group. Scripts must wait for their own work. Daemonized/detached commands (`nohup`, `setsid`, self-backgrounding processes), existing PID adoption, PTYs and interactive stdin are not supported.
|
|
157
141
|
- This is a distinct **local execution** tool. A third-party sandbox or remote backend installed only for Bash does not automatically cover it. Enable it only where direct local shell execution is permitted.
|
|
158
142
|
- It is not an OS sandbox: CPU/memory quotas, cleanup after SIGKILL/power loss, automatic retries, deadline renewal and persistence are out of scope. Native signal delivery and timers are best-effort.
|
package/TESTING.md
CHANGED
|
@@ -13,8 +13,8 @@ Tests use Node's built-in test runner. They resolve host peers from the installe
|
|
|
13
13
|
- `tasks.mjs`: fake execution and clock at the task-manager interface; immediate return, two slots, validation, timeout/cancel races, final failure, disk budgets, write errors, bounded history and shutdown.
|
|
14
14
|
- `output.mjs`: compares the shared 100-line/8-KiB preview with the real host Bash tool’s output, retaining unchanged small-output display parity and deliberately tighter truncation for large output. 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. Checks both return paths carry the same tail, omission metadata reports total size, and full captured bytes remain on disk. The former Bash-sized display/1-MiB structured contract is retired; each retained fixture now verifies the bounded replacement.
|
|
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
|
-
- `extension.mjs`: real extension registration with fake execution/clock; schema errors,
|
|
17
|
-
- `
|
|
16
|
+
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection 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, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks explicit failure for an incompatible replacement footer and cleanup of the temporary zero-line capture widget. Checks fixed `model-only` exposure and separate concise declaration and task-specific start guidance, no start-text log path or redundant structured guidance field, and explicit running-task `list`/`output` availability; 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
|
+
- `panel.mjs`: singular/plural counter, mouse hit region, screenshot-style field alignment, original multiline command, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
|
|
18
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.
|
|
19
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 reminders for zero, one or two first-wave terminal outputs read directly by the model before the boundary; no output bodies are attached to any completion notice; no extra requests follow the final report. Complete pending-batch consumption remains covered by the deterministic extension tests. Also verifies that the model receives distinct declaration/start guidance without a Codemode suffix, and that the next request receives status/log locations without command output, 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.
|
|
20
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 status/log-location metadata 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.
|
|
@@ -28,7 +28,7 @@ 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.
|
|
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.
|
|
32
32
|
|
|
33
33
|
## Real Pi TUI
|
|
34
34
|
|
|
@@ -36,6 +36,7 @@ Requires Python 3 with the existing `pexpect` module; process fixtures use Bash,
|
|
|
36
36
|
|
|
37
37
|
```bash
|
|
38
38
|
python3 packages/background-tasks/tests/tui-smoke.py .cache/verification/background-tui
|
|
39
|
+
BG_SMOKE_TUI_MODE=regular python3 packages/background-tasks/tests/tui-smoke.py .cache/verification/background-tui-regular
|
|
39
40
|
```
|
|
40
41
|
|
|
41
42
|
This starts a real Pi in a PTY with the production extension, Scheduler, the built-in Codemode tool and a deterministic fixture provider. It checks two jobs, rejection of a third, model turn completion while jobs remain alive and rejection of Codemode background calls, explicit output, cancellation, automatic main-agent notification, reload/new/quit cleanup and log removal. It observes both persisted boundary entries and idle custom messages by unique session-entry ID, and rejects duplicate notifications. No network model calls occur. Mocked UI tests separately verify the exact five-second boundary.
|
|
@@ -50,22 +51,23 @@ gnome-terminal.real --wait --window --title='Pi Background Tasks Smoke' --geomet
|
|
|
50
51
|
|
|
51
52
|
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.
|
|
52
53
|
|
|
53
|
-
##
|
|
54
|
+
## Browser/TUI flow and media
|
|
54
55
|
|
|
55
|
-
|
|
56
|
+
```bash
|
|
57
|
+
node scripts/capture-background-tasks-media.mjs .cache/background-ui
|
|
58
|
+
BG_MEDIA_EDITOR=none node scripts/capture-background-tasks-media.mjs .cache/background-ui-no-editor
|
|
59
|
+
node scripts/capture-package-media.mjs background-tasks
|
|
60
|
+
```
|
|
56
61
|
|
|
57
|
-
|
|
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.
|
|
59
|
-
- With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
|
|
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`).
|
|
61
|
-
- No warning is shown, and the private log directory is removed after session shutdown.
|
|
62
|
+
Requires Python 3, Chrome, the web-browser skill launcher, Pillow and an installed `@xterm/xterm` package. Set `XTERM_DIR` to its package directory if it is not under `~/.pi/agent/npm/node_modules/@xterm/xterm`. No Herdr or graphical desktop is required.
|
|
62
63
|
|
|
63
|
-
|
|
64
|
+
The recorder starts a real Pi PTY with the production extension and offline provider. By default it also loads the production Codex Edit extension; that offline model correctly selects `editor: edit`. Deterministic tests additionally cover `editor: apply_patch`. `BG_MEDIA_EDITOR=none` verifies the same flow without an editor extension. Chrome renders the actual ANSI stream through xterm.js in a recorder-owned temporary browser profile, without touching an existing skill browser. CDP sends real mouse press/release events to the shell counter and task rows, and keyboard events for selection, return, close, stop and Alt+J. It asserts that the count is on the last nonempty row beside editor status when present, with no duplicate above the footer. Both list and details hide path, usage, model and status rows; closing restores them. It also verifies aligned fields, live output, completion, cancellation, retained history and session-log cleanup. The Python bridge only transports PTY bytes; it does not draw replacement UI. Its local HTTP/WebSocket server uses a random path token and same-origin upgrade checks and is closed after the run.
|
|
64
65
|
|
|
65
|
-
|
|
66
|
+
The unified media entry first runs `tests/tui-smoke.py`, then the browser/TUI recorder. `result.json`, tool events and raw screen text/screenshots are saved under `.cache/package-media/background-terminal`. The renderer builds `docs/screenshot.png`, `docs/shell-list.png` and `docs/demo.gif` from real captured states. The old Herdr pane screenshot and WebM are retired.
|
|
67
|
+
|
|
68
|
+
Inspect the gallery in Chrome: `docs/package-media-gallery.html`. Verify images load and the GIF shows counter → details → list → selected details → completion/cancel → history. Record results in `docs/verification.md`.
|
|
66
69
|
|
|
67
70
|
```bash
|
|
68
|
-
HERDR_MEDIA_WINDOW_ID=<visible-herdr-window-id> node scripts/capture-package-media.mjs background-tasks
|
|
69
71
|
node tests/package-layout.mjs
|
|
70
72
|
node tests/release-check.mjs
|
|
71
73
|
npm test
|
|
@@ -74,12 +76,4 @@ npm pack --dry-run
|
|
|
74
76
|
git diff --check
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
|
|
78
|
-
|
|
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.
|
|
80
|
-
|
|
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.
|
|
82
|
-
|
|
83
|
-
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.
|
|
84
|
-
|
|
85
|
-
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.
|
|
79
|
+
Missing Chrome, a failed interaction or a skipped real-TUI check blocks release acceptance. Deterministic suites alone do not verify the mouse path.
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
|
Binary file
|
|
@@ -4,9 +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 {
|
|
8
|
-
import {
|
|
9
|
-
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
7
|
+
import { BackgroundPanel } from "../src/panel.ts";
|
|
8
|
+
import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
10
9
|
|
|
11
10
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
12
11
|
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.";
|
|
@@ -63,20 +62,7 @@ function completionText(task: TaskSnapshot): string {
|
|
|
63
62
|
return lines.join("\n");
|
|
64
63
|
}
|
|
65
64
|
|
|
66
|
-
function
|
|
67
|
-
const parts = input.trim().split(/\s+/).filter(Boolean);
|
|
68
|
-
if (parts.length === 0 || (parts.length === 1 && parts[0] === "list")) return { action: "list" };
|
|
69
|
-
if (parts.length === 2 && (parts[0] === "output" || parts[0] === "cancel" || parts[0] === "watch")) return { action: parts[0], id: parts[1] };
|
|
70
|
-
throw new Error("usage: /bg [list | output <id> | cancel <id> | watch <id>]");
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Herdr panes are a view for the user's own Pi session; subagent children keep only their widget. */
|
|
74
|
-
function herdrWorkspace(env: NodeJS.ProcessEnv): string | undefined {
|
|
75
|
-
if (env.HERDR_ENV !== "1" || env.PI_HERDR_SUBAGENTS_CHILD === "1") return;
|
|
76
|
-
return env.HERDR_WORKSPACE_ID?.trim() || undefined;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string; herdr?: HerdrCall; env?: NodeJS.ProcessEnv; sleep?: (ms: number) => Promise<void> } = {}) {
|
|
65
|
+
export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string } = {}) {
|
|
80
66
|
const clock = dependencies.clock ?? systemClock;
|
|
81
67
|
let manager: BackgroundTasks | undefined;
|
|
82
68
|
let context: ExtensionContext | undefined;
|
|
@@ -86,8 +72,8 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
86
72
|
let completedNormally = true;
|
|
87
73
|
let interrupted = false;
|
|
88
74
|
const pending = new Map<string, TaskSnapshot>();
|
|
89
|
-
let mounted: {
|
|
90
|
-
let
|
|
75
|
+
let mounted: { footer: BackgroundFooter; tui: { requestRender(): void } } | undefined;
|
|
76
|
+
let panel: { close(): void } | undefined;
|
|
91
77
|
|
|
92
78
|
const clearNotificationTimer = () => {
|
|
93
79
|
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
@@ -166,11 +152,27 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
166
152
|
if (!event.aborted && completedNormally) scheduleNotification();
|
|
167
153
|
});
|
|
168
154
|
|
|
169
|
-
const
|
|
155
|
+
const openPanel = async () => {
|
|
170
156
|
const current = context;
|
|
171
|
-
|
|
172
|
-
|
|
157
|
+
const tasks = manager;
|
|
158
|
+
if (!current?.hasUI || current.mode !== "tui" || !tasks || panel) return;
|
|
159
|
+
const interaction = { close: () => {} };
|
|
160
|
+
panel = interaction;
|
|
161
|
+
mounted?.tui.requestRender();
|
|
162
|
+
try {
|
|
163
|
+
await current.ui.custom<void>((tui, theme, keybindings, done) => {
|
|
164
|
+
const component = new BackgroundPanel(tasks, clock, theme, keybindings, () => tui.requestRender(), () => done());
|
|
165
|
+
interaction.close = () => { component.dispose(); done(); };
|
|
166
|
+
return component;
|
|
167
|
+
});
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (context === current) current.ui.notify(`Cannot show shells: ${errorText(error)}`, "error");
|
|
170
|
+
} finally {
|
|
171
|
+
if (panel === interaction) panel = undefined;
|
|
172
|
+
mounted?.tui.requestRender();
|
|
173
|
+
}
|
|
173
174
|
};
|
|
175
|
+
pi.registerShortcut("alt+j", { description: "Show background shells", handler: openPanel });
|
|
174
176
|
const clearTimer = () => {
|
|
175
177
|
if (timer !== undefined) clock.clearTimeout(timer);
|
|
176
178
|
timer = undefined;
|
|
@@ -179,29 +181,16 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
179
181
|
if (!context?.hasUI || !manager) return;
|
|
180
182
|
const list = manager.list();
|
|
181
183
|
if (context.mode !== "tui") {
|
|
182
|
-
context.ui.setStatus(WIDGET_KEY, list.running ?
|
|
184
|
+
context.ui.setStatus(WIDGET_KEY, list.running ? `${list.running} ${list.running === 1 ? "shell" : "shells"}` : undefined);
|
|
183
185
|
return;
|
|
184
186
|
}
|
|
185
187
|
const visible = visibleTasks(list.tasks, clock.now());
|
|
188
|
+
mounted?.footer.invalidate();
|
|
189
|
+
mounted?.tui.requestRender();
|
|
186
190
|
if (visible.length === 0) {
|
|
187
191
|
clearTimer();
|
|
188
|
-
if (mounted) {
|
|
189
|
-
context.ui.setWidget(WIDGET_KEY, undefined);
|
|
190
|
-
mounted.tui.requestRender();
|
|
191
|
-
mounted = undefined;
|
|
192
|
-
}
|
|
193
192
|
return;
|
|
194
193
|
}
|
|
195
|
-
if (mounted) {
|
|
196
|
-
mounted.widget.invalidate();
|
|
197
|
-
mounted.tui.requestRender();
|
|
198
|
-
} else {
|
|
199
|
-
context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
|
|
200
|
-
const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, viewer ? watch : undefined);
|
|
201
|
-
mounted = { widget, tui };
|
|
202
|
-
return widget;
|
|
203
|
-
}, { placement: "aboveEditor" });
|
|
204
|
-
}
|
|
205
194
|
if (timer === undefined) {
|
|
206
195
|
const delay = Math.min(1000, ...visible.filter((task) => task.ended_at !== undefined).map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
|
|
207
196
|
timer = clock.setTimeout(() => { timer = undefined; refresh(); }, Math.max(1, delay));
|
|
@@ -211,10 +200,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
211
200
|
generation++;
|
|
212
201
|
const previous = manager;
|
|
213
202
|
const previousContext = context;
|
|
214
|
-
|
|
203
|
+
panel?.close();
|
|
204
|
+
panel = undefined;
|
|
215
205
|
manager = undefined;
|
|
216
206
|
context = undefined;
|
|
217
|
-
viewer = undefined;
|
|
218
207
|
clearTimer();
|
|
219
208
|
clearNotificationTimer();
|
|
220
209
|
pending.clear();
|
|
@@ -223,34 +212,45 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
223
212
|
try {
|
|
224
213
|
if (previousContext?.hasUI) {
|
|
225
214
|
previousContext.ui.setStatus(WIDGET_KEY, undefined);
|
|
226
|
-
if (previousContext.mode === "tui") previousContext.ui.
|
|
215
|
+
if (previousContext.mode === "tui" && mounted) previousContext.ui.setFooter(undefined);
|
|
227
216
|
}
|
|
228
217
|
mounted = undefined;
|
|
229
218
|
} finally {
|
|
230
|
-
|
|
231
|
-
await Promise.all([previous?.shutdown(), previousViewer?.dispose()]);
|
|
219
|
+
await previous?.shutdown();
|
|
232
220
|
}
|
|
233
221
|
};
|
|
234
222
|
pi.on("session_start", async (_event, ctx) => {
|
|
235
223
|
await dispose();
|
|
236
224
|
context = ctx;
|
|
237
225
|
const epoch = generation;
|
|
238
|
-
const workspaceId = ctx.mode === "tui" && ctx.hasUI ? herdrWorkspace(dependencies.env ?? process.env) : undefined;
|
|
239
|
-
viewer = workspaceId ? new HerdrViewer({
|
|
240
|
-
call: dependencies.herdr ?? cliHerdr(), workspaceId, sleep: dependencies.sleep,
|
|
241
|
-
tasks: () => manager?.list().tasks ?? [],
|
|
242
|
-
warn: (message) => { if (generation === epoch) ctx.ui.notify(message, "warning"); },
|
|
243
|
-
}) : undefined;
|
|
244
226
|
manager = new BackgroundTasks({
|
|
245
227
|
operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
|
|
246
228
|
onChange() { if (generation === epoch) refresh(); },
|
|
247
229
|
onComplete(task) {
|
|
248
230
|
if (generation !== epoch || !context) return;
|
|
249
|
-
viewer?.finished(task);
|
|
250
231
|
pending.set(task.id, task);
|
|
251
232
|
scheduleNotification();
|
|
252
233
|
},
|
|
253
234
|
});
|
|
235
|
+
if (ctx.hasUI && ctx.mode === "tui") {
|
|
236
|
+
// setFooter clears its container before invoking the factory. Capture the
|
|
237
|
+
// native component first, using a temporary, zero-line widget factory.
|
|
238
|
+
try {
|
|
239
|
+
ctx.ui.setWidget(WIDGET_KEY, (tui) => {
|
|
240
|
+
const native = findNativeFooter(tui.children);
|
|
241
|
+
if (!native) throw new Error("Background Tasks requires Pi's built-in footer; another extension has replaced it.");
|
|
242
|
+
ctx.ui.setFooter((footerTui, theme, data) => {
|
|
243
|
+
const footer = new BackgroundFooter(native, () => manager?.list().tasks ?? [], clock, theme,
|
|
244
|
+
() => data.getExtensionStatuses().size > 0, () => panel !== undefined, () => { void openPanel(); });
|
|
245
|
+
mounted = { footer, tui: footerTui };
|
|
246
|
+
return footer;
|
|
247
|
+
});
|
|
248
|
+
return { render: () => [], invalidate() {} };
|
|
249
|
+
});
|
|
250
|
+
} finally {
|
|
251
|
+
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
254
|
});
|
|
255
255
|
pi.on("session_shutdown", dispose);
|
|
256
256
|
|
|
@@ -259,7 +259,6 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
259
259
|
if (!manager) throw new Error("Background tasks session is not ready");
|
|
260
260
|
if (params.action === "start") {
|
|
261
261
|
const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
|
|
262
|
-
void viewer?.show(task, params.command!);
|
|
263
262
|
return {
|
|
264
263
|
text: `Started ${formatTask(task)}\n${startNotice}`,
|
|
265
264
|
data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
|
|
@@ -297,7 +296,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
297
296
|
if (signal?.aborted) throw new Error("Tool call aborted before task acceptance");
|
|
298
297
|
const result = await perform(params, ctx?.cwd ?? context?.cwd ?? process.cwd());
|
|
299
298
|
// A terminal result was consumed by the model.
|
|
300
|
-
// User
|
|
299
|
+
// User panel inspections and running snapshots do not acknowledge completion.
|
|
301
300
|
if (params.action === "output" && "task" in result.data && result.data.task.status !== "running") {
|
|
302
301
|
pending.delete(result.data.task.id);
|
|
303
302
|
if (pending.size === 0) clearNotificationTimer();
|
|
@@ -317,21 +316,4 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
317
316
|
return new Text(theme.fg(result.isError ? "error" : "muted", text), 0, 0);
|
|
318
317
|
},
|
|
319
318
|
});
|
|
320
|
-
pi.registerCommand("bg", {
|
|
321
|
-
description: "List background shell tasks, read output, cancel a task, or watch it in Herdr",
|
|
322
|
-
handler: async (args, ctx) => {
|
|
323
|
-
try {
|
|
324
|
-
const params = parseCommand(args);
|
|
325
|
-
if (params.action === "watch") {
|
|
326
|
-
if (!manager) throw new Error("Background tasks session is not ready");
|
|
327
|
-
const task = manager.get(params.id);
|
|
328
|
-
if (!viewer) throw new Error("/bg watch needs this Pi session to run inside Herdr");
|
|
329
|
-
await viewer.watch(task);
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
const result = await perform(params, ctx.cwd);
|
|
333
|
-
pi.sendMessage({ customType: "background-task-inspect", content: result.text, display: true, details: result.details }, { triggerTurn: false });
|
|
334
|
-
} catch (error) { ctx.ui.notify(errorText(error), "error"); }
|
|
335
|
-
},
|
|
336
|
-
});
|
|
337
319
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
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 tests/
|
|
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/panel.mjs tests/media.mjs",
|
|
38
38
|
"load-test": "node --experimental-strip-types tests/load.mjs"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
package/src/background-tasks.ts
CHANGED
|
@@ -39,6 +39,7 @@ export interface StartParams {
|
|
|
39
39
|
timeout?: number;
|
|
40
40
|
}
|
|
41
41
|
interface Task {
|
|
42
|
+
command: string;
|
|
42
43
|
data: TaskSnapshot;
|
|
43
44
|
log: TaskLog;
|
|
44
45
|
controller: AbortController;
|
|
@@ -115,6 +116,7 @@ export class BackgroundTasks {
|
|
|
115
116
|
do { id = `bg-${randomUUID().replace(/-/g, "").slice(0, 12)}`; } while (this.tasks.has(id));
|
|
116
117
|
const log = new TaskLog(join(this.directory, `${id}.log`), this.logWrite);
|
|
117
118
|
const task: Task = {
|
|
119
|
+
command: params.command,
|
|
118
120
|
data: {
|
|
119
121
|
id, status: "running", description: summary(params.description || params.command.split("\n", 1)[0]), cwd,
|
|
120
122
|
started_at: this.clock.now(), timeout, elapsed_seconds: 0, log_path: log.path,
|
|
@@ -133,6 +135,9 @@ export class BackgroundTasks {
|
|
|
133
135
|
|
|
134
136
|
get(id: string): TaskSnapshot { return this.snapshot(this.find(id)); }
|
|
135
137
|
|
|
138
|
+
/** Original command for the local UI; not repeated in tool/notification metadata. */
|
|
139
|
+
command(id: string): string { return this.find(id).command; }
|
|
140
|
+
|
|
136
141
|
list(): TaskList {
|
|
137
142
|
const all = [...this.tasks.values()];
|
|
138
143
|
const active = all.filter((task) => task.data.status === "running");
|