@maxiaochao/pi-background-tasks 0.3.0 → 0.4.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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-11-13 - v0.4.0
4
+
5
+ - Replace Herdr task views and /bg commands with a local shell counter and details panel
6
+ - 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.
7
+ - Support arrows, Enter, Escape, Space and `x` to inspect, return, dismiss and stop without a model call. Keep finished history accessible with Alt+J.
8
+ - 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.
9
+ - Replace the retired Herdr suite/media flow with deterministic panel tests and real Pi PTY interaction in Chrome.
10
+
11
+ ## 2026-11-05 - v0.3.1
12
+
13
+ - Use descriptive task views and clarify captured logs and automatic completion waiting
14
+ - Name Herdr tabs `BG · <task description>` and panes `<number> · <task description>`, following Herdr Subagents. Update the shared tab name on start/watch/completion, retain task numbers across pane reuse/reopening, and print the task name above the command so it is visible with one pane.
15
+ - Clarify in the command parameter that stdout/stderr are saved to a unique per-task log and the path is reported on completion.
16
+ - Tighten the start reminder: when nothing else remains, end the turn instead of sleeping, tailing logs or querying just to wait.
17
+
3
18
  ## 2026-11-03 - v0.3.0
4
19
 
5
20
  - Report completion status and log paths for progressive inspection with bounded explicit output
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
- ![Real parent Pi: click either background task row to watch it in Herdr](docs/screenshot.png)
5
+ ![Real Pi shell details with aligned Status, Runtime and Command](docs/screenshot.png)
6
6
 
7
- ![Real Herdr task panes: command headers and streaming build/test output](docs/task-panes.png)
7
+ ![Real Pi list of background shells](docs/shell-list.png)
8
8
 
9
- ![Real Pi and Herdr: start two jobs, click each task, watch live output, then automatic tab cleanup](docs/demo.gif)
9
+ ![Real Pi shell counter, list, live details, cancellation and history](docs/demo.gif)
10
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.
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. 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.
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 `/bg` command would be registered twice.
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
 
@@ -41,7 +39,7 @@ The tool is fixed to `exposure: "model-only"`: the model calls it directly; Code
41
39
 
42
40
  The tool declaration describes automatic completion notifications, concurrency and session lifetime. The action parameter explicitly permits `list` and `output` while tasks are still running. Each accepted start returns only its task data and this short, task-specific reminder:
43
41
 
44
- > Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.
42
+ > Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.
45
43
 
46
44
  The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
47
45
 
@@ -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 actions, not only user `/bg` commands. 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:
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" })
@@ -60,7 +58,7 @@ background_task({ action: "cancel", id: "<returned-task-id>" })
60
58
 
61
59
  Start returns a running task's ID and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
62
60
 
63
- - `command`: unchanged multi-line shell script; only for start.
61
+ - `command`: unchanged multi-line shell script; only for start. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.
64
62
  - `description`: optional display label, shortened to 200 characters.
65
63
  - `cwd`: optional directory, resolved relative to the current session directory.
66
64
  - `timeout`: integer seconds, **1800 by default**, from 1 through 7200. Zero and unlimited mode are rejected.
@@ -72,31 +70,17 @@ 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
- ```text
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.
86
-
87
- ## Herdr task view
73
+ A compact **`1 shell` / `N shells`** counter sits below the editor without replacing Pi's footer. 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.
88
74
 
89
- 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:
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. Closing the panel 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.
90
80
 
91
- - The tab is created on the first start without taking focus, and holds at most two panes, one per running task. A new task reuses the pane of a finished one.
92
- - 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]`.
93
- - The pane is a **viewer only**. The task runs through the same local backend as outside Herdr, with the same logs, limits, status and notifications. The command has no TTY, so tools that detect one may drop colour or animated progress bars.
94
- - Closing a pane, or the whole tab, does not cancel the task. Clicking a task row in the widget (Pi 1.4+ fullscreen mode) or `/bg watch <id>` reopens the pane if needed and focuses that tab and pane; use `/bg cancel <id>` to stop the task.
95
- - 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.
96
- - 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.
97
- - A failed Herdr call shows one warning. Tasks keep running and the widget stays current.
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.
98
82
 
99
- There is no setting to turn the view off.
83
+ ## Completion delivery
100
84
 
101
85
  Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
102
86
 
@@ -104,7 +88,7 @@ Completion, failure, cancellation, timeout and output-limit termination update t
104
88
  - 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.
105
89
  - 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.
106
90
  - 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.
107
- - 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 `/bg output` inspection does not consume the main agent's reminder. Consumption does not mean the task passed validation.
91
+ - 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.
108
92
  - Aborted/error boundaries do not request continuation or replay a previously scheduled wake. An error does not suppress later completions.
109
93
  - 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.
110
94
  - Cancelling manual compaction is separate from interrupting the agent. Pending completions still wake an otherwise-idle session after compaction succeeds, fails or is cancelled.
@@ -150,7 +134,7 @@ The tool description is compact. This package adds no `promptGuidelines` or extr
150
134
  ## Lifetime and scope
