@maxiaochao/pi-background-tasks 0.1.2 → 0.3.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,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-11-03 - v0.3.0
4
+
5
+ - Report completion status and log paths for progressive inspection with bounded explicit output
6
+ - Send only terminal status, timestamps, reason and captured log paths on completion, with guidance to search relevant terms or read bounded ranges progressively as needed. Do not automatically read, summarize or inject stdout/stderr.
7
+ - Keep a defensive 16-KiB model-visible status/path batch cap and retain overflow tasks for later boundaries; remove the automatic log-preview pipeline and its separate output budget.
8
+ - Keep a short task-specific completion-notification reminder separate from the capability/lifecycle declaration. Preserve running-task list/output inspection; remove start-text log paths and the redundant structured guidance field.
9
+ - Preserve consumption filtering, interrupt/compaction behavior and synchronous send-failure retention. Verify that missing logs are not opened during notification and explicit inspections diagnose them independently.
10
+ - Use one 100-line/8-KiB tail for explicit model and structured output, with truncation metadata and targeted full-log access; retire the separate 1-MiB program view.
11
+
12
+ ## 2026-10-29 - v0.2.0
13
+
14
+ - Add live read-only Herdr task views, exact widget navigation and real two-task terminal media
15
+ - 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.
16
+ - 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.
17
+ - 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.
18
+ - 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.
19
+
3
20
  ## 2026-10-26 - v0.1.2
4
21
 
5
22
  - restrict background tasks to model-only and use concise automatic-notification guidance
package/README.md CHANGED
@@ -1,18 +1,24 @@
1
1
  # Pi Background Tasks
2
2
 
3
- Run shell commands in the background, then notify the main agent when they finish. These are local processes, not subagents.
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
- ![Two real background jobs beside Scheduler](docs/screenshot.png)
5
+ ![Real parent Pi: click either background task row to watch it in Herdr](docs/screenshot.png)
6
6
 
7
- ![Real Pi: start, cancel, completion and output](docs/demo.gif)
7
+ ![Real Herdr task panes: command headers and streaming build/test output](docs/task-panes.png)
8
+
9
+ ![Real Pi and Herdr: start two jobs, click each task, watch live output, then automatic tab cleanup](docs/demo.gif)
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 or Herdr pane.
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
- 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.
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. 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.
16
22
 
17
23
  ## Install and update
18
24
 
