@maxiaochao/pi-background-tasks 0.3.1 → 0.4.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/src/viewer.ts DELETED
@@ -1,212 +0,0 @@
1
- import { existsSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
- import { stripVTControlCharacters } from "node:util";
4
- import { errorText, summary, type TaskSnapshot } from "./background-tasks.ts";
5
- import { isMissing, type HerdrCall } from "./herdr.ts";
6
- import { duration } from "./widget.ts";
7
-
8
- const UNFOCUS_POLL_MS = 1000;
9
-
10
- // Runs inside the pane's own shell. It only reads files; the task itself runs elsewhere.
11
- // Arguments are file paths, so the user's command text never becomes shell syntax here.
12
- export const VIEW_SCRIPT = `printf '\\033[2J\\033[3J\\033[H'
13
- cat "$3"
14
- tail -n +1 -f "$1" &
15
- tail_pid=$!
16
- while [ ! -e "$2" ]; do sleep 0.5; done
17
- sleep 1
18
- kill "$tail_pid" 2>/dev/null
19
- wait "$tail_pid" 2>/dev/null
20
- cat "$2"
21
- `;
22
-
23
- interface Pane { id: string; task: string }
24
- interface Options {
25
- call: HerdrCall;
26
- workspaceId: string;
27
- /** Current tasks, used to free panes and decide when the tab can close. */
28
- tasks: () => TaskSnapshot[];
29
- warn: (message: string) => void;
30
- /** Delay between focus checks while the user is looking at a finished tab. */
31
- sleep?: (ms: number) => Promise<void>;
32
- }
33
-
34
- function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
35
- function clean(text: string): string { return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); }
36
- function tabLabel(task: TaskSnapshot): string { return summary(`BG · ${task.description}`, 80); }
37
-
38
- /**
39
- * Shows background task logs in one Herdr tab per session. Display only: every failure
40
- * is reported once and never affects task execution or status.
41
- */
42
- export class HerdrViewer {
43
- private readonly options: Options;
44
- private readonly commands = new Map<string, { text: string; order: number }>();
45
- private tab?: string;
46
- private panes: Pane[] = [];
47
- private chain: Promise<unknown> = Promise.resolve();
48
- private closing = false;
49
- private disposed = false;
50
- private warned = false;
51
-
52
- private readonly sleep: (ms: number) => Promise<void>;
53
-
54
- constructor(options: Options) {
55
- this.options = options;
56
- this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms).unref()));
57
- }
58
-
59
- /** Opens a pane for a newly started task without taking focus. */
60
- show(task: TaskSnapshot, command: string): Promise<void> {
61
- this.commands.set(task.id, { text: command, order: this.commands.size + 1 });
62
- return this.enqueue(async () => { await this.open(task, false); });
63
- }
64
-
65
- /** Reopens a task's pane on user request, then focuses its tab and pane. */
66
- watch(task: TaskSnapshot): Promise<string> {
67
- return this.enqueue(async () => {
68
- await this.prune();
69
- const existing = this.panes.find((entry) => entry.task === task.id);
70
- const pane = existing ?? await this.open(task, false);
71
- if (existing) await this.options.call(["tab", "rename", this.tab!, tabLabel(task)]);
72
- await this.options.call(["tab", "focus", this.tab!]);
73
- // Panes are split left to right; Herdr focuses a pane through its neighbour.
74
- const index = this.panes.indexOf(pane);
75
- if (index > 0) await this.options.call(["pane", "focus", "--pane", this.panes[index - 1].id, "--direction", "right"]);
76
- else if (this.panes.length > 1) await this.options.call(["pane", "focus", "--pane", this.panes[1].id, "--direction", "left"]);
77
- this.closeWhenIdle();
78
- return pane.id;
79
- }, true);
80
- }
81
-
82
- /** Writes the result line into the task's pane, then closes the tab once nothing runs. */
83
- finished(task: TaskSnapshot): void {
84
- if (this.disposed) return;
85
- try { this.writeDone(task); }
86
- catch (error) { this.report(error); }
87
- void this.enqueue(async () => {
88
- const remaining = this.options.tasks().find((task) => task.status === "running");
89
- if (!this.tab || !remaining) return;
90
- try { await this.options.call(["tab", "rename", this.tab, tabLabel(remaining)]); }
91
- catch (error) { if (!isMissing(error)) throw error; }
92
- });
93
- this.closeWhenIdle();
94
- }
95
-
96
- /** Closes the tab immediately, for session shutdown, reload and replacement. */
97
- async dispose(): Promise<void> {
98
- this.disposed = true;
99
- await this.chain.catch(() => {});
100
- const tab = this.tab;
101
- this.tab = undefined;
102
- this.panes = [];
103
- if (tab) await this.options.call(["tab", "close", tab]).catch(() => {});
104
- }
105
-
106
- private enqueue<T>(step: () => Promise<T>, rethrow = false): Promise<T> {
107
- const run = this.chain.then(() => {
108
- if (this.disposed) throw new Error("Background tasks session is closed");
109
- return step();
110
- });
111
- this.chain = run.catch(() => {});
112
- return rethrow ? run : run.catch((error) => { this.report(error); return undefined as T; });
113
- }
114
-
115
- private report(error: unknown): void {
116
- if (this.disposed || this.warned) return;
117
- this.warned = true;
118
- this.options.warn(`Herdr task view unavailable; tasks keep running and the widget stays current. ${errorText(error)}`);
119
- }
120
-
121
- private running(): Set<string> {
122
- return new Set(this.options.tasks().filter((task) => task.status === "running").map((task) => task.id));
123
- }
124
-
125
- private async open(task: TaskSnapshot, retried: boolean): Promise<Pane> {
126
- const running = this.running();
127
- let pane = this.panes.find((entry) => !running.has(entry.task));
128
- try {
129
- if (!this.tab) {
130
- const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label", tabLabel(task), "--no-focus"]);
131
- this.tab = created.tab?.tab_id;
132
- const root = created.root_pane?.pane_id;
133
- if (!this.tab || !root) throw new Error("herdr tab create omitted the tab or pane id");
134
- pane = { id: root, task: task.id };
135
- this.panes = [pane];
136
- } else if (pane) {
137
- pane.task = task.id;
138
- await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
139
- } else {
140
- const split = await this.options.call(["pane", "split", this.panes.at(-1)!.id, "--direction", "right", "--cwd", task.cwd, "--no-focus"]);
141
- if (!split.pane?.pane_id) throw new Error("herdr pane split omitted the pane id");
142
- pane = { id: split.pane.pane_id, task: task.id };
143
- this.panes.push(pane);
144
- await this.options.call(["tab", "rename", this.tab, tabLabel(task)]);
145
- }
146
- const label = summary(`${String(this.commands.get(task.id)!.order).padStart(2, "0")} · ${task.description}`, 80);
147
- await this.options.call(["pane", "rename", pane.id, label]);
148
- await this.options.call(["pane", "run", pane.id, this.viewCommand(task, label)]);
149
- return pane;
150
- } catch (error) {
151
- // The user may close a pane or the whole tab; drop stale handles and retry once.
152
- if (retried || !isMissing(error)) throw error;
153
- await this.prune();
154
- return this.open(task, true);
155
- }
156
- }
157
-
158
- /** Forgets panes the user closed. Without any of our panes, the tab is gone or closed. */
159
- private async prune(): Promise<void> {
160
- const alive: Pane[] = [];
161
- for (const pane of this.panes) {
162
- try { await this.options.call(["pane", "get", pane.id]); alive.push(pane); }
163
- catch (error) { if (!isMissing(error)) throw error; }
164
- }
165
- this.panes = alive;
166
- if (alive.length > 0 || !this.tab) return;
167
- const tab = this.tab;
168
- this.tab = undefined;
169
- await this.options.call(["tab", "close", tab]).catch(() => {});
170
- }
171
-
172
- private viewCommand(task: TaskSnapshot, label: string): string {
173
- const directory = dirname(task.log_path);
174
- const script = join(directory, "view.sh");
175
- const header = join(directory, `${task.id}.header`);
176
- if (!existsSync(script)) writeFileSync(script, VIEW_SCRIPT, { mode: 0o600 });
177
- const lines = clean(this.commands.get(task.id)!.text).split("\n");
178
- writeFileSync(header, `${label}\n${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
179
- if (task.status !== "running") this.writeDone(task);
180
- // The leading space keeps the line out of shell history where HISTCONTROL allows it.
181
- return ` sh ${[script, task.log_path, this.donePath(task), header].map(quote).join(" ")}`;
182
- }
183
-
184
- private donePath(task: TaskSnapshot): string { return join(dirname(task.log_path), `${task.id}.done`); }
185
-
186
- private writeDone(task: TaskSnapshot): void {
187
- const exit = task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`;
188
- const reason = task.reason ? `\n${clean(task.reason)}` : "";
189
- writeFileSync(this.donePath(task), `\n[${task.status}${exit} · ${duration(task.elapsed_seconds)}]${reason}\n`, { mode: 0o600 });
190
- }
191
-
192
- /** Closes the tab after the last task ends; waits while the user is looking at it. */
193
- private closeWhenIdle(): void {
194
- if (this.closing || this.disposed) return;
195
- this.closing = true;
196
- const check = (): Promise<void> => this.enqueue(async (): Promise<"wait" | "done"> => {
197
- if (!this.tab || this.running().size > 0) return "done";
198
- const tab = this.tab;
199
- try {
200
- const info = await this.options.call(["tab", "get", tab]);
201
- if (info.tab?.focused) return "wait";
202
- await this.options.call(["tab", "close", tab]);
203
- } catch (error) { if (!isMissing(error)) throw error; }
204
- this.tab = undefined;
205
- this.panes = [];
206
- return "done";
207
- }).then((state) => {
208
- if (state === "wait" && !this.disposed) return this.sleep(UNFOCUS_POLL_MS).then(check);
209
- });
210
- void check().finally(() => { this.closing = false; });
211
- }
212
- }
package/tests/viewer.mjs DELETED
@@ -1,340 +0,0 @@
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, { label: args[args.indexOf("--label") + 1] });
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 === "rename") tabs.get(id).label = args[3];
34
- if (verb === "close") {
35
- tabs.delete(id);
36
- for (const [pane, value] of panes) if (value.tab === id) panes.delete(pane);
37
- }
38
- return { tab: { tab_id: id, focused: state.focused } };
39
- }
40
- if (!panes.has(id)) throw missing("pane", id);
41
- if (verb === "rename") panes.get(id).label = args[3];
42
- if (verb === "split") {
43
- const pane = `w:p${++next}`;
44
- panes.set(pane, { tab: panes.get(id).tab, runs: [] });
45
- return { pane: { pane_id: pane } };
46
- }
47
- if (verb === "run") panes.get(id).runs.push(args[3]);
48
- return { pane: { pane_id: id } };
49
- };
50
- return { call, calls, tabs, panes, state, closePane: (id) => panes.delete(id) };
51
- }
52
-
53
- function harness(env = { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w" }) {
54
- const f = fixture();
55
- const herdr = fakeHerdr();
56
- const handlers = new Map();
57
- const commands = new Map();
58
- const notices = [];
59
- const widgets = new Map();
60
- let tool;
61
- const theme = { fg: (_color, text) => text, bold: (text) => text };
62
- const ctx = {
63
- cwd: f.root, mode: "tui", hasUI: true, isIdle: () => true,
64
- ui: {
65
- setWidget(key, factory) { if (factory) widgets.set(key, factory({ requestRender() {} }, theme)); else widgets.delete(key); },
66
- setStatus() {}, notify(message, level) { notices.push({ message, level }); },
67
- },
68
- };
69
- const pi = {
70
- on(name, handler) { handlers.set(name, handler); },
71
- registerTool(value) { tool = value; },
72
- registerCommand(name, value) { commands.set(name, value); },
73
- sendMessage() {},
74
- };
75
- register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, herdr: herdr.call, env, sleep: () => flush() });
76
- return {
77
- ...f, herdr, handlers, commands, notices, widgets, ctx,
78
- start: async (command, description) => (await tool.execute(command, { action: "start", command, description })).structuredContent.task,
79
- begin: () => handlers.get("session_start")({}, ctx),
80
- async close() {
81
- const closing = handlers.get("session_shutdown")({}, ctx);
82
- for (const call of f.calls) call.resolve();
83
- await closing;
84
- await f.close();
85
- },
86
- };
87
- }
88
-
89
- async function settle() { for (let i = 0; i < 20; i++) await flush(); }
90
-
91
- test("a single task names its tab, pane and visible header; watch and pane reuse update the names", async () => {
92
- const h = harness();
93
- try {
94
- await h.begin();
95
- const first = await h.start("make release", "Release build");
96
- await settle();
97
- const [tab] = h.herdr.tabs.keys();
98
- const [left] = h.herdr.panes.keys();
99
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Release build");
100
- assert.equal(h.herdr.panes.get(left).label, "01 · Release build");
101
- assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · Release build\n\$ make release\n/);
102
-
103
- await h.start("make test", "Unit tests");
104
- await settle();
105
- assert.equal(h.herdr.tabs.size, 1);
106
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Unit tests");
107
- assert.equal([...h.herdr.panes.values()][1].label, "02 · Unit tests");
108
- await h.commands.get("bg").handler(`watch ${first.id}`, h.ctx);
109
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Release build");
110
- assert.equal(h.herdr.panes.get(left).runs.length, 1, "watch must not restart an existing viewer");
111
-
112
- h.calls[0].resolve();
113
- await settle();
114
- const third = await h.start("make lint", "Lint");
115
- await settle();
116
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Lint");
117
- assert.equal(h.herdr.panes.get(left).label, "03 · Lint");
118
- assert.match(readFileSync(third.log_path.replace(/\.log$/, ".header"), "utf8"), /^03 · Lint\n\$ make lint\n/);
119
- assert.equal(h.herdr.panes.size, 2);
120
- } finally { await h.close(); }
121
- });
122
-
123
- test("task numbers survive closing the left pane and reopening it beside another task", async () => {
124
- const h = harness();
125
- try {
126
- await h.begin();
127
- const first = await h.start("make build", "Build");
128
- await h.start("make test", "Tests");
129
- await settle();
130
- const [left] = h.herdr.panes.keys();
131
- h.herdr.closePane(left);
132
- await h.commands.get("bg").handler(`watch ${first.id}`, h.ctx);
133
- assert.deepEqual([...h.herdr.panes.values()].map((pane) => pane.label), ["02 · Tests", "01 · Build"]);
134
- assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · Build\n/);
135
- } finally { await h.close(); }
136
- });
137
-
138
- test("when the named task finishes, the tab names the remaining running task", async () => {
139
- const h = harness();
140
- try {
141
- await h.begin();
142
- await h.start("make build", "Build");
143
- await h.start("make test", "Tests");
144
- await settle();
145
- const [tab] = h.herdr.tabs.keys();
146
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Tests");
147
- h.calls[1].resolve();
148
- await settle();
149
- assert.equal(h.herdr.tabs.get(tab).label, "BG · Build");
150
- assert.equal(h.herdr.tabs.size, 1);
151
- } finally { await h.close(); }
152
- });
153
-
154
- test("two tasks share one unfocused tab, one pane each; the pane shows the command, then the log", async () => {
155
- const h = harness();
156
- try {
157
- await h.begin();
158
- const first = await h.start("printf 'a\\n'; sleep 1");
159
- const second = await h.start("make test");
160
- await settle();
161
- assert.equal(h.herdr.tabs.size, 1);
162
- assert.equal(h.herdr.panes.size, 2);
163
- const create = h.herdr.calls.find((args) => args[0] === "tab" && args[1] === "create");
164
- assert.ok(create.includes("--no-focus"));
165
- assert.ok(h.herdr.calls.filter((args) => args[1] === "split").every((args) => args.includes("--no-focus")));
166
- const runs = [...h.herdr.panes.values()].map((pane) => pane.runs.at(-1));
167
- assert.ok(runs[0].includes(first.log_path) && runs[1].includes(second.log_path));
168
- assert.doesNotMatch(runs.join("\n"), /make test|printf/, "the command text is never passed as shell syntax");
169
- assert.match(readFileSync(first.log_path.replace(/\.log$/, ".header"), "utf8"), /^01 · printf 'a\\n'; sleep 1\n\$ printf 'a\\n'; sleep 1\n# bg-.* · cwd .* · timeout 30m\n/);
170
- } finally { await h.close(); }
171
- });
172
-
173
- test("a finished task's pane shows the result, is reused, and the tab closes once nothing runs", async () => {
174
- const h = harness();
175
- try {
176
- await h.begin();
177
- const first = await h.start("one");
178
- await h.start("two");
179
- await settle();
180
- h.calls[0].resolve(3);
181
- await settle();
182
- assert.match(readFileSync(first.log_path.replace(/\.log$/, ".done"), "utf8"), /\[failed · exit 3 · 0s\]/);
183
- assert.equal(h.herdr.tabs.size, 1, "the tab stays while a task still runs");
184
- const third = await h.start("three");
185
- await settle();
186
- assert.equal(h.herdr.panes.size, 2, "the finished task's pane is reused");
187
- assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(third.log_path)));
188
- h.calls[1].resolve();
189
- h.calls[2].resolve();
190
- await settle();
191
- assert.equal(h.herdr.tabs.size, 0);
192
- } finally { await h.close(); }
193
- });
194
-
195
- test("the tab waits while the user looks at it, then closes after focus moves away", async () => {
196
- const h = harness();
197
- try {
198
- await h.begin();
199
- await h.start("one");
200
- await settle();
201
- h.herdr.state.focused = true;
202
- h.calls[0].resolve();
203
- await settle();
204
- assert.equal(h.herdr.tabs.size, 1);
205
- h.herdr.state.focused = false;
206
- await settle();
207
- assert.equal(h.herdr.tabs.size, 0);
208
- } finally { await h.close(); }
209
- });
210
-
211
- test("closing a pane keeps the task running; /bg watch reopens and focuses it", async () => {
212
- const h = harness();
213
- try {
214
- await h.begin();
215
- const task = await h.start("one");
216
- await settle();
217
- h.herdr.closePane([...h.herdr.panes.keys()][0]);
218
- assert.equal(h.calls[0].signal.aborted, false);
219
- await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
220
- await settle();
221
- assert.equal(h.herdr.tabs.size, 1);
222
- assert.equal(h.herdr.panes.size, 1);
223
- assert.ok([...h.herdr.panes.values()][0].runs.at(-1).includes(task.log_path));
224
- assert.equal([...h.herdr.tabs.values()][0].label, "BG · one");
225
- assert.equal([...h.herdr.panes.values()][0].label, "01 · one");
226
- assert.ok(h.herdr.calls.some((args) => args[0] === "tab" && args[1] === "focus"));
227
- assert.deepEqual(h.notices, []);
228
- } finally { await h.close(); }
229
- });
230
-
231
- test("clicking a widget task row opens its view and focuses the tab; other clicks do nothing", async () => {
232
- const h = harness();
233
- try {
234
- await h.begin();
235
- await h.start("one");
236
- const second = await h.start("two");
237
- await settle();
238
- h.herdr.closePane([...h.herdr.panes.keys()][1]);
239
- const widget = h.widgets.get("background-tasks");
240
- const lines = widget.render(120);
241
- assert.match(lines[2], new RegExp(second.id));
242
- 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 });
243
- assert.equal(click(0), undefined, "the title row is not a task");
244
- assert.equal(click(2, { button: "right" }), undefined);
245
- const before = h.herdr.calls.length;
246
- assert.deepEqual(click(2), { handled: true, render: false });
247
- await settle();
248
- assert.ok(h.herdr.calls.length > before);
249
- assert.ok([...h.herdr.panes.values()].some((pane) => pane.runs.at(-1).includes(second.log_path)), "the closed pane was reopened");
250
- const [first] = h.herdr.panes.keys();
251
- assert.deepEqual(h.herdr.calls.at(-2).slice(0, 2), ["tab", "focus"]);
252
- assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", first, "--direction", "right"], "the reopened right pane gets focus");
253
- click(1);
254
- await settle();
255
- const [, right] = h.herdr.panes.keys();
256
- assert.deepEqual(h.herdr.calls.at(-1), ["pane", "focus", "--pane", right, "--direction", "left"], "the left pane gets focus");
257
- } finally { await h.close(); }
258
- });
259
-
260
- test("completion after the user closes the tab does not consume the warning for real Herdr failures", async () => {
261
- const h = harness();
262
- try {
263
- await h.begin();
264
- await h.start("one");
265
- await h.start("two");
266
- await settle();
267
- const [tab] = h.herdr.tabs.keys();
268
- await h.herdr.call(["tab", "close", tab]);
269
- h.calls[0].resolve();
270
- await settle();
271
- assert.deepEqual(h.notices, [], "closing a view is not a Herdr failure");
272
- assert.equal(h.calls[1].signal.aborted, false);
273
- h.herdr.state.fail = () => true;
274
- await h.start("three");
275
- await settle();
276
- assert.equal(h.notices.length, 1, "a later real failure still warns");
277
- assert.equal(h.notices[0].level, "warning");
278
- } finally { await h.close(); }
279
- });
280
-
281
- test("Herdr failures warn once and never affect tasks", async () => {
282
- const h = harness();
283
- try {
284
- await h.begin();
285
- h.herdr.state.fail = () => true;
286
- await h.start("one");
287
- await h.start("two");
288
- await settle();
289
- assert.equal(h.notices.length, 1);
290
- assert.equal(h.notices[0].level, "warning");
291
- assert.ok(h.calls.every((call) => !call.signal.aborted), "tasks keep running");
292
- h.calls[0].resolve();
293
- h.calls[1].resolve();
294
- await settle();
295
- assert.equal(h.notices.length, 1, "the warning is shown once");
296
- } finally { await h.close(); }
297
- });
298
-
299
- test("session shutdown closes the tab immediately", async () => {
300
- const h = harness();
301
- await h.begin();
302
- await h.start("one");
303
- await settle();
304
- h.herdr.state.focused = true;
305
- await h.close();
306
- assert.equal(h.herdr.tabs.size, 0);
307
- });
308
-
309
- for (const [label, env] of [
310
- ["outside Herdr", {}],
311
- ["in a Herdr subagent child", { HERDR_ENV: "1", HERDR_WORKSPACE_ID: "w", PI_HERDR_SUBAGENTS_CHILD: "1" }],
312
- ]) {
313
- test(`${label}, no Herdr call is made and /bg watch explains why`, async () => {
314
- const h = harness(env);
315
- try {
316
- await h.begin();
317
- const task = await h.start("one");
318
- await settle();
319
- await h.commands.get("bg").handler(`watch ${task.id}`, h.ctx);
320
- const widget = h.widgets.get("background-tasks");
321
- widget.render(120);
322
- assert.equal(widget.handleMouse({ type: "click", button: "left", x: 4, y: 1, width: 120, height: 2 }), undefined, "rows are not clickable without a view");
323
- assert.deepEqual(h.herdr.calls, []);
324
- assert.match(h.notices[0].message, /inside Herdr/);
325
- } finally { await h.close(); }
326
- });
327
- }
328
-
329
- test("the view script follows a real log, then prints the result line", async () => {
330
- const dir = mkdtempSync(join(tmpdir(), "pi-bg-view-"));
331
- try {
332
- const [log, done, header, script] = ["t.log", "t.done", "t.header", "view.sh"].map((name) => join(dir, name));
333
- writeFileSync(log, "line 1\nline 2\n");
334
- writeFileSync(header, "$ echo hi\n");
335
- writeFileSync(script, VIEW_SCRIPT);
336
- setTimeout(() => writeFileSync(done, "\n[succeeded · exit 0 · 1s]\n"), 300);
337
- const { stdout: output } = await promisify(execFile)("sh", [script, log, done, header], { encoding: "utf8", timeout: 10000 });
338
- assert.match(output, /\$ echo hi\nline 1\nline 2\n\n\[succeeded · exit 0 · 1s\]\n$/);
339
- } finally { rmSync(dir, { recursive: true, force: true }); }
340
- });