151
135
 
152
136
  - 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.
153
- - 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 `/bg cancel` to stop the job itself.
137
+ - 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.
154
138
  - 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.
155
139
  - 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.
156
140
  - 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, 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, 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, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. 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
- - `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.
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, below-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. 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,12 +28,15 @@ 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.
32
+
31
33
  ## Real Pi TUI
32
34
 
33
35
  Requires Python 3 with the existing `pexpect` module; process fixtures use Bash, Python and `ps`. The current native-process/TUI suite is verified on Linux.
34
36
 
35
37
  ```bash
36
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
37
40
  ```
38
41
 
39
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.
@@ -48,22 +51,22 @@ gnome-terminal.real --wait --window --title='Pi Background Tasks Smoke' --geomet
48
51
 
49
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.
50
53
 
51
- ## Real Herdr view
54
+ ## Browser/TUI flow and media
55
+
56
+ ```bash
57
+ node scripts/capture-background-tasks-media.mjs .cache/background-ui
58
+ node scripts/capture-package-media.mjs background-tasks
59
+ ```
52
60
 
53
- 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`:
61
+ 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.
54
62
 
55
- - One unfocused **Background tasks** tab with two panes while both run.
56
- - Each pane shows the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`).
57
- - With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
58
- - In a fullscreen Pi started in its own Herdr pane, an SGR click on each widget task row (`herdr pane send-text <pane> $'\e[<0;10;<row>M\e[<0;10;<row>m'`) focuses the tab and that task's pane (`herdr pane list`).
59
- - No warning is shown, and the private log directory is removed after session shutdown.
63
+ The recorder starts a real Pi PTY with the production extension and offline provider. Chrome renders the actual ANSI stream through xterm.js. 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 verifies single-shell details, two-shell list, 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.
60
64
 
61
- 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.
65
+ 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.
62
66
 
63
- ## Media and workspace checks
67
+ 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`.
64
68
 
65
69
  ```bash
66
- HERDR_MEDIA_WINDOW_ID=<visible-herdr-window-id> node scripts/capture-package-media.mjs background-tasks
67
70
  node tests/package-layout.mjs
68
71
  node tests/release-check.mjs
69
72
  npm test
@@ -72,12 +75,4 @@ npm pack --dry-run
72
75
  git diff --check
73
76
  ```
74
77
 
75
- The media command requires the real-TUI screenshot prerequisites above, Pillow, and GStreamer (`ximagesrc`, VP8/WebM encoding/decoding, and PNG encoding). Select the X11 window that already displays a working Herdr client with `HERDR_MEDIA_WINDOW_ID`; the GNOME desktop must be unlocked. The recorder checks the lock state before starting and at each screenshot; hidden windows can return stale pixels.
76
-
77
- The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
78
-
79
- The recorder captures the selected client window continuously, rejects uniform/blank screenshot centres, restores the original workspace/tab, and removes its own workspace. It never starts paid models or copies credentials. `result.json`, tool events and diagnostic frames are stored under `.cache/package-media/background-herdr`. The renderer publishes `docs/screenshot.png` (parent widget), `docs/task-panes.png` (actual task panes), `docs/demo.gif` (frames decoded from the recording), and the complete `docs/demo.webm`. No synthetic UI is drawn.
80
-
81
- 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.
82
-
83
- 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.
78
+ 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
Binary file
Binary file
@@ -4,12 +4,11 @@ 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
+ import { BackgroundPanel } from "../src/panel.ts";
9
8
  import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
10
9
 
11
10
  const actions = ["start", "list", "output", "cancel"] as const;
12
- const startNotice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
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.";
13
12
  // Bound model-visible status text when many completions accumulate.
14
13
  const NOTIFICATION_MAX_BYTES = 16 * 1024;
15
14
  type Action = typeof actions[number];
@@ -23,7 +22,7 @@ interface Params {
23
22
  }
24
23
  const Parameters = Type.Object({
25
24
  action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task. list and output also work while tasks are running." }),
26
- command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed." })),
25
+ command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion." })),
27
26
  description: Type.Optional(Type.String({ description: "Short display label for start" })),
28
27
  cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
29
28
  timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 7200, description: "Runtime limit for start, in seconds: default 1800 (30 minutes), maximum 7200 (2 hours); no unlimited mode" })),
@@ -63,20 +62,7 @@ function completionText(task: TaskSnapshot): string {
63
62
  return lines.join("\n");
64
63
  }
65
64
 
66
- function parseCommand(input: string): Params | { action: "watch"; id: string } {
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;
@@ -87,7 +73,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
87
73
  let interrupted = false;
88
74
  const pending = new Map<string, TaskSnapshot>();
89
75
  let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
90
- let viewer: HerdrViewer | undefined;
76
+ let panel: { close(): void } | undefined;
91
77
 
92
78
  const clearNotificationTimer = () => {
93
79
  if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
@@ -166,11 +152,25 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
166
152
  if (!event.aborted && completedNormally) scheduleNotification();
167
153
  });
168
154
 