@@ -33,24 +39,26 @@ background_task({ action: "start", command: "sleep 10; printf 'checks complete\\
33
39
 
34
40
  The tool is fixed to `exposure: "model-only"`: the model calls it directly; Codemode and other tools cannot call it. There is no exposure setting.
35
41
 
36
- Each accepted start includes this guidance in the tool description, result text and `structuredContent.guidance`:
42
+ The tool declaration describes automatic completion notifications, concurrency and session lifetime. The action parameter explicitly permits `list` and `output` while tasks are still running. Each accepted start returns only its task data and this short, task-specific reminder:
37
43
 
38
- > Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.
44
+ > Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.
39
45
 
40
- After the completion notification, read the result:
46
+ The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
47
+
48
+ Inspect a running or finished task whenever its output is needed; no completion or timeout notification is required:
41
49
 
42
50
  ```text
43
51
  background_task({ action: "output", id: "<returned-task-id>" })
44
52
  ```
45
53
 
46
- The tool also supports listing and cancellation:
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:
47
55
 
48
56
  ```text
49
57
  background_task({ action: "list" })
50
58
  background_task({ action: "cancel", id: "<returned-task-id>" })
51
59
  ```
52
60
 
53
- Start returns a running task's ID, log path and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
61
+ Start returns a running task's ID and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
54
62
 
55
63
  - `command`: unchanged multi-line shell script; only for start.
56
64
  - `description`: optional display label, shortened to 200 characters.
@@ -69,16 +77,31 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
69
77
  /bg list
70
78
  /bg output <returned-task-id>
71
79
  /bg cancel <returned-task-id>
80
+ /bg watch <returned-task-id>
72
81
  ```
73
82
 
74
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`.
75
84
 
76
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.
77
86
 
87
+ ## Herdr task view
88
+
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:
90
+
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.
98
+
99
+ There is no setting to turn the view off.
100
+
78
101
  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
102
 
80
- - 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.
81
- - While idle, pending completions are combined on the next event-loop tick and wake the main agent once. Jobs that finish after that batch can produce another notification. Pi's global steering/follow-up queue settings are unchanged.
103
+ - While the main agent is busy, completions are combined into a bounded 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.
104
+ - 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.
82
105
  - 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.
83
106
  - 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.
84
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.
@@ -88,7 +111,15 @@ Completion, failure, cancellation, timeout and output-limit termination update t
88
111
 
89
112
  Pi's public interrupted-run event does not include the abort reason. In particular, starting `/compact` during an active run first interrupts that run. This package preserves that interruption until the next user-message run; it does not infer that compaction grants permission to restart the agent. Compaction started while already idle does not create this interrupted-run state.
90
113
 
91
- Each message includes actual completion times, statuses and log paths, **not the output body**. The agent can call output when it needs details. Completions that arrive near final settlement are checked again before the run settles. No per-task `followUp` messages are left behind the main agent's final report.
114
+ Each completion message includes task status, exit code when available, actual end time, reason when applicable and **the captured log path**, followed by:
115
+
116
+ > Inspect logs progressively as needed: search for relevant terms or read bounded ranges; avoid loading the whole log by default.
117
+
118
+ No stdout/stderr body, automatic preview or generated log summary is included. Building a notification does not open the log file. Agents may filter the reported file directly or call `output` for a bounded snapshot; no notification is required for running-task inspection either. Missing log files are reported only when an inspection is requested, not by silently changing task status during notification.
119
+
120
+ Status/path batches have a defensive **16-KiB model-visible text cap**. Tasks that cannot fit remain pending for the next safe boundary; this is a metadata backlog guard, not a log-preview allowance. There is no automatic log-output budget because no log bodies are attached. Captured files remain until session cleanup.
121
+
122
+ Completions that arrive near final settlement are checked again before the run settles. No per-task `followUp` messages are left behind the main agent’s final report.
92
123
 
93
124
  Pi reports asynchronous message/run-start failures through its extension error channel. This extension does not automatically replay a message after such a failure; task metadata and captured logs remain queryable for the lifetime of the session.
94
125
 
@@ -96,19 +127,21 @@ Pi reports asynchronous message/run-start failures through its extension error c
96
127
 
97
128
  | View | Limit |
98
129
  | --- | --- |
99
- | Model-visible output | Last 2000 lines or 50 KiB, whichever is reached first, like Bash |
100
- | Internal `structuredContent.output` | Up to 1 MiB of raw log bytes; larger logs keep their first and last 512 KiB with an omission marker |
130
+ | Model-visible output body | Last 100 lines or 8 KiB, whichever is reached first |
131
+ | `structuredContent.output` | The same bounded tail; no separate 1 MiB program view |
132
+ | Automatic completion log bodies | None; only status, log paths and progressive-inspection guidance |
133
+ | Completion status/path text | 16 KiB defensive batch cap; remaining tasks stay pending |
101
134
  | Disk capture | 32 MiB per task, 256 MiB total per session |
102
135
 
103
- Display/program-view truncation does **not** stop the command. Disk limits **do** stop the overflowing task with `output_limit`; a full session budget rejects new starts. Nothing silently evicts old logs.
136
+ Preview truncation does **not** stop the command. Disk limits **do** stop the overflowing task with `output_limit`; a full session budget rejects new starts. Nothing silently evicts old logs.
104
137
 
105
- Output includes a log path for further reads. `truncated` describes the program view, not disk capture. `task.capture_complete` is false while running or when log data was lost. The states are `running`, `succeeded`, `failed`, `cancelled`, `timed_out` and `output_limit`.
138
+ Output includes a log path for further reads. `truncated` describes the shared preview, not disk capture. The preview includes omission information and total lines/bytes; the task includes captured byte count and a full-log path for targeted follow-up reads. A smaller preview can miss an earlier root cause; use a focused search when it does. `task.capture_complete` is false while running or when log data was lost. The states are `running`, `succeeded`, `failed`, `cancelled`, `timed_out` and `output_limit`.
106
139
 
107
- Output streams to private temporary logs (directory 0700, files 0600 on Unix), with bounded memory and range-limited reads. Log errors stop the task and are reported. Stdout and stderr are merged; strict ordering across the two streams is not promised. Logs and command arguments can contain secrets: choose commands accordingly.
140
+ Output streams to private temporary logs (directory 0700, files 0600 on Unix), with bounded memory and range-limited reads. Log errors stop the task and are reported. Stdout and stderr are merged; strict ordering across the two streams is not promised. Logs and command arguments can contain secrets: avoid commands that print credentials or other sensitive data, and inspect captured content only when needed.
108
141
 
109
142
  ## Bash and background execution
110
143
 
111
- Use Bash when you need a command's result before proceeding. Use `background_task` directly when the command should keep running after the model's turn ends. Completion notifies the model automatically; do not add sleep or polling calls to wait for it.
144
+ Use Bash when you need a command's result before proceeding. Use `background_task` directly when the command should keep running after the model's turn ends. Completion notifies the model automatically. Inspect status with `list` or logs with `output` on demand, including while running and before any notification; do not add sleep or repeated polling to wait for completion.
112
145
 
113
146
  Codemode cannot call this model-only tool. Starting an unawaited Bash call in Codemode is not a substitute: Codemode cancels unfinished nested calls when its script ends.
114
147
 
package/TESTING.md CHANGED
@@ -11,13 +11,17 @@ npm pack ./packages/background-tasks --dry-run
11
11
  Tests use Node's built-in test runner. They resolve host peers from the installed Pi rather than installing another copy. npm's workspace `node_modules/.bin` directories are excluded from this lookup because they can contain an older development Pi. Set `PI_TEST_BINARY=/absolute/path/to/pi` to choose a specific host.
12
12
 
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
- - `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.
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, 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
- - `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
- - `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.
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.
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
+ - `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
+ - `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.
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.
20
22
 
23
+ The compaction fixtures seed a completed earlier turn and sufficient recent context explicitly; their ability to compact must not depend on how verbose the start result is. Active-compaction interrupt cases count their completed warm-up request separately.
24
+
21
25
  Compaction cancellation assertions use native lifecycle `aborted` flags and the absence of a saved compaction entry, not version-dependent error strings. Agent interruption is a different state and is tested separately.
22
26
 
23
27
  Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second delays, the repeated 30-second cap, retention across 24 hours of busy time, one timer shared by new completions, immediate boundary delivery, fresh-batch reset, and cleanup on terminal reads, abort/error boundaries and session replacement. No compression-event subscription or notification pause action is introduced. Offline fixtures prove guidance delivery, not that a live model always obeys it; no paid/live-model anti-polling evaluation is part of this suite.
@@ -44,12 +48,22 @@ gnome-terminal.real --wait --window --title='Pi Background Tasks Smoke' --geomet
44
48
 
45
49
  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
50
 
51
+ ## Real Herdr view
52
+
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`:
54
+
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.
60
+
47
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.
48
62
 
49
63
  ## Media and workspace checks
50
64
 
51
65
  ```bash
52
- node scripts/capture-package-media.mjs background-tasks
66
+ HERDR_MEDIA_WINDOW_ID=<visible-herdr-window-id> node scripts/capture-package-media.mjs background-tasks
53
67
  node tests/package-layout.mjs
54
68
  node tests/release-check.mjs
55
69
  npm test
@@ -58,6 +72,12 @@ npm pack --dry-run
58
72
  git diff --check
59
73
  ```
60
74
 
61
- The media command requires the real-TUI screenshot prerequisites above, plus Pillow. It reruns the real TUI and renders PNG/GIF from captured running/completed/history frames, not invented output. Inspect and click both links in `docs/package-media-gallery.html` with Chrome. The root tarball must include `packages/background-tasks/`, and the root default loadout must enable its extension exactly once. The standalone tarball remains independently loadable.
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.
62
82
 
63
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.
package/docs/demo.gif CHANGED
Binary file
package/docs/demo.webm ADDED
Binary file
Binary file
Binary file
@@ -4,10 +4,14 @@ 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;
10
- const startGuidance = "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.";
12
+ const startNotice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
13
+ // Bound model-visible status text when many completions accumulate.
14
+ const NOTIFICATION_MAX_BYTES = 16 * 1024;
11
15
  type Action = typeof actions[number];
12
16
  interface Params {
13
17
  action: Action;
@@ -18,12 +22,12 @@ interface Params {
18
22
  id?: string;
19
23
  }
20
24
  const Parameters = Type.Object({
21
- action: StringEnum(actions, { description: "start returns a task ID immediately; list checks tasks; output reads a bash-limited snapshot; cancel stops one task" }),
25
+ action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task. list and output also work while tasks are running." }),
22
26
  command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed." })),
23
27
  description: Type.Optional(Type.String({ description: "Short display label for start" })),
24
28
  cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
25
29
  timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 7200, description: "Runtime limit for start, in seconds: default 1800 (30 minutes), maximum 7200 (2 hours); no unlimited mode" })),
26
- id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output shows the last 2000 lines or 50 KiB, plus a log path." })),
30
+ id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output returns a bounded snapshot (last 100 lines or 8 KiB) and the captured log path." })),
27
31
  }, { additionalProperties: false });
