@maxiaochao/pi-background-tasks 0.4.2 → 0.5.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 +18 -0
- package/README.md +19 -6
- package/TESTING.md +4 -4
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/shell-list.png +0 -0
- package/extensions/background-tasks.ts +84 -14
- package/package.json +2 -2
- package/src/widget.ts +64 -20
- package/tests/extension.mjs +190 -12
- package/tests/interruptions.mjs +3 -1
- package/tests/notifications.mjs +87 -3
- package/tests/panel.mjs +48 -41
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-11-26 - v0.5.1
|
|
4
|
+
|
|
5
|
+
- Compose footer statuses safely and prevent foreground waiting after background starts
|
|
6
|
+
- Restore an explicit post-start guard: automatic completion resumes the agent, while Bash sleeps, log tails, and `list`/`output` calls used only to wait are prohibited.
|
|
7
|
+
- Publish shell counts through Pi's keyed status interface and keep the clickable footer as a best-effort decorator.
|
|
8
|
+
- Compose arbitrary peer statuses without extension-specific rules, drop the shortcut hint before truncating peer state, and keep shell counts visible on narrow rows.
|
|
9
|
+
- Degrade safely when another extension owns or replaces the footer; preserve Alt+J access and never clear a later footer during reload or shutdown.
|
|
10
|
+
- Remove the unnecessary one-second TUI repaint timer while tasks are only running.
|
|
11
|
+
|
|
12
|
+
## 2026-11-25 - v0.5.0
|
|
13
|
+
|
|
14
|
+
- Add 30-minute aggregate progress turns and concise automatic-completion guidance
|
|
15
|
+
- Keep the start reminder action-oriented: continue independent work or end the turn while automatic completion delivery handles the wait. Remove the running-query prompt that encouraged status polling.
|
|
16
|
+
- Add one combined progress turn after every 30 idle minutes while background tasks remain active.
|
|
17
|
+
- Report task status, elapsed time, timeout, description, captured bytes and byte growth without injecting log contents.
|
|
18
|
+
- Reset progress timing around parent runs, preserve interrupt suppression and completion precedence, and keep `promptGuidelines` undefined.
|
|
19
|
+
- Put long-running-command selection guidance in the concise model-visible tool description.
|
|
20
|
+
|
|
3
21
|
## 2026-11-17 - v0.4.2
|
|
4
22
|
|
|
5
23
|
- Keep multiline shell previews compact without changing script execution
|
package/README.md
CHANGED
|
@@ -37,9 +37,13 @@ background_task({ action: "start", command: "sleep 10; printf 'checks complete\\
|
|
|
37
37
|
|
|
38
38
|
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.
|
|
39
39
|
|
|
40
|
-
The tool
|
|
40
|
+
The model-visible tool description is:
|
|
41
41
|
|
|
42
|
-
>
|
|
42
|
+
> Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.
|
|
43
|
+
|
|
44
|
+
Each accepted start returns only its task data and this short, task-specific reminder:
|
|
45
|
+
|
|
46
|
+
> Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.
|
|
43
47
|
|
|
44
48
|
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`.
|
|
45
49
|
|
|
@@ -49,7 +53,7 @@ Inspect a running or finished task whenever its output is needed; no completion
|
|
|
49
53
|
background_task({ action: "output", id: "<returned-task-id>" })
|
|
50
54
|
```
|
|
51
55
|
|
|
52
|
-
Use `list`
|
|
56
|
+
Use `list` when the current task status is needed. These actions are agent-callable. 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
57
|
|
|
54
58
|
```text
|
|
55
59
|
background_task({ action: "list" })
|
|
@@ -70,7 +74,7 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
|
|
|
70
74
|
|
|
71
75
|
## User controls and status
|
|
72
76
|
|
|
73
|
-
A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status row**, beside `editor: apply_patch` or other extension statuses. Without another status,
|
|
77
|
+
A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status row**, beside `editor: apply_patch` or any other extension statuses. The counter is always published through Pi's keyed status interface. A best-effort footer decorator keeps peer statuses in stable key order, pins the shell count after them, and adds click handling without naming specific extensions. Without another status, the count occupies that row alone. The existing native path, usage and model rows stay unchanged. Click the count in fullscreen mode, or press **Alt+J** in either terminal mode. One active task opens **Shell details** directly; multiple tasks open **Background**. With no active tasks, Alt+J still opens retained history.
|
|
74
78
|
|
|
75
79
|
- **List:** ↑/↓ selects a shell, Enter opens its details, and clicking a task row opens that task. Running tasks appear first, followed by **Earlier in this session**. At most eight task rows are visible; selection scrolls the retained history (latest 20 finished tasks).
|
|
76
80
|
- **Details:** `Status:`, `Runtime:` and `Command:` share a fixed value column. The command preview folds script line breaks and indentation into spaces, then wraps continuously to the panel width, up to three visual lines with an ellipsis. This is a display-only summary; the executed script is unchanged. **Output:** shows the last ten captured lines, clipped to the current width, refreshed every second. Empty output says `No output available`; truncated tails show the log path for further inspection. Finished tasks also show their exit code, reason and incomplete-capture warning when applicable.
|
|
@@ -80,7 +84,15 @@ A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status
|
|
|
80
84
|
|
|
81
85
|
The preview is intentionally bounded, not a full log viewer. Use the retained log path for earlier output or long lines. Commands have no TTY, so TTY-only colour and progress rendering may be absent. Other extensions' widgets remain intact.
|
|
82
86
|
|
|
83
|
-
The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter.
|
|
87
|
+
The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter, so the decorator is optional rather than authoritative. If another extension already owns the footer, Background Tasks keeps publishing its keyed status and leaves that footer untouched. If another extension replaces the decorator later, disposal releases ownership so reload or shutdown cannot clobber the new footer. `Alt+J` remains available in both cases. Click handling and hiding the whole footer while the panel is open require the decorator; a foreign footer that ignores Pi extension statuses may also omit the counter. A host-provided OMP-style keyed status-item interface with priority and click actions would remove this remaining constraint.
|
|
88
|
+
|
|
89
|
+
## Progress turns
|
|
90
|
+
|
|
91
|
+
After the parent agent settles, one session-scoped timer starts when one or more tasks are still running. If the parent stays idle for 30 minutes, the extension sends one combined progress turn for all running tasks. Each row includes the task ID, status, elapsed time, timeout, description, captured bytes, and byte growth since the previous progress report. It does not include log contents or log tails.
|
|
92
|
+
|
|
93
|
+
> No action is required. Completion will be reported automatically.
|
|
94
|
+
|
|
95
|
+
A new agent run clears the deadline. The timer restarts after that run settles if work remains. Completion delivery takes precedence over progress. A user interrupt suppresses both automatic progress and completion wakes until the next real user message. Terminal tasks, session replacement, reload, and shutdown remove progress scheduling.
|
|
84
96
|
|
|
85
97
|
## Completion delivery
|
|
86
98
|
|
|
@@ -115,6 +127,7 @@ Pi reports asynchronous message/run-start failures through its extension error c
|
|
|
115
127
|
| --- | --- |
|
|
116
128
|
| Model-visible output body | Last 100 lines or 8 KiB, whichever is reached first |
|
|
117
129
|
| `structuredContent.output` | The same bounded tail; no separate 1 MiB program view |
|
|
130
|
+
| Automatic progress log bodies | None; one combined 30-minute status and captured-byte delta |
|
|
118
131
|
| Automatic completion log bodies | None; only status, log paths and progressive-inspection guidance |
|
|
119
132
|
| Completion status/path text | 16 KiB defensive batch cap; remaining tasks stay pending |
|
|
120
133
|
| Disk capture | 32 MiB per task, 256 MiB total per session |
|
|
@@ -140,7 +153,7 @@ The tool description is compact. This package adds no `promptGuidelines` or extr
|
|
|
140
153
|
- Cancellation and runtime limits stop the native shell process group. Scripts must wait for their own work. Daemonized/detached commands (`nohup`, `setsid`, self-backgrounding processes), existing PID adoption, PTYs and interactive stdin are not supported.
|
|
141
154
|
- This is a distinct **local execution** tool. A third-party sandbox or remote backend installed only for Bash does not automatically cover it. Enable it only where direct local shell execution is permitted.
|
|
142
155
|
- It is not an OS sandbox: CPU/memory quotas, cleanup after SIGKILL/power loss, automatic retries, deadline renewal and persistence are out of scope. Native signal delivery and timers are best-effort.
|
|
143
|
-
- Pending reminders and notification timers are cleared on session shutdown. Once a completion is delivered into conversation history, reading output does not erase that history. Messages queued by an older installed version cannot be selectively withdrawn by this version.
|
|
156
|
+
- Pending reminders, progress timers and notification timers are cleared on session shutdown. Once a completion is delivered into conversation history, reading output does not erase that history. Messages queued by an older installed version cannot be selectively withdrawn by this version.
|
|
144
157
|
|
|
145
158
|
## Remove
|
|
146
159
|
|
package/TESTING.md
CHANGED
|
@@ -13,10 +13,10 @@ Tests use Node's built-in test runner. They resolve host peers from the installe
|
|
|
13
13
|
- `tasks.mjs`: fake execution and clock at the task-manager interface; immediate return, two slots, validation, timeout/cancel races, final failure, disk budgets, write errors, bounded history and shutdown.
|
|
14
14
|
- `output.mjs`: compares the shared 100-line/8-KiB preview with the real host Bash tool’s output, retaining unchanged small-output display parity and deliberately tighter truncation for large output. Covers line/byte limits, long lines, empty output, missing final newline, UTF-8 split across chunks, invalid UTF-8 and logs larger than 1 MiB. Checks both return paths carry the same tail, omission metadata reports total size, and full captured bytes remain on disk. The former Bash-sized display/1-MiB structured contract is retired; each retained fixture now verifies the bounded replacement.
|
|
15
15
|
- `processes.mjs`: the native backend, a multi-line Python log check, non-blocking concurrency, PID-observed process-tree cleanup, silent busy-loop timeout and the default 32 MiB disk limit.
|
|
16
|
-
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes.
|
|
17
|
-
- `panel.mjs`: singular/plural counter, mouse hit region, screenshot-style field alignment, compact continuous command previews, unchanged execution of original multiline scripts, CR/LF and indentation folding, preserved inline spaces, post-folding length limits, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
|
|
16
|
+
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. It verifies keyed-status fallback with a pre-existing foreign footer, safe self-detachment when a later footer replaces the decorator, and no running-task repaint timer. Checks one aggregate progress turn after 30 fake minutes, byte deltas without log contents, timer reset by a new parent run, completion precedence, interruption cleanup, the exact three-sentence tool description, the explicit end-turn/no-sleep start reminder, fixed `model-only` exposure, no prompt guidelines, and running-task `list`/`output` availability when inspection is actually needed.
|
|
17
|
+
- `panel.mjs`: singular/plural counter, arbitrary peer-status ordering and sanitization, narrow-width priority, mouse hit region, screenshot-style field alignment, compact continuous command previews, unchanged execution of original multiline scripts, CR/LF and indentation folding, preserved inline spaces, post-folding length limits, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
|
|
18
18
|
- `media.mjs`: actual demo Python jobs stream in-place/line output and exit with 0/3 only after explicit release files; the offline provider issues exactly two direct starts, then returns without polling. This tests the fixtures used by the real recorder, not an invented screen.
|
|
19
|
-
- `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.
|
|
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. An accelerated production registration also proves that real Pi receives repeated idle progress turns before the real shell completes, then receives one completion turn. Also verifies distinct declaration/start guidance without a Codemode suffix and that native Codemode cannot discover or call `background_task`. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
|
|
20
20
|
- `compaction.mjs`: isolated native Pi SDK sessions call `session.compact()`, the same manual-compaction entry point used by `/compact` and RPC. Real shell jobs exit during a held offline summary request. Covers successful native compaction, a provider summary error and `abortCompaction()` cancellation; each must retain the pending completion while busy and automatically deliver status/log-location metadata once afterward, without another user prompt. Checks actual compaction lifecycle/events, saved compaction entries, completion timestamps/logs and exactly one automatic conversation request. Uses real timers and native `isIdle`/`isCompacting`, not injected busy state or replacement compaction results; no paid model call or TUI keyboard invocation of `/compact`. `BG_TEST_EXTENSION` also supports a negative-control extension.
|
|
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
|
|
|
@@ -24,7 +24,7 @@ The compaction fixtures seed a completed earlier turn and sufficient recent cont
|
|
|
24
24
|
|
|
25
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.
|
|
26
26
|
|
|
27
|
-
Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second delays
|
|
27
|
+
Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second completion delays and the separate 30-minute progress deadline, retention across 24 hours of busy time, one aggregate progress turn for all running tasks, 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.
|
|
28
28
|
|
|
29
29
|
Load-test uses an isolated temporary agent directory, the production extension and an offline fixture provider. It does not access real provider credentials or alter the user's installed packages. From the workspace, `npm --prefix packages/background-tasks run load-test -- --toolkit` loads the complete toolkit directory through its manifest and verifies exactly one background-task tool; the root load-test runs this check too.
|
|
30
30
|
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
package/docs/shell-list.png
CHANGED
|
Binary file
|
|
@@ -5,10 +5,11 @@ 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
7
|
import { BackgroundPanel } from "../src/panel.ts";
|
|
8
|
-
import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
8
|
+
import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, taskStatusLabel, visibleTasks } from "../src/widget.ts";
|
|
9
9
|
|
|
10
10
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
11
|
-
const startNotice = "Completion
|
|
11
|
+
const startNotice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
|
|
12
|
+
const PROGRESS_INTERVAL_MS = 30 * 60_000;
|
|
12
13
|
// Bound model-visible status text when many completions accumulate.
|
|
13
14
|
const NOTIFICATION_MAX_BYTES = 16 * 1024;
|
|
14
15
|
type Action = typeof actions[number];
|
|
@@ -21,7 +22,7 @@ interface Params {
|
|
|
21
22
|
id?: string;
|
|
22
23
|
}
|
|
23
24
|
const Parameters = Type.Object({
|
|
24
|
-
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; 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." }),
|
|
25
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." })),
|
|
26
27
|
description: Type.Optional(Type.String({ description: "Short display label for start" })),
|
|
27
28
|
cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
|
|
@@ -62,16 +63,25 @@ function completionText(task: TaskSnapshot): string {
|
|
|
62
63
|
return lines.join("\n");
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
export default function (pi: ExtensionAPI, dependencies: {
|
|
66
|
+
export default function (pi: ExtensionAPI, dependencies: {
|
|
67
|
+
operations?: BashOperations;
|
|
68
|
+
clock?: Clock;
|
|
69
|
+
logRoot?: string;
|
|
70
|
+
progressIntervalMs?: number;
|
|
71
|
+
} = {}) {
|
|
66
72
|
const clock = dependencies.clock ?? systemClock;
|
|
73
|
+
const progressIntervalMs = dependencies.progressIntervalMs ?? PROGRESS_INTERVAL_MS;
|
|
74
|
+
if (!Number.isFinite(progressIntervalMs) || progressIntervalMs <= 0) throw new Error("Progress interval must be positive");
|
|
67
75
|
let manager: BackgroundTasks | undefined;
|
|
68
76
|
let context: ExtensionContext | undefined;
|
|
69
77
|
let generation = 0;
|
|
70
78
|
let timer: unknown;
|
|
71
79
|
let notificationTimer: unknown;
|
|
80
|
+
let progressTimer: unknown;
|
|
72
81
|
let completedNormally = true;
|
|
73
82
|
let interrupted = false;
|
|
74
83
|
const pending = new Map<string, TaskSnapshot>();
|
|
84
|
+
const progressBytes = new Map<string, number>();
|
|
75
85
|
let mounted: { footer: BackgroundFooter; tui: { requestRender(): void } } | undefined;
|
|
76
86
|
let panel: { close(): void } | undefined;
|
|
77
87
|
|
|
@@ -79,6 +89,44 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
79
89
|
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
80
90
|
notificationTimer = undefined;
|
|
81
91
|
};
|
|
92
|
+
const clearProgressTimer = () => {
|
|
93
|
+
if (progressTimer !== undefined) clock.clearTimeout(progressTimer);
|
|
94
|
+
progressTimer = undefined;
|
|
95
|
+
};
|
|
96
|
+
const runningTasks = () => manager?.list().tasks.filter((task) => task.status === "running") ?? [];
|
|
97
|
+
const scheduleProgress = () => {
|
|
98
|
+
clearProgressTimer();
|
|
99
|
+
if (interrupted || pending.size > 0 || runningTasks().length === 0) return;
|
|
100
|
+
const epoch = generation;
|
|
101
|
+
progressTimer = clock.setTimeout(() => {
|
|
102
|
+
progressTimer = undefined;
|
|
103
|
+
if (generation !== epoch || !context || !manager || interrupted || pending.size > 0) return;
|
|
104
|
+
const tasks = runningTasks();
|
|
105
|
+
if (tasks.length === 0) return;
|
|
106
|
+
if (!context.isIdle()) {
|
|
107
|
+
scheduleProgress();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const deltas = new Map(tasks.map((task) => [task.id, task.bytes - (progressBytes.get(task.id) ?? 0)]));
|
|
111
|
+
const content = [
|
|
112
|
+
"[Background tasks still running]",
|
|
113
|
+
"",
|
|
114
|
+
...tasks.map((task) => `${formatTask(task)} · ${task.bytes} captured bytes (+${deltas.get(task.id)} since last report)`),
|
|
115
|
+
"",
|
|
116
|
+
"No action is required. Completion will be reported automatically.",
|
|
117
|
+
].join("\n");
|
|
118
|
+
try {
|
|
119
|
+
pi.sendMessage({
|
|
120
|
+
customType: "background-task-progress", display: true,
|
|
121
|
+
details: { tasks, byteDeltas: Object.fromEntries(deltas) },
|
|
122
|
+
content,
|
|
123
|
+
}, { triggerTurn: true, deliverAs: "steer" });
|
|
124
|
+
for (const task of tasks) progressBytes.set(task.id, task.bytes);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.error(`Background progress notification failed: ${errorText(error)}`);
|
|
127
|
+
}
|
|
128
|
+
}, progressIntervalMs);
|
|
129
|
+
};
|
|
82
130
|
const takeNotification = () => {
|
|
83
131
|
clearNotificationTimer();
|
|
84
132
|
if (pending.size === 0) return;
|
|
@@ -144,12 +192,17 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
144
192
|
const message = takeNotification();
|
|
145
193
|
if (message) return { message };
|
|
146
194
|
});
|
|
195
|
+
pi.on("agent_start", clearProgressTimer);
|
|
147
196
|
pi.on("agent_settled", (event) => {
|
|
148
197
|
if (event.aborted) {
|
|
149
198
|
interrupted = true;
|
|
150
199
|
clearNotificationTimer();
|
|
200
|
+
clearProgressTimer();
|
|
201
|
+
return;
|
|
151
202
|
}
|
|
152
|
-
if (!
|
|
203
|
+
if (!completedNormally) return;
|
|
204
|
+
scheduleNotification();
|
|
205
|
+
scheduleProgress();
|
|
153
206
|
});
|
|
154
207
|
|
|
155
208
|
const openPanel = async () => {
|
|
@@ -185,14 +238,16 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
185
238
|
return;
|
|
186
239
|
}
|
|
187
240
|
const visible = visibleTasks(list.tasks, clock.now());
|
|
241
|
+
context.ui.setStatus(WIDGET_KEY, taskStatusLabel(visible));
|
|
188
242
|
mounted?.footer.invalidate();
|
|
189
243
|
mounted?.tui.requestRender();
|
|
190
|
-
|
|
244
|
+
const finished = visible.filter((task) => task.ended_at !== undefined);
|
|
245
|
+
if (finished.length === 0) {
|
|
191
246
|
clearTimer();
|
|
192
247
|
return;
|
|
193
248
|
}
|
|
194
249
|
if (timer === undefined) {
|
|
195
|
-
const delay = Math.min(
|
|
250
|
+
const delay = Math.min(...finished.map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
|
|
196
251
|
timer = clock.setTimeout(() => { timer = undefined; refresh(); }, Math.max(1, delay));
|
|
197
252
|
}
|
|
198
253
|
};
|
|
@@ -206,15 +261,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
206
261
|
context = undefined;
|
|
207
262
|
clearTimer();
|
|
208
263
|
clearNotificationTimer();
|
|
264
|
+
clearProgressTimer();
|
|
209
265
|
pending.clear();
|
|
266
|
+
progressBytes.clear();
|
|
210
267
|
completedNormally = true;
|
|
211
268
|
interrupted = false;
|
|
269
|
+
const activeFooter = mounted;
|
|
270
|
+
mounted = undefined;
|
|
212
271
|
try {
|
|
213
272
|
if (previousContext?.hasUI) {
|
|
214
273
|
previousContext.ui.setStatus(WIDGET_KEY, undefined);
|
|
215
|
-
if (
|
|
274
|
+
if (activeFooter) previousContext.ui.setFooter(undefined);
|
|
216
275
|
}
|
|
217
|
-
mounted = undefined;
|
|
218
276
|
} finally {
|
|
219
277
|
await previous?.shutdown();
|
|
220
278
|
}
|
|
@@ -225,9 +283,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
225
283
|
const epoch = generation;
|
|
226
284
|
manager = new BackgroundTasks({
|
|
227
285
|
operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
|
|
228
|
-
onChange() {
|
|
286
|
+
onChange() {
|
|
287
|
+
if (generation !== epoch) return;
|
|
288
|
+
refresh();
|
|
289
|
+
if (manager?.list().running === 0) {
|
|
290
|
+
clearProgressTimer();
|
|
291
|
+
progressBytes.clear();
|
|
292
|
+
}
|
|
293
|
+
},
|
|
229
294
|
onComplete(task) {
|
|
230
295
|
if (generation !== epoch || !context) return;
|
|
296
|
+
clearProgressTimer();
|
|
297
|
+
progressBytes.delete(task.id);
|
|
231
298
|
pending.set(task.id, task);
|
|
232
299
|
scheduleNotification();
|
|
233
300
|
},
|
|
@@ -238,10 +305,13 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
238
305
|
try {
|
|
239
306
|
ctx.ui.setWidget(WIDGET_KEY, (tui) => {
|
|
240
307
|
const native = findNativeFooter(tui.children);
|
|
241
|
-
if (!native)
|
|
308
|
+
if (!native) return { render: () => [], invalidate() {} };
|
|
242
309
|
ctx.ui.setFooter((footerTui, theme, data) => {
|
|
243
|
-
|
|
244
|
-
|
|
310
|
+
let footer: BackgroundFooter;
|
|
311
|
+
footer = new BackgroundFooter(native, theme, () => data.getExtensionStatuses(),
|
|
312
|
+
() => panel !== undefined, () => { void openPanel(); }, () => {
|
|
313
|
+
if (mounted?.footer === footer) mounted = undefined;
|
|
314
|
+
});
|
|
245
315
|
mounted = { footer, tui: footerTui };
|
|
246
316
|
return footer;
|
|
247
317
|
});
|
|
@@ -288,7 +358,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
288
358
|
pi.registerTool({
|
|
289
359
|
name: "background_task", label: "Background task",
|
|
290
360
|
exposure: "model-only",
|
|
291
|
-
description: "Run up to two concurrent background shell tasks with automatic completion notifications. Tasks
|
|
361
|
+
description: "Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.",
|
|
292
362
|
parameters: Parameters, outputSchema: OutputSchema,
|
|
293
363
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
294
364
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Session-scoped background shell tasks with completion notifications for Pi.",
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"description": "Session-scoped background shell tasks with progress and completion notifications for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"pi-package",
|
package/src/widget.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { FooterComponent, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { truncateToWidth, visibleWidth, type Component, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
3
|
-
import type {
|
|
3
|
+
import type { TaskSnapshot } from "./background-tasks.ts";
|
|
4
4
|
|
|
5
5
|
export const WIDGET_KEY = "background-tasks";
|
|
6
6
|
export const FINISHED_VISIBLE_MS = 5000;
|
|
@@ -9,6 +9,13 @@ export function visibleTasks(tasks: TaskSnapshot[], now: number): TaskSnapshot[]
|
|
|
9
9
|
return tasks.filter((task) => task.status === "running" || (task.ended_at !== undefined && now < task.ended_at + FINISHED_VISIBLE_MS));
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
export function taskStatusLabel(tasks: TaskSnapshot[]): string | undefined {
|
|
13
|
+
if (!tasks.length) return undefined;
|
|
14
|
+
const active = tasks.filter((task) => task.status === "running").length;
|
|
15
|
+
const ended = tasks.length - active;
|
|
16
|
+
return `${active} ${active === 1 ? "shell" : "shells"}${ended ? ` · ${ended} done` : ""}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
12
19
|
export function duration(seconds: number): string {
|
|
13
20
|
const value = Math.max(0, Math.floor(seconds));
|
|
14
21
|
if (value >= 3600) return `${Math.floor(value / 3600)}h${value % 3600 ? ` ${Math.floor(value % 3600 / 60)}m` : ""}`;
|
|
@@ -27,24 +34,27 @@ export function findNativeFooter(children: Component[]): FooterComponent | undef
|
|
|
27
34
|
}
|
|
28
35
|
}
|
|
29
36
|
|
|
37
|
+
function sanitizeStatusText(text: string): string {
|
|
38
|
+
return text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim();
|
|
39
|
+
}
|
|
40
|
+
|
|
30
41
|
/** Keep native usage/model rendering; add a clickable count to its final status row. */
|
|
31
42
|
export class BackgroundFooter {
|
|
32
43
|
private hit?: { x: number; y: number; width: number };
|
|
33
44
|
private readonly native: Component;
|
|
34
|
-
private readonly getTasks: () => TaskSnapshot[];
|
|
35
|
-
private readonly clock: Clock;
|
|
36
45
|
private readonly theme: Theme;
|
|
37
|
-
private readonly
|
|
46
|
+
private readonly getStatuses: () => ReadonlyMap<string, string>;
|
|
38
47
|
private readonly panelOpen: () => boolean;
|
|
39
48
|
private readonly onSelect: () => void;
|
|
40
|
-
|
|
49
|
+
private readonly onDispose: () => void;
|
|
50
|
+
private disposed = false;
|
|
51
|
+
constructor(native: Component, theme: Theme, getStatuses: () => ReadonlyMap<string, string>, panelOpen: () => boolean, onSelect: () => void, onDispose: () => void = () => {}) {
|
|
41
52
|
this.native = native;
|
|
42
|
-
this.getTasks = getTasks;
|
|
43
|
-
this.clock = clock;
|
|
44
53
|
this.theme = theme;
|
|
45
|
-
this.
|
|
54
|
+
this.getStatuses = getStatuses;
|
|
46
55
|
this.panelOpen = panelOpen;
|
|
47
56
|
this.onSelect = onSelect;
|
|
57
|
+
this.onDispose = onDispose;
|
|
48
58
|
}
|
|
49
59
|
|
|
50
60
|
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
@@ -58,19 +68,53 @@ export class BackgroundFooter {
|
|
|
58
68
|
this.hit = undefined;
|
|
59
69
|
if (this.panelOpen()) return [];
|
|
60
70
|
const lines = this.native.render(width);
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
const statuses = this.getStatuses();
|
|
72
|
+
const label = sanitizeStatusText(statuses.get(WIDGET_KEY) ?? "");
|
|
73
|
+
if (visibleWidth(label) === 0) return lines;
|
|
74
|
+
lines.pop();
|
|
75
|
+
|
|
76
|
+
const separator = this.theme.fg("dim", " · ");
|
|
77
|
+
const peers = [...statuses.entries()]
|
|
78
|
+
.filter(([key]) => key !== WIDGET_KEY)
|
|
79
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
80
|
+
.map(([, text]) => sanitizeStatusText(text))
|
|
81
|
+
.filter((text) => visibleWidth(text) > 0)
|
|
82
|
+
.join(separator);
|
|
83
|
+
const styledLabel = this.theme.fg("accent", label);
|
|
84
|
+
const hint = this.theme.fg("dim", " · Alt+J");
|
|
85
|
+
let prefix = "";
|
|
86
|
+
const renderedLabel = truncateToWidth(styledLabel, width, "");
|
|
87
|
+
let suffix = renderedLabel;
|
|
88
|
+
|
|
89
|
+
if (visibleWidth(renderedLabel) === visibleWidth(label)) {
|
|
90
|
+
if (peers) {
|
|
91
|
+
const withoutHint = peers + separator + renderedLabel;
|
|
92
|
+
if (visibleWidth(withoutHint + hint) <= width) {
|
|
93
|
+
prefix = peers + separator;
|
|
94
|
+
suffix = renderedLabel + hint;
|
|
95
|
+
} else if (visibleWidth(withoutHint) <= width) {
|
|
96
|
+
prefix = peers + separator;
|
|
97
|
+
} else {
|
|
98
|
+
const available = width - visibleWidth(renderedLabel) - visibleWidth(separator);
|
|
99
|
+
const truncatedPeers = truncateToWidth(peers, available, "…");
|
|
100
|
+
if (visibleWidth(truncatedPeers) > 1) prefix = truncatedPeers + separator;
|
|
101
|
+
}
|
|
102
|
+
} else if (visibleWidth(renderedLabel + hint) <= width) {
|
|
103
|
+
suffix = renderedLabel + hint;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const hitWidth = visibleWidth(renderedLabel);
|
|
108
|
+
if (hitWidth > 0) this.hit = { x: visibleWidth(prefix), y: lines.length, width: hitWidth };
|
|
109
|
+
return [...lines, prefix + suffix];
|
|
73
110
|
}
|
|
74
111
|
|
|
75
112
|
invalidate(): void { this.hit = undefined; this.native.invalidate(); }
|
|
113
|
+
|
|
114
|
+
dispose(): void {
|
|
115
|
+
if (this.disposed) return;
|
|
116
|
+
this.disposed = true;
|
|
117
|
+
this.hit = undefined;
|
|
118
|
+
this.onDispose();
|
|
119
|
+
}
|
|
76
120
|
}
|
package/tests/extension.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { fixture, flush } from "./helpers.mjs";
|
|
|
8
8
|
|
|
9
9
|
const keys = new KeybindingsManager(TUI_KEYBINDINGS);
|
|
10
10
|
|
|
11
|
-
function harness(mode = "tui", hasUI = true) {
|
|
11
|
+
function harness(mode = "tui", hasUI = true, dependencies = {}) {
|
|
12
12
|
const f = fixture();
|
|
13
13
|
const handlers = new Map();
|
|
14
14
|
const commands = new Map();
|
|
@@ -19,11 +19,11 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
19
19
|
const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
|
|
20
20
|
const statuses = new Map();
|
|
21
21
|
const idleChecks = [];
|
|
22
|
-
let tool, renders = 0, idle = true, failSend = false;
|
|
22
|
+
let tool, renders = 0, footerChanges = 0, idle = true, failSend = false;
|
|
23
23
|
const theme = { fg: (_color, text) => text, bold: (text) => text };
|
|
24
24
|
const native = Object.assign(Object.create(FooterComponent.prototype), {
|
|
25
25
|
render: (width) => ["fixture/path (main)", "↑42k fixture-model", ...(
|
|
26
|
-
statuses.size ? [
|
|
26
|
+
statuses.size ? [[...statuses.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, text]) => text).join(" ")] : []
|
|
27
27
|
)].map((line) => line.slice(0, width)),
|
|
28
28
|
invalidate() {},
|
|
29
29
|
});
|
|
@@ -37,10 +37,12 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
37
37
|
widgets.set(key, factory(tui, theme));
|
|
38
38
|
},
|
|
39
39
|
setFooter(factory) {
|
|
40
|
+
footer?.dispose?.();
|
|
40
41
|
footer = undefined;
|
|
41
42
|
container.children = [];
|
|
42
43
|
if (factory) footer = factory(tui, theme, { getExtensionStatuses: () => statuses });
|
|
43
44
|
container.children = [footer ?? native];
|
|
45
|
+
footerChanges++;
|
|
44
46
|
tui.requestRender();
|
|
45
47
|
},
|
|
46
48
|
custom(factory) {
|
|
@@ -62,13 +64,14 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
62
64
|
messages.push({ message, options });
|
|
63
65
|
},
|
|
64
66
|
};
|
|
65
|
-
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
|
|
67
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, ...dependencies });
|
|
66
68
|
return {
|
|
67
69
|
...f, handlers, commands, messages, notices, widgets, statuses, idleChecks, ctx, tui, native,
|
|
68
70
|
setIdle(value) { idle = value; },
|
|
69
71
|
failNextSend() { failSend = true; },
|
|
70
72
|
get panel() { return panel; },
|
|
71
73
|
get footer() { return footer; },
|
|
74
|
+
get footerChanges() { return footerChanges; },
|
|
72
75
|
open() { void shortcuts.get("alt+j").handler(ctx); },
|
|
73
76
|
get tool() { return tool; }, get renders() { return renders; },
|
|
74
77
|
async close() {
|
|
@@ -424,6 +427,112 @@ test("idle wake batches current completions and a terminal read can remove the w
|
|
|
424
427
|
} finally { await h.close(); }
|
|
425
428
|
});
|
|
426
429
|
|
|
430
|
+
test("running tasks send one merged progress turn per 30 minutes of parent inactivity", async () => {
|
|
431
|
+
const interval = 30 * 60_000;
|
|
432
|
+
const h = harness("print", false);
|
|
433
|
+
try {
|
|
434
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
435
|
+
for (const command of ["first", "second"]) {
|
|
436
|
+
await h.tool.execute(command, { action: "start", command, timeout: 7200 });
|
|
437
|
+
}
|
|
438
|
+
h.calls[0].onData(Buffer.from("first output"));
|
|
439
|
+
h.calls[1].onData(Buffer.from("two"));
|
|
440
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
441
|
+
h.clock.advance(interval - 1);
|
|
442
|
+
assert.equal(h.messages.length, 0);
|
|
443
|
+
h.clock.advance(1);
|
|
444
|
+
assert.equal(h.messages.length, 1);
|
|
445
|
+
const first = h.messages[0];
|
|
446
|
+
assert.equal(first.message.customType, "background-task-progress");
|
|
447
|
+
assert.equal(first.options.triggerTurn, true);
|
|
448
|
+
assert.equal(first.options.deliverAs, "steer");
|
|
449
|
+
assert.equal(first.message.details.tasks.length, 2);
|
|
450
|
+
assert.deepEqual(Object.values(first.message.details.byteDeltas).sort((a, b) => a - b), [3, 12]);
|
|
451
|
+
assert.match(first.message.content, /30m \/ 2h · "first" · 12 captured bytes \(\+12 since last report\)/);
|
|
452
|
+
assert.match(first.message.content, /30m \/ 2h · "second" · 3 captured bytes \(\+3 since last report\)/);
|
|
453
|
+
assert.match(first.message.content, /No action is required\. Completion will be reported automatically\./);
|
|
454
|
+
assert.doesNotMatch(first.message.content, /first output|Untrusted shell output|Captured log:/);
|
|
455
|
+
|
|
456
|
+
// The progress-triggered parent run settles and starts the next deadline.
|
|
457
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
458
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
459
|
+
h.calls[0].onData(Buffer.from(" more"));
|
|
460
|
+
h.clock.advance(interval - 1);
|
|
461
|
+
// A new parent run must clear an already-armed progress deadline.
|
|
462
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
463
|
+
h.clock.advance(interval);
|
|
464
|
+
assert.equal(h.messages.length, 1, "an active parent run clears the progress deadline");
|
|
465
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
466
|
+
h.clock.advance(interval);
|
|
467
|
+
assert.equal(h.messages.length, 2);
|
|
468
|
+
assert.equal(h.messages[1].message.details.tasks.length, 2);
|
|
469
|
+
assert.equal(h.messages[1].message.details.byteDeltas[first.message.details.tasks[0].id], 5);
|
|
470
|
+
assert.equal(h.messages[1].message.details.byteDeltas[first.message.details.tasks[1].id], 0);
|
|
471
|
+
} finally { await h.close(); }
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
test("busy sessions defer progress and error boundaries do not wake them later", async () => {
|
|
475
|
+
const interval = 30 * 60_000;
|
|
476
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
477
|
+
try {
|
|
478
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
479
|
+
await h.tool.execute("start", { action: "start", command: "busy", timeout: 7200 });
|
|
480
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
481
|
+
h.setIdle(false);
|
|
482
|
+
h.clock.advance(interval);
|
|
483
|
+
assert.equal(h.messages.length, 0);
|
|
484
|
+
h.setIdle(true);
|
|
485
|
+
h.clock.advance(interval);
|
|
486
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
487
|
+
|
|
488
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
489
|
+
h.handlers.get("turn_end")({ entries: [], continue: false, outcome: "error" }, h.ctx);
|
|
490
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
491
|
+
h.clock.advance(interval * 2);
|
|
492
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
493
|
+
} finally { await h.close(); }
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
test("an interrupted parent suppresses progress until the next user message", async () => {
|
|
497
|
+
const interval = 30 * 60_000;
|
|
498
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
499
|
+
try {
|
|
500
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
501
|
+
await h.tool.execute("start", { action: "start", command: "interrupted", timeout: 7200 });
|
|
502
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
503
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
504
|
+
h.handlers.get("agent_settled")({ aborted: true }, h.ctx);
|
|
505
|
+
h.clock.advance(interval * 2);
|
|
506
|
+
assert.equal(h.messages.length, 0);
|
|
507
|
+
h.handlers.get("before_agent_start")({ messageType: "custom", prompt: "other wake" }, h.ctx);
|
|
508
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
509
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
510
|
+
h.clock.advance(interval);
|
|
511
|
+
assert.equal(h.messages.length, 0, "custom wakes do not release an interrupted parent");
|
|
512
|
+
h.handlers.get("before_agent_start")({ messageType: "user", prompt: "continue" }, h.ctx);
|
|
513
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
514
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
515
|
+
h.clock.advance(interval);
|
|
516
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
517
|
+
} finally { await h.close(); }
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
test("completion cancels the pending progress deadline", async () => {
|
|
521
|
+
const interval = 30 * 60_000;
|
|
522
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
523
|
+
try {
|
|
524
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
525
|
+
await h.tool.execute("start", { action: "start", command: "finishes", timeout: 7200 });
|
|
526
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
527
|
+
h.clock.advance(interval - 1);
|
|
528
|
+
h.calls[0].resolve();
|
|
529
|
+
await flush();
|
|
530
|
+
h.clock.advance(interval + 1);
|
|
531
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 0);
|
|
532
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-finished").length, 1);
|
|
533
|
+
} finally { await h.close(); }
|
|
534
|
+
});
|
|
535
|
+
|
|
427
536
|
for (const outcome of ["aborted", "error"]) {
|
|
428
537
|
test(`${outcome} boundaries do not force continuation or replay a scheduled idle wake`, async () => {
|
|
429
538
|
const h = harness();
|
|
@@ -494,7 +603,7 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
494
603
|
try {
|
|
495
604
|
assert.equal(h.tool.name, "background_task");
|
|
496
605
|
assert.equal(h.tool.exposure, "model-only");
|
|
497
|
-
assert.
|
|
606
|
+
assert.equal(h.tool.description, "Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.");
|
|
498
607
|
assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
|
|
499
608
|
assert.equal(h.tool.parameters.properties.command.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.");
|
|
500
609
|
assert.ok(h.tool.description.length < 500);
|
|
@@ -508,21 +617,24 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
508
617
|
} finally { await h.close(); }
|
|
509
618
|
});
|
|
510
619
|
|
|
511
|
-
test("start keeps
|
|
620
|
+
test("start keeps concise task-specific guidance while the declaration describes lifecycle", async () => {
|
|
512
621
|
const h = harness();
|
|
513
622
|
try {
|
|
514
623
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
515
624
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
516
625
|
const { task } = started.structuredContent;
|
|
517
|
-
const notice = "Completion
|
|
626
|
+
const notice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
|
|
518
627
|
assert.equal(task.status, "running");
|
|
519
628
|
assert.ok(started.content[0].text.includes(notice));
|
|
629
|
+
assert.match(started.content[0].text, /end the turn now/);
|
|
630
|
+
assert.match(started.content[0].text, /Do not call Bash sleep/);
|
|
631
|
+
assert.match(started.content[0].text, /list\/output solely to wait/);
|
|
520
632
|
assert.ok(!started.content[0].text.includes(task.log_path));
|
|
521
633
|
assert.ok(!started.content[0].text.includes("session changes"));
|
|
522
634
|
assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
|
|
523
635
|
assert.match(h.tool.description, /automatic completion notifications/);
|
|
524
|
-
assert.match(h.tool.description, /session
|
|
525
|
-
assert.
|
|
636
|
+
assert.match(h.tool.description, /session-scoped and do not survive reload or exit/);
|
|
637
|
+
assert.doesNotMatch(h.tool.parameters.properties.action.description, /while tasks are running/);
|
|
526
638
|
assert.equal(started.structuredContent.guidance, undefined);
|
|
527
639
|
assert.equal(h.tool.outputSchema.properties.guidance, undefined);
|
|
528
640
|
const list = await h.tool.execute("list", { action: "list" });
|
|
@@ -551,6 +663,7 @@ test("tools, clean panel, bottom footer and idle notifications share the same se
|
|
|
551
663
|
parentSignal.abort();
|
|
552
664
|
assert.equal(h.calls[0].signal.aborted, false, "parent turn cancellation does not own the accepted background job");
|
|
553
665
|
assert.equal(h.widgets.has("background-tasks"), false, "no counter above the native footer");
|
|
666
|
+
assert.equal(h.clock.timers.size, 1, "a running task needs only its execution deadline, not a footer repaint timer");
|
|
554
667
|
h.clock.advance(1000);
|
|
555
668
|
const footer = h.footer;
|
|
556
669
|
h.statuses.set("codex-edit", "editor: apply_patch");
|
|
@@ -592,6 +705,34 @@ test("tools, clean panel, bottom footer and idle notifications share the same se
|
|
|
592
705
|
} finally { await h.close(); }
|
|
593
706
|
});
|
|
594
707
|
|
|
708
|
+
test("keyed TUI status follows staggered five-second completion expiry without running repaint timers", async () => {
|
|
709
|
+
const h = harness();
|
|
710
|
+
try {
|
|
711
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
712
|
+
await h.tool.execute("first", { action: "start", command: "first" });
|
|
713
|
+
await h.tool.execute("second", { action: "start", command: "second" });
|
|
714
|
+
assert.equal(h.statuses.get("background-tasks"), "2 shells");
|
|
715
|
+
assert.equal(h.clock.timers.size, 2, "only the two execution deadlines run");
|
|
716
|
+
h.handlers.get("agent_settled")({ aborted: true });
|
|
717
|
+
|
|
718
|
+
h.calls[0].resolve();
|
|
719
|
+
await flush();
|
|
720
|
+
assert.equal(h.statuses.get("background-tasks"), "1 shell · 1 done");
|
|
721
|
+
h.clock.advance(3000);
|
|
722
|
+
h.calls[1].resolve();
|
|
723
|
+
await flush();
|
|
724
|
+
assert.equal(h.statuses.get("background-tasks"), "0 shells · 2 done");
|
|
725
|
+
|
|
726
|
+
h.clock.advance(2000);
|
|
727
|
+
assert.equal(h.statuses.get("background-tasks"), "0 shells · 1 done");
|
|
728
|
+
h.clock.advance(2999);
|
|
729
|
+
assert.equal(h.statuses.get("background-tasks"), "0 shells · 1 done");
|
|
730
|
+
h.clock.advance(1);
|
|
731
|
+
assert.equal(h.statuses.has("background-tasks"), false);
|
|
732
|
+
assert.equal(h.clock.timers.size, 0);
|
|
733
|
+
} finally { await h.close(); }
|
|
734
|
+
});
|
|
735
|
+
|
|
595
736
|
test("cancel and shutdown are idempotent; new sessions cannot receive old completions", async () => {
|
|
596
737
|
const h = harness();
|
|
597
738
|
try {
|
|
@@ -700,12 +841,49 @@ test("footer count opens one local panel; shutdown closes it and clears refresh
|
|
|
700
841
|
} finally { await h.close(); }
|
|
701
842
|
});
|
|
702
843
|
|
|
703
|
-
test("a pre-existing replacement footer
|
|
844
|
+
test("a pre-existing replacement footer keeps native status and Alt+J without taking footer ownership", async () => {
|
|
704
845
|
const h = harness();
|
|
705
846
|
try {
|
|
706
|
-
|
|
707
|
-
|
|
847
|
+
const foreign = { render: () => ["another footer"], invalidate() {} };
|
|
848
|
+
h.tui.children = [foreign];
|
|
849
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
850
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
708
851
|
assert.equal(h.footer, undefined);
|
|
709
852
|
assert.equal(h.widgets.has("background-tasks"), false, "temporary capture widget is cleaned on failure");
|
|
853
|
+
assert.equal(h.statuses.get("background-tasks"), "1 shell");
|
|
854
|
+
h.open();
|
|
855
|
+
assert.match(h.panel.render(140).join("\n"), /Command: first/);
|
|
856
|
+
h.panel.handleInput("\x1b");
|
|
857
|
+
await flush();
|
|
858
|
+
const changes = h.footerChanges;
|
|
859
|
+
h.calls[0].resolve();
|
|
860
|
+
await h.handlers.get("session_shutdown")({}, h.ctx);
|
|
861
|
+
assert.equal(h.footerChanges, changes, "shutdown must not replace a footer it never owned");
|
|
862
|
+
assert.equal(h.statuses.has("background-tasks"), false);
|
|
863
|
+
assert.equal(h.tui.children[0], foreign);
|
|
864
|
+
} finally { await h.close(); }
|
|
865
|
+
});
|
|
866
|
+
|
|
867
|
+
test("a later replacement footer evicts the decorator without being clobbered on shutdown", async () => {
|
|
868
|
+
const h = harness();
|
|
869
|
+
try {
|
|
870
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
871
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
872
|
+
const decorator = h.footer;
|
|
873
|
+
const foreign = { render: () => ["another footer"], invalidate() {} };
|
|
874
|
+
h.ctx.ui.setFooter(() => foreign);
|
|
875
|
+
assert.notEqual(h.footer, decorator);
|
|
876
|
+
assert.equal(h.footer, foreign);
|
|
877
|
+
assert.equal(h.statuses.get("background-tasks"), "1 shell");
|
|
878
|
+
h.open();
|
|
879
|
+
assert.match(h.panel.render(140).join("\n"), /Command: first/);
|
|
880
|
+
h.panel.handleInput("\x1b");
|
|
881
|
+
await flush();
|
|
882
|
+
const changes = h.footerChanges;
|
|
883
|
+
h.calls[0].resolve();
|
|
884
|
+
await h.handlers.get("session_shutdown")({}, h.ctx);
|
|
885
|
+
assert.equal(h.footerChanges, changes, "shutdown must not clear a later footer owner");
|
|
886
|
+
assert.equal(h.footer, foreign);
|
|
887
|
+
assert.equal(h.statuses.has("background-tasks"), false);
|
|
710
888
|
} finally { await h.close(); }
|
|
711
889
|
});
|
package/tests/interruptions.mjs
CHANGED
|
@@ -105,7 +105,9 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
105
105
|
const interruptRequestedAt = Date.now();
|
|
106
106
|
if (timing === "after active compaction") {
|
|
107
107
|
await session.compact();
|
|
108
|
-
|
|
108
|
+
// Native compaction may summarize history and a split turn separately.
|
|
109
|
+
// This contract needs a real summary without allowing a retry loop.
|
|
110
|
+
assert.ok(summaries >= 1 && summaries <= 2, "manual compaction must summarize after interrupting the active agent without looping");
|
|
109
111
|
} else await session.abort();
|
|
110
112
|
await prompting;
|
|
111
113
|
const interruptedAt = Date.now();
|
package/tests/notifications.mjs
CHANGED
|
@@ -3,10 +3,24 @@ import { execFileSync } from "node:child_process";
|
|
|
3
3
|
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
|
-
import {
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
8
|
import { test } from "node:test";
|
|
8
9
|
import { piBinary } from "./runtime.mjs";
|
|
9
10
|
|
|
11
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
|
|
12
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
13
|
+
const { default: registerBackgroundTasks } = await import(process.env.BG_TEST_EXTENSION
|
|
14
|
+
? pathToFileURL(process.env.BG_TEST_EXTENSION).href : new URL("../extensions/background-tasks.ts", import.meta.url).href);
|
|
15
|
+
|
|
16
|
+
async function waitFor(check, label) {
|
|
17
|
+
for (let i = 0; i < 1000; i++) {
|
|
18
|
+
if (check()) return;
|
|
19
|
+
await delay(10);
|
|
20
|
+
}
|
|
21
|
+
throw new Error(`Timed out waiting for ${label}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
10
24
|
test("native model receives distinct declaration and start guidance without Codemode instructions", () => {
|
|
11
25
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
|
|
12
26
|
try {
|
|
@@ -22,20 +36,90 @@ test("native model receives distinct declaration and start guidance without Code
|
|
|
22
36
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
37
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
38
|
assert.equal(started.isError, false);
|
|
25
|
-
const notice = "Completion
|
|
39
|
+
const notice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
|
|
26
40
|
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
41
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
42
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
43
|
assert.match(requests[0].backgroundCommandDescription, /Stdout\/stderr are saved to a unique per-task log; its path is reported on completion\./);
|
|
30
44
|
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
31
|
-
assert.match(requests[0].backgroundDescription, /
|
|
45
|
+
assert.match(requests[0].backgroundDescription, /Use background_task for long-running commands or standalone waits/);
|
|
46
|
+
assert.match(requests[0].backgroundDescription, /session-scoped and do not survive reload or exit/);
|
|
32
47
|
assert.ok(!requests[0].backgroundDescription.includes(notice));
|
|
33
48
|
assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
|
|
34
49
|
assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
|
|
50
|
+
assert.match(requests[1].text, /Do not call Bash sleep/);
|
|
35
51
|
assert.ok(!started.result.content[0].text.includes(started.result.structuredContent.task.log_path));
|
|
36
52
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
37
53
|
});
|
|
38
54
|
|
|
55
|
+
test("real Pi receives accelerated progress turns until the background task completes", { timeout: 20000 }, async () => {
|
|
56
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-progress-"));
|
|
57
|
+
const requests = [];
|
|
58
|
+
let session;
|
|
59
|
+
try {
|
|
60
|
+
const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
|
|
61
|
+
modelRuntime.registerProvider("bg-progress", {
|
|
62
|
+
name: "Offline progress fixture", baseUrl: "http://127.0.0.1:1", api: "bg-progress", apiKey: "fixture-not-a-secret",
|
|
63
|
+
models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
64
|
+
streamSimple(model, context) {
|
|
65
|
+
const stream = createAssistantMessageEventStream();
|
|
66
|
+
queueMicrotask(() => {
|
|
67
|
+
const last = context.messages.at(-1);
|
|
68
|
+
const text = typeof last.content === "string" ? last.content : last.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
69
|
+
requests.push(text);
|
|
70
|
+
const start = last.role === "user" && text.includes("SMOKE_PROGRESS");
|
|
71
|
+
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: start ? "toolUse" : "stop",
|
|
72
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
73
|
+
if (start) message.content.push({ type: "toolCall", id: "progress-start", name: "background_task", arguments: {
|
|
74
|
+
action: "start", command: "sleep 0.6; printf 'PROGRESS COMPLETE\\n'", description: "Progress check", timeout: 5,
|
|
75
|
+
} });
|
|
76
|
+
else message.content.push({ type: "text", text: text.includes("[Background task finished]") ? "COMPLETION_ACK" : "PROGRESS_ACK" });
|
|
77
|
+
stream.push({ type: "start", partial: message });
|
|
78
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
79
|
+
});
|
|
80
|
+
return stream;
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false }, cacheWarming: "off" });
|
|
84
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
85
|
+
cwd: directory, agentDir: directory, settingsManager,
|
|
86
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
87
|
+
extensionFactories: [(pi) => registerBackgroundTasks(pi, { progressIntervalMs: 100 })],
|
|
88
|
+
});
|
|
89
|
+
await resourceLoader.reload();
|
|
90
|
+
const created = await createAgentSession({
|
|
91
|
+
cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-progress", "deterministic"),
|
|
92
|
+
thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task"],
|
|
93
|
+
});
|
|
94
|
+
session = created.session;
|
|
95
|
+
assert.deepEqual(created.extensionsResult.errors, []);
|
|
96
|
+
await session.bindExtensions({});
|
|
97
|
+
await session.prompt("SMOKE_PROGRESS");
|
|
98
|
+
const entries = (type) => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === type);
|
|
99
|
+
await waitFor(() => entries("background-task-progress").length >= 1, "accelerated progress notification");
|
|
100
|
+
await waitFor(() => entries("background-task-finished").length === 1, "completion notification");
|
|
101
|
+
await session.waitForIdle();
|
|
102
|
+
const progress = entries("background-task-progress");
|
|
103
|
+
assert.ok(progress.length >= 2, "the accelerated fixture must prove repeated progress turns");
|
|
104
|
+
for (const message of progress) {
|
|
105
|
+
assert.equal(message.details.tasks.length, 1);
|
|
106
|
+
assert.match(message.content, /Progress check/);
|
|
107
|
+
assert.match(message.content, /No action is required/);
|
|
108
|
+
assert.doesNotMatch(message.content, /PROGRESS COMPLETE|Captured log:|Untrusted shell output/);
|
|
109
|
+
}
|
|
110
|
+
assert.ok(requests.some((text) => text.includes("[Background tasks still running]")));
|
|
111
|
+
assert.ok(requests.some((text) => text.includes("[Background task finished]")));
|
|
112
|
+
assert.equal(entries("background-task-finished").length, 1);
|
|
113
|
+
} finally {
|
|
114
|
+
if (session) {
|
|
115
|
+
await session.abort();
|
|
116
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
117
|
+
session.dispose();
|
|
118
|
+
}
|
|
119
|
+
rmSync(directory, { recursive: true, force: true });
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
|
|
39
123
|
test("native Codemode cannot discover or call the model-only background tool", () => {
|
|
40
124
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-exposure-"));
|
|
41
125
|
try {
|
package/tests/panel.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { unlinkSync, readFileSync } from "node:fs";
|
|
|
3
3
|
import { test } from "node:test";
|
|
4
4
|
import { KeybindingsManager, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
|
|
5
5
|
import { BackgroundPanel } from "../src/panel.ts";
|
|
6
|
-
import { BackgroundFooter } from "../src/widget.ts";
|
|
6
|
+
import { BackgroundFooter, WIDGET_KEY } from "../src/widget.ts";
|
|
7
7
|
import { fixture, flush } from "./helpers.mjs";
|
|
8
8
|
|
|
9
9
|
const keys = new KeybindingsManager(TUI_KEYBINDINGS);
|
|
@@ -15,46 +15,53 @@ function panel(f) {
|
|
|
15
15
|
return { view, text: (width = 120) => view.render(width).join("\n"), get renders() { return renders; }, get closed() { return closed; } };
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
test("compact count,
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
18
|
+
test("compact count, arbitrary peer statuses, narrow widths and bounded mouse hit region", () => {
|
|
19
|
+
let opened = 0;
|
|
20
|
+
let panelOpen = false;
|
|
21
|
+
const statuses = new Map([[WIDGET_KEY, "1 shell"]]);
|
|
22
|
+
const native = { render: () => ["path", "usage model", ...(statuses.size ? [[...statuses.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, text]) => text).join(" ")] : [])], invalidate() {} };
|
|
23
|
+
const widget = new BackgroundFooter(native, theme, () => statuses, () => panelOpen, () => opened++);
|
|
24
|
+
assert.deepEqual(widget.render(120), ["path", "usage model", "1 shell · Alt+J"]);
|
|
25
|
+
assert.equal(widget.handleMouse(click(7, 2)), undefined);
|
|
26
|
+
assert.equal(widget.handleMouse(click(2, 1)), undefined);
|
|
27
|
+
assert.equal(widget.handleMouse(click(2, 2, "right")), undefined);
|
|
28
|
+
assert.equal(widget.handleMouse(click(2, 2)).handled, true);
|
|
29
|
+
assert.equal(opened, 1);
|
|
30
|
+
statuses.set(WIDGET_KEY, "2 shells");
|
|
31
|
+
assert.match(widget.render(120).at(-1), /^2 shells/);
|
|
32
|
+
statuses.set(WIDGET_KEY, "1 shell · 1 done");
|
|
33
|
+
assert.match(widget.render(120).at(-1), /^1 shell · 1 done/);
|
|
34
|
+
statuses.set(WIDGET_KEY, "1 shell");
|
|
35
|
+
assert.equal(widget.render(120).at(-1), "1 shell · Alt+J");
|
|
36
|
+
statuses.set("codex-edit", "editor: apply_patch");
|
|
37
|
+
assert.equal(widget.render(120).at(-1), "editor: apply_patch · 1 shell · Alt+J");
|
|
38
|
+
assert.equal(widget.handleMouse(click(2, 2)), undefined, "editor status is not a shell click");
|
|
39
|
+
assert.equal(widget.handleMouse(click(23, 2)).handled, true);
|
|
40
|
+
assert.equal(widget.render(29).at(-1), "editor: apply_patch · 1 shell", "drop the shortcut before truncating a peer status");
|
|
41
|
+
statuses.set("scheduler", "2 schedules");
|
|
42
|
+
statuses.set("z-custom", "future\tstatus\nready");
|
|
43
|
+
statuses.set("zero-width", "\x1b[31m\x1b[0m");
|
|
44
|
+
assert.equal(widget.render(120).at(-1), "editor: apply_patch · 2 schedules · future status ready · 1 shell · Alt+J");
|
|
45
|
+
const compact = widget.render(30).at(-1);
|
|
46
|
+
assert.doesNotMatch(compact, /Alt\+J/, "drop the shortcut before peer statuses");
|
|
47
|
+
assert.match(compact, /1 shell$/, "keep the shell count visible after truncating peers");
|
|
48
|
+
const compactShell = visibleWidth(compact.slice(0, compact.indexOf("1 shell")));
|
|
49
|
+
assert.equal(widget.handleMouse(click(compactShell - 1, 2)), undefined);
|
|
50
|
+
assert.equal(widget.handleMouse(click(compactShell + 1, 2)).handled, true, "truncated peer text keeps the shell hit box aligned");
|
|
51
|
+
panelOpen = true;
|
|
52
|
+
assert.deepEqual(widget.render(120), []);
|
|
53
|
+
assert.equal(widget.handleMouse(click(23, 2)), undefined);
|
|
54
|
+
panelOpen = false;
|
|
55
|
+
statuses.set("z-custom", "中文状态".repeat(20));
|
|
56
|
+
for (const width of [0, 1, 8, 40]) {
|
|
57
|
+
const row = widget.render(width).at(-1);
|
|
58
|
+
assert.ok(visibleWidth(row) <= width);
|
|
59
|
+
if (width >= 8) assert.match(row, /1 shell/, "keep the count visible even if other statuses are long");
|
|
60
|
+
}
|
|
61
|
+
widget.invalidate();
|
|
62
|
+
assert.equal(widget.handleMouse(click(2, 2)), undefined, "resize/theme invalidation clears stale hit regions");
|
|
63
|
+
statuses.delete(WIDGET_KEY);
|
|
64
|
+
assert.deepEqual(widget.render(120), native.render(120), "missing shell status leaves the native footer untouched");
|
|
58
65
|
});
|
|
59
66
|
|
|
60
67
|
test("single shell opens aligned, compact details without changing the original script", async () => {
|