@maxiaochao/pi-background-tasks 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +33 -19
- package/TESTING.md +11 -7
- package/docs/demo.gif +0 -0
- package/docs/demo.webm +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/task-panes.png +0 -0
- package/extensions/background-tasks.ts +34 -13
- package/package.json +1 -1
- package/src/output.ts +14 -25
- package/src/viewer.ts +22 -11
- package/tests/compaction.mjs +5 -1
- package/tests/extension.mjs +163 -14
- package/tests/fixtures/notifications.ts +1 -1
- package/tests/fixtures/provider.ts +8 -3
- package/tests/interruptions.mjs +19 -10
- package/tests/media.mjs +16 -0
- package/tests/notifications.mjs +18 -6
- package/tests/output.mjs +32 -8
- package/tests/processes.mjs +2 -2
- package/tests/runtime.mjs +12 -0
- package/tests/viewer.mjs +91 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-11-05 - v0.3.1
|
|
4
|
+
|
|
5
|
+
- Use descriptive task views and clarify captured logs and automatic completion waiting
|
|
6
|
+
- Name Herdr tabs `BG · <task description>` and panes `<number> · <task description>`, following Herdr Subagents. Update the shared tab name on start/watch/completion, retain task numbers across pane reuse/reopening, and print the task name above the command so it is visible with one pane.
|
|
7
|
+
- Clarify in the command parameter that stdout/stderr are saved to a unique per-task log and the path is reported on completion.
|
|
8
|
+
- Tighten the start reminder: when nothing else remains, end the turn instead of sleeping, tailing logs or querying just to wait.
|
|
9
|
+
|
|
10
|
+
## 2026-11-03 - v0.3.0
|
|
11
|
+
|
|
12
|
+
- Report completion status and log paths for progressive inspection with bounded explicit output
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
- 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.
|
|
18
|
+
|
|
3
19
|
## 2026-10-29 - v0.2.0
|
|
4
20
|
|
|
5
21
|
- Add live read-only Herdr task views, exact widget navigation and real two-task terminal media
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Pi Background Tasks
|
|
2
2
|
|
|
3
|
-
Run shell commands in the background, then notify the main agent
|
|
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
5
|