28
32
  const TaskSchema = Type.Object({
29
33
  id: Type.String(), status: StringEnum(["running", "succeeded", "failed", "cancelled", "timed_out", "output_limit"] as const),
@@ -35,7 +39,6 @@ const OutputSchema = Type.Object({
35
39
  action: Type.Optional(StringEnum(actions)), task: Type.Optional(TaskSchema), tasks: Type.Optional(Type.Array(TaskSchema)),
36
40
  running: Type.Optional(Type.Number()), total: Type.Optional(Type.Number()), omitted: Type.Optional(Type.Number()),
37
41
  output: Type.Optional(Type.String()), truncated: Type.Optional(Type.Boolean()), full_output_path: Type.Optional(Type.String()),
38
- guidance: Type.Optional(Type.String()),
39
42
  error: Type.Optional(Type.String()),
40
43
  });
41
44
 
@@ -51,14 +54,29 @@ function validate(params: Params): void {
51
54
  function formatTask(task: TaskSnapshot): string {
52
55
  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
56
  }
54
- function parseCommand(input: string): Params {
57
+
58
+ function completionText(task: TaskSnapshot): string {
59
+ const lines = [formatTask(task), `Ended at: ${new Date(task.ended_at!).toISOString()}`];
60
+ if (task.reason) lines.push(`Reason: ${task.reason}`);
61
+ lines.push(`Captured log: ${task.log_path}`);
62
+ if (!task.capture_complete) lines.push("Output capture is incomplete.");
63
+ return lines.join("\n");
64
+ }
65
+
66
+ function parseCommand(input: string): Params | { action: "watch"; id: string } {
55
67
  const parts = input.trim().split(/\s+/).filter(Boolean);
56
68
  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>]");
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;
59
77
  }
60
78
 
61
- export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string } = {}) {
79
+ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string; herdr?: HerdrCall; env?: NodeJS.ProcessEnv; sleep?: (ms: number) => Promise<void> } = {}) {
62
80
  const clock = dependencies.clock ?? systemClock;
63
81
  let manager: BackgroundTasks | undefined;
64
82
  let context: ExtensionContext | undefined;
@@ -69,6 +87,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
69
87
  let interrupted = false;
70
88
  const pending = new Map<string, TaskSnapshot>();
71
89
  let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
90
+ let viewer: HerdrViewer | undefined;
72
91
 
73
92
  const clearNotificationTimer = () => {
74
93
  if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
@@ -77,14 +96,25 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
77
96
  const takeNotification = () => {
78
97
  clearNotificationTimer();
79
98
  if (pending.size === 0) return;
99
+ if (!manager) throw new Error("Cannot deliver background results without their session manager");
80
100
  const tasks = [...pending.values()].sort((a, b) => a.ended_at! - b.ended_at!);
81
- pending.clear();
101
+ const selected: TaskSnapshot[] = [];
102
+ const parts = ["[Background task finished]"];
103
+ const guidance = "\n\nInspect logs progressively as needed: search for relevant terms or read bounded ranges; avoid loading the whole log by default.";
104
+ const more = "\n\nMore completed task results remain pending.";
105
+ for (const record of tasks) {
106
+ const task = manager.get(record.id);
107
+ const text = completionText(task);
108
+ if (Buffer.byteLength([...parts, text].join("\n\n") + guidance + more) > NOTIFICATION_MAX_BYTES) break;
109
+ parts.push(text);
110
+ selected.push(task);
111
+ }
112
+ if (!selected.length) throw new Error("A background completion exceeds the notification byte limit");
113
+ for (const task of selected) pending.delete(task.id);
82
114
  return {
83
115
  customType: "background-task-finished", display: true,
84
- details: { tasks, ...(tasks.length === 1 ? { task: tasks[0] } : {}) },
85
- content: `[Background task finished]\n${tasks.map((task) =>
86
- `${formatTask(task)}\nEnded at: ${new Date(task.ended_at!).toISOString()}${task.reason ? `\nReason: ${task.reason}` : ""}\nCaptured log: ${task.log_path}${task.capture_complete ? "" : "\nOutput capture is incomplete."}`
87
- ).join("\n\n")}`,
116
+ details: { tasks: selected, ...(selected.length === 1 ? { task: selected[0] } : {}) },
117
+ content: parts.join("\n\n") + guidance + (pending.size ? more : ""),
88
118
  };
89
119
  };
90
120
  const scheduleNotification = (delay = 0) => {
@@ -136,6 +166,11 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
136
166
  if (!event.aborted && completedNormally) scheduleNotification();
137
167
  });
138
168
 
169
+ const watch = (id: string) => {
170
+ 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"));
173
+ };
139
174
  const clearTimer = () => {
140
175
  if (timer !== undefined) clock.clearTimeout(timer);
141
176
  timer = undefined;
@@ -162,7 +197,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
162
197
  mounted.tui.requestRender();
163
198
  } else {
164
199
  context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
165
- const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme);
200
+ const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, viewer ? watch : undefined);
166
201
  mounted = { widget, tui };
