@maxiaochao/pi-background-tasks 0.1.1 → 0.2.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 +14 -0
- package/README.md +33 -21
- package/TESTING.md +23 -5
- 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 +47 -11
- package/package.json +2 -2
- package/src/herdr.ts +38 -0
- package/src/viewer.ts +201 -0
- package/src/widget.ts +15 -2
- package/tests/extension.mjs +5 -4
- package/tests/fixtures/media-job.py +22 -0
- package/tests/fixtures/notifications.ts +46 -36
- package/tests/fixtures/provider.ts +43 -21
- package/tests/media.mjs +54 -0
- package/tests/notifications.mjs +48 -22
- package/tests/tui-smoke.py +11 -4
- package/tests/viewer.mjs +252 -0
package/tests/notifications.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
|
-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { test } from "node:test";
|
|
8
8
|
import { piBinary } from "./runtime.mjs";
|
|
9
9
|
|
|
10
|
-
test("native
|
|
10
|
+
test("native model receives concise 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");
|
|
@@ -23,19 +23,44 @@ test("native Codemode receives start guidance and exposes it to the model", () =
|
|
|
23
23
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
24
|
assert.equal(started.isError, false);
|
|
25
25
|
const guidance = started.result.structuredContent.guidance;
|
|
26
|
-
assert.equal(guidance, "
|
|
27
|
-
|
|
28
|
-
assert.equal(codemode.isError, false);
|
|
29
|
-
assert.ok(codemode.result.content.some((block) => block.type === "text" && block.text.includes(guidance)));
|
|
26
|
+
assert.equal(guidance, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
|
|
27
|
+
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
30
28
|
const requests = records.filter((entry) => entry.event === "request");
|
|
31
29
|
assert.ok(requests[0].backgroundDescription.includes(guidance));
|
|
32
|
-
assert.ok(requests[
|
|
30
|
+
assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
|
|
31
|
+
assert.ok(requests[1].text.includes(guidance), "the next model request sees the startup guidance");
|
|
32
|
+
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("native Codemode cannot discover or call the model-only background tool", () => {
|
|
36
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-exposure-"));
|
|
37
|
+
try {
|
|
38
|
+
const events = join(directory, "events.jsonl");
|
|
39
|
+
const output = execFileSync(piBinary, [
|
|
40
|
+
"--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
|
|
41
|
+
"-e", "builtin:codemode", "-e", fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
|
|
42
|
+
"-e", fileURLToPath(new URL("fixtures/provider.ts", import.meta.url)),
|
|
43
|
+
"--tools", "codemode,background_task", "--model", "bg-fixture/deterministic", "-p", "SMOKE_EXPOSURE",
|
|
44
|
+
], { cwd: directory, encoding: "utf8", timeout: 30000,
|
|
45
|
+
env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_SMOKE_EVENTS: events }, stdio: ["ignore", "pipe", "pipe"] });
|
|
46
|
+
assert.match(output, /Main agent is ready/);
|
|
47
|
+
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
48
|
+
const codemode = records.find((entry) => entry.event === "tool_end" && entry.name === "codemode");
|
|
49
|
+
assert.equal(codemode.isError, false);
|
|
50
|
+
const text = codemode.result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
51
|
+
assert.match(text, /"discovered":false/);
|
|
52
|
+
assert.match(text, /"available":false/);
|
|
53
|
+
assert.match(text, /BACKGROUND_CALL_BLOCKED/);
|
|
54
|
+
assert.doesNotMatch(text, /UNEXPECTED_SUCCESS/);
|
|
55
|
+
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "background_task"), false);
|
|
56
|
+
assert.equal(existsSync(join(directory, "should-not-exist")), false);
|
|
57
|
+
assert.ok(records.find((entry) => entry.event === "request").tools.includes("background_task"));
|
|
33
58
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
34
59
|
});
|
|
35
60
|
|
|
36
61
|
for (const mode of ["codemode", "direct"]) {
|
|
37
|
-
for (const reads of [0, 1,
|
|
38
|
-
test(`real Pi ${mode} merges four completions
|
|
62
|
+
for (const reads of [0, 1, 2]) {
|
|
63
|
+
test(`real Pi ${mode} blocker merges four completions, excluding ${reads} model-read results`, () => {
|
|
39
64
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-notifications-"));
|
|
40
65
|
try {
|
|
41
66
|
const events = join(directory, "events.jsonl");
|
|
@@ -51,26 +76,27 @@ for (const mode of ["codemode", "direct"]) {
|
|
|
51
76
|
const returned = records.find((entry) => entry.event === "returned");
|
|
52
77
|
assert.ok(returned, `the blocking tool finished all real shell jobs\n${output}`);
|
|
53
78
|
assert.equal(returned.tasks.length, 4);
|
|
54
|
-
assert.
|
|
79
|
+
assert.equal(returned.consumed.length, reads);
|
|
80
|
+
assert.ok(returned.tasks.filter((task) => returned.consumed.includes(task.id)).every((task) => task.status === "failed" && task.exit_code === 7));
|
|
55
81
|
const transcript = output.trim().split("\n").map((line) => JSON.parse(line));
|
|
56
82
|
const notifications = transcript.filter((entry) =>
|
|
57
83
|
(entry.type === "entry_appended" && entry.entry.customType === "background-task-finished") ||
|
|
58
84
|
(entry.type === "message_start" && entry.message.customType === "background-task-finished")
|
|
59
85
|
);
|
|
60
|
-
assert.equal(notifications.length,
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
86
|
+
assert.equal(notifications.length, 1);
|
|
87
|
+
const message = notifications[0].entry ?? notifications[0].message;
|
|
88
|
+
const tasks = message.details.tasks;
|
|
89
|
+
assert.equal(tasks.length, 4 - reads);
|
|
90
|
+
assert.ok(tasks.every((task) => task.status === "failed" && task.exit_code === 7));
|
|
91
|
+
assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
|
|
92
|
+
assert.deepEqual([...returned.consumed, ...tasks.map((task) => task.id)].sort(), returned.tasks.map((task) => task.id).sort());
|
|
93
|
+
const toolEnd = transcript.findLastIndex((entry) => entry.type === "tool_execution_end" && ["synchronous_subagent_fixture", "codemode"].includes(entry.toolName));
|
|
94
|
+
assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
|
|
95
|
+
assert.match(message.content, /Ended at: \d{4}-/);
|
|
70
96
|
const requests = records.filter((entry) => entry.event === "request");
|
|
71
|
-
assert.equal(requests.length,
|
|
97
|
+
assert.equal(requests.length, 3, "no extra model turns after the final report");
|
|
72
98
|
const nextContext = JSON.stringify(requests.at(-1).messages);
|
|
73
|
-
assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length,
|
|
99
|
+
assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, 1);
|
|
74
100
|
assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
|
|
75
101
|
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
102
|
for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) assert.ok(contextText.includes(task.id));
|
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'),
|
|
@@ -126,15 +127,21 @@ try:
|
|
|
126
127
|
assert loaded['tools'].count('background_task') == 1
|
|
127
128
|
send('/schedule add 1h Check release status')
|
|
128
129
|
wait(lambda: 'active schedule' in raw, 'Scheduler widget')
|
|
130
|
+
send('SMOKE_EXPOSURE')
|
|
131
|
+
wait(lambda: bool(tools('codemode')), 'Codemode exposure check')
|
|
132
|
+
assert 'BACKGROUND_CALL_BLOCKED' in str(tools('codemode')[-1]['result'])
|
|
133
|
+
assert not (work / 'should-not-exist').exists()
|
|
134
|
+
wait(lambda: any(e.get('event') == 'settled' for e in events()), 'exposure turn completion')
|
|
135
|
+
settled_count = len([e for e in events() if e.get('event') == 'settled'])
|
|
129
136
|
send('SMOKE_START')
|
|
130
|
-
wait(lambda: len(tools()) >= 3
|
|
137
|
+
wait(lambda: len(tools()) >= 3, 'model startup batch')
|
|
131
138
|
starts = tools()[:3]
|
|
132
139
|
assert not starts[0]['isError'] and not starts[1]['isError'] and starts[2]['isError'], starts
|
|
133
140
|
first = starts[0]['result']['structuredContent']['task']
|
|
134
141
|
second = starts[1]['result']['structuredContent']['task']
|
|
135
142
|
assert first['status'] == second['status'] == 'running'
|
|
136
|
-
|
|
137
|
-
assert not finished('succeeded'), 'Sleeping job must survive
|
|
143
|
+
wait(lambda: len([e for e in events() if e.get('event') == 'settled']) > settled_count, 'foreground turn completion')
|
|
144
|
+
assert not finished('succeeded'), 'Sleeping job must survive foreground turn completion'
|
|
138
145
|
shot('running')
|
|
139
146
|
send('/bg output ' + first['id'])
|
|
140
147
|
send('SMOKE_CANCEL')
|
|
@@ -176,7 +183,7 @@ try:
|
|
|
176
183
|
assert all(not Path(path).exists() for path in logs), 'Session logs were not removed'
|
|
177
184
|
(OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
|
|
178
185
|
(OUT / 'result.json').write_text(json.dumps({'passed': True, 'screenshots': screens,
|
|
179
|
-
'checks': ['two jobs', 'third rejected', 'Codemode returns while jobs live', 'Scheduler coexistence', '/bg output',
|
|
186
|
+
'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', '/bg output',
|
|
180
187
|
'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
|
|
181
188
|
'5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
|
|
182
189
|
except Exception:
|
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
|
+
});
|