@maxiaochao/pi-background-tasks 0.3.0 → 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.
@@ -0,0 +1,144 @@
1
+ import assert from "node:assert/strict";
2
+ import { unlinkSync, readFileSync } from "node:fs";
3
+ import { test } from "node:test";
4
+ import { KeybindingsManager, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { BackgroundPanel } from "../src/panel.ts";
6
+ import { BackgroundWidget } from "../src/widget.ts";
7
+ import { fixture, flush } from "./helpers.mjs";
8
+
9
+ const keys = new KeybindingsManager(TUI_KEYBINDINGS);
10
+ const theme = { fg: (_color, text) => text, bold: (text) => text };
11
+ const click = (x, y, button = "left") => ({ type: "click", button, x, y });
12
+ function panel(f) {
13
+ let renders = 0, closed = 0;
14
+ const view = new BackgroundPanel(f.tasks, f.clock, theme, keys, () => renders++, () => closed++);
15
+ return { view, text: (width = 120) => view.render(width).join("\n"), get renders() { return renders; }, get closed() { return closed; } };
16
+ }
17
+
18
+ test("compact count, singular/plural, five-second retention and bounded mouse hit region", async () => {
19
+ const f = fixture();
20
+ try {
21
+ f.tasks.start({ command: "first" }, f.root);
22
+ let opened = 0;
23
+ const widget = new BackgroundWidget(() => f.tasks.list().tasks, f.clock, theme, () => opened++);
24
+ assert.deepEqual(widget.render(120), ["1 shell · Alt+J"]);
25
+ assert.equal(widget.handleMouse(click(7, 0)), undefined);
26
+ assert.equal(widget.handleMouse(click(2, 1)), undefined);
27
+ assert.equal(widget.handleMouse(click(2, 0, "right")), undefined);
28
+ assert.equal(widget.handleMouse(click(2, 0)).handled, true);
29
+ assert.equal(opened, 1);
30
+ f.tasks.start({ command: "second" }, f.root);
31
+ assert.match(widget.render(120)[0], /^2 shells/);
32
+ f.calls[1].resolve(3); await flush();
33
+ assert.match(widget.render(120)[0], /^1 shell · 1 done/);
34
+ f.clock.advance(5000);
35
+ assert.equal(widget.render(120)[0], "1 shell · Alt+J");
36
+ for (const width of [0, 1, 8, 40]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
37
+ } finally { await f.close(); }
38
+ });
39
+
40
+ test("single shell opens aligned details; full original multiline command is separate from metadata", async () => {
41
+ const f = fixture(); let p;
42
+ try {
43
+ const command = 'printf "hello"\nprintf "中文"';
44
+ const task = f.tasks.start({ command, description: "Short label" }, f.root);
45
+ assert.equal(f.tasks.command(task.id), command);
46
+ assert.equal(task.command, undefined);
47
+ p = panel(f);
48
+ assert.match(p.text(), /Shell details\n\n Status: running\n Runtime: 0s\n Command: printf "hello"\n printf "中文"\n\n Output:\n No output available/);
49
+ f.clock.advance(209000);
50
+ assert.match(p.text(), /Runtime: 3m 29s/);
51
+ assert.ok(p.renders > 0);
52
+ p.view.handleInput("\x1b[D");
53
+ assert.match(p.text(), /Background\n 1 active shell/);
54
+ p.view.handleInput("\r");
55
+ assert.match(p.text(), /Shell details/);
56
+ p.view.handleInput(" ");
57
+ assert.equal(p.closed, 1);
58
+ assert.equal(f.calls[0].signal.aborted, false, "closing only dismisses the view");
59
+ assert.equal(f.clock.timers.size, 1, "only the job deadline remains");
60
+ } finally { p?.view.dispose(); await f.close(); }
61
+ });
62
+
63
+ test("multiple shells: arrow selection, click, identity across completion, x stops only selected job", async () => {
64
+ const f = fixture(); let p;
65
+ try {
66
+ const a = f.tasks.start({ command: "first" }, f.root);
67
+ const b = f.tasks.start({ command: "second" }, f.root);
68
+ p = panel(f);
69
+ assert.match(p.text(), /Background\n 2 active shells/);
70
+ assert.match(p.text(), /❯ ●first/);
71
+ p.view.handleInput("\x1b[B");
72
+ assert.match(p.text(), /❯ ●second/);
73
+ f.calls[0].resolve(); await flush();
74
+ assert.match(p.text(), /❯ ●second/);
75
+ p.view.handleInput("\r");
76
+ assert.match(p.text(), /Command: second/);
77
+ p.view.handleInput("x"); p.view.handleInput("x");
78
+ assert.equal(f.calls[1].signal.aborted, true);
79
+ assert.equal(f.calls[0].signal.aborted, false);
80
+ assert.match(p.text(), /Status: stopping/);
81
+ f.calls[1].reject(new Error("cancelled")); await flush();
82
+ assert.equal(f.tasks.get(b.id).status, "cancelled");
83
+ assert.doesNotMatch(p.text(), /x to stop/);
84
+ p.view.handleInput("\x1b[D");
85
+ const lines = p.view.render(120);
86
+ assert.match(lines.join("\n"), /Earlier in this session \(2\)/);
87
+ const row = lines.findIndex((line) => line.includes("●first"));
88
+ assert.equal(p.view.handleMouse(click(4, 1)), undefined);
89
+ assert.equal(p.view.handleMouse(click(4, row)).handled, true);
90
+ assert.match(p.text(), /Command: first/);
91
+ assert.equal(f.tasks.get(a.id).status, "succeeded");
92
+ } finally { p?.view.dispose(); await f.close(); }
93
+ });
94
+
95
+ test("bounded, sanitized output, long command wrapping, error states and narrow/CJK widths", async () => {
96
+ const f = fixture(); let p;
97
+ try {
98
+ const task = f.tasks.start({ command: "echo 中文".repeat(1000) }, f.root);
99
+ p = panel(f);
100
+ f.calls[0].onData(Buffer.from("\x1b]52;c;c2VjcmV0\x07\x1b[31mRED\x1b[0m\uFFF9\n" + Array.from({ length: 120 }, (_, i) => `line ${i}`).join("\n")));
101
+ const text = p.text();
102
+ assert.match(text, /…/);
103
+ assert.match(text, /line 119/);
104
+ assert.doesNotMatch(text, /line 109|\x1b|\uFFF9/);
105
+ assert.match(text, /Tail only/);
106
+ for (const width of [0, 1, 8, 20, 40, 80, 120]) assert.ok(p.view.render(width).every((line) => visibleWidth(line) <= width), `width ${width}`);
107
+ f.calls[0].resolve(4); await flush();
108
+ assert.match(p.text(), /Status: failed/);
109
+ assert.match(p.text(), /Exit: 4/);
110
+ assert.match(p.text(), /Reason: Command exited with code 4/);
111
+ unlinkSync(task.log_path);
112
+ assert.match(p.text(), /Cannot read task log/);
113
+ } finally { p?.view.dispose(); await f.close(); }
114
+ });
115
+
116
+ test("empty state, history paging, stable selected completed ID, timer disposal", async () => {
117
+ const f = fixture(); let p;
118
+ try {
119
+ p = panel(f);
120
+ assert.match(p.text(), /No shells in this session/);
121
+ p.view.handleInput("x"); p.view.handleInput("\r");
122
+ for (let i = 0; i < 25; i++) {
123
+ f.tasks.start({ command: `job ${i}` }, f.root);
124
+ f.calls.at(-1).resolve(); await flush();
125
+ }
126
+ assert.match(p.text(), /Earlier in this session \(25\)/);
127
+ for (let i = 0; i < 19; i++) p.view.handleInput("\x1b[B");
128
+ assert.match(p.text(), /❯ ●job 5/);
129
+ assert.match(p.text(), /5 older tasks omitted/);
130
+ p.view.handleInput("\r");
131
+ assert.match(p.text(), /Command: job 5/);
132
+ p.view.handleInput("\r");
133
+ assert.equal(p.closed, 1);
134
+ assert.equal(f.clock.timers.size, 0);
135
+ const renders = p.renders;
136
+ f.clock.advance(3000);
137
+ assert.equal(p.renders, renders);
138
+ } finally { p?.view.dispose(); await f.close(); }
139
+ });
140
+
141
+ test("production extension registers no slash command and has no Herdr execution dependency", () => {
142
+ const source = readFileSync(new URL("../extensions/background-tasks.ts", import.meta.url), "utf8");
143
+ assert.doesNotMatch(source, /registerCommand|Herdr|herdr|\/bg/);
144
+ });
package/tests/runtime.mjs CHANGED
@@ -7,10 +7,22 @@ import { pathToFileURL } from "node:url";
7
7
 
8
8
  // npm prepends workspace .bin paths, which may contain an older development Pi.
9
9
  const hostPath = (process.env.PATH ?? "").split(delimiter).filter((entry) => !entry.endsWith("node_modules/.bin")).join(delimiter);
10
+ // The managed installer's launcher is a shell script outside the Pi package. Like
11
+ // that launcher, read install/current-version on each run so Pi updates need no change.
12
+ function managedPiModules(launcher) {
13
+ const install = join(dirname(launcher), "..", "install");
14
+ try {
15
+ const version = readFileSync(join(install, "current-version"), "utf8").trim();
16
+ const modules = join(install, "releases", version, "node_modules");
17
+ return existsSync(join(modules, "@earendil-works", "pi-coding-agent", "package.json")) ? modules : undefined;
18
+ } catch { return undefined; }
19
+ }
10
20
  const binary = process.env.PI_TEST_BINARY || execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", env: { ...process.env, PATH: hostPath } }).trim();
11
21
  let root = dirname(realpathSync(binary));
12
22
  while (!existsSync(join(root, "package.json")) || JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name !== "@earendil-works/pi-coding-agent") {
13
23
  const parent = dirname(root);
24
+ const managed = parent === root ? managedPiModules(realpathSync(binary)) : undefined;
25
+ if (managed) { root = join(managed, "@earendil-works", "pi-coding-agent"); break; }
14
26
  if (parent === root) throw new Error(`Cannot locate Pi runtime next to ${binary}`);
15
27
  root = parent;
16
28
  }
@@ -28,12 +28,12 @@ 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
+ # Task UI is local and independent of terminal host.
32
32
  (work / 'settings.json').write_text(json.dumps({'quietStartup': True}))
33
33
  args = ['--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session', '--offline',
34
34
  '-e', 'builtin:codemode', '-e', str(PKG / 'extensions/background-tasks.ts'),
35
35
  '-e', str(ROOT / 'packages/scheduler/extensions/scheduler.ts'), '-e', str(PKG / 'tests/fixtures/provider.ts'),
36
- '--tools', 'codemode,background_task,schedule', '--model', 'bg-fixture/deterministic', '--tui-mode', 'fullscreen']
36
+ '--tools', 'codemode,background_task,schedule', '--model', 'bg-fixture/deterministic', '--tui-mode', os.environ.get('BG_SMOKE_TUI_MODE', 'fullscreen')]
37
37
  size = os.get_terminal_size(sys.stdout.fileno()) if render else os.terminal_size((140, 42))
38
38
  terminal_settings = termios.tcgetattr(sys.stdin.fileno()) if render else None
39
39
  if render:
@@ -143,7 +143,13 @@ try:
143
143
  wait(lambda: len([e for e in events() if e.get('event') == 'settled']) > settled_count, 'foreground turn completion')
144
144
  assert not finished('succeeded'), 'Sleeping job must survive foreground turn completion'
145
145
  shot('running')
146
- send('/bg output ' + first['id'])
146
+ child.send('\x1bj')
147
+ wait(lambda: 'active shells' in raw, 'shell list')
148
+ child.send('\r')
149
+ wait(lambda: 'Shell details' in raw, 'shell details')
150
+ shot('details')
151
+ child.send('\x1b')
152
+ pump(0.2)
147
153
  send('SMOKE_CANCEL')
148
154
  wait(lambda: bool(finished('cancelled')), 'cancel notification')
149
155
  wait(lambda: bool(finished('succeeded')), 'successful background notification')
@@ -183,7 +189,7 @@ try:
183
189
  assert all(not Path(path).exists() for path in logs), 'Session logs were not removed'
184
190
  (OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
185
191
  (OUT / 'result.json').write_text(json.dumps({'passed': True, 'screenshots': screens,
186
- 'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', '/bg output',
192
+ 'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', 'Alt+J list/details',
187
193
  'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
188
194
  '5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
189
195
  except Exception:
package/docs/demo.webm DELETED
Binary file
Binary file
package/src/herdr.ts DELETED
@@ -1,38 +0,0 @@
1
- import { spawn } from "node:child_process";
2
-
3
- /** One Herdr CLI call: arguments in, parsed `result` object out. */
4
- export type HerdrCall = (args: string[]) => Promise<Record<string, any>>;
5
-
6
- export class HerdrError extends Error {
7
- readonly code?: string;
8
- constructor(message: string, code?: string) {
9
- super(message);
10
- this.name = "HerdrError";
11
- this.code = code;
12
- }
13
- }
14
-
15
- export function isMissing(error: unknown): boolean {
16
- return error instanceof HerdrError && /^(tab|pane)_not_found$/.test(error.code ?? "");
17
- }
18
-
19
- /** Spawns the Herdr CLI without a shell. A hung call fails after `timeoutMs`. */
20
- export function cliHerdr(binary = "herdr", timeoutMs = 10_000): HerdrCall {
21
- return (args) => new Promise((resolve, reject) => {
22
- let stdout = "";
23
- let stderr = "";
24
- const child = spawn(binary, args, { stdio: ["ignore", "pipe", "pipe"], shell: false, signal: AbortSignal.timeout(timeoutMs) });
25
- child.stdout.on("data", (chunk) => { stdout += chunk; });
26
- child.stderr.on("data", (chunk) => { stderr += chunk; });
27
- child.once("error", (error) => reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${error.message}`)));
28
- child.once("close", (code) => {
29
- let parsed: { result?: Record<string, any>; error?: { code?: string; message?: string } } | undefined;
30
- try { parsed = JSON.parse(stdout); } catch { /* Reported below. */ }
31
- if (code === 0 && parsed?.result) return resolve(parsed.result);
32
- // Some commands, such as `pane run`, succeed without printing a response.
33
- if (code === 0 && !stdout.trim()) return resolve({});
34
- const detail = parsed?.error?.message ?? (stderr.trim() || stdout.trim() || `exit code ${code}`);
35
- reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${detail}`, parsed?.error?.code));
36
- });
37
- });
38
- }
package/src/viewer.ts DELETED
@@ -1,201 +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, type TaskSnapshot } from "./background-tasks.ts";
5
- import { isMissing, type HerdrCall } from "./herdr.ts";
6
- import { duration } from "./widget.ts";
7
-
8
- export const TAB_LABEL = "Background tasks";
9
- const UNFOCUS_POLL_MS = 1000;
10
-
11
- // Runs inside the pane's own shell. It only reads files; the task itself runs elsewhere.
12
- // Arguments are file paths, so the user's command text never becomes shell syntax here.
13
- export const VIEW_SCRIPT = `printf '\\033[2J\\033[3J\\033[H'
14
- cat "$3"
15
- tail -n +1 -f "$1" &
16
- tail_pid=$!
17
- while [ ! -e "$2" ]; do sleep 0.5; done
18
- sleep 1
19
- kill "$tail_pid" 2>/dev/null
20
- wait "$tail_pid" 2>/dev/null
21
- cat "$2"
22
- `;
23
-
24
- interface Pane { id: string; task: string }
25
- interface Options {
26
- call: HerdrCall;
27
- workspaceId: string;
28
- /** Current tasks, used to free panes and decide when the tab can close. */
29
- tasks: () => TaskSnapshot[];
30
- warn: (message: string) => void;
31
- /** Delay between focus checks while the user is looking at a finished tab. */
32
- sleep?: (ms: number) => Promise<void>;
33
- }
34
-
35
- function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
36
- function clean(text: string): string { return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); }
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, string>();
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, command);
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 pane = this.panes.find((entry) => entry.task === task.id) ?? await this.open(task, false);
70
- await this.options.call(["tab", "focus", this.tab!]);
71
- // Panes are split left to right; Herdr focuses a pane through its neighbour.
72
- const index = this.panes.indexOf(pane);
73
- if (index > 0) await this.options.call(["pane", "focus", "--pane", this.panes[index - 1].id, "--direction", "right"]);
74
- else if (this.panes.length > 1) await this.options.call(["pane", "focus", "--pane", this.panes[1].id, "--direction", "left"]);
75
- this.closeWhenIdle();
76
- return pane.id;
77
- }, true);
78
- }
79
-
80
- /** Writes the result line into the task's pane, then closes the tab once nothing runs. */
81
- finished(task: TaskSnapshot): void {
82
- if (this.disposed) return;
83
- try { this.writeDone(task); }
84
- catch (error) { this.report(error); }
85
- this.closeWhenIdle();
86
- }
87
-
88
- /** Closes the tab immediately, for session shutdown, reload and replacement. */
89
- async dispose(): Promise<void> {
90
- this.disposed = true;
91
- await this.chain.catch(() => {});
92
- const tab = this.tab;
93
- this.tab = undefined;
94
- this.panes = [];
95
- if (tab) await this.options.call(["tab", "close", tab]).catch(() => {});
96
- }
97
-
98
- private enqueue<T>(step: () => Promise<T>, rethrow = false): Promise<T> {
99
- const run = this.chain.then(() => {
100
- if (this.disposed) throw new Error("Background tasks session is closed");
101
- return step();
102
- });
103
- this.chain = run.catch(() => {});
104
- return rethrow ? run : run.catch((error) => { this.report(error); return undefined as T; });
105
- }
106
-
107
- private report(error: unknown): void {
108
- if (this.disposed || this.warned) return;
109
- this.warned = true;
110
- this.options.warn(`Herdr task view unavailable; tasks keep running and the widget stays current. ${errorText(error)}`);
111
- }
112
-
113
- private running(): Set<string> {
114
- return new Set(this.options.tasks().filter((task) => task.status === "running").map((task) => task.id));
115
- }
116
-
117
- private async open(task: TaskSnapshot, retried: boolean): Promise<Pane> {
118
- const running = this.running();
119
- let pane = this.panes.find((entry) => !running.has(entry.task));
120
- try {
121
- if (!this.tab) {
122
- const created = await this.options.call(["tab", "create", "--workspace", this.options.workspaceId, "--cwd", task.cwd, "--label", TAB_LABEL, "--no-focus"]);
123
- this.tab = created.tab?.tab_id;
124
- const root = created.root_pane?.pane_id;
125
- if (!this.tab || !root) throw new Error("herdr tab create omitted the tab or pane id");
126
- pane = { id: root, task: task.id };
127
- this.panes = [pane];
128
- } else if (pane) {
129
- pane.task = task.id;
130
- } else {
131
- const split = await this.options.call(["pane", "split", this.panes.at(-1)!.id, "--direction", "right", "--cwd", task.cwd, "--no-focus"]);
132
- if (!split.pane?.pane_id) throw new Error("herdr pane split omitted the pane id");
133
- pane = { id: split.pane.pane_id, task: task.id };
134
- this.panes.push(pane);
135
- }
136
- await this.options.call(["pane", "rename", pane.id, `${task.id} · ${task.description}`.slice(0, 80)]);
137
- await this.options.call(["pane", "run", pane.id, this.viewCommand(task)]);
138
- return pane;
139
- } catch (error) {
140
- // The user may close a pane or the whole tab; drop stale handles and retry once.
141
- if (retried || !isMissing(error)) throw error;
142
- await this.prune();
143
- return this.open(task, true);
144
- }
145
- }
146
-
147
- /** Forgets panes the user closed. Without any of our panes, the tab is gone or closed. */
148
- private async prune(): Promise<void> {
149
- const alive: Pane[] = [];
150
- for (const pane of this.panes) {
151
- try { await this.options.call(["pane", "get", pane.id]); alive.push(pane); }
152
- catch (error) { if (!isMissing(error)) throw error; }
153
- }
154
- this.panes = alive;
155
- if (alive.length > 0 || !this.tab) return;
156
- const tab = this.tab;
157
- this.tab = undefined;
158
- await this.options.call(["tab", "close", tab]).catch(() => {});
159
- }
160
-
161
- private viewCommand(task: TaskSnapshot): string {
162
- const directory = dirname(task.log_path);
163
- const script = join(directory, "view.sh");
164
- const header = join(directory, `${task.id}.header`);
165
- if (!existsSync(script)) writeFileSync(script, VIEW_SCRIPT, { mode: 0o600 });
166
- const lines = clean(this.commands.get(task.id) ?? task.description).split("\n");
167
- writeFileSync(header, `${lines.map((line, index) => `${index ? ">" : "$"} ${line}`).join("\n")}\n# ${task.id} · cwd ${clean(task.cwd)} · timeout ${duration(task.timeout)}\n\n`, { mode: 0o600 });
168
- if (task.status !== "running") this.writeDone(task);
169
- // The leading space keeps the line out of shell history where HISTCONTROL allows it.
170
- return ` sh ${[script, task.log_path, this.donePath(task), header].map(quote).join(" ")}`;
171
- }
172
-
173
- private donePath(task: TaskSnapshot): string { return join(dirname(task.log_path), `${task.id}.done`); }
174
-
175
- private writeDone(task: TaskSnapshot): void {
176
- const exit = task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`;
177
- const reason = task.reason ? `\n${clean(task.reason)}` : "";
178
- writeFileSync(this.donePath(task), `\n[${task.status}${exit} · ${duration(task.elapsed_seconds)}]${reason}\n`, { mode: 0o600 });
179
- }
180
-
181
- /** Closes the tab after the last task ends; waits while the user is looking at it. */
182
- private closeWhenIdle(): void {
183
- if (this.closing || this.disposed) return;
184
- this.closing = true;
185
- const check = (): Promise<void> => this.enqueue(async (): Promise<"wait" | "done"> => {
186
- if (!this.tab || this.running().size > 0) return "done";
187
- const tab = this.tab;
188
- try {
189
- const info = await this.options.call(["tab", "get", tab]);
190
- if (info.tab?.focused) return "wait";
191
- await this.options.call(["tab", "close", tab]);
192
- } catch (error) { if (!isMissing(error)) throw error; }
193
- this.tab = undefined;
194
- this.panes = [];
195
- return "done";
196
- }).then((state) => {
197
- if (state === "wait" && !this.disposed) return this.sleep(UNFOCUS_POLL_MS).then(check);
198
- });
199
- void check().finally(() => { this.closing = false; });
200
- }
201
- }