@maxiaochao/pi-background-tasks 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +52 -19
- package/TESTING.md +26 -6
- package/docs/demo.gif +0 -0
- package/docs/demo.webm +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/task-panes.png +0 -0
- package/extensions/background-tasks.ts +76 -20
- package/package.json +2 -2
- package/src/herdr.ts +38 -0
- package/src/output.ts +14 -25
- package/src/viewer.ts +201 -0
- package/src/widget.ts +15 -2
- package/tests/compaction.mjs +5 -1
- package/tests/extension.mjs +163 -15
- package/tests/fixtures/media-job.py +22 -0
- package/tests/fixtures/notifications.ts +1 -1
- package/tests/fixtures/provider.ts +9 -2
- package/tests/interruptions.mjs +19 -10
- package/tests/media.mjs +54 -0
- package/tests/notifications.mjs +17 -6
- package/tests/output.mjs +32 -8
- package/tests/processes.mjs +2 -2
- package/tests/tui-smoke.py +1 -0
- package/tests/viewer.mjs +252 -0
package/tests/interruptions.mjs
CHANGED
|
@@ -19,6 +19,7 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
19
19
|
const release = join(directory, "release");
|
|
20
20
|
const exited = join(directory, "exited");
|
|
21
21
|
const requests = [], settlements = [], errors = [];
|
|
22
|
+
const warmupRequests = timing === "after active compaction" ? 1 : 0;
|
|
22
23
|
let session, task, output, holding = false, summaries = 0;
|
|
23
24
|
const waitFor = async (check, label) => {
|
|
24
25
|
for (let i = 0; i < 1000; i++) {
|
|
@@ -43,11 +44,14 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
43
44
|
if (compacting) {
|
|
44
45
|
message.stopReason = "stop";
|
|
45
46
|
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
|
|
47
|
-
|
|
47
|
+
} else if (requests.length <= warmupRequests) {
|
|
48
|
+
message.stopReason = "stop";
|
|
49
|
+
message.content.push({ type: "text", text: "WARMUP_ACK" });
|
|
50
|
+
} else if (requests.length === warmupRequests + 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
|
|
51
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", description: "Interrupted shell fixture", timeout: 10,
|
|
48
52
|
} });
|
|
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 } });
|
|
53
|
+
else if (requests.length === warmupRequests + 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
|
|
54
|
+
else if (requests.length === warmupRequests + 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
|
|
51
55
|
else {
|
|
52
56
|
message.stopReason = "stop";
|
|
53
57
|
message.content.push({ type: "text", text: "RESUMED_RESULT_ACK" });
|
|
@@ -87,6 +91,9 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
87
91
|
else if (event.result.structuredContent.action === "output") output = event.result.structuredContent;
|
|
88
92
|
});
|
|
89
93
|
await session.bindExtensions({});
|
|
94
|
+
// Native compaction needs an earlier completed turn; do not depend
|
|
95
|
+
// on how verbose the background tool's start result happens to be.
|
|
96
|
+
if (warmupRequests) await session.prompt("Warmup history to summarize. ".repeat(200));
|
|
90
97
|
const prompting = session.prompt("Start a job and hold the agent so the user can interrupt. " + "Prior history to compact. ".repeat(200));
|
|
91
98
|
await waitFor(() => holding, "the real blocking tool");
|
|
92
99
|
assert.equal(task.status, "running");
|
|
@@ -102,32 +109,34 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
102
109
|
} else await session.abort();
|
|
103
110
|
await prompting;
|
|
104
111
|
const interruptedAt = Date.now();
|
|
105
|
-
assert.deepEqual(settlements, [true], "native settlement must confirm the user interrupt");
|
|
112
|
+
assert.deepEqual(settlements, [...Array(warmupRequests).fill(false), true], "native settlement must confirm the user interrupt");
|
|
106
113
|
assert.equal(session.isIdle, true);
|
|
107
114
|
writeFileSync(release, "finish after user interruption");
|
|
108
115
|
await waitFor(() => existsSync(exited), "the background shell surviving the interrupt");
|
|
109
116
|
await delay(1250);
|
|
110
|
-
assert.equal(requests.length, 2, "late completion must not start a model request");
|
|
117
|
+
assert.equal(requests.length, warmupRequests + 2, "late completion must not start a model request");
|
|
111
118
|
assert.match(readFileSync(task.log_path, "utf8"), /late shell result/);
|
|
112
119
|
assert.equal(session.isIdle, true);
|
|
113
120
|
await session.prompt("Continue and inspect the completed job.");
|
|
114
|
-
assert.equal(requests.length, 4);
|
|
115
|
-
const resumedContext = JSON.stringify(requests[2]);
|
|
121
|
+
assert.equal(requests.length, warmupRequests + 4);
|
|
122
|
+
const resumedContext = JSON.stringify(requests[warmupRequests + 2]);
|
|
116
123
|
assert.equal((resumedContext.match(/\[Background task finished\]/g) ?? []).length, 1, "retained completion enters context before the resumed model request");
|
|
117
124
|
assert.ok(resumedContext.includes(task.id));
|
|
118
125
|
assert.equal(output.task.exit_code, 7);
|
|
119
126
|
assert.equal(output.output, "late shell result\n");
|
|
120
127
|
await delay(50);
|
|
121
|
-
assert.equal(requests.length, 4, "consumed completion must not trigger another turn");
|
|
128
|
+
assert.equal(requests.length, warmupRequests + 4, "consumed completion must not trigger another turn");
|
|
122
129
|
const notifications = session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
123
130
|
assert.equal(notifications.length, 1);
|
|
131
|
+
assert.doesNotMatch(notifications[0].content, /late shell result/);
|
|
132
|
+
assert.ok(notifications[0].content.includes(task.log_path));
|
|
124
133
|
assert.equal(notifications[0].details.tasks[0].id, task.id);
|
|
125
134
|
assert.equal(notifications[0].details.tasks[0].status, "failed");
|
|
126
135
|
if (timing === "before interrupt") assert.ok(notifications[0].details.tasks[0].ended_at <= interruptRequestedAt);
|
|
127
136
|
else assert.ok(notifications[0].details.tasks[0].ended_at >= interruptedAt);
|
|
128
137
|
assert.equal(session.getLastAssistantText(), "RESUMED_RESULT_ACK");
|
|
129
138
|
assert.deepEqual(errors, []);
|
|
130
|
-
t.diagnostic(JSON.stringify({ timing, requestsBeforeResume: 2, requestsAfterResume: 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
|
|
139
|
+
t.diagnostic(JSON.stringify({ timing, warmupRequests, requestsBeforeResume: warmupRequests + 2, requestsAfterResume: warmupRequests + 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
|
|
131
140
|
} finally {
|
|
132
141
|
if (session) {
|
|
133
142
|
await session.abort();
|
package/tests/media.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, 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 register from "./fixtures/provider.ts";
|
|
9
|
+
|
|
10
|
+
for (const [kind, marker, code] of [["build", "Compiling module", 0], ["tests", "test_001", 3]]) {
|
|
11
|
+
test(`media ${kind} job streams real output and exits only after its release file`, async () => {
|
|
12
|
+
const root = mkdtempSync(join(tmpdir(), "pi-bg-media-job-"));
|
|
13
|
+
const child = spawn("python3", [fileURLToPath(new URL("./fixtures/media-job.py", import.meta.url)), kind], {
|
|
14
|
+
cwd: root, stdio: ["ignore", "pipe", "pipe"], signal: AbortSignal.timeout(5000),
|
|
15
|
+
});
|
|
16
|
+
let output = "";
|
|
17
|
+
let error = "";
|
|
18
|
+
try {
|
|
19
|
+
const exited = new Promise((resolve, reject) => {
|
|
20
|
+
child.once("error", reject);
|
|
21
|
+
child.stdout.on("data", (data) => {
|
|
22
|
+
output += data.toString();
|
|
23
|
+
if (output.includes(marker)) writeFileSync(join(root, `release-${kind}`), "release");
|
|
24
|
+
});
|
|
25
|
+
child.stderr.on("data", (data) => { error += data.toString(); });
|
|
26
|
+
child.once("close", (exitCode) => resolve(exitCode));
|
|
27
|
+
});
|
|
28
|
+
assert.equal(await exited, code, error);
|
|
29
|
+
assert.ok(output.includes(marker));
|
|
30
|
+
assert.match(output, kind === "build" ? /\rCompiling module.*BUILD SUCCESSFUL/s : /test_001.*one demo failure/s);
|
|
31
|
+
} finally {
|
|
32
|
+
child.kill("SIGKILL");
|
|
33
|
+
rmSync(root, { recursive: true, force: true });
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("offline media provider issues exactly two direct background starts, then returns while they run", async () => {
|
|
39
|
+
let provider;
|
|
40
|
+
register({ registerProvider(_name, value) { provider = value; }, on() {} });
|
|
41
|
+
const user = { role: "user", content: "Start two background demo jobs: build progress and a test suite." };
|
|
42
|
+
const model = { api: "bg-fixture", provider: "bg-fixture", id: "deterministic" };
|
|
43
|
+
const events = [];
|
|
44
|
+
for await (const event of provider.streamSimple(model, { messages: [user] })) events.push(event);
|
|
45
|
+
const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
|
|
46
|
+
assert.deepEqual(calls.map((call) => [call.name, call.arguments.command, call.arguments.description]), [
|
|
47
|
+
["background_task", "python3 demo-job.py build", "Build progress"],
|
|
48
|
+
["background_task", "python3 demo-job.py tests", "Test suite"],
|
|
49
|
+
]);
|
|
50
|
+
const next = [];
|
|
51
|
+
for await (const event of provider.streamSimple(model, { messages: [user, { role: "toolResult", toolCallId: calls[1].id, toolName: "background_task", content: [{ type: "text", text: "Started" }] }] })) next.push(event);
|
|
52
|
+
assert.equal(next.filter((event) => event.type === "toolcall_end").length, 0);
|
|
53
|
+
assert.match(next.find((event) => event.type === "text_end").content, /Click a task row/);
|
|
54
|
+
});
|
package/tests/notifications.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
|
|
|
7
7
|
import { test } from "node:test";
|
|
8
8
|
import { piBinary } from "./runtime.mjs";
|
|
9
9
|
|
|
10
|
-
test("native model receives
|
|
10
|
+
test("native model receives distinct declaration and start guidance without Codemode instructions", () => {
|
|
11
11
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
|
|
12
12
|
try {
|
|
13
13
|
const events = join(directory, "events.jsonl");
|
|
@@ -22,13 +22,16 @@ test("native model receives concise start guidance without Codemode instructions
|
|
|
22
22
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
23
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
24
|
assert.equal(started.isError, false);
|
|
25
|
-
const
|
|
26
|
-
assert.equal(guidance,
|
|
25
|
+
const notice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
|
|
26
|
+
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
27
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
28
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
|
-
assert.
|
|
29
|
+
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
30
|
+
assert.match(requests[0].backgroundDescription, /session changes, reload, or exit/);
|
|
31
|
+
assert.ok(!requests[0].backgroundDescription.includes(notice));
|
|
30
32
|
assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
|
|
31
|
-
assert.ok(requests[1].text.includes(
|
|
33
|
+
assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
|
|
34
|
+
assert.ok(!started.result.content[0].text.includes(started.result.structuredContent.task.log_path));
|
|
32
35
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
33
36
|
});
|
|
34
37
|
|
|
@@ -89,6 +92,11 @@ for (const mode of ["codemode", "direct"]) {
|
|
|
89
92
|
assert.equal(tasks.length, 4 - reads);
|
|
90
93
|
assert.ok(tasks.every((task) => task.status === "failed" && task.exit_code === 7));
|
|
91
94
|
assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
|
|
95
|
+
for (const task of tasks) assert.ok(message.content.includes(task.log_path), "completion provides the captured output location");
|
|
96
|
+
assert.doesNotMatch(message.content, /RESULT wave/, "command output is not injected automatically");
|
|
97
|
+
assert.match(message.content, /Inspect logs progressively as needed/);
|
|
98
|
+
for (const task of returned.tasks.filter((task) => returned.consumed.includes(task.id))) assert.ok(!message.content.includes(`RESULT ${task.description}`), "consumed output is not delivered twice");
|
|
99
|
+
assert.ok(Buffer.byteLength(message.content) <= 16384);
|
|
92
100
|
assert.deepEqual([...returned.consumed, ...tasks.map((task) => task.id)].sort(), returned.tasks.map((task) => task.id).sort());
|
|
93
101
|
const toolEnd = transcript.findLastIndex((entry) => entry.type === "tool_execution_end" && ["synchronous_subagent_fixture", "codemode"].includes(entry.toolName));
|
|
94
102
|
assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
|
|
@@ -99,7 +107,10 @@ for (const mode of ["codemode", "direct"]) {
|
|
|
99
107
|
assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, 1);
|
|
100
108
|
assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
|
|
101
109
|
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");
|
|
102
|
-
for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id)))
|
|
110
|
+
for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) {
|
|
111
|
+
assert.ok(contextText.includes(task.id));
|
|
112
|
+
assert.ok(contextText.includes(task.log_path), "the next model request can locate output for on-demand inspection");
|
|
113
|
+
}
|
|
103
114
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
104
115
|
});
|
|
105
116
|
}
|
package/tests/output.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { test } from "node:test";
|
|
3
|
-
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { createBashTool } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { createBashTool, truncateTail } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import { fixture, flush } from "./helpers.mjs";
|
|
7
7
|
|
|
8
8
|
const cases = [
|
|
@@ -17,8 +17,27 @@ const cases = [
|
|
|
17
17
|
["utf8-long-line", Buffer.from("中文🙂".repeat(130000))],
|
|
18
18
|
["invalid-utf8", Buffer.from([65, 0xf0, 0x9f])],
|
|
19
19
|
];
|
|
20
|
+
|
|
21
|
+
test("output exposes one bounded tail in both views while the full log remains on disk", async () => {
|
|
22
|
+
const f = fixture();
|
|
23
|
+
try {
|
|
24
|
+
const job = f.tasks.start({ command: "fixture" }, f.root);
|
|
25
|
+
const data = Array.from({ length: 110 }, (_, i) => `line-${i}`).join("\n");
|
|
26
|
+
f.calls[0].onData(Buffer.from(data));
|
|
27
|
+
f.calls[0].resolve();
|
|
28
|
+
await flush();
|
|
29
|
+
const result = f.tasks.output(job.id);
|
|
30
|
+
assert.equal(result.output, Array.from({ length: 100 }, (_, i) => `line-${i + 10}`).join("\n"));
|
|
31
|
+
assert.equal(result.output, result.truncation.content);
|
|
32
|
+
assert.ok(result.text.startsWith(result.output));
|
|
33
|
+
assert.equal(result.truncated, true);
|
|
34
|
+
assert.equal(result.truncation.totalLines, 110);
|
|
35
|
+
assert.equal(result.bytes, Buffer.byteLength(data));
|
|
36
|
+
} finally { await f.close(); }
|
|
37
|
+
});
|
|
38
|
+
|
|
20
39
|
for (const [name, data] of cases) {
|
|
21
|
-
test(`output
|
|
40
|
+
test(`bounded output compared with native bash model/structured views: ${name}`, async () => {
|
|
22
41
|
const f = fixture();
|
|
23
42
|
try {
|
|
24
43
|
const path = join(f.root, "fixture.log");
|
|
@@ -31,12 +50,17 @@ for (const [name, data] of cases) {
|
|
|
31
50
|
await flush();
|
|
32
51
|
const actual = f.tasks.output(job.id);
|
|
33
52
|
const normalize = (text) => text.replace(/Full output: [^\]]+/g, "Full output: <log>");
|
|
34
|
-
|
|
35
|
-
assert.equal(actual.output,
|
|
36
|
-
assert.equal(actual.
|
|
53
|
+
const expected = truncateTail(native.structuredContent.output, { maxLines: 100, maxBytes: 8192 });
|
|
54
|
+
assert.equal(actual.output, expected.content);
|
|
55
|
+
assert.equal(actual.output, actual.truncation.content);
|
|
56
|
+
assert.equal(actual.truncated, native.structuredContent.truncated || expected.truncated);
|
|
57
|
+
if (!actual.truncated) assert.equal(normalize(actual.text), normalize(native.content[0].text));
|
|
58
|
+
else assert.match(actual.text, /Showing .*Full output:/);
|
|
59
|
+
if (name === "long-line-with-newline") assert.match(actual.text, /line is 146\.5KB/);
|
|
60
|
+
assert.deepEqual(readFileSync(actual.log_path), data);
|
|
37
61
|
assert.equal(actual.capture_complete, true);
|
|
38
|
-
assert.ok(Buffer.byteLength(actual.truncation.content) <=
|
|
39
|
-
assert.ok(Buffer.byteLength(actual.output)
|
|
62
|
+
assert.ok(Buffer.byteLength(actual.truncation.content) <= 8192);
|
|
63
|
+
assert.ok(Buffer.byteLength(actual.output) <= 8192);
|
|
40
64
|
} finally { await f.close(); }
|
|
41
65
|
});
|
|
42
66
|
}
|
package/tests/processes.mjs
CHANGED
|
@@ -90,7 +90,7 @@ test("native large output truncates display, then stops at the 32 MiB disk budge
|
|
|
90
90
|
assert.equal(result.bytes, 32 * 1024 * 1024);
|
|
91
91
|
assert.equal(result.capture_complete, false);
|
|
92
92
|
assert.equal(result.truncated, true);
|
|
93
|
-
assert.ok(result.truncation.outputBytes <=
|
|
94
|
-
assert.ok(Buffer.byteLength(result.output)
|
|
93
|
+
assert.ok(result.truncation.outputBytes <= 8192);
|
|
94
|
+
assert.ok(Buffer.byteLength(result.output) <= 8192);
|
|
95
95
|
} finally { await tasks.shutdown(); }
|
|
96
96
|
});
|
package/tests/tui-smoke.py
CHANGED
|
@@ -28,6 +28,7 @@ render = os.environ.get('BG_SMOKE_RENDER') == '1'
|
|
|
28
28
|
capture = os.environ.get('BG_SMOKE_CAPTURE') == '1'
|
|
29
29
|
env = dict(os.environ, PI_CODING_AGENT_DIR=str(work), PI_OFFLINE='1', BG_SMOKE_EVENTS=str(events_path), TERM='xterm-256color', COLORTERM='truecolor')
|
|
30
30
|
env.pop('PI_HERDR_SUBAGENTS_CHILD', None)
|
|
31
|
+
env.pop('HERDR_ENV', None) # Keep this smoke run's widget-only path; Herdr views are covered by viewer.mjs.
|
|
31
32
|
(work / 'settings.json').write_text(json.dumps({'quietStartup': True}))
|
|
32
33
|
args = ['--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session', '--offline',
|
|
33
34
|
'-e', 'builtin:codemode', '-e', str(PKG / 'extensions/background-tasks.ts'),
|
package/tests/viewer.mjs
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import register from "../extensions/background-tasks.ts";
|
|
9
|
+
import { HerdrError } from "../src/herdr.ts";
|
|
10
|
+
import { VIEW_SCRIPT } from "../src/viewer.ts";
|
|
11
|
+
import { fixture, flush } from "./helpers.mjs";
|
|
12
|
+
|
|
13
|
+
/** In-memory Herdr: records CLI calls and models tabs, panes and focus. */
|
|
14
|
+
function fakeHerdr() {
|
|
15
|
+
const calls = [];
|
|
16
|
+
const tabs = new Map();
|
|
17
|
+
const panes = new Map();
|
|
18
|
+
let next = 0;
|
|
19
|
+
const state = { focused: false, fail: undefined };
|
|
20
|
+
const missing = (kind, id) => new HerdrError(`${kind} ${id} not found`, `${kind}_not_found`);
|
|
21
|
+
const call = async (args) => {
|
|
22
|
+
calls.push(args);
|
|
23
|
+
if (state.fail?.(args)) throw new Error(`herdr ${args.join(" ")} failed`);
|
|
24
|
+
const [noun, verb, id] = args;
|
|
25
|
+
if (noun === "tab" && verb === "create") {
|
|
26
|
+
const tab = `w:t${++next}`, pane = `w:p${++next}`;
|
|
27
|
+
tabs.set(tab, true);
|
|
28
|
+
panes.set(pane, { tab, runs: [] });
|
|
29
|
+
return { tab: { tab_id: tab }, root_pane: { pane_id: pane } };
|
|
30
|
+
}
|
|
31
|
+
if (noun === "tab") {
|
|
32
|
+
if (!tabs.has(id)) throw missing("tab", id);
|
|
33
|
+
if (verb === "close") {
|
|
34
|
+
tabs.delete(id);
|
|
35
|
+
for (const [pane, value] of panes) if (value.tab === id) panes.delete(pane);
|
|
36
|
+
}
|
|
37
|
+
return { tab: { tab_id: id, focused: state.focused } };
|
|
38
|
+
}
|
|
39
|
+
if (!panes.has(id)) throw missing("pane", id);
|
|
40
|
+
if (verb === "split") {
|
|
41
|
+
const pane = `w:p${++next}`;
|
|
42
|
+
panes.set(pane, { tab: panes.get(id).tab, runs: [] });
|
|
43
|
+
return { pane: { pane_id: pane } };
|
|
44
|
+
}
|
|
45
|
+
if (verb === "run") panes.get(id).runs.push(args[3]);
|
|
46
|
+
return { pane: { pane_id: id } };
|
|
47
|
+
};
|
|
48
|
+
return { call, calls, tabs, panes, state, closePane: (id) => panes.delete(id) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function harness(env = { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w" }) {
|
|
52
|
+
const f = fixture();
|
|
53
|
+
const herdr = fakeHerdr();
|
|
54
|
+
const handlers = new Map();
|
|
55
|
+
const commands = new Map();
|
|
56
|
+
const notices = [];
|
|
57
|
+
const widgets = new Map();
|
|
58
|
+
let tool;
|
|
59
|
+
const theme = { fg: (_color, text) => text, bold: (text) => text };
|
|
60
|
+
const ctx = {
|
|
61
|
+
cwd: f.root, mode: "tui", hasUI: true, isIdle: () => true,
|
|
62
|
+
ui: {
|
|
63
|
+
setWidget(key, factory) { if (factory) widgets.set(key, factory({ requestRender() {} }, theme)); else widgets.delete(key); },
|
|
64
|
+
setStatus() {}, notify(message, level) { notices.push({ message, level }); },
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
const pi = {
|
|
68
|
+
on(name, handler) { handlers.set(name, handler); },
|
|
69
|
+
registerTool(value) { tool = value; },
|
|
70
|
+
registerCommand(name, value) { commands.set(name, value); },
|
|
71
|
+
sendMessage() {},
|
|
72
|
+
};
|
|
73
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, herdr: herdr.call, env, sleep: () => flush() });
|
|
74
|
+
return {
|
|
75
|
+
...f, herdr, handlers, commands, notices, widgets, ctx,
|
|
76
|
+
start: async (command) => (await tool.execute(command, { action: "start", command })).structuredContent.task,
|
|
77
|
+
begin: () => handlers.get("session_start")({}, ctx),
|
|
78
|
+
async close() {
|
|
79
|
+
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
80
|
+
for (const call of f.calls) call.resolve();
|
|
81
|
+
await closing;
|
|
82
|
+
await f.close();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function settle() { for (let i = 0; i < 20; i++) await flush(); }
|
|
88
|
+
|
|
89
|
+
test("two tasks share one unfocused tab, one pane each; the pane shows the command, then the log", async () => {
|
|
90
|
+
const h = harness();
|
|
91
|
+
try {
|
|
92
|
+
await h.begin();
|
|
93
|
+
const first = await h.start("printf 'a\\n'; sleep 1");
|
|
94
|
+
const second = await h.start("make test");
|
|
95
|
+
await settle();
|
|
96
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
97
|
+
assert.equal(h.herdr.panes.size, 2);
|
|
98
|
+
const create = h.herdr.calls.find((args) => args[0] === "tab" && args[1] === "create");
|
|
99
|
+
assert.ok(create.includes("--no-focus"));
|
|
100
|
+
assert.ok(h.herdr.calls.filter((args) => args[1] === "split").every((args) => args.includes("--no-focus")));
|
|
101
|
+
const runs = [...h.herdr.panes.values()].map((pane) => pane.runs.at(-1));
|
|
102
|
+
assert.ok(runs[0].includes(first.log_path) && runs[1].includes(second.log_path));
|
|
103
|
+
assert.doesNotMatch(runs.join("\n"), /make test|printf/, "the command text is never passed as shell syntax");
|
|
104
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^\$ printf 'a\\n'; sleep 1\n# bg-.* · cwd .* · timeout 30m\n/);
|
|
105
|
+
} finally { await h.close(); }
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("a finished task's pane shows the result, is reused, and the tab closes once nothing runs", async () => {
|
|
109
|
+
const h = harness();
|
|
110
|
+
try {
|
|
111
|
+
await h.begin();
|
|
112
|
+
const first = await h.start("one");
|
|
113
|
+
await h.start("two");
|
|
114
|
+
await settle();
|
|
115
|
+
h.calls[0].resolve(3);
|
|
116
|
+
await settle();
|
|
117
|
+
assert.match(readFileSync(first.log_path.replace(/\.log$/, ".done"), "utf8"), /\[failed · exit 3 · 0s\]/);
|
|
118
|
+
assert.equal(h.herdr.tabs.size, 1, "the tab stays while a task still runs");
|
|
119
|
+
const third = await h.start("three");
|
|
120
|
+
await settle();
|
|
121
|
+
assert.equal(h.herdr.panes.size, 2, "the finished task's pane is reused");
|
|
122
|
+
assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(third.log_path)));
|
|
123
|
+
h.calls[1].resolve();
|
|
124
|
+
h.calls[2].resolve();
|
|
125
|
+
await settle();
|
|
126
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
127
|
+
} finally { await h.close(); }
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("the tab waits while the user looks at it, then closes after focus moves away", async () => {
|
|
131
|
+
const h = harness();
|
|
132
|
+
try {
|
|
133
|
+
await h.begin();
|
|
134
|
+
await h.start("one");
|
|
135
|
+
await settle();
|
|
136
|
+
h.herdr.state.focused = true;
|
|
137
|
+
h.calls[0].resolve();
|
|
138
|
+
await settle();
|
|
139
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
140
|
+
h.herdr.state.focused = false;
|
|
141
|
+
await settle();
|
|
142
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
143
|
+
} finally { await h.close(); }
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("closing a pane keeps the task running; /bg watch reopens and focuses it", async () => {
|
|
147
|
+
const h = harness();
|
|
148
|
+
try {
|
|
149
|
+
await h.begin();
|
|
150
|
+
const task = await h.start("one");
|
|
151
|
+
await settle();
|
|
152
|
+
h.herdr.closePane([...h.herdr.panes.keys()][0]);
|
|
153
|
+
assert.equal(h.calls[0].signal.aborted, false);
|
|
154
|
+
await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
|
|
155
|
+
await settle();
|
|
156
|
+
assert.equal(h.herdr.tabs.size, 1);
|
|
157
|
+
assert.equal(h.herdr.panes.size, 1);
|
|
158
|
+
assert.ok([...h.herdr.panes.values()][0].runs.at(-1).includes(task.log_path));
|
|
159
|
+
assert.ok(h.herdr.calls.some((args) => args[0] === "tab" && args[1] === "focus"));
|
|
160
|
+
assert.deepEqual(h.notices, []);
|
|
161
|
+
} finally { await h.close(); }
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("clicking a widget task row opens its view and focuses the tab; other clicks do nothing", async () => {
|
|
165
|
+
const h = harness();
|
|
166
|
+
try {
|
|
167
|
+
await h.begin();
|
|
168
|
+
await h.start("one");
|
|
169
|
+
const second = await h.start("two");
|
|
170
|
+
await settle();
|
|
171
|
+
h.herdr.closePane([...h.herdr.panes.keys()][1]);
|
|
172
|
+
const widget = h.widgets.get("background-tasks");
|
|
173
|
+
const lines = widget.render(120);
|
|
174
|
+
assert.match(lines[2], new RegExp(second.id));
|
|
175
|
+
const click = (y, extra = {}) => widget.handleMouse({ type: "click", button: "left", x: 4, y, screenX: 4, screenY: y, width: 120, height: lines.length, shift: false, alt: false, ctrl: false, ...extra });
|
|
176
|
+
assert.equal(click(0), undefined, "the title row is not a task");
|
|
177
|
+
assert.equal(click(2, { button: "right" }), undefined);
|
|
178
|
+
const before = h.herdr.calls.length;
|
|
179
|
+
assert.deepEqual(click(2), { handled: true, render: false });
|
|
180
|
+
await settle();
|
|
181
|
+
assert.ok(h.herdr.calls.length > before);
|
|
182
|
+
assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(second.log_path)), "the closed pane was reopened");
|
|
183
|
+
const [first] = h.herdr.panes.keys();
|
|
184
|
+
assert.deepEqual(h.herdr.calls.at(-2).slice(0, 2), ["tab", "focus"]);
|
|
185
|
+
assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", first, "--direction", "right"], "the reopened right pane gets focus");
|
|
186
|
+
click(1);
|
|
187
|
+
await settle();
|
|
188
|
+
const [, right] = h.herdr.panes.keys();
|
|
189
|
+
assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", right, "--direction", "left"], "the left pane gets focus");
|
|
190
|
+
} finally { await h.close(); }
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("Herdr failures warn once and never affect tasks", async () => {
|
|
194
|
+
const h = harness();
|
|
195
|
+
try {
|
|
196
|
+
await h.begin();
|
|
197
|
+
h.herdr.state.fail = () => true;
|
|
198
|
+
await h.start("one");
|
|
199
|
+
await h.start("two");
|
|
200
|
+
await settle();
|
|
201
|
+
assert.equal(h.notices.length, 1);
|
|
202
|
+
assert.equal(h.notices[0].level, "warning");
|
|
203
|
+
assert.ok(h.calls.every((call) => !call.signal.aborted), "tasks keep running");
|
|
204
|
+
h.calls[0].resolve();
|
|
205
|
+
h.calls[1].resolve();
|
|
206
|
+
await settle();
|
|
207
|
+
assert.equal(h.notices.length, 1, "the warning is shown once");
|
|
208
|
+
} finally { await h.close(); }
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test("session shutdown closes the tab immediately", async () => {
|
|
212
|
+
const h = harness();
|
|
213
|
+
await h.begin();
|
|
214
|
+
await h.start("one");
|
|
215
|
+
await settle();
|
|
216
|
+
h.herdr.state.focused = true;
|
|
217
|
+
await h.close();
|
|
218
|
+
assert.equal(h.herdr.tabs.size, 0);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
for (const [label, env] of [
|
|
222
|
+
["outside Herdr", {}],
|
|
223
|
+
["in a Herdr subagent child", { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w", PI_HERDR_SUBAGENTS_CHILD: "1" }],
|
|
224
|
+
]) {
|
|
225
|
+
test(`${label}, no Herdr call is made and /bg watch explains why`, async () => {
|
|
226
|
+
const h = harness(env);
|
|
227
|
+
try {
|
|
228
|
+
await h.begin();
|
|
229
|
+
const task = await h.start("one");
|
|
230
|
+
await settle();
|
|
231
|
+
await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
|
|
232
|
+
const widget = h.widgets.get("background-tasks");
|
|
233
|
+
widget.render(120);
|
|
234
|
+
assert.equal(widget.handleMouse({ type: "click", button: "left", x: 4, y: 1, width: 120, height: 2 }), undefined, "rows are not clickable without a view");
|
|
235
|
+
assert.deepEqual(h.herdr.calls, []);
|
|
236
|
+
assert.match(h.notices[0].message, /inside Herdr/);
|
|
237
|
+
} finally { await h.close(); }
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
test("the view script follows a real log, then prints the result line", async () => {
|
|
242
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-bg-view-"));
|
|
243
|
+
try {
|
|
244
|
+
const [log, done, header, script] = ["t.log", "t.done", "t.header", "view.sh"].map((name) => join(dir, name));
|
|
245
|
+
writeFileSync(log, "line 1\nline 2\n");
|
|
246
|
+
writeFileSync(header, "$ echo hi\n");
|
|
247
|
+
writeFileSync(script, VIEW_SCRIPT);
|
|
248
|
+
setTimeout(() => writeFileSync(done, "\n[succeeded · exit 0 · 1s]\n"), 300);
|
|
249
|
+
const { stdout: output } = await promisify(execFile)("sh", [script, log, done, header], { encoding: "utf8", timeout: 10000 });
|
|
250
|
+
assert.match(output, /\$ echo hi\nline 1\nline 2\n\n\[succeeded · exit 0 · 1s\]\n$/);
|
|
251
|
+
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
252
|
+
});
|