167
202
  return widget;
168
203
  }, { placement: "aboveEditor" });
@@ -176,8 +211,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
176
211
  generation++;
177
212
  const previous = manager;
178
213
  const previousContext = context;
214
+ const previousViewer = viewer;
179
215
  manager = undefined;
180
216
  context = undefined;
217
+ viewer = undefined;
181
218
  clearTimer();
182
219
  clearNotificationTimer();
183
220
  pending.clear();
@@ -189,17 +226,27 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
189
226
  if (previousContext.mode === "tui") previousContext.ui.setWidget(WIDGET_KEY, undefined);
190
227
  }
191
228
  mounted = undefined;
192
- } finally { await previous?.shutdown(); }
229
+ } finally {
230
+ // Cancel tasks first and synchronously; closing the view tab must not delay that.
231
+ await Promise.all([previous?.shutdown(), previousViewer?.dispose()]);
232
+ }
193
233
  };
194
234
  pi.on("session_start", async (_event, ctx) => {
195
235
  await dispose();
196
236
  context = ctx;
197
237
  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;
198
244
  manager = new BackgroundTasks({
199
245
  operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
200
246
  onChange() { if (generation === epoch) refresh(); },
201
247
  onComplete(task) {
202
248
  if (generation !== epoch || !context) return;
249
+ viewer?.finished(task);
203
250
  pending.set(task.id, task);
204
251
  scheduleNotification();
205
252
  },
@@ -212,9 +259,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
212
259
  if (!manager) throw new Error("Background tasks session is not ready");
213
260
  if (params.action === "start") {
214
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!);
215
263
  return {
216
- 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
- data: { action: params.action, task, guidance: startGuidance }, details: { action: params.action, task }, isError: false,
264
+ text: `Started ${formatTask(task)}\n${startNotice}`,
265
+ data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
218
266
  };
219
267
  }
220
268
  if (params.action === "list") {
@@ -241,7 +289,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
241
289
  pi.registerTool({
242
290
  name: "background_task", label: "Background task",
243
291
  exposure: "model-only",
244
- description: `Start shell commands as background tasks and return task IDs immediately. Supports status, output, and cancellation. After start: ${startGuidance}`,
292
+ description: "Run up to two concurrent background shell tasks with automatic completion notifications. Tasks stop and captured logs are deleted on session changes, reload, or exit.",
245
293
  parameters: Parameters, outputSchema: OutputSchema,
246
294
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
247
295
  async execute(_id, params, signal, _onUpdate, ctx) {
@@ -270,10 +318,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
270
318
  },
271
319
  });
272
320
  pi.registerCommand("bg", {
273
- description: "List background shell tasks, read output, or cancel a task",
321
+ description: "List background shell tasks, read output, cancel a task, or watch it in Herdr",
274
322
  handler: async (args, ctx) => {
275
323
  try {
276
- const result = await perform(parseCommand(args), ctx.cwd);
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);
277
333
  pi.sendMessage({ customType: "background-task-inspect", content: result.text, display: true, details: result.details }, { triggerTurn: false });
278
334
  } catch (error) { ctx.ui.notify(errorText(error), "error"); }
279
335
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxiaochao/pi-background-tasks",
3
- "version": "0.1.2",
3
+ "version": "0.3.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
+ }