169
- const watch = (id: string) => {
155
+ const openPanel = async () => {
170
156
  const current = context;
171
- if (!manager || !viewer || !current) return;
172
- viewer.watch(manager.get(id)).catch((error) => current.ui.notify(`Cannot show task ${id}: ${errorText(error)}`, "error"));
157
+ const tasks = manager;
158
+ if (!current?.hasUI || current.mode !== "tui" || !tasks || panel) return;
159
+ const interaction = { close: () => {} };
160
+ panel = interaction;
161
+ try {
162
+ await current.ui.custom<void>((tui, theme, keybindings, done) => {
163
+ const component = new BackgroundPanel(tasks, clock, theme, keybindings, () => tui.requestRender(), () => done());
164
+ interaction.close = () => { component.dispose(); done(); };
165
+ return component;
166
+ });
167
+ } catch (error) {
168
+ if (context === current) current.ui.notify(`Cannot show shells: ${errorText(error)}`, "error");
169
+ } finally {
170
+ if (panel === interaction) panel = undefined;
171
+ }
173
172
  };
173
+ pi.registerShortcut("alt+j", { description: "Show background shells", handler: openPanel });
174
174
  const clearTimer = () => {
175
175
  if (timer !== undefined) clock.clearTimeout(timer);
176
176
  timer = undefined;
@@ -179,7 +179,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
179
179
  if (!context?.hasUI || !manager) return;
180
180
  const list = manager.list();
181
181
  if (context.mode !== "tui") {
182
- context.ui.setStatus(WIDGET_KEY, list.running ? `Background tasks ${list.running}/2` : undefined);
182
+ context.ui.setStatus(WIDGET_KEY, list.running ? `${list.running} ${list.running === 1 ? "shell" : "shells"}` : undefined);
183
183
  return;
184
184
  }
185
185
  const visible = visibleTasks(list.tasks, clock.now());
@@ -197,10 +197,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
197
197
  mounted.tui.requestRender();
198
198
  } else {
199
199
  context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
200
- const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, viewer ? watch : undefined);
200
+ const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, () => { void openPanel(); });
201
201
  mounted = { widget, tui };
202
202
  return widget;
203
- }, { placement: "aboveEditor" });
203
+ }, { placement: "belowEditor" });
204
204
  }
205
205
  if (timer === undefined) {
206
206
  const delay = Math.min(1000, ...visible.filter((task) => task.ended_at !== undefined).map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
@@ -211,10 +211,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
211
211
  generation++;
212
212
  const previous = manager;
213
213
  const previousContext = context;
214
- const previousViewer = viewer;
214
+ panel?.close();
215
+ panel = undefined;
215
216
  manager = undefined;
216
217
  context = undefined;
217
- viewer = undefined;
218
218
  clearTimer();
219
219
  clearNotificationTimer();
220
220
  pending.clear();
@@ -227,26 +227,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
227
227
  }
228
228
  mounted = undefined;
229
229
  } finally {
230
- // Cancel tasks first and synchronously; closing the view tab must not delay that.
231
- await Promise.all([previous?.shutdown(), previousViewer?.dispose()]);
230
+ await previous?.shutdown();
232
231
  }
233
232
  };
234
233
  pi.on("session_start", async (_event, ctx) => {
235
234
  await dispose();
236
235
  context = ctx;
237
236
  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
237
  manager = new BackgroundTasks({
245
238
  operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
246
239
  onChange() { if (generation === epoch) refresh(); },
247
240
  onComplete(task) {
248
241
  if (generation !== epoch || !context) return;
249
- viewer?.finished(task);
250
242
  pending.set(task.id, task);
251
243
  scheduleNotification();
252
244
  },
@@ -259,7 +251,6 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
259
251
  if (!manager) throw new Error("Background tasks session is not ready");
260
252
  if (params.action === "start") {
261
253
  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
254
  return {
264
255
  text: `Started ${formatTask(task)}\n${startNotice}`,
265
256
  data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
@@ -297,7 +288,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
297
288
  if (signal?.aborted) throw new Error("Tool call aborted before task acceptance");
298
289
  const result = await perform(params, ctx?.cwd ?? context?.cwd ?? process.cwd());
299
290
  // A terminal result was consumed by the model.
300
- // User /bg inspections and running snapshots do not acknowledge completion.
291
+ // User panel inspections and running snapshots do not acknowledge completion.
301
292
  if (params.action === "output" && "task" in result.data && result.data.task.status !== "running") {
302
293
  pending.delete(result.data.task.id);
303
294
  if (pending.size === 0) clearNotificationTimer();
@@ -317,21 +308,4 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
317
308
  return new Text(theme.fg(result.isError ? "error" : "muted", text), 0, 0);
318
309
  },
319
310
  });
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
311
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxiaochao/pi-background-tasks",
3
- "version": "0.3.0",
3
+ "version": "0.4.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 tests/viewer.mjs tests/media.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/panel.mjs tests/media.mjs",
38
38
  "load-test": "node --experimental-strip-types tests/load.mjs"
39
39
  },
40
40
  "publishConfig": {
@@ -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");