|
|
6
6
|
|
|
@@ -18,7 +18,7 @@ A command such as `sleep 60; python3 ...` can spend most of its time waiting to
|
|
|
18
18
|
|
|
19
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.
|
|
20
20
|
|
|
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.
|
|
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.
|
|
22
22
|
|
|
23
23
|
## Install and update
|
|
24
24
|
|
|
@@ -39,26 +39,28 @@ background_task({ action: "start", command: "sleep 10; printf 'checks complete\\
|
|
|
39
39
|
|
|
40
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.
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
The tool declaration describes automatic completion notifications, concurrency and session lifetime. The action parameter explicitly permits `list` and `output` while tasks are still running. Each accepted start returns only its task data and this short, task-specific reminder:
|
|
43
43
|
|
|
44
|
-
>
|
|
44
|
+
> Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.
|
|
45
45
|
|
|
46
|
-
|
|
46
|
+
The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
|
|
47
|
+
|
|
48
|
+
Inspect a running or finished task whenever its output is needed; no completion or timeout notification is required:
|
|
47
49
|
|
|
48
50
|
```text
|
|
49
51
|
background_task({ action: "output", id: "<returned-task-id>" })
|
|
50
52
|
```
|
|
51
53
|
|
|
52
|
-
The tool also supports
|
|
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:
|
|
53
55
|
|
|
54
56
|
```text
|
|
55
57
|
background_task({ action: "list" })
|
|
56
58
|
background_task({ action: "cancel", id: "<returned-task-id>" })
|
|
57
59
|
```
|
|
58
60
|
|
|
59
|
-
Start returns a running task's ID
|
|
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.
|
|
60
62
|
|
|
61
|
-
- `command`: unchanged multi-line shell script; only for start.
|
|
63
|
+
- `command`: unchanged multi-line shell script; only for start. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.
|
|
62
64
|
- `description`: optional display label, shortened to 200 characters.
|
|
63
65
|
- `cwd`: optional directory, resolved relative to the current session directory.
|
|
64
66
|
- `timeout`: integer seconds, **1800 by default**, from 1 through 7200. Zero and unlimited mode are rejected.
|
|
@@ -84,10 +86,12 @@ A fixed widget **above the editor** shows each task's ID, status, elapsed time,
|
|
|
84
86
|
|
|
85
87
|
## Herdr task view
|
|
86
88
|
|
|
87
|
-
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one
|
|
89
|
+
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one per-session **BG · <task description>** tab:
|
|
88
90
|
|
|
89
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.
|
|
90
|
-
-
|
|
92
|
+
- Like Herdr Subagents, the tab has a descriptive name and panes use numbered task names (`01 · Release build`, `02 · Unit tests`). Starting or watching a task updates the shared tab's name to that task's description. When one task ends, the tab names the remaining running task. Task numbers stay stable when panes are closed, reopened or reused.
|
|
93
|
+
- Each pane prints its numbered task name, the command (`$ ...`), cwd and runtime limit, then follows the task's captured log with `tail -f`. The task name remains visible even when the single-pane layout hides the pane label. Line output and `\r` progress updates appear live. When the task ends, the pane prints a result line such as `[failed · exit 4 · 6s]`.
|
|
94
|
+
- The view follows the tool's captured stdout/stderr, not files chosen by the command. Redirecting all output to another file leaves this log empty. No extra redirection is needed merely to inspect output later; use the reported log path. If an extra copy is required, `set -o pipefail; command 2>&1 | tee <unique-path>` preserves live output and command failures. The copy still counts toward the capture limit.
|
|
91
95
|
- The pane is a **viewer only**. The task runs through the same local backend as outside Herdr, with the same logs, limits, status and notifications. The command has no TTY, so tools that detect one may drop colour or animated progress bars.
|
|
92
96
|
- Closing a pane, or the whole tab, does not cancel the task. Clicking a task row in the widget (Pi 1.4+ fullscreen mode) or `/bg watch <id>` reopens the pane if needed and focuses that tab and pane; use `/bg cancel <id>` to stop the task.
|
|
93
97
|
- When no task runs any more, the tab closes. If the user is looking at it, it closes after focus moves to another tab. Session shutdown, reload and replacement close it immediately, together with the logs.
|
|
@@ -98,8 +102,8 @@ There is no setting to turn the view off.
|
|
|
98
102
|
|
|
99
103
|
Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
|
|
100
104
|
|
|
101
|
-
- While the main agent is busy, completions are combined into
|
|
102
|
-
- 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.
|
|
105
|
+
- 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.
|
|
106
|
+
- 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.
|
|
103
107
|
- 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.
|
|
104
108
|
- 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.
|
|
105
109
|
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks. A running snapshot, `list`, a failed log read, or a user `/bg output` inspection does not consume the main agent's reminder. Consumption does not mean the task passed validation.
|
|
@@ -109,7 +113,15 @@ Completion, failure, cancellation, timeout and output-limit termination update t
|
|
|
109
113
|
|
|
110
114
|
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.
|
|
111
115
|
|
|
112
|
-
Each message includes
|
|
116
|
+
Each completion message includes task status, exit code when available, actual end time, reason when applicable and **the captured log path**, followed by:
|
|
117
|
+
|
|
118
|
+
> Inspect logs progressively as needed: search for relevant terms or read bounded ranges; avoid loading the whole log by default.
|
|
119
|
+
|
|
120
|
+
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.
|
|
121
|
+
|
|
122
|
+
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.
|
|
123
|
+
|
|
124
|
+
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.
|
|
113
125
|
|
|
114
126
|
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.
|
|
115
127
|
|
|
@@ -117,19 +129,21 @@ Pi reports asynchronous message/run-start failures through its extension error c
|
|
|
117
129
|
|
|
118
130
|
| View | Limit |
|
|
119
131
|
| --- | --- |
|
|
120
|
-
| Model-visible output | Last
|
|
121
|
-
|
|
|
132
|
+
| Model-visible output body | Last 100 lines or 8 KiB, whichever is reached first |
|
|
133
|
+
| `structuredContent.output` | The same bounded tail; no separate 1 MiB program view |
|
|
134
|
+
| Automatic completion log bodies | None; only status, log paths and progressive-inspection guidance |
|
|
135
|
+
| Completion status/path text | 16 KiB defensive batch cap; remaining tasks stay pending |
|
|
122
136
|
| Disk capture | 32 MiB per task, 256 MiB total per session |
|
|
123
137
|
|
|
124
|
-
|
|
138
|
+
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.
|
|
125
139
|
|
|
126
|
-
Output includes a log path for further reads. `truncated` describes the
|
|
140
|
+
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`.
|
|
127
141
|
|
|
128
|
-
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:
|
|
142
|
+
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.
|
|
129
143
|
|
|
130
144
|
## Bash and background execution
|
|
131
145
|
|
|
132
|
-
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
|
|
146
|
+
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.
|
|
133
147
|
|
|
134
148
|
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.
|
|
135
149
|
|
package/TESTING.md
CHANGED
|
@@ -11,21 +11,25 @@ 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
|
|
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
|
|
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
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
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 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
|
|
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
|
|
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.
|
|
21
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.
|
|
22
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
|
+
|
|
23
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.
|
|
24
26
|
|
|
25
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.
|
|
26
28
|
|
|
27
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.
|
|
28
30
|
|
|
31
|
+
The deterministic registration test checks the approved per-task-log sentence in the `command` parameter description. The native offline-provider test verifies it is visible in the first model request, before starting a task. Viewer tests check single-task names, shared-tab renaming on start/watch/completion, stable task numbers when the left pane is closed and reopened, and pane reuse.
|
|
32
|
+
|
|
29
33
|
## Real Pi TUI
|
|
30
34
|
|
|
31
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.
|
|
@@ -50,8 +54,8 @@ It relays the real PTY output, captures only the test window, then closes it. In
|
|
|
50
54
|
|
|
51
55
|
Run from a Pi or shell inside Herdr (`HERDR_ENV=1`). Start two real tasks through the production extension, for example one `printf 'tick %s\r'` loop that succeeds and one `sleep 6; exit 4` that fails. Check with `herdr tab list`, `herdr pane list` and `herdr pane read`:
|
|
52
56
|
|
|
53
|
-
- One unfocused **
|
|
54
|
-
- Each pane shows the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`).
|
|
57
|
+
- One unfocused **BG · <task description>** tab with two panes while both run. Starting or watching a task updates the tab name; each pane has a numbered task name.
|
|
58
|
+
- Each pane shows its task name above the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`). Check the name is visible with only one pane too.
|
|
55
59
|
- With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
|
|
56
60
|
- In a fullscreen Pi started in its own Herdr pane, an SGR click on each widget task row (`herdr pane send-text <pane> $'\e[<0;10;<row>M\e[<0;10;<row>m'`) focuses the tab and that task's pane (`herdr pane list`).
|
|
57
61
|
- No warning is shown, and the private log directory is removed after session shutdown.
|
|
@@ -72,7 +76,7 @@ git diff --check
|
|
|
72
76
|
|
|
73
77
|
The media command requires the real-TUI screenshot prerequisites above, Pillow, and GStreamer (`ximagesrc`, VP8/WebM encoding/decoding, and PNG encoding). Select the X11 window that already displays a working Herdr client with `HERDR_MEDIA_WINDOW_ID`; the GNOME desktop must be unlocked. The recorder checks the lock state before starting and at each screenshot; hidden windows can return stale pixels.
|
|
74
78
|
|
|
75
|
-
The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
|
|
79
|
+
The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs in sequence. It first verifies the single-pane tab name and visible task header, then adds the second task. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
|
|
76
80
|
|
|
77
81
|
The recorder captures the selected client window continuously, rejects uniform/blank screenshot centres, restores the original workspace/tab, and removes its own workspace. It never starts paid models or copies credentials. `result.json`, tool events and diagnostic frames are stored under `.cache/package-media/background-herdr`. The renderer publishes `docs/screenshot.png` (parent widget), `docs/task-panes.png` (actual task panes), `docs/demo.gif` (frames decoded from the recording), and the complete `docs/demo.webm`. No synthetic UI is drawn.
|
|
78
82
|
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/demo.webm
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
package/docs/task-panes.png
CHANGED
|
Binary file
|
|
@@ -9,7 +9,9 @@ import { HerdrViewer } from "../src/viewer.ts";
|
|
|
9
9
|
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
10
10
|
|
|
11
11
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
12
|
-
const
|
|
12
|
+
const startNotice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
13
|
+
// Bound model-visible status text when many completions accumulate.
|
|
14
|
+
const NOTIFICATION_MAX_BYTES = 16 * 1024;
|
|
13
15
|
type Action = typeof actions[number];
|
|
14
16
|
interface Params {
|
|
15
17
|
action: Action;
|
|
@@ -20,12 +22,12 @@ interface Params {
|
|
|
20
22
|
id?: string;
|
|
21
23
|
}
|
|
22
24
|
const Parameters = Type.Object({
|
|
23
|
-
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks
|
|
24
|
-
command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed." })),
|
|
25
|
+
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task. list and output also work while tasks are running." }),
|
|
26
|
+
command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion." })),
|
|
25
27
|
description: Type.Optional(Type.String({ description: "Short display label for start" })),
|
|
26
28
|
cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
|
|
27
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" })),
|
|
28
|
-
id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output
|
|
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." })),
|
|
29
31
|
}, { additionalProperties: false });
|
|
30
32
|
const TaskSchema = Type.Object({
|
|
31
33
|
id: Type.String(), status: StringEnum(["running", "succeeded", "failed", "cancelled", "timed_out", "output_limit"] as const),
|
|
@@ -37,7 +39,6 @@ const OutputSchema = Type.Object({
|
|
|
37
39
|
action: Type.Optional(StringEnum(actions)), task: Type.Optional(TaskSchema), tasks: Type.Optional(Type.Array(TaskSchema)),
|
|
38
40
|
running: Type.Optional(Type.Number()), total: Type.Optional(Type.Number()), omitted: Type.Optional(Type.Number()),
|
|
39
41
|
output: Type.Optional(Type.String()), truncated: Type.Optional(Type.Boolean()), full_output_path: Type.Optional(Type.String()),
|
|
40
|
-
guidance: Type.Optional(Type.String()),
|
|
41
42
|
error: Type.Optional(Type.String()),
|
|
42
43
|
});
|
|
43
44
|
|
|
@@ -53,6 +54,15 @@ function validate(params: Params): void {
|
|
|
53
54
|
function formatTask(task: TaskSnapshot): string {
|
|
54
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)}`;
|
|
55
56
|
}
|
|
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
|
+
|
|
56
66
|
function parseCommand(input: string): Params | { action: "watch"; id: string } {
|
|
57
67
|
const parts = input.trim().split(/\s+/).filter(Boolean);
|
|
58
68
|
if (parts.length === 0 || (parts.length === 1 && parts[0] === "list")) return { action: "list" };
|
|
@@ -86,14 +96,25 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
86
96
|
const takeNotification = () => {
|
|
87
97
|
clearNotificationTimer();
|
|
88
98
|
if (pending.size === 0) return;
|
|
99
|
+
if (!manager) throw new Error("Cannot deliver background results without their session manager");
|
|
89
100
|
const tasks = [...pending.values()].sort((a, b) => a.ended_at! - b.ended_at!);
|
|
90
|
-
|
|
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);
|
|
91
114
|
return {
|
|
92
115
|
customType: "background-task-finished", display: true,
|
|
93
|
-
details: { tasks, ...(
|
|
94
|
-
content:
|
|
95
|
-
`${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."}`
|
|
96
|
-
).join("\n\n")}`,
|
|
116
|
+
details: { tasks: selected, ...(selected.length === 1 ? { task: selected[0] } : {}) },
|
|
117
|
+
content: parts.join("\n\n") + guidance + (pending.size ? more : ""),
|
|
97
118
|
};
|
|
98
119
|
};
|
|
99
120
|
const scheduleNotification = (delay = 0) => {
|
|
@@ -240,8 +261,8 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
240
261
|
const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
|
|
241
262
|
void viewer?.show(task, params.command!);
|
|
242
263
|
return {
|
|
243
|
-
text: `Started ${formatTask(task)}\n${
|
|
244
|
-
data: { action: params.action, task
|
|
264
|
+
text: `Started ${formatTask(task)}\n${startNotice}`,
|
|
265
|
+
data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
|
|
245
266
|
};
|
|
246
267
|
}
|
|
247
268
|
if (params.action === "list") {
|
|
@@ -268,7 +289,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
268
289
|
pi.registerTool({
|
|
269
290
|
name: "background_task", label: "Background task",
|
|
270
291
|
exposure: "model-only",
|
|
271
|
-
description:
|
|
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.",
|
|
272
293
|
parameters: Parameters, outputSchema: OutputSchema,
|
|
273
294
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
274
295
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
package/package.json
CHANGED
package/src/output.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { closeSync, openSync, readSync, writeSync } from "node:fs";
|
|
2
|
-
import {
|
|
2
|
+
import { formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const OUTPUT_MAX_BYTES = 8 * 1024;
|
|
5
|
+
const OUTPUT_MAX_LINES = 100;
|
|
5
6
|
export type LogWrite = (fd: number, data: Buffer) => number;
|
|
6
7
|
|
|
7
8
|
export interface OutputView {
|
|
@@ -23,6 +24,7 @@ export class TaskLog {
|
|
|
23
24
|
private lines = 0;
|
|
24
25
|
private openLine = false;
|
|
25
26
|
private lastLineBytes = 0;
|
|
27
|
+
private lastCompletedLineBytes = 0;
|
|
26
28
|
|
|
27
29
|
constructor(path: string, write: LogWrite = (fd, data) => writeSync(fd, data)) {
|
|
28
30
|
this.path = path;
|
|
@@ -55,7 +57,7 @@ export class TaskLog {
|
|
|
55
57
|
try {
|
|
56
58
|
// Keep a bounded working window comparable to Bash's rolling tail. This
|
|
57
59
|
// preserves an oversized last line that ends with a newline before trimming.
|
|
58
|
-
const start = Math.max(0, this.bytes -
|
|
60
|
+
const start = Math.max(0, this.bytes - OUTPUT_MAX_BYTES * 4 - 4);
|
|
59
61
|
const tail = this.range(fd, start, this.bytes - start);
|
|
60
62
|
let first = 0;
|
|
61
63
|
while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
|
|
@@ -64,14 +66,14 @@ export class TaskLog {
|
|
|
64
66
|
const previous = this.range(fd, start - 1, 1)[0];
|
|
65
67
|
if (first > 0 || previous !== 0x0a) {
|
|
66
68
|
const newline = snapshot.indexOf("\n");
|
|
67
|
-
if (newline !== -1) snapshot = snapshot.slice(newline + 1);
|
|
69
|
+
if (newline !== -1 && newline < snapshot.length - 1) snapshot = snapshot.slice(newline + 1);
|
|
68
70
|
}
|
|
69
71
|
}
|
|
70
|
-
const truncation = truncateTail(snapshot);
|
|
72
|
+
const truncation = truncateTail(snapshot, { maxLines: OUTPUT_MAX_LINES, maxBytes: OUTPUT_MAX_BYTES });
|
|
71
73
|
const totalLines = this.lines + (this.openLine ? 1 : 0);
|
|
72
|
-
truncation.truncated = totalLines >
|
|
74
|
+
truncation.truncated = totalLines > OUTPUT_MAX_LINES || this.decodedBytes > OUTPUT_MAX_BYTES;
|
|
73
75
|
truncation.truncatedBy = truncation.truncated
|
|
74
|
-
? (truncation.truncatedBy ?? (this.decodedBytes >
|
|
76
|
+
? (truncation.truncatedBy ?? (this.decodedBytes > OUTPUT_MAX_BYTES ? "bytes" : "lines")) : null;
|
|
75
77
|
truncation.totalLines = totalLines;
|
|
76
78
|
truncation.totalBytes = this.decodedBytes;
|
|
77
79
|
let text = truncation.content || "(no output)";
|
|
@@ -79,29 +81,14 @@ export class TaskLog {
|
|
|
79
81
|
const end = totalLines;
|
|
80
82
|
const begin = end - truncation.outputLines + 1;
|
|
81
83
|
const detail = truncation.lastLinePartial
|
|
82
|
-
? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.lastLineBytes)})`
|
|
83
|
-
: `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(
|
|
84
|
+
? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.openLine ? this.lastLineBytes : this.lastCompletedLineBytes)})`
|
|
85
|
+
: `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(OUTPUT_MAX_BYTES)} limit)` : ""}`;
|
|
84
86
|
text += `\n\n[Showing ${detail}. Full output: ${this.path}]`;
|
|
85
87
|
}
|
|
86
|
-
|
|
87
|
-
return { text, output: program.content, truncated: program.truncated, truncation };
|
|
88
|
+
return { text, output: truncation.content, truncated: truncation.truncated, truncation };
|
|
88
89
|
} finally { closeSync(fd); }
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
private readProgram(fd: number): { content: string; truncated: boolean } {
|
|
92
|
-
if (this.bytes <= PROGRAM_BYTES) {
|
|
93
|
-
return { content: new TextDecoder().decode(this.range(fd, 0, this.bytes), { stream: !this.closed }), truncated: false };
|
|
94
|
-
}
|
|
95
|
-
const half = PROGRAM_BYTES / 2;
|
|
96
|
-
const head = this.range(fd, 0, half);
|
|
97
|
-
const tail = this.range(fd, this.bytes - half, half);
|
|
98
|
-
const headText = new TextDecoder().decode(head, { stream: true });
|
|
99
|
-
let first = 0;
|
|
100
|
-
while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
|
|
101
|
-
const tailText = new TextDecoder().decode(tail.subarray(first), { stream: !this.closed });
|
|
102
|
-
return { content: `${headText}\n\n[... ${this.bytes - PROGRAM_BYTES} bytes omitted ...]\n\n${tailText}`, truncated: true };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
92
|
private range(fd: number, position: number, length: number): Buffer {
|
|
106
93
|
const data = Buffer.alloc(length);
|
|
107
94
|
let offset = 0;
|
|
@@ -120,6 +107,8 @@ export class TaskLog {
|
|
|
120
107
|
if (text.length) this.openLine = true;
|
|
121
108
|
this.lastLineBytes += Buffer.byteLength(text);
|
|
122
109
|
} else {
|
|
110
|
+
const previous = last === 0 ? -1 : text.lastIndexOf("\n", last - 1);
|
|
111
|
+
this.lastCompletedLineBytes = Buffer.byteLength(text.slice(previous + 1, last)) + (previous === -1 ? this.lastLineBytes : 0);
|
|
123
112
|
for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) this.lines++;
|
|
124
113
|
this.lastLineBytes = Buffer.byteLength(text.slice(last + 1));
|
|
125
114
|
this.openLine = last < text.length - 1;
|
package/src/viewer.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { existsSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { stripVTControlCharacters } from "node:util";
|
|
4
|
-
import { errorText, type TaskSnapshot } from "./background-tasks.ts";
|
|
4
|
+
import { errorText, summary, type TaskSnapshot } from "./background-tasks.ts";
|
|
5
5
|
import { isMissing, type HerdrCall } from "./herdr.ts";
|
|
6
6
|
import { duration } from "./widget.ts";
|
|
7
7
|
|
|
8
|
-
export const TAB_LABEL = "Background tasks";
|
|
9
8
|
const UNFOCUS_POLL_MS = 1000;
|
|
10
9
|
|
|
11
10
|
// Runs inside the pane's own shell. It only reads files; the task itself runs elsewhere.
|
|
@@ -34,6 +33,7 @@ interface Options {
|
|
|
34
33
|
|
|
35
34
|
function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
|
|
36
35
|
function clean(text: string): string { return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); }
|
|
36
|
+
function tabLabel(task: TaskSnapshot): string { return summary(`BG · ${task.description}`, 80); }
|
|
37
37
|
|
|
38
38
|
/**
|
|
39
39
|
* Shows background task logs in one Herdr tab per session. Display only: every failure
|
|
@@ -41,7 +41,7 @@ function clean(text: string): string { return stripVTControlCharacters(text).rep
|
|
|
41
41
|
*/
|
|
42
42
|
export class HerdrViewer {
|
|
43
43
|
private readonly options: Options;
|
|
44
|
-
private readonly commands = new Map<string, string>();
|
|
44
|
+
private readonly commands = new Map<string, { text: string; order: number }>();
|
|
45
45
|
private tab?: string;
|
|
46
46
|
private panes: Pane[] = [];
|
|
47
47
|
private chain: Promise<unknown> = Promise.resolve();
|
|
@@ -58,7 +58,7 @@ export class HerdrViewer {
|
|
|
58
58
|
|
|
59
59
|
/** Opens a pane for a newly started task without taking focus. */
|
|
60
60
|
show(task: TaskSnapshot, command: string): Promise<void> {
|
|
61
|
-
this.commands.set(task.id, command);
|
|
61
|
+
this.commands.set(task.id, { text: command, order: this.commands.size + 1 });
|
|
62
62
|
return this.enqueue(async () => { await this.open(task, false); });
|
|
63
63
|
}
|
|
64
64
|
|
|
@@ -66,7 +66,9 @@ export class HerdrViewer {
|
|
|
66
66
|
watch(task: TaskSnapshot): Promise<string> {
|
|
67
67
|
return this.enqueue(async () => {
|
|
68
68
|
await this.prune();
|
|
69
|
-
const
|
|
69
|
+
const existing = this.panes.find((entry) => entry.task === task.id);
|
|
70
|
+
const pane = existing ?? await this.open(task, false);
|
|
71
|
+
if (existing) await this.options.call(["tab", "rename", this.tab!, tabLabel(task)]);
|
|
70
72
|
await this.options.call(["tab", "focus", this.tab!]);
|
|
71
73
|
// Panes are split left to right; Herdr focuses a pane through its neighbour.
|
|
72
74
|
const index = this.panes.indexOf(pane);
|
|
@@ -82,6 +84,12 @@ export class HerdrViewer {
|
|
|
82
84
|
if (this.disposed) return;
|
|
83
85
|
try { this.writeDone(task); }
|
|
84
86
|
catch (error) { this.report(error); }
|
|
87
|
+
void this.enqueue(async () => {
|
|
88
|
+
const remaining = this.options.tasks().find((task) => task.status === "running");
|
|
89
|
+
if (!this.tab || !remaining) return;
|
|
90
|
+
try { await this.options.call(["tab", "rename", this.tab, tabLabel(remaining)]); }
|
|
91
|
+
catch (error) { if (!isMissing(error)) throw error; }
|
|
92
|
+
});
|
|
85
93
|
this.closeWhenIdle();
|
|
86
94
|
}
|
|
87
95
|
|
|
@@ -119,7 +127,7 @@ export class HerdrViewer {
|
|
|
119
127
|
let pane = this.panes.find((entry) => !running.has(entry.task));
|
|
120
128
|
try {
|
|
121
129
|
if (!this.tab) {
|
|
122
|
-
const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label",
|
|
130
|
+
const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label", tabLabel(task), "--no-focus"]);
|
|
123
131
|
this.tab = created.tab?.tab_id;
|
|
124
132
|
const root = created.root_pane?.pane_id;
|
|
125
133
|
if (!this.tab || !root) throw new Error("herdr tab create omitted the tab or pane id");
|
|
@@ -127,14 +135,17 @@ export class HerdrViewer {
|
|
|
127
135
|
this.panes = [pane];
|
|
128
136
|
} else if (pane) {
|
|
129
137
|
pane.task = task.id;
|
|
138
|
+
await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
|
|
130
139
|
} else {
|
|
131
140
|
const split = await this.options.call(["pane", "split", this.panes.at(-1)!.id, "--direction", "right", "--cwd", task.cwd, "--no-focus"]);
|
|
132
141
|
if (!split.pane?.pane_id) throw new Error("herdr pane split omitted the pane id");
|
|
133
142
|
pane = { id: split.pane.pane_id, task: task.id };
|
|
134
143
|
this.panes.push(pane);
|
|
144
|
+
await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
await this.options.call(["pane", "
|
|
146
|
+
const label = summary(`${String(this.commands.get(task.id)!.order).padStart(2, "0")} · ${task.description}`, 80);
|
|
147
|
+
await this.options.call(["pane", "rename", pane.id, label]);
|
|
148
|
+
await this.options.call(["pane", "run", pane.id, this.viewCommand(task, label)]);
|
|
138
149
|
return pane;
|
|
139
150
|
} catch (error) {
|
|
140
151
|
// The user may close a pane or the whole tab; drop stale handles and retry once.
|
|
@@ -158,13 +169,13 @@ export class HerdrViewer {
|
|
|
158
169
|
await this.options.call(["tab", "close", tab]).catch(() => {});
|
|
159
170
|
}
|
|
160
171
|
|
|
161
|
-
private viewCommand(task: TaskSnapshot): string {
|
|
172
|
+
private viewCommand(task: TaskSnapshot, label: string): string {
|
|
162
173
|
const directory = dirname(task.log_path);
|
|
163
174
|
const script = join(directory, "view.sh");
|
|
164
175
|
const header = join(directory, `${task.id}.header`);
|
|
165
176
|
if (!existsSync(script)) writeFileSync(script, VIEW_SCRIPT, { mode: 0o600 });
|
|
166
|
-
const lines = clean(this.commands.get(task.id)
|
|
167
|
-
writeFileSync(header, `${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
|
|
177
|
+
const lines = clean(this.commands.get(task.id)!.text).split("\n");
|
|
178
|
+
writeFileSync(header, `${label}\n${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
|
|
168
179
|
if (task.status !== "running") this.writeDone(task);
|
|
169
180
|
// The leading space keeps the line out of shell history where HISTCONTROL allows it.
|
|
170
181
|
return ` sh ${[script, task.log_path, this.donePath(task), header].map(quote).join(" ")}`;
|
package/tests/compaction.mjs
CHANGED
|
@@ -97,7 +97,9 @@ for (const outcome of ["success", "failure", "cancel"]) {
|
|
|
97
97
|
});
|
|
98
98
|
await session.bindExtensions({});
|
|
99
99
|
await session.prompt("Earlier context to summarize: " + "background verification history ".repeat(200));
|
|
100
|
-
|
|
100
|
+
// Keep a complete earlier turn summarizable independently of the
|
|
101
|
+
// background tool's start-result length.
|
|
102
|
+
await session.prompt("START_COMPACTION_JOB " + "Recent context to keep. ".repeat(200));
|
|
101
103
|
assert.equal(startedTask?.status, "running");
|
|
102
104
|
assert.equal(session.isIdle, true);
|
|
103
105
|
const notifications = () => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
@@ -134,6 +136,8 @@ for (const outcome of ["success", "failure", "cancel"]) {
|
|
|
134
136
|
assert.equal(notifications().length, 1);
|
|
135
137
|
assert.equal(conversationRequests().length, before + 1, "no user prompt is submitted after compact()");
|
|
136
138
|
const notification = notifications()[0];
|
|
139
|
+
assert.doesNotMatch(notification.content, /finished during compaction/);
|
|
140
|
+
assert.ok(notification.content.includes(notification.details.tasks[0].log_path));
|
|
137
141
|
const task = notification.details.tasks[0];
|
|
138
142
|
assert.equal(task.id, startedTask.id);
|
|
139
143
|
assert.equal(task.status, "failed");
|