@maxiaochao/pi-background-tasks 0.1.0 → 0.1.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 +12 -0
- package/README.md +37 -6
- package/TESTING.md +9 -2
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/extensions/background-tasks.ts +88 -8
- package/package.json +2 -2
- package/tests/compaction.mjs +167 -0
- package/tests/extension.mjs +309 -9
- package/tests/fixtures/notifications.ts +77 -0
- package/tests/fixtures/provider.ts +14 -4
- package/tests/interruptions.mjs +140 -0
- package/tests/notifications.mjs +80 -0
- package/tests/tui-smoke.py +8 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-10-22 - v0.1.1
|
|
4
|
+
|
|
5
|
+
- batch unread completions at tool boundaries, preserve interrupted runs, and provide non-polling startup guidance
|
|
6
|
+
- Include the approved non-polling startup guidance in the tool description, model-visible start result and Codemode's structured result. Keep ordinary output reads separate from waiting.
|
|
7
|
+
- Follow OMP's user-interrupt semantics: retain pending and later results without restarting the stopped agent, then hand unread results to the next user-message run. Do not confuse manual-compaction cancellation with an agent interrupt; add no switch or waiting tool.
|
|
8
|
+
- Cover direct native tool batches as well as Codemode, and real user interrupts before/after shell completion. Determine native compaction cancellation from lifecycle state instead of error wording.
|
|
9
|
+
- Deliver pending completions together after the current tool batch, before the next model request, instead of queuing one follow-up turn per task after the final report. Idle completions still wake the main agent automatically.
|
|
10
|
+
- Consume pending reminders when tool callers read terminal output, show actual completion times, and clear pending notification timers on session changes. Keep process/subagent execution and global queue settings unchanged; add no notification pause switch.
|
|
11
|
+
- Add a real-Pi four-completion queue regression with direct nested/Codemode reads, alongside deterministic busy/idle, consumption and abort/error checks.
|
|
12
|
+
- Back off busy-session notification checks through 1/2/4/8/16/30-second intervals, capped at 30 seconds without a retry limit or unread-result expiry. Tool boundaries still deliver immediately; fresh batches reset the delay. Keep the generic idle check instead of subscribing to individual busy-operation events.
|
|
13
|
+
- Verify native Pi manual compaction success, summary failure and cancellation with real shell jobs finishing during an offline summary request; pending results wake the main agent once after compaction, without another user prompt.
|
|
14
|
+
|
|
3
15
|
## 2026-10-20 - v0.1.0
|
|
4
16
|
|
|
5
17
|
- bundle background shell tasks with runtime limits, bounded logs, completion notifications and /bg controls
|
package/README.md
CHANGED
|
@@ -12,6 +12,8 @@ A command such as `sleep 60; python3 ...` can spend most of its time waiting to
|
|
|
12
12
|
|
|
13
13
|
It uses Pi's public `createLocalBashOperations()` backend for shell execution and process-group cancellation. It adds session ownership, bounded logs, status, and completion messages. It neither replaces Bash nor starts another model or Herdr pane.
|
|
14
14
|
|
|
15
|
+
Completion delivery follows [oh-my-pi's yield-queue approach](https://github.com/can1357/oh-my-pi/blob/3a2758b68f7c8e6bdf22c3a76b86c8675e5e0c9e/packages/coding-agent/src/session/yield-queue.ts): retain results, combine them at a safe boundary, and filter consumed results before delivery. This package uses Pi's public extension API, not patched host code; a local idle retry covers busy operations that expose no final agent boundary.
|
|
16
|
+
|
|
15
17
|
## Install and update
|
|
16
18
|
|
|
17
19
|
Requires Pi **1.3.0 or later**.
|
|
@@ -27,8 +29,22 @@ The complete `@maxiaochao/pi-toolkit` package **bundles and enables Background T
|
|
|
27
29
|
|
|
28
30
|
```text
|
|
29
31
|
background_task({ action: "start", command: "sleep 10; printf 'checks complete\\n'", description: "Delayed check", timeout: 120 })
|
|
30
|
-
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Each accepted start includes this exact guidance in the tool's text and `structuredContent.guidance`. The tool description carries it too, including for Codemode discovery:
|
|
35
|
+
|
|
36
|
+
> 完成会自动通知。现在不要查询等待;继续其他独立工作,没有其他工作就结束当前轮,收到通知后再取结果。
|
|
37
|
+
|
|
38
|
+
After the completion notification, read the result:
|
|
39
|
+
|
|
40
|
+
```text
|
|
31
41
|
background_task({ action: "output", id: "<returned-task-id>" })
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The tool also supports listing and cancellation:
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
background_task({ action: "list" })
|
|
32
48
|
background_task({ action: "cancel", id: "<returned-task-id>" })
|
|
33
49
|
```
|
|
34
50
|
|
|
@@ -57,7 +73,22 @@ The commands inspect the same jobs without asking a model to perform the operati
|
|
|
57
73
|
|
|
58
74
|
A fixed widget **above the editor** shows each task's ID, status, elapsed time, runtime limit and description. It coexists with Scheduler, Todo, and Herdr widgets. Finished rows remain for five seconds; hiding a row does not delete its record. RPC gets a compact active count; non-interactive tools work without the widget.
|
|
59
75
|
|
|
60
|
-
Completion, failure, cancellation, timeout and output-limit termination
|
|
76
|
+
Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
|
|
77
|
+
|
|
78
|
+
- While the main agent is busy, completions are combined into one message after the current tool batch returns, before the next model request. This includes waiting for a synchronous Herdr subagent; it does not cancel or interrupt that subagent.
|
|
79
|
+
- 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.
|
|
80
|
+
- 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.
|
|
81
|
+
- 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.
|
|
82
|
+
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks. This applies to direct and Codemode callers; a script that reads and filters a result has consumed it even if it does not print it. 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.
|
|
83
|
+
- Aborted/error boundaries do not request continuation or replay a previously scheduled wake. An error does not suppress later completions.
|
|
84
|
+
- A user interrupt keeps the agent stopped: accepted jobs still run, but even later completions cannot restart it. Unread results remain queryable and are handed to the next user-message run before its first model request. Another extension's custom wake does not release this interrupt state; a new user-message run or session replacement does. This adds no notification pause switch.
|
|
85
|
+
- Cancelling manual compaction is separate from interrupting the agent. Pending completions still wake an otherwise-idle session after compaction succeeds, fails or is cancelled.
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
Each message includes actual completion times, statuses and log paths, **not the output body**. The agent can call output when it needs details. Completions that arrive near final settlement are checked again before the run settles. No per-task `followUp` messages are left behind the main agent's final report.
|
|
90
|
+
|
|
91
|
+
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.
|
|
61
92
|
|
|
62
93
|
## Output and safety limits
|
|
63
94
|
|
|
@@ -85,21 +116,21 @@ const started = await tools.background_task({
|
|
|
85
116
|
command: "sleep 10; printf 'done\\n'",
|
|
86
117
|
timeout: 120,
|
|
87
118
|
});
|
|
88
|
-
text(started
|
|
119
|
+
text(started);
|
|
89
120
|
```
|
|
90
121
|
|
|
91
|
-
|
|
122
|
+
This prints the startup guidance as well as the task. Continue independent work or end the turn; do not keep a Codemode worker open to sleep or poll for completion. After notification, another script can read the result. Merely starting an unawaited Bash call is different: Codemode cancels unfinished nested calls when its script ends.
|
|
92
123
|
|
|
93
124
|
The tool description is compact. This package adds no `promptGuidelines` or extra global system-prompt rules.
|
|
94
125
|
|
|
95
126
|
## Lifetime and scope
|
|
96
127
|
|
|
97
128
|
- Exit, new/resumed/forked sessions and reload terminate active tasks, remove the widget and timers, and delete this package's captured logs. Commands' own files are left alone. History is not restored.
|
|
98
|
-
- Aborting the main agent's current turn does not cancel an accepted job. Use cancel or `/bg cancel
|
|
129
|
+
- Aborting the main agent's current turn does not cancel an accepted job, but its completion cannot automatically restart the interrupted agent. Use cancel or `/bg cancel` to stop the job itself.
|
|
99
130
|
- 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.
|
|
100
131
|
- 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.
|
|
101
132
|
- 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.
|
|
102
|
-
-
|
|
133
|
+
- 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.
|
|
103
134
|
|
|
104
135
|
## Remove
|
|
105
136
|
|
package/TESTING.md
CHANGED
|
@@ -13,7 +13,14 @@ 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 both output views with the real host Bash tool. Covers line/byte limits, long lines, empty output, missing final newline, UTF-8 split across chunks, invalid UTF-8 and logs larger than 1 MiB.
|
|
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,
|
|
16
|
+
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, command parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, no output in notifications, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks the exact approved startup guidance in both return paths and the tool description; verifies 24-hour retention after an interrupt, output consumption while stopped, custom-wake isolation and restoration of automatic delivery by a new user-message run.
|
|
17
|
+
- `notifications.mjs`: isolated real Pi with direct tool batches or its native Codemode tool, default one-at-a-time queues and an offline provider. Four actual failing shell jobs finish while a synchronous tool stands in for a subagent. The next model request gets one merged notification, excluding zero, one or four consumed terminal outputs; no extra requests follow the final report. Also verifies that native Codemode and the next model request receive the exact startup guidance. The blocking tool is a fixture, not a real Herdr child. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
|
|
18
|
+
- `compaction.mjs`: isolated native Pi SDK sessions call `session.compact()`, the same manual-compaction entry point used by `/compact` and RPC. Real shell jobs exit during a held offline summary request. Covers successful native compaction, a provider summary error and `abortCompaction()` cancellation; each must retain the pending completion while busy and automatically deliver it once afterward, without another user prompt. Checks actual compaction lifecycle/events, saved compaction entries, completion timestamps/logs and exactly one automatic conversation request. Uses real timers and native `isIdle`/`isCompacting`, not injected busy state or replacement compaction results; no paid model call or TUI keyboard invocation of `/compact`. `BG_TEST_EXTENSION` also supports a negative-control extension.
|
|
19
|
+
- `interruptions.mjs`: isolated native Pi SDK sessions call the real `session.abort()` while a foreground tool is held. A real shell finishes before or after the interrupt; terminal timestamps verify the ordering. Native `agent_settled.aborted` must confirm the stop; no completion may start another model request. A new user prompt sees the retained completion in its first request, reads the real failed task's output, and finishes without duplicate delivery or extension errors. A third case starts actual manual compaction while the foreground tool is held: Pi itself interrupts the active agent, which must stay stopped even after compaction and background completion. The public abort event has no reason field, so the extension preserves this native interruption rather than guessing its source. `BG_TEST_EXTENSION` supports a negative control without interrupt suppression.
|
|
20
|
+
|
|
21
|
+
Compaction cancellation assertions use native lifecycle `aborted` flags and the absence of a saved compaction entry, not version-dependent error strings. Agent interruption is a different state and is tested separately.
|
|
22
|
+
|
|
23
|
+
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.
|
|
17
24
|
|
|
18
25
|
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.
|
|
19
26
|
|
|
@@ -25,7 +32,7 @@ Requires Python 3 with the existing `pexpect` module; process fixtures use Bash,
|
|
|
25
32
|
python3 packages/background-tasks/tests/tui-smoke.py .cache/verification/background-tui
|
|
26
33
|
```
|
|
27
34
|
|
|
28
|
-
This starts a real Pi in a PTY with the production extension, Scheduler, the built-in Codemode tool and a deterministic fixture provider. It checks two jobs, rejection of a third, Codemode completion while jobs remain alive, explicit output, cancellation, automatic main-agent
|
|
35
|
+
This starts a real Pi in a PTY with the production extension, Scheduler, the built-in Codemode tool and a deterministic fixture provider. It checks two jobs, rejection of a third, Codemode completion while jobs remain alive, explicit output, cancellation, automatic main-agent notification, reload/new/quit cleanup and log removal. It observes both persisted boundary entries and idle custom messages by unique session-entry ID, and rejects duplicate notifications. No network model calls occur. Mocked UI tests separately verify the exact five-second boundary.
|
|
29
36
|
|
|
30
37
|
Results and the actual ANSI stream are stored under the chosen evidence directory. Real screenshots require an isolated X11 terminal window, `gnome-terminal.real`, `xwininfo` and ImageMagick `import`:
|
|
31
38
|
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
2
|
-
import { createLocalBashOperations, type BashOperations, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createLocalBashOperations, type AgentBeforeSettleEvent, type BashOperations, type ExtensionAPI, type ExtensionContext, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { Text } from "@earendil-works/pi-tui";
|
|
4
4
|
import { stripVTControlCharacters } from "node:util";
|
|
5
5
|
import { Type } from "typebox";
|
|
@@ -7,6 +7,7 @@ import { BackgroundTasks, errorText, summary, systemClock, type Clock, type Task
|
|
|
7
7
|
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
8
8
|
|
|
9
9
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
10
|
+
const startGuidance = "完成会自动通知。现在不要查询等待;继续其他独立工作,没有其他工作就结束当前轮,收到通知后再取结果。";
|
|
10
11
|
type Action = typeof actions[number];
|
|
11
12
|
interface Params {
|
|
12
13
|
action: Action;
|
|
@@ -34,6 +35,7 @@ const OutputSchema = Type.Object({
|
|
|
34
35
|
action: Type.Optional(StringEnum(actions)), task: Type.Optional(TaskSchema), tasks: Type.Optional(Type.Array(TaskSchema)),
|
|
35
36
|
running: Type.Optional(Type.Number()), total: Type.Optional(Type.Number()), omitted: Type.Optional(Type.Number()),
|
|
36
37
|
output: Type.Optional(Type.String()), truncated: Type.Optional(Type.Boolean()), full_output_path: Type.Optional(Type.String()),
|
|
38
|
+
guidance: Type.Optional(Type.String()),
|
|
37
39
|
error: Type.Optional(Type.String()),
|
|
38
40
|
});
|
|
39
41
|
|
|
@@ -62,8 +64,78 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
62
64
|
let context: ExtensionContext | undefined;
|
|
63
65
|
let generation = 0;
|
|
64
66
|
let timer: unknown;
|
|
67
|
+
let notificationTimer: unknown;
|
|
68
|
+
let completedNormally = true;
|
|
69
|
+
let interrupted = false;
|
|
70
|
+
const pending = new Map<string, TaskSnapshot>();
|
|
65
71
|
let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
|
|
66
72
|
|
|
73
|
+
const clearNotificationTimer = () => {
|
|
74
|
+
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
75
|
+
notificationTimer = undefined;
|
|
76
|
+
};
|
|
77
|
+
const takeNotification = () => {
|
|
78
|
+
clearNotificationTimer();
|
|
79
|
+
if (pending.size === 0) return;
|
|
80
|
+
const tasks = [...pending.values()].sort((a, b) => a.ended_at! - b.ended_at!);
|
|
81
|
+
pending.clear();
|
|
82
|
+
return {
|
|
83
|
+
customType: "background-task-finished", display: true,
|
|
84
|
+
details: { tasks, ...(tasks.length === 1 ? { task: tasks[0] } : {}) },
|
|
85
|
+
content: `[Background task finished]\n${tasks.map((task) =>
|
|
86
|
+
`${formatTask(task)}\nEnded at: ${new Date(task.ended_at!).toISOString()}${task.reason ? `\nReason: ${task.reason}` : ""}\nCaptured log: ${task.log_path}${task.capture_complete ? "" : "\nOutput capture is incomplete."}`
|
|
87
|
+
).join("\n\n")}`,
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
const scheduleNotification = (delay = 0) => {
|
|
91
|
+
if (interrupted || notificationTimer !== undefined || pending.size === 0) return;
|
|
92
|
+
const epoch = generation;
|
|
93
|
+
notificationTimer = clock.setTimeout(() => {
|
|
94
|
+
notificationTimer = undefined;
|
|
95
|
+
if (generation !== epoch || !context) return;
|
|
96
|
+
if (!context.isIdle()) {
|
|
97
|
+
// Manual compaction has no agent boundary when it finishes.
|
|
98
|
+
// Keep one wake pending, without expiring unread results or polling every second.
|
|
99
|
+
scheduleNotification(Math.min(delay === 0 ? 1000 : delay * 2, 30_000));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const message = takeNotification();
|
|
103
|
+
if (!message) return;
|
|
104
|
+
try { pi.sendMessage(message, { triggerTurn: true, deliverAs: "steer" }); }
|
|
105
|
+
catch (error) {
|
|
106
|
+
// Native Pi reports async send/run failures itself; this covers synchronous adapters.
|
|
107
|
+
for (const task of message.details.tasks) pending.set(task.id, task);
|
|
108
|
+
console.error(`Background completion notification failed: ${errorText(error)}`);
|
|
109
|
+
}
|
|
110
|
+
}, delay);
|
|
111
|
+
};
|
|
112
|
+
const deliverAtBoundary = (event: TurnEndEvent | AgentBeforeSettleEvent) => {
|
|
113
|
+
completedNormally = event.outcome === "completed";
|
|
114
|
+
if (event.outcome === "aborted") interrupted = true;
|
|
115
|
+
if (!completedNormally || interrupted) {
|
|
116
|
+
clearNotificationTimer();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const message = takeNotification();
|
|
120
|
+
if (message) return { entries: [...event.entries, { type: "custom_message" as const, ...message }], continue: true };
|
|
121
|
+
};
|
|
122
|
+
pi.on("turn_end", deliverAtBoundary);
|
|
123
|
+
pi.on("agent_before_settle", deliverAtBoundary);
|
|
124
|
+
pi.on("before_agent_start", (event) => {
|
|
125
|
+
if (event.messageType !== "user" || !interrupted) return;
|
|
126
|
+
// Only a new user prompt releases an interrupt, not another extension's custom wake.
|
|
127
|
+
interrupted = false;
|
|
128
|
+
const message = takeNotification();
|
|
129
|
+
if (message) return { message };
|
|
130
|
+
});
|
|
131
|
+
pi.on("agent_settled", (event) => {
|
|
132
|
+
if (event.aborted) {
|
|
133
|
+
interrupted = true;
|
|
134
|
+
clearNotificationTimer();
|
|
135
|
+
}
|
|
136
|
+
if (!event.aborted && completedNormally) scheduleNotification();
|
|
137
|
+
});
|
|
138
|
+
|
|
67
139
|
const clearTimer = () => {
|
|
68
140
|
if (timer !== undefined) clock.clearTimeout(timer);
|
|
69
141
|
timer = undefined;
|
|
@@ -107,6 +179,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
107
179
|
manager = undefined;
|
|
108
180
|
context = undefined;
|
|
109
181
|
clearTimer();
|
|
182
|
+
clearNotificationTimer();
|
|
183
|
+
pending.clear();
|
|
184
|
+
completedNormally = true;
|
|
185
|
+
interrupted = false;
|
|
110
186
|
try {
|
|
111
187
|
if (previousContext?.hasUI) {
|
|
112
188
|
previousContext.ui.setStatus(WIDGET_KEY, undefined);
|
|
@@ -124,10 +200,8 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
124
200
|
onChange() { if (generation === epoch) refresh(); },
|
|
125
201
|
onComplete(task) {
|
|
126
202
|
if (generation !== epoch || !context) return;
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
content: `[Background task finished]\n${formatTask(task)}${task.reason ? `\nReason: ${task.reason}` : ""}\nCaptured log: ${task.log_path}${task.capture_complete ? "" : "\nOutput capture is incomplete."}`,
|
|
130
|
-
}, { triggerTurn: true, deliverAs: "followUp" });
|
|
203
|
+
pending.set(task.id, task);
|
|
204
|
+
scheduleNotification();
|
|
131
205
|
},
|
|
132
206
|
});
|
|
133
207
|
});
|
|
@@ -139,8 +213,8 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
139
213
|
if (params.action === "start") {
|
|
140
214
|
const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
|
|
141
215
|
return {
|
|
142
|
-
text: `Started ${formatTask(task)}\nLog: ${task.log_path}\nAt most 2 tasks run at once. Tasks stop on session changes, reload, or exit; captured logs are then removed.`,
|
|
143
|
-
data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
|
|
216
|
+
text: `Started ${formatTask(task)}\n${startGuidance}\nLog: ${task.log_path}\nAt most 2 tasks run at once. Tasks stop on session changes, reload, or exit; captured logs are then removed.`,
|
|
217
|
+
data: { action: params.action, task, guidance: startGuidance }, details: { action: params.action, task }, isError: false,
|
|
144
218
|
};
|
|
145
219
|
}
|
|
146
220
|
if (params.action === "list") {
|
|
@@ -166,13 +240,19 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
166
240
|
|
|
167
241
|
pi.registerTool({
|
|
168
242
|
name: "background_task", label: "Background task",
|
|
169
|
-
description:
|
|
243
|
+
description: `Start shell commands as background tasks and return task IDs immediately. Supports status, output, and cancellation. After start: ${startGuidance}`,
|
|
170
244
|
parameters: Parameters, outputSchema: OutputSchema,
|
|
171
245
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
172
246
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
173
247
|
try {
|
|
174
248
|
if (signal?.aborted) throw new Error("Tool call aborted before task acceptance");
|
|
175
249
|
const result = await perform(params, ctx?.cwd ?? context?.cwd ?? process.cwd());
|
|
250
|
+
// A terminal result was consumed by this tool's caller (including Codemode).
|
|
251
|
+
// User /bg inspections and running snapshots do not acknowledge completion.
|
|
252
|
+
if (params.action === "output" && "task" in result.data && result.data.task.status !== "running") {
|
|
253
|
+
pending.delete(result.data.task.id);
|
|
254
|
+
if (pending.size === 0) clearNotificationTimer();
|
|
255
|
+
}
|
|
176
256
|
return { content: [{ type: "text" as const, text: result.text }], structuredContent: result.data, details: result.details, isError: result.isError };
|
|
177
257
|
} catch (error) {
|
|
178
258
|
const message = errorText(error);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Session-scoped background shell tasks with completion notifications for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"typebox": "*"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
|
-
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs",
|
|
37
|
+
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs tests/notifications.mjs tests/compaction.mjs tests/interruptions.mjs",
|
|
38
38
|
"load-test": "node --experimental-strip-types tests/load.mjs"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import "./runtime.mjs";
|
|
9
|
+
|
|
10
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
|
|
11
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
12
|
+
const { default: register } = await import(process.env.BG_TEST_EXTENSION
|
|
13
|
+
? pathToFileURL(process.env.BG_TEST_EXTENSION).href : new URL("../extensions/background-tasks.ts", import.meta.url).href);
|
|
14
|
+
|
|
15
|
+
async function waitFor(check, label) {
|
|
16
|
+
for (let i = 0; i < 1000; i++) {
|
|
17
|
+
if (check()) return;
|
|
18
|
+
await delay(10);
|
|
19
|
+
}
|
|
20
|
+
throw new Error(`Timed out waiting for ${label}`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
for (const outcome of ["success", "failure", "cancel"]) {
|
|
24
|
+
test(`real Pi manual compaction ${outcome} delivers a job completed during summarization once, without another user prompt`, { timeout: 20000 }, async (t) => {
|
|
25
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-compact-"));
|
|
26
|
+
const release = join(directory, "release");
|
|
27
|
+
const exited = join(directory, "exited");
|
|
28
|
+
const finishSummary = Promise.withResolvers();
|
|
29
|
+
const requests = [], lifecycle = [], events = [], errors = [];
|
|
30
|
+
let session, startedTask;
|
|
31
|
+
try {
|
|
32
|
+
const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
|
|
33
|
+
modelRuntime.registerProvider("bg-compaction", {
|
|
34
|
+
name: "Offline real-compaction fixture", baseUrl: "http://127.0.0.1:1", api: "bg-compaction", apiKey: "fixture-not-a-secret",
|
|
35
|
+
models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
36
|
+
streamSimple(model, context, options) {
|
|
37
|
+
const stream = createAssistantMessageEventStream();
|
|
38
|
+
const compacting = session.isCompacting;
|
|
39
|
+
requests.push({ compacting, messages: context.messages });
|
|
40
|
+
void (async () => {
|
|
41
|
+
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: "stop",
|
|
42
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
43
|
+
try {
|
|
44
|
+
if (compacting) {
|
|
45
|
+
assert.ok(options.signal, "native summarization supplies its cancellation signal");
|
|
46
|
+
writeFileSync(release, "release background shell\n");
|
|
47
|
+
const aborted = () => finishSummary.resolve();
|
|
48
|
+
options.signal.addEventListener("abort", aborted, { once: true });
|
|
49
|
+
try { await finishSummary.promise; }
|
|
50
|
+
finally { options.signal.removeEventListener("abort", aborted); }
|
|
51
|
+
if (options.signal.aborted) {
|
|
52
|
+
message.stopReason = "aborted";
|
|
53
|
+
message.errorMessage = "Fixture summary aborted";
|
|
54
|
+
} else if (outcome === "failure") {
|
|
55
|
+
message.stopReason = "error";
|
|
56
|
+
message.errorMessage = "Fixture summary failure";
|
|
57
|
+
} else message.content.push({ type: "text", text: "## Goal\nVerify compaction delivery.\n## Progress\nA background shell remains owned by this session." });
|
|
58
|
+
} else {
|
|
59
|
+
const last = context.messages.at(-1);
|
|
60
|
+
const text = typeof last.content === "string" ? last.content : last.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
61
|
+
if (last.role === "user" && text.includes("START_COMPACTION_JOB")) {
|
|
62
|
+
message.stopReason = "toolUse";
|
|
63
|
+
message.content.push({ type: "toolCall", id: "compaction-start", name: "background_task", arguments: {
|
|
64
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'finished during compaction\\n'; printf done > exited; exit 7", description: "Finishes during native compaction", timeout: 10,
|
|
65
|
+
} });
|
|
66
|
+
} else message.content.push({ type: "text", text: text.includes("[Background task finished]") ? "COMPLETION_ACK" : "JOB_ACCEPTED" });
|
|
67
|
+
}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
message.stopReason = "error";
|
|
70
|
+
message.errorMessage = String(error);
|
|
71
|
+
}
|
|
72
|
+
stream.push({ type: "start", partial: message });
|
|
73
|
+
if (["error", "aborted"].includes(message.stopReason)) stream.push({ type: "error", reason: message.stopReason, error: message });
|
|
74
|
+
else stream.push({ type: "done", reason: message.stopReason, message });
|
|
75
|
+
})();
|
|
76
|
+
return stream;
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false, keepRecentTokens: 128 }, retry: { enabled: false }, cacheWarming: "off" });
|
|
80
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
81
|
+
cwd: directory, agentDir: directory, settingsManager,
|
|
82
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
83
|
+
extensionFactories: [register, (pi) => {
|
|
84
|
+
for (const type of ["session_before_compact", "session_compact", "session_compact_failed"]) pi.on(type, (event, ctx) => {
|
|
85
|
+
lifecycle.push({ type, reason: event.reason, aborted: event.aborted, fromExtension: event.fromExtension, idle: ctx.isIdle() });
|
|
86
|
+
});
|
|
87
|
+
}],
|
|
88
|
+
});
|
|
89
|
+
await resourceLoader.reload();
|
|
90
|
+
const created = await createAgentSession({ cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-compaction", "deterministic"), thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task"] });
|
|
91
|
+
session = created.session;
|
|
92
|
+
assert.deepEqual(created.extensionsResult.errors, []);
|
|
93
|
+
session.extensionRunner.onError((error) => errors.push(error));
|
|
94
|
+
session.subscribe((event) => {
|
|
95
|
+
events.push({ ...event, observedAt: Date.now() });
|
|
96
|
+
if (event.type === "tool_execution_end" && event.toolName === "background_task") startedTask = event.result.structuredContent.task;
|
|
97
|
+
});
|
|
98
|
+
await session.bindExtensions({});
|
|
99
|
+
await session.prompt("Earlier context to summarize: " + "background verification history ".repeat(200));
|
|
100
|
+
await session.prompt("START_COMPACTION_JOB");
|
|
101
|
+
assert.equal(startedTask?.status, "running");
|
|
102
|
+
assert.equal(session.isIdle, true);
|
|
103
|
+
const notifications = () => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
104
|
+
const conversationRequests = () => requests.filter((request) => !request.compacting);
|
|
105
|
+
const before = conversationRequests().length;
|
|
106
|
+
// This is the same public manual-compaction entry point used by /compact and RPC.
|
|
107
|
+
const compacting = session.compact("COMPACTION_DELIVERY_FIXTURE").then((value) => ({ value }), (error) => ({ error }));
|
|
108
|
+
await waitFor(() => lifecycle.some((event) => event.type === "session_before_compact"), "native compaction start");
|
|
109
|
+
await waitFor(() => requests.some((request) => request.compacting), "native summarizer request");
|
|
110
|
+
await waitFor(() => existsSync(exited), "real background shell exit marker");
|
|
111
|
+
await delay(1250); // Let the real first retry run while native compaction is still busy.
|
|
112
|
+
assert.equal(session.isCompacting, true);
|
|
113
|
+
assert.equal(session.isIdle, false);
|
|
114
|
+
assert.equal(notifications().length, 0, "completion cannot interrupt native compaction");
|
|
115
|
+
assert.equal(conversationRequests().length, before, "busy retries must not start another conversation request");
|
|
116
|
+
if (outcome === "cancel") session.abortCompaction();
|
|
117
|
+
else finishSummary.resolve();
|
|
118
|
+
const result = await compacting;
|
|
119
|
+
if (outcome === "success") {
|
|
120
|
+
assert.equal(result.error, undefined);
|
|
121
|
+
assert.match(result.value.summary, /Verify compaction delivery/);
|
|
122
|
+
} else {
|
|
123
|
+
assert.ok(result.error, "native compaction must reject on failure or cancellation");
|
|
124
|
+
if (outcome === "failure") assert.match(result.error.message, /Fixture summary failure/);
|
|
125
|
+
}
|
|
126
|
+
assert.equal(session.isCompacting, false);
|
|
127
|
+
assert.deepEqual(lifecycle.map((event) => event.type), ["session_before_compact", outcome === "success" ? "session_compact" : "session_compact_failed"]);
|
|
128
|
+
assert.ok(lifecycle.every((event) => event.reason === "manual"));
|
|
129
|
+
assert.equal(lifecycle[1].fromExtension, false, "the fixture must not supply a replacement compaction result");
|
|
130
|
+
if (outcome !== "success") assert.equal(lifecycle[1].aborted, outcome === "cancel");
|
|
131
|
+
await waitFor(() => notifications().length > 0, "automatic completion delivery after compaction");
|
|
132
|
+
await session.waitForIdle();
|
|
133
|
+
await delay(50);
|
|
134
|
+
assert.equal(notifications().length, 1);
|
|
135
|
+
assert.equal(conversationRequests().length, before + 1, "no user prompt is submitted after compact()");
|
|
136
|
+
const notification = notifications()[0];
|
|
137
|
+
const task = notification.details.tasks[0];
|
|
138
|
+
assert.equal(task.id, startedTask.id);
|
|
139
|
+
assert.equal(task.status, "failed");
|
|
140
|
+
assert.equal(task.exit_code, 7);
|
|
141
|
+
assert.match(readFileSync(task.log_path, "utf8"), /finished during compaction/);
|
|
142
|
+
const start = events.find((event) => event.type === "compaction_start");
|
|
143
|
+
const end = events.find((event) => event.type === "compaction_end");
|
|
144
|
+
assert.ok(start && end, "native compaction lifecycle must actually run");
|
|
145
|
+
assert.ok(task.ended_at >= start.observedAt && task.ended_at <= end.observedAt, "the actual task completed during compaction, not beforehand");
|
|
146
|
+
assert.equal(end.aborted, outcome === "cancel");
|
|
147
|
+
assert.equal(session.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, outcome === "success" ? 1 : 0);
|
|
148
|
+
assert.equal(session.getLastAssistantText(), "COMPLETION_ACK");
|
|
149
|
+
assert.deepEqual(errors, []);
|
|
150
|
+
t.diagnostic(JSON.stringify({
|
|
151
|
+
outcome, lifecycle, taskCompletedDuringCompaction: true,
|
|
152
|
+
summaryRequests: requests.filter((request) => request.compacting).length,
|
|
153
|
+
automaticConversationRequests: conversationRequests().length - before,
|
|
154
|
+
completionEntries: notifications().length,
|
|
155
|
+
}));
|
|
156
|
+
} finally {
|
|
157
|
+
finishSummary.resolve();
|
|
158
|
+
if (session) {
|
|
159
|
+
session.abortCompaction();
|
|
160
|
+
await session.abort();
|
|
161
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
162
|
+
session.dispose();
|
|
163
|
+
}
|
|
164
|
+
rmSync(directory, { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
package/tests/extension.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { unlinkSync } from "node:fs";
|
|
2
3
|
import { test } from "node:test";
|
|
3
4
|
import { visibleWidth } from "@earendil-works/pi-tui";
|
|
4
5
|
import register from "../extensions/background-tasks.ts";
|
|
@@ -13,10 +14,11 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
13
14
|
const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
|
|
14
15
|
const placements = new Map();
|
|
15
16
|
const statuses = new Map();
|
|
16
|
-
|
|
17
|
+
const idleChecks = [];
|
|
18
|
+
let tool, renders = 0, idle = true;
|
|
17
19
|
const theme = { fg: (_color, text) => text, bold: (text) => text };
|
|
18
20
|
const ctx = {
|
|
19
|
-
cwd: f.root, mode, hasUI,
|
|
21
|
+
cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
|
|
20
22
|
ui: {
|
|
21
23
|
setWidget(key, factory, options) {
|
|
22
24
|
if (!factory) { widgets.delete(key); return; }
|
|
@@ -35,7 +37,8 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
35
37
|
};
|
|
36
38
|
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
|
|
37
39
|
return {
|
|
38
|
-
...f, handlers, commands, messages, notices, widgets, placements, statuses, ctx,
|
|
40
|
+
...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
|
|
41
|
+
setIdle(value) { idle = value; },
|
|
39
42
|
get tool() { return tool; }, get renders() { return renders; },
|
|
40
43
|
async close() {
|
|
41
44
|
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
@@ -46,24 +49,318 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
46
49
|
};
|
|
47
50
|
}
|
|
48
51
|
|
|
52
|
+
test("completions during a synchronous tool are merged before the next model request", async () => {
|
|
53
|
+
const h = harness();
|
|
54
|
+
try {
|
|
55
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
56
|
+
h.setIdle(false);
|
|
57
|
+
for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
|
|
58
|
+
h.calls[0].resolve(1);
|
|
59
|
+
h.calls[1].resolve(2);
|
|
60
|
+
await flush();
|
|
61
|
+
assert.equal(h.messages.length, 0, "busy completions must not enter an irrevocable host queue");
|
|
62
|
+
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
|
|
63
|
+
const existing = { type: "custom", customType: "other-extension", data: { preserved: true } };
|
|
64
|
+
const boundary = h.handlers.get("turn_end")({ entries: [existing], continue: true, outcome: "completed" }, h.ctx);
|
|
65
|
+
assert.equal(boundary.continue, true);
|
|
66
|
+
assert.equal(boundary.entries.length, 2);
|
|
67
|
+
assert.deepEqual(boundary.entries[0], existing);
|
|
68
|
+
assert.equal(boundary.entries[1].details.tasks.length, 2);
|
|
69
|
+
assert.match(boundary.entries[1].content, /Ended at: 1970-01-01T00:00:01.000Z/);
|
|
70
|
+
assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
71
|
+
} finally { await h.close(); }
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("a completion during manual compaction wakes after idle without another agent boundary", async () => {
|
|
75
|
+
const h = harness("print", false);
|
|
76
|
+
try {
|
|
77
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
78
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
79
|
+
h.setIdle(false);
|
|
80
|
+
h.calls[0].resolve();
|
|
81
|
+
await flush();
|
|
82
|
+
h.clock.advance(0);
|
|
83
|
+
h.clock.advance(1000);
|
|
84
|
+
assert.equal(h.messages.length, 0);
|
|
85
|
+
h.setIdle(true); // Manual compaction succeeds, fails or is cancelled; none emits agent_settled.
|
|
86
|
+
h.clock.advance(2000);
|
|
87
|
+
assert.equal(h.messages.length, 1);
|
|
88
|
+
assert.equal(h.clock.timers.size, 0);
|
|
89
|
+
} finally { await h.close(); }
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("busy notification checks back off to 30 seconds without expiring unread results", async () => {
|
|
93
|
+
const h = harness("print", false);
|
|
94
|
+
try {
|
|
95
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
96
|
+
h.setIdle(false);
|
|
97
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
98
|
+
h.calls[0].resolve();
|
|
99
|
+
await flush();
|
|
100
|
+
const started = h.clock.now();
|
|
101
|
+
h.clock.advance(91000);
|
|
102
|
+
assert.deepEqual(h.idleChecks.map((time) => time - started), [0, 1000, 3000, 7000, 15000, 31000, 61000, 91000]);
|
|
103
|
+
assert.equal(h.messages.length, 0);
|
|
104
|
+
assert.equal(h.clock.timers.size, 1);
|
|
105
|
+
h.clock.advance(24 * 60 * 60 * 1000);
|
|
106
|
+
assert.equal(h.messages.length, 0, "no timeout may silently drop the unread batch");
|
|
107
|
+
assert.equal(h.clock.timers.size, 1);
|
|
108
|
+
h.setIdle(true);
|
|
109
|
+
const checks = h.idleChecks.length;
|
|
110
|
+
h.clock.advance(29999);
|
|
111
|
+
assert.equal(h.idleChecks.length, checks);
|
|
112
|
+
h.clock.advance(1);
|
|
113
|
+
assert.equal(h.messages.length, 1);
|
|
114
|
+
assert.equal(h.clock.timers.size, 0);
|
|
115
|
+
} finally { await h.close(); }
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("new completions share the backed-off timer, while tool boundaries deliver immediately and reset backoff", async () => {
|
|
119
|
+
const h = harness("print", false);
|
|
120
|
+
try {
|
|
121
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
122
|
+
h.setIdle(false);
|
|
123
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
124
|
+
h.calls[0].resolve();
|
|
125
|
+
await flush();
|
|
126
|
+
h.clock.advance(61000);
|
|
127
|
+
await h.tool.execute("second", { action: "start", command: "second" });
|
|
128
|
+
h.calls[1].resolve();
|
|
129
|
+
await flush();
|
|
130
|
+
assert.equal(h.clock.timers.size, 1);
|
|
131
|
+
const checks = h.idleChecks.length;
|
|
132
|
+
h.clock.advance(0);
|
|
133
|
+
assert.equal(h.idleChecks.length, checks, "a new completion must not restart an active backoff");
|
|
134
|
+
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
135
|
+
assert.equal(boundary.entries[0].details.tasks.length, 2);
|
|
136
|
+
assert.equal(h.clock.timers.size, 0, "the boundary must not wait for the 30-second timer");
|
|
137
|
+
await h.tool.execute("third", { action: "start", command: "third" });
|
|
138
|
+
h.calls[2].resolve();
|
|
139
|
+
await flush();
|
|
140
|
+
h.clock.advance(0);
|
|
141
|
+
assert.equal(h.idleChecks.length, checks + 1, "a fresh batch starts with an immediate check");
|
|
142
|
+
h.clock.advance(999);
|
|
143
|
+
assert.equal(h.idleChecks.length, checks + 1);
|
|
144
|
+
h.clock.advance(1);
|
|
145
|
+
assert.equal(h.idleChecks.length, checks + 2, "a fresh batch retries after one second, not thirty");
|
|
146
|
+
} finally { await h.close(); }
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
for (const action of ["agent_before_settle", "output", "aborted", "error", "session_shutdown"]) {
|
|
150
|
+
test(`${action} clears a capped notification retry without stale wakes`, async () => {
|
|
151
|
+
const h = harness("print", false);
|
|
152
|
+
try {
|
|
153
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
154
|
+
h.setIdle(false);
|
|
155
|
+
const task = (await h.tool.execute("start", { action: "start", command: "first" })).structuredContent.task;
|
|
156
|
+
h.calls[0].resolve();
|
|
157
|
+
await flush();
|
|
158
|
+
h.clock.advance(61000);
|
|
159
|
+
assert.equal(h.clock.timers.size, 1);
|
|
160
|
+
if (action === "output") {
|
|
161
|
+
await h.tool.execute("read", { action, id: task.id });
|
|
162
|
+
} else if (action === "session_shutdown") {
|
|
163
|
+
await h.handlers.get(action)({}, h.ctx);
|
|
164
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
165
|
+
} else {
|
|
166
|
+
const event = { entries: [], outcome: action === "agent_before_settle" ? "completed" : action };
|
|
167
|
+
const boundary = h.handlers.get("agent_before_settle")(event, h.ctx);
|
|
168
|
+
if (action === "agent_before_settle") assert.equal(boundary.entries[0].details.tasks[0].id, task.id);
|
|
169
|
+
else assert.equal(boundary, undefined);
|
|
170
|
+
}
|
|
171
|
+
assert.equal(h.clock.timers.size, 0);
|
|
172
|
+
h.setIdle(true);
|
|
173
|
+
const checks = h.idleChecks.length;
|
|
174
|
+
h.clock.advance(24 * 60 * 60 * 1000);
|
|
175
|
+
assert.equal(h.idleChecks.length, checks);
|
|
176
|
+
assert.equal(h.messages.length, 0);
|
|
177
|
+
} finally { await h.close(); }
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
test("failed terminal log reads do not consume pending completion", async () => {
|
|
182
|
+
const h = harness("print", false);
|
|
183
|
+
try {
|
|
184
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
185
|
+
h.setIdle(false);
|
|
186
|
+
const task = (await h.tool.execute("start", { action: "start", command: "first" })).structuredContent.task;
|
|
187
|
+
h.calls[0].resolve();
|
|
188
|
+
await flush();
|
|
189
|
+
unlinkSync(task.log_path);
|
|
190
|
+
const result = await h.tool.execute("read", { action: "output", id: task.id });
|
|
191
|
+
assert.equal(result.isError, true);
|
|
192
|
+
assert.match(result.structuredContent.error, /Cannot read task log/);
|
|
193
|
+
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
194
|
+
assert.equal(boundary.entries[0].details.tasks[0].id, task.id);
|
|
195
|
+
} finally { await h.close(); }
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("terminal output consumed by the agent removes only that pending reminder", async () => {
|
|
199
|
+
const h = harness();
|
|
200
|
+
try {
|
|
201
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
202
|
+
h.setIdle(false);
|
|
203
|
+
const a = (await h.tool.execute("a", { action: "start", command: "first" })).structuredContent.task;
|
|
204
|
+
const b = (await h.tool.execute("b", { action: "start", command: "second" })).structuredContent.task;
|
|
205
|
+
await h.tool.execute("running", { action: "output", id: b.id });
|
|
206
|
+
h.calls[0].resolve(7);
|
|
207
|
+
h.calls[1].resolve();
|
|
208
|
+
await flush();
|
|
209
|
+
await h.tool.execute("list", { action: "list" });
|
|
210
|
+
await h.commands.get("bg").handler(`output ${b.id}`, h.ctx);
|
|
211
|
+
const output = await h.tool.execute("read", { action: "output", id: a.id });
|
|
212
|
+
assert.equal(output.isError, true, "a nonzero command is still a successful log read");
|
|
213
|
+
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
214
|
+
assert.deepEqual(boundary.entries[0].details.tasks.map((task) => task.id), [b.id]);
|
|
215
|
+
assert.equal(h.messages.length, 1, "only the user's inspection message was sent");
|
|
216
|
+
} finally { await h.close(); }
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("idle completions coalesce, but a newly busy session receives them at its next boundary", async () => {
|
|
220
|
+
const h = harness();
|
|
221
|
+
try {
|
|
222
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
223
|
+
for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
|
|
224
|
+
h.calls[0].resolve();
|
|
225
|
+
h.calls[1].resolve(1);
|
|
226
|
+
await flush();
|
|
227
|
+
assert.equal(h.messages.length, 0);
|
|
228
|
+
h.setIdle(false);
|
|
229
|
+
h.clock.advance(0);
|
|
230
|
+
assert.equal(h.messages.length, 0, "idle wake must recheck state before sending");
|
|
231
|
+
const boundary = h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx);
|
|
232
|
+
assert.equal(boundary.entries[0].details.tasks.length, 2);
|
|
233
|
+
assert.equal(boundary.continue, true);
|
|
234
|
+
assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
235
|
+
} finally { await h.close(); }
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("idle wake batches current completions and a terminal read can remove the whole batch", async () => {
|
|
239
|
+
const h = harness("print", false);
|
|
240
|
+
try {
|
|
241
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
242
|
+
for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
|
|
243
|
+
h.calls[0].resolve();
|
|
244
|
+
h.calls[1].resolve(1);
|
|
245
|
+
await flush();
|
|
246
|
+
h.clock.advance(0);
|
|
247
|
+
assert.equal(h.messages.length, 1);
|
|
248
|
+
assert.equal(h.messages[0].message.details.tasks.length, 2);
|
|
249
|
+
const task = (await h.tool.execute("third", { action: "start", command: "third" })).structuredContent.task;
|
|
250
|
+
h.calls[2].resolve();
|
|
251
|
+
await flush();
|
|
252
|
+
await h.tool.execute("read", { action: "output", id: task.id });
|
|
253
|
+
h.clock.advance(0);
|
|
254
|
+
assert.equal(h.messages.length, 1);
|
|
255
|
+
assert.equal(h.clock.timers.size, 0);
|
|
256
|
+
} finally { await h.close(); }
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
for (const outcome of ["aborted", "error"]) {
|
|
260
|
+
test(`${outcome} boundaries do not force continuation or replay a scheduled idle wake`, async () => {
|
|
261
|
+
const h = harness();
|
|
262
|
+
try {
|
|
263
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
264
|
+
await h.tool.execute("start", { action: "start", command: "first" });
|
|
265
|
+
h.calls[0].resolve();
|
|
266
|
+
await flush();
|
|
267
|
+
h.setIdle(false);
|
|
268
|
+
assert.equal(h.handlers.get("turn_end")({ entries: [], outcome }, h.ctx), undefined);
|
|
269
|
+
assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome }, h.ctx), undefined);
|
|
270
|
+
h.handlers.get("agent_settled")({ aborted: outcome === "aborted" }, h.ctx);
|
|
271
|
+
h.setIdle(true);
|
|
272
|
+
h.clock.advance(0);
|
|
273
|
+
assert.equal(h.messages.length, 0);
|
|
274
|
+
if (outcome === "aborted") {
|
|
275
|
+
const resumed = h.handlers.get("before_agent_start")({ messageType: "user", prompt: "Continue" }, h.ctx);
|
|
276
|
+
assert.equal(resumed.message.details.tasks.length, 1, "the next user prompt receives retained results");
|
|
277
|
+
assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
281
|
+
assert.equal(boundary.entries[0].details.tasks.length, 1, "unread results remain available");
|
|
282
|
+
} finally { await h.close(); }
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
test("jobs finishing after a user interrupt stay queryable without restarting the agent until the next user prompt", async () => {
|
|
287
|
+
const h = harness("print", false);
|
|
288
|
+
try {
|
|
289
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
290
|
+
const tasks = [];
|
|
291
|
+
for (const command of ["first", "second"]) {
|
|
292
|
+
tasks.push((await h.tool.execute(command, { action: "start", command })).structuredContent.task);
|
|
293
|
+
}
|
|
294
|
+
h.setIdle(false);
|
|
295
|
+
h.handlers.get("turn_end")({ entries: [], outcome: "aborted" }, h.ctx);
|
|
296
|
+
h.handlers.get("agent_before_settle")({ entries: [], outcome: "aborted" }, h.ctx);
|
|
297
|
+
h.handlers.get("agent_settled")({ aborted: true }, h.ctx);
|
|
298
|
+
h.setIdle(true);
|
|
299
|
+
for (const call of h.calls) {
|
|
300
|
+
assert.equal(call.signal.aborted, false, "interrupting the agent must not cancel accepted jobs");
|
|
301
|
+
call.resolve(7);
|
|
302
|
+
}
|
|
303
|
+
await flush();
|
|
304
|
+
h.clock.advance(24 * 60 * 60 * 1000);
|
|
305
|
+
assert.equal(h.messages.length, 0, "late completions must not restart the interrupted agent");
|
|
306
|
+
assert.equal(h.clock.timers.size, 0);
|
|
307
|
+
const list = await h.tool.execute("list", { action: "list" });
|
|
308
|
+
assert.ok(list.structuredContent.tasks.every((task) => task.status === "failed"));
|
|
309
|
+
assert.equal(h.handlers.get("before_agent_start")?.({ messageType: "custom" }, h.ctx), undefined);
|
|
310
|
+
assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined, "another extension's run must not release the interrupt");
|
|
311
|
+
const output = await h.tool.execute("read", { action: "output", id: tasks[0].id });
|
|
312
|
+
assert.equal(output.structuredContent.task.exit_code, 7);
|
|
313
|
+
const resumed = h.handlers.get("before_agent_start")({ messageType: "user", prompt: "Continue" }, h.ctx);
|
|
314
|
+
assert.deepEqual(resumed.message.details.tasks.map((task) => task.id), [tasks[1].id]);
|
|
315
|
+
assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
316
|
+
await h.tool.execute("new", { action: "start", command: "new" });
|
|
317
|
+
h.calls[2].resolve();
|
|
318
|
+
await flush();
|
|
319
|
+
h.clock.advance(0);
|
|
320
|
+
assert.equal(h.messages.length, 1, "the user prompt restores normal automatic delivery");
|
|
321
|
+
} finally { await h.close(); }
|
|
322
|
+
});
|
|
323
|
+
|
|
49
324
|
test("registration is compact, does not inject prompt rules or start session resources", async () => {
|
|
50
325
|
const h = harness();
|
|
51
326
|
try {
|
|
52
327
|
assert.equal(h.tool.name, "background_task");
|
|
53
328
|
assert.match(h.tool.description, /return task IDs immediately/);
|
|
54
|
-
assert.ok(h.tool.description.length <
|
|
329
|
+
assert.ok(h.tool.description.length < 500);
|
|
55
330
|
assert.equal(h.tool.promptGuidelines, undefined);
|
|
56
331
|
assert.ok(h.tool.outputSchema);
|
|
57
332
|
assert.equal(h.tool.annotations.readOnlyHint, false);
|
|
58
333
|
assert.equal(h.tool.annotations.destructiveHint, true);
|
|
59
|
-
assert.ok(!h.handlers.has("before_agent_start"));
|
|
60
334
|
assert.equal(h.clock.timers.size, 0);
|
|
61
335
|
assert.equal(h.calls.length, 0);
|
|
62
336
|
assert.equal((await h.tool.execute("early", { action: "list" })).isError, true);
|
|
63
337
|
} finally { await h.close(); }
|
|
64
338
|
});
|
|
65
339
|
|
|
66
|
-
test("
|
|
340
|
+
test("start provides non-blocking next steps in both model text and structured results", async () => {
|
|
341
|
+
const h = harness();
|
|
342
|
+
try {
|
|
343
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
344
|
+
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
345
|
+
const { task, guidance } = started.structuredContent;
|
|
346
|
+
assert.equal(task.status, "running");
|
|
347
|
+
assert.equal(guidance, "完成会自动通知。现在不要查询等待;继续其他独立工作,没有其他工作就结束当前轮,收到通知后再取结果。");
|
|
348
|
+
assert.ok(started.content[0].text.includes(guidance), "ordinary tool callers must see the same guidance as Codemode");
|
|
349
|
+
assert.ok(h.tool.description.includes(guidance), "scripts that filter out guidance still discover the lifecycle in the tool description");
|
|
350
|
+
assert.equal(h.tool.outputSchema.properties.guidance.type, "string");
|
|
351
|
+
assert.equal(h.tool.outputSchema.required?.includes("guidance") ?? false, false);
|
|
352
|
+
const list = await h.tool.execute("list", { action: "list" });
|
|
353
|
+
const output = await h.tool.execute("output", { action: "output", id: task.id });
|
|
354
|
+
assert.equal(list.structuredContent.guidance, undefined);
|
|
355
|
+
assert.equal(output.structuredContent.guidance, undefined);
|
|
356
|
+
h.calls[0].resolve();
|
|
357
|
+
await flush();
|
|
358
|
+
h.clock.advance(0);
|
|
359
|
+
assert.equal(h.messages.filter((entry) => entry.message.customType === "background-task-finished").length, 1);
|
|
360
|
+
} finally { await h.close(); }
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
test("tools, commands, widget and idle notifications share the same session jobs", async () => {
|
|
67
364
|
const h = harness();
|
|
68
365
|
try {
|
|
69
366
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
@@ -91,9 +388,10 @@ test("tools, commands, widget and followUp share the same session jobs", async (
|
|
|
91
388
|
|
|
92
389
|
h.calls[0].resolve(7);
|
|
93
390
|
await flush();
|
|
391
|
+
h.clock.advance(0);
|
|
94
392
|
const completed = h.messages.filter((m) => m.message.customType === "background-task-finished");
|
|
95
393
|
assert.equal(completed.length, 1);
|
|
96
|
-
assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "
|
|
394
|
+
assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "steer" });
|
|
97
395
|
assert.match(completed[0].message.content, /failed.*exit 7/);
|
|
98
396
|
assert.ok(!completed[0].message.content.includes("logs only"));
|
|
99
397
|
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
|
|
@@ -117,6 +415,7 @@ test("cancel and shutdown are idempotent; new sessions cannot receive old comple
|
|
|
117
415
|
const cancel = h.tool.execute("cancel", { action: "cancel", id: a.id });
|
|
118
416
|
h.calls[0].reject(new Error("aborted"));
|
|
119
417
|
assert.equal((await cancel).structuredContent.task.status, "cancelled");
|
|
418
|
+
h.clock.advance(0);
|
|
120
419
|
const count = h.messages.length;
|
|
121
420
|
await h.commands.get("bg").handler(`cancel ${a.id}`, h.ctx);
|
|
122
421
|
assert.equal(h.messages.filter((m) => m.message.customType === "background-task-finished").length, 1);
|
|
@@ -145,9 +444,10 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
|
|
|
145
444
|
if (hasUI) assert.match(h.statuses.get("background-tasks"), /1\/2/);
|
|
146
445
|
h.calls[0].resolve();
|
|
147
446
|
await flush();
|
|
447
|
+
h.clock.advance(0);
|
|
148
448
|
assert.equal(h.clock.timers.size, 0);
|
|
149
449
|
assert.equal(h.statuses.has("background-tasks"), false);
|
|
150
|
-
assert.equal(h.messages.at(-1).options.deliverAs, "
|
|
450
|
+
assert.equal(h.messages.at(-1).options.deliverAs, "steer");
|
|
151
451
|
} finally { await h.close(); }
|
|
152
452
|
});
|
|
153
453
|
}
|
|
@@ -157,7 +457,7 @@ test("bad actions, irrelevant fields, aborted acceptance and command syntax fail
|
|
|
157
457
|
try {
|
|
158
458
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
159
459
|
for (const params of [
|
|
160
|
-
{ action: "other" }, { action: "start" }, { action: "list", command: "ignored" },
|
|
460
|
+
{ action: "other" }, { action: "notifications", enabled: false }, { action: "start" }, { action: "list", command: "ignored" },
|
|
161
461
|
{ action: "output" }, { action: "cancel", id: "unknown" },
|
|
162
462
|
{ action: "start", command: "x", id: "irrelevant" },
|
|
163
463
|
]) {
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// A blocking tool stands in for a synchronous subagent. Pi queues and shell jobs are real.
|
|
2
|
+
import { appendFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
|
|
9
|
+
export default function (pi: ExtensionAPI) {
|
|
10
|
+
const record = (entry: unknown) => appendFileSync(process.env.BG_NOTIFICATION_EVENTS!, JSON.stringify(entry) + "\n");
|
|
11
|
+
pi.registerTool({
|
|
12
|
+
name: "synchronous_subagent_fixture", label: "Synchronous subagent fixture",
|
|
13
|
+
description: "Wait for four real shell jobs while holding one synchronous tool call open.",
|
|
14
|
+
parameters: Type.Object({ reads: Type.Number() }),
|
|
15
|
+
async execute(_id, { reads }, _signal, _update, ctx) {
|
|
16
|
+
record({ event: "waiting" });
|
|
17
|
+
writeFileSync(join(ctx.cwd, "release"), "ready");
|
|
18
|
+
const list = async () => (await ctx.executeTool("background_task", { action: "list" })).result.structuredContent as any;
|
|
19
|
+
const wait = async () => {
|
|
20
|
+
for (let i = 0; i < 1000; i++) {
|
|
21
|
+
const tasks = await list();
|
|
22
|
+
if (tasks.running === 0) return tasks.tasks;
|
|
23
|
+
await delay(5);
|
|
24
|
+
}
|
|
25
|
+
throw new Error("Fixture shell jobs did not finish");
|
|
26
|
+
};
|
|
27
|
+
await wait();
|
|
28
|
+
for (let i = 0; i < 2; i++) await ctx.executeTool("background_task", {
|
|
29
|
+
action: "start", command: "printf 'second wave\\n'; exit 7", description: `second wave ${i}`, timeout: 10,
|
|
30
|
+
});
|
|
31
|
+
const tasks = await wait();
|
|
32
|
+
for (const task of tasks.slice(0, reads)) await ctx.executeTool("background_task", { action: "output", id: task.id });
|
|
33
|
+
record({ event: "returned", tasks, consumed: tasks.slice(0, reads).map((task: any) => task.id) });
|
|
34
|
+
return { content: [{ type: "text", text: "Synchronous subagent returned; final build report is ready." }], details: undefined };
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
let requests = 0;
|
|
38
|
+
pi.registerProvider("bg-notifications", {
|
|
39
|
+
name: "Offline notification fixture", baseUrl: "http://127.0.0.1:1", api: "bg-notifications", apiKey: "fixture-not-a-secret",
|
|
40
|
+
models: [{ id: "deterministic", name: "Offline notification fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
41
|
+
streamSimple(model, context) {
|
|
42
|
+
const stream = createAssistantMessageEventStream();
|
|
43
|
+
queueMicrotask(() => {
|
|
44
|
+
requests++;
|
|
45
|
+
record({ event: "request", number: requests, messages: context.messages });
|
|
46
|
+
const direct = process.env.BG_NOTIFICATION_MODE === "direct";
|
|
47
|
+
const toolTurn = requests === 1 || (direct && requests === 2);
|
|
48
|
+
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: toolTurn ? "toolUse" : "stop",
|
|
49
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
50
|
+
stream.push({ type: "start", partial: message });
|
|
51
|
+
if (toolTurn) {
|
|
52
|
+
const reads = Number(process.env.BG_NOTIFICATION_READS);
|
|
53
|
+
if (direct && requests === 1) {
|
|
54
|
+
for (let i = 0; i < 2; i++) message.content.push({ type: "toolCall", id: `direct-start-${i}`, name: "background_task", arguments: {
|
|
55
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'first wave\\n'; exit 7", description: `first wave ${i}`, timeout: 10,
|
|
56
|
+
} });
|
|
57
|
+
} else if (direct) message.content.push({ type: "toolCall", id: "direct-blocking-tool", name: "synchronous_subagent_fixture", arguments: { reads } });
|
|
58
|
+
else {
|
|
59
|
+
const code = `for (let i = 0; i < 2; i++) text(await tools.background_task({ action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'first wave\\\\n'; exit 7", description: "first wave " + i, timeout: 10 }));\ntext(await tools.synchronous_subagent_fixture({ reads: ${reads} }));`;
|
|
60
|
+
message.content.push({ type: "toolCall", id: "notification-fixture", name: "codemode", arguments: { code } });
|
|
61
|
+
}
|
|
62
|
+
for (let i = 0; i < message.content.length; i++) {
|
|
63
|
+
stream.push({ type: "toolcall_start", contentIndex: i, partial: message });
|
|
64
|
+
stream.push({ type: "toolcall_end", contentIndex: i, toolCall: message.content[i], partial: message });
|
|
65
|
+
}
|
|
66
|
+
} else {
|
|
67
|
+
message.content.push({ type: "text", text: "FINAL_REPORT" });
|
|
68
|
+
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
|
69
|
+
stream.push({ type: "text_delta", contentIndex: 0, delta: "FINAL_REPORT", partial: message });
|
|
70
|
+
stream.push({ type: "text_end", contentIndex: 0, content: "FINAL_REPORT", partial: message });
|
|
71
|
+
}
|
|
72
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
73
|
+
});
|
|
74
|
+
return stream;
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -8,6 +8,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
8
8
|
if (process.env.BG_SMOKE_EVENTS) appendFileSync(process.env.BG_SMOKE_EVENTS, JSON.stringify(entry) + "\n");
|
|
9
9
|
};
|
|
10
10
|
let sequence = 0;
|
|
11
|
+
const observedNotifications = new Set<string>();
|
|
11
12
|
pi.registerProvider("bg-fixture", {
|
|
12
13
|
name: "Offline background-task fixture", baseUrl: "http://127.0.0.1:1", api: "bg-fixture",
|
|
13
14
|
apiKey: "fixture-not-a-secret",
|
|
@@ -17,7 +18,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
17
18
|
queueMicrotask(() => {
|
|
18
19
|
const last = context.messages.at(-1) as any;
|
|
19
20
|
const text = typeof last?.content === "string" ? last.content : (last?.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n");
|
|
20
|
-
|
|
21
|
+
const tools = getCurrentTools(context.messages);
|
|
22
|
+
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
23
|
+
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description });
|
|
21
24
|
let code: string | undefined;
|
|
22
25
|
if (last?.role !== "toolResult") {
|
|
23
26
|
if (text.includes("SMOKE_START")) code = `const a = await tools.background_task({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\\\n'", description: "Release build", timeout: 30 });
|
|
@@ -32,6 +35,7 @@ const task = list.tasks.find(t => t.description === "Release build");
|
|
|
32
35
|
const result = await tools.background_task({ action: "output", id: task.id });
|
|
33
36
|
text({ status: result.task.status, output: result.output });`;
|
|
34
37
|
else if (text.includes("SMOKE_LONG")) code = `text(await tools.background_task({ action: "start", command: "echo $$ > shell.pid; sleep 300 & echo $! > child.pid; wait", description: "Lifecycle cleanup check", timeout: 300 }));`;
|
|
38
|
+
else if (text.includes("SMOKE_GUIDANCE")) code = `text(await tools.background_task({ action: "start", command: "sleep 300", description: "Guidance check", timeout: 300 }));`;
|
|
35
39
|
}
|
|
36
40
|
const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: code ? "toolUse" : "stop",
|
|
37
41
|
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
@@ -41,7 +45,7 @@ text({ status: result.task.status, output: result.output });`;
|
|
|
41
45
|
stream.push({ type: "toolcall_start", contentIndex: 0, partial: message });
|
|
42
46
|
stream.push({ type: "toolcall_end", contentIndex: 0, toolCall: message.content[0], partial: message });
|
|
43
47
|
} else {
|
|
44
|
-
const reply = text.includes("[Background task finished]") ? "
|
|
48
|
+
const reply = text.includes("[Background task finished]") ? "BACKGROUND_NOTIFICATION_RECEIVED" : "Main agent is ready; accepted background tasks keep running.";
|
|
45
49
|
message.content.push({ type: "text", text: reply });
|
|
46
50
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
|
47
51
|
stream.push({ type: "text_delta", contentIndex: 0, delta: reply, partial: message });
|
|
@@ -57,7 +61,13 @@ text({ status: result.task.status, output: result.output });`;
|
|
|
57
61
|
if (ctx.hasUI) ctx.ui.setTitle("Pi Background Tasks Smoke");
|
|
58
62
|
});
|
|
59
63
|
pi.on("tool_execution_end", (event) => record({ event: "tool_end", name: event.toolName, isError: event.isError, result: event.result }));
|
|
60
|
-
pi.on("
|
|
61
|
-
|
|
64
|
+
pi.on("context", (_event, ctx) => {
|
|
65
|
+
// Both boundary entries and idle messages are persisted before the provider request.
|
|
66
|
+
// Key by entry ID so two actual notifications for the same tasks remain observable.
|
|
67
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
68
|
+
if (entry.type !== "custom_message" || observedNotifications.has(entry.id)) continue;
|
|
69
|
+
observedNotifications.add(entry.id);
|
|
70
|
+
record({ event: "custom", entryId: entry.id, type: entry.customType, details: entry.details });
|
|
71
|
+
}
|
|
62
72
|
});
|
|
63
73
|
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import "./runtime.mjs";
|
|
9
|
+
|
|
10
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
|
|
11
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
12
|
+
const { Type } = await import("typebox");
|
|
13
|
+
const { default: register } = 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
|
+
for (const timing of ["before interrupt", "after interrupt", "after active compaction"]) {
|
|
17
|
+
test(`real Pi completion ${timing} stays stopped until the next user prompt, then delivers once`, { timeout: 20000 }, async (t) => {
|
|
18
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-interrupt-"));
|
|
19
|
+
const release = join(directory, "release");
|
|
20
|
+
const exited = join(directory, "exited");
|
|
21
|
+
const requests = [], settlements = [], errors = [];
|
|
22
|
+
let session, task, output, holding = false, summaries = 0;
|
|
23
|
+
const waitFor = async (check, label) => {
|
|
24
|
+
for (let i = 0; i < 1000; i++) {
|
|
25
|
+
if (check()) return;
|
|
26
|
+
await delay(10);
|
|
27
|
+
}
|
|
28
|
+
throw new Error(`Timed out waiting for ${label}`);
|
|
29
|
+
};
|
|
30
|
+
try {
|
|
31
|
+
const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
|
|
32
|
+
modelRuntime.registerProvider("bg-interrupt", {
|
|
33
|
+
name: "Offline interrupt fixture", baseUrl: "http://127.0.0.1:1", api: "bg-interrupt", apiKey: "fixture-not-a-secret",
|
|
34
|
+
models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
35
|
+
streamSimple(model, context) {
|
|
36
|
+
const compacting = session.isCompacting;
|
|
37
|
+
if (compacting) summaries++;
|
|
38
|
+
else requests.push(context.messages);
|
|
39
|
+
const stream = createAssistantMessageEventStream();
|
|
40
|
+
queueMicrotask(() => {
|
|
41
|
+
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: "toolUse",
|
|
42
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
43
|
+
if (compacting) {
|
|
44
|
+
message.stopReason = "stop";
|
|
45
|
+
message.content.push({ type: "text", text: "## Goal\nKeep the interrupted agent stopped. A shell job remains owned by this session." });
|
|
46
|
+
} else if (requests.length === 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
|
|
47
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", timeout: 10,
|
|
48
|
+
} });
|
|
49
|
+
else if (requests.length === 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
|
|
50
|
+
else if (requests.length === 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
|
|
51
|
+
else {
|
|
52
|
+
message.stopReason = "stop";
|
|
53
|
+
message.content.push({ type: "text", text: "RESUMED_RESULT_ACK" });
|
|
54
|
+
}
|
|
55
|
+
stream.push({ type: "start", partial: message });
|
|
56
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
57
|
+
});
|
|
58
|
+
return stream;
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false, keepRecentTokens: 128 }, retry: { enabled: false }, cacheWarming: "off" });
|
|
62
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
63
|
+
cwd: directory, agentDir: directory, settingsManager,
|
|
64
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
65
|
+
extensionFactories: [register, (pi) => {
|
|
66
|
+
pi.on("agent_settled", (event) => { settlements.push(event.aborted); });
|
|
67
|
+
pi.registerTool({
|
|
68
|
+
name: "interrupt_fixture", label: "Interrupt fixture", description: "Hold a real tool until the user interrupts the agent.",
|
|
69
|
+
parameters: Type.Object({}),
|
|
70
|
+
async execute(_id, _params, signal) {
|
|
71
|
+
holding = true;
|
|
72
|
+
assert.ok(signal);
|
|
73
|
+
if (!signal.aborted) await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true }));
|
|
74
|
+
return { content: [{ type: "text", text: "User interrupted the held tool." }], details: undefined };
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}],
|
|
78
|
+
});
|
|
79
|
+
await resourceLoader.reload();
|
|
80
|
+
const created = await createAgentSession({ cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-interrupt", "deterministic"), thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task", "interrupt_fixture"] });
|
|
81
|
+
session = created.session;
|
|
82
|
+
assert.deepEqual(created.extensionsResult.errors, []);
|
|
83
|
+
session.extensionRunner.onError((error) => errors.push(error));
|
|
84
|
+
session.subscribe((event) => {
|
|
85
|
+
if (event.type !== "tool_execution_end" || event.toolName !== "background_task") return;
|
|
86
|
+
if (event.result.structuredContent.action === "start") task = event.result.structuredContent.task;
|
|
87
|
+
else if (event.result.structuredContent.action === "output") output = event.result.structuredContent;
|
|
88
|
+
});
|
|
89
|
+
await session.bindExtensions({});
|
|
90
|
+
const prompting = session.prompt("Start a job and hold the agent so the user can interrupt. " + "Prior history to compact. ".repeat(200));
|
|
91
|
+
await waitFor(() => holding, "the real blocking tool");
|
|
92
|
+
assert.equal(task.status, "running");
|
|
93
|
+
if (timing === "before interrupt") {
|
|
94
|
+
writeFileSync(release, "finish while the tool is held");
|
|
95
|
+
await waitFor(() => existsSync(exited), "the background shell exit marker");
|
|
96
|
+
await delay(100);
|
|
97
|
+
}
|
|
98
|
+
const interruptRequestedAt = Date.now();
|
|
99
|
+
if (timing === "after active compaction") {
|
|
100
|
+
await session.compact();
|
|
101
|
+
assert.equal(summaries, 1, "manual compaction must run its native summary after interrupting the active agent");
|
|
102
|
+
} else await session.abort();
|
|
103
|
+
await prompting;
|
|
104
|
+
const interruptedAt = Date.now();
|
|
105
|
+
assert.deepEqual(settlements, [true], "native settlement must confirm the user interrupt");
|
|
106
|
+
assert.equal(session.isIdle, true);
|
|
107
|
+
writeFileSync(release, "finish after user interruption");
|
|
108
|
+
await waitFor(() => existsSync(exited), "the background shell surviving the interrupt");
|
|
109
|
+
await delay(1250);
|
|
110
|
+
assert.equal(requests.length, 2, "late completion must not start a model request");
|
|
111
|
+
assert.match(readFileSync(task.log_path, "utf8"), /late shell result/);
|
|
112
|
+
assert.equal(session.isIdle, true);
|
|
113
|
+
await session.prompt("Continue and inspect the completed job.");
|
|
114
|
+
assert.equal(requests.length, 4);
|
|
115
|
+
const resumedContext = JSON.stringify(requests[2]);
|
|
116
|
+
assert.equal((resumedContext.match(/\[Background task finished\]/g) ?? []).length, 1, "retained completion enters context before the resumed model request");
|
|
117
|
+
assert.ok(resumedContext.includes(task.id));
|
|
118
|
+
assert.equal(output.task.exit_code, 7);
|
|
119
|
+
assert.equal(output.output, "late shell result\n");
|
|
120
|
+
await delay(50);
|
|
121
|
+
assert.equal(requests.length, 4, "consumed completion must not trigger another turn");
|
|
122
|
+
const notifications = session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
123
|
+
assert.equal(notifications.length, 1);
|
|
124
|
+
assert.equal(notifications[0].details.tasks[0].id, task.id);
|
|
125
|
+
assert.equal(notifications[0].details.tasks[0].status, "failed");
|
|
126
|
+
if (timing === "before interrupt") assert.ok(notifications[0].details.tasks[0].ended_at <= interruptRequestedAt);
|
|
127
|
+
else assert.ok(notifications[0].details.tasks[0].ended_at >= interruptedAt);
|
|
128
|
+
assert.equal(session.getLastAssistantText(), "RESUMED_RESULT_ACK");
|
|
129
|
+
assert.deepEqual(errors, []);
|
|
130
|
+
t.diagnostic(JSON.stringify({ timing, requestsBeforeResume: 2, requestsAfterResume: 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
|
|
131
|
+
} finally {
|
|
132
|
+
if (session) {
|
|
133
|
+
await session.abort();
|
|
134
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
135
|
+
session.dispose();
|
|
136
|
+
}
|
|
137
|
+
rmSync(directory, { recursive: true, force: true });
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import { piBinary } from "./runtime.mjs";
|
|
9
|
+
|
|
10
|
+
test("native Codemode receives start guidance and exposes it to the model", () => {
|
|
11
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
|
|
12
|
+
try {
|
|
13
|
+
const events = join(directory, "events.jsonl");
|
|
14
|
+
const output = execFileSync(piBinary, [
|
|
15
|
+
"--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
|
|
16
|
+
"-e", "builtin:codemode", "-e", fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
|
|
17
|
+
"-e", fileURLToPath(new URL("fixtures/provider.ts", import.meta.url)),
|
|
18
|
+
"--tools", "codemode,background_task", "--model", "bg-fixture/deterministic", "-p", "SMOKE_GUIDANCE",
|
|
19
|
+
], { cwd: directory, encoding: "utf8", timeout: 30000,
|
|
20
|
+
env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_SMOKE_EVENTS: events }, stdio: ["ignore", "pipe", "pipe"] });
|
|
21
|
+
assert.match(output, /Main agent is ready/);
|
|
22
|
+
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
|
+
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
|
+
assert.equal(started.isError, false);
|
|
25
|
+
const guidance = started.result.structuredContent.guidance;
|
|
26
|
+
assert.equal(guidance, "完成会自动通知。现在不要查询等待;继续其他独立工作,没有其他工作就结束当前轮,收到通知后再取结果。");
|
|
27
|
+
const codemode = records.find((entry) => entry.event === "tool_end" && entry.name === "codemode");
|
|
28
|
+
assert.equal(codemode.isError, false);
|
|
29
|
+
assert.ok(codemode.result.content.some((block) => block.type === "text" && block.text.includes(guidance)));
|
|
30
|
+
const requests = records.filter((entry) => entry.event === "request");
|
|
31
|
+
assert.ok(requests[0].backgroundDescription.includes(guidance));
|
|
32
|
+
assert.ok(requests[1].text.includes(guidance), "the next model request sees guidance printed from the programmatic result");
|
|
33
|
+
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
for (const mode of ["codemode", "direct"]) {
|
|
37
|
+
for (const reads of [0, 1, 4]) {
|
|
38
|
+
test(`real Pi ${mode} merges four completions before the next model call, excluding ${reads} consumed results`, () => {
|
|
39
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-notifications-"));
|
|
40
|
+
try {
|
|
41
|
+
const events = join(directory, "events.jsonl");
|
|
42
|
+
writeFileSync(join(directory, "settings.json"), JSON.stringify({ quietStartup: true, followUpMode: "one-at-a-time", steeringMode: "one-at-a-time" }));
|
|
43
|
+
const output = execFileSync(piBinary, [
|
|
44
|
+
"--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
|
|
45
|
+
"-e", "builtin:codemode", "-e", process.env.BG_TEST_EXTENSION ?? fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
|
|
46
|
+
"-e", fileURLToPath(new URL("fixtures/notifications.ts", import.meta.url)),
|
|
47
|
+
"--tools", "codemode,background_task,synchronous_subagent_fixture", "--model", "bg-notifications/deterministic", "--mode", "json", "-p", "Run the synchronous subagent scenario",
|
|
48
|
+
], { cwd: directory, encoding: "utf8", timeout: 30000, env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_NOTIFICATION_EVENTS: events, BG_NOTIFICATION_READS: String(reads), BG_NOTIFICATION_MODE: mode }, stdio: ["ignore", "pipe", "pipe"] });
|
|
49
|
+
assert.doesNotMatch(output, /Failed to load|Error loading|Fixture shell jobs did not finish/);
|
|
50
|
+
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
51
|
+
const returned = records.find((entry) => entry.event === "returned");
|
|
52
|
+
assert.ok(returned, `the blocking tool finished all real shell jobs\n${output}`);
|
|
53
|
+
assert.equal(returned.tasks.length, 4);
|
|
54
|
+
assert.ok(returned.tasks.every((task) => task.status === "failed" && task.exit_code === 7));
|
|
55
|
+
const transcript = output.trim().split("\n").map((line) => JSON.parse(line));
|
|
56
|
+
const notifications = transcript.filter((entry) =>
|
|
57
|
+
(entry.type === "entry_appended" && entry.entry.customType === "background-task-finished") ||
|
|
58
|
+
(entry.type === "message_start" && entry.message.customType === "background-task-finished")
|
|
59
|
+
);
|
|
60
|
+
assert.equal(notifications.length, reads === 4 ? 0 : 1);
|
|
61
|
+
if (reads !== 4) {
|
|
62
|
+
const message = notifications[0].entry ?? notifications[0].message;
|
|
63
|
+
const tasks = message.details.tasks;
|
|
64
|
+
assert.equal(tasks.length, 4 - reads);
|
|
65
|
+
assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
|
|
66
|
+
const toolEnd = transcript.findIndex((entry) => entry.type === "tool_execution_end" && entry.toolName === "synchronous_subagent_fixture");
|
|
67
|
+
assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
|
|
68
|
+
assert.match(message.content, /Ended at: \d{4}-/);
|
|
69
|
+
}
|
|
70
|
+
const requests = records.filter((entry) => entry.event === "request");
|
|
71
|
+
assert.equal(requests.length, mode === "direct" ? 3 : 2, "no extra model turns after the final report");
|
|
72
|
+
const nextContext = JSON.stringify(requests.at(-1).messages);
|
|
73
|
+
assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, reads === 4 ? 0 : 1);
|
|
74
|
+
assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
|
|
75
|
+
const contextText = requests.at(-1).messages.flatMap((message) => typeof message.content === "string" ? [message.content] : (message.content ?? []).filter((block) => block.type === "text").map((block) => block.text)).join("\n");
|
|
76
|
+
for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) assert.ok(contextText.includes(task.id));
|
|
77
|
+
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
package/tests/tui-smoke.py
CHANGED
|
@@ -138,12 +138,15 @@ try:
|
|
|
138
138
|
shot('running')
|
|
139
139
|
send('/bg output ' + first['id'])
|
|
140
140
|
send('SMOKE_CANCEL')
|
|
141
|
-
wait(lambda: bool(finished('cancelled')), 'cancel
|
|
142
|
-
wait(lambda: bool(finished('succeeded')), 'successful background
|
|
141
|
+
wait(lambda: bool(finished('cancelled')), 'cancel notification')
|
|
142
|
+
wait(lambda: bool(finished('succeeded')), 'successful background notification')
|
|
143
143
|
shot('completed')
|
|
144
144
|
send('SMOKE_OUTPUT')
|
|
145
145
|
wait(lambda: any(e.get('result', {}).get('structuredContent', {}).get('output') == 'BUILD SUCCESSFUL\n' for e in tools()), 'explicit output query')
|
|
146
|
-
wait(lambda: '
|
|
146
|
+
wait(lambda: 'BACKGROUND_NOTIFICATION_RECEIVED' in raw, 'main agent automatic response')
|
|
147
|
+
pump(0.5)
|
|
148
|
+
notifications = [e for e in events() if e.get('event') == 'custom' and e.get('type') == 'background-task-finished']
|
|
149
|
+
assert len(notifications) == 2, 'Duplicate persisted busy/idle notifications'
|
|
147
150
|
pump(5.3)
|
|
148
151
|
shot('history')
|
|
149
152
|
|
|
@@ -174,7 +177,8 @@ try:
|
|
|
174
177
|
(OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
|
|
175
178
|
(OUT / 'result.json').write_text(json.dumps({'passed': True, 'screenshots': screens,
|
|
176
179
|
'checks': ['two jobs', 'third rejected', 'Codemode returns while jobs live', 'Scheduler coexistence', '/bg output',
|
|
177
|
-
'cancel notification', 'success notification', 'main agent
|
|
180
|
+
'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
|
|
181
|
+
'5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
|
|
178
182
|
except Exception:
|
|
179
183
|
(OUT / 'error.txt').write_text(traceback.format_exc())
|
|
180
184
|
raise
|