@maxiaochao/pi-background-tasks 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +18 -34
- package/TESTING.md +16 -22
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/shell-list.png +0 -0
- package/extensions/background-tasks.ts +51 -69
- package/package.json +2 -2
- package/src/background-tasks.ts +5 -0
- package/src/panel.ts +167 -0
- package/src/widget.ts +41 -32
- package/tests/extension.mjs +96 -27
- package/tests/fixtures/provider.ts +3 -3
- package/tests/fixtures/terminal.py +52 -0
- package/tests/load.mjs +1 -0
- package/tests/media.mjs +2 -2
- package/tests/panel.mjs +164 -0
- package/tests/tui-smoke.py +10 -4
- package/docs/demo.webm +0 -0
- package/docs/task-panes.png +0 -0
- package/src/herdr.ts +0 -38
- package/src/viewer.ts +0 -212
- package/tests/viewer.mjs +0 -340
package/tests/panel.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
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 { BackgroundFooter } 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
|
+
let status = "", panelOpen = false;
|
|
24
|
+
const native = { render: () => ["path", "usage model", ...(status ? [status] : [])], invalidate() {} };
|
|
25
|
+
const widget = new BackgroundFooter(native, () => f.tasks.list().tasks, f.clock, theme, () => !!status, () => panelOpen, () => opened++);
|
|
26
|
+
assert.deepEqual(widget.render(120), ["path", "usage model", "1 shell · Alt+J"]);
|
|
27
|
+
assert.equal(widget.handleMouse(click(7, 2)), undefined);
|
|
28
|
+
assert.equal(widget.handleMouse(click(2, 1)), undefined);
|
|
29
|
+
assert.equal(widget.handleMouse(click(2, 2, "right")), undefined);
|
|
30
|
+
assert.equal(widget.handleMouse(click(2, 2)).handled, true);
|
|
31
|
+
assert.equal(opened, 1);
|
|
32
|
+
f.tasks.start({ command: "second" }, f.root);
|
|
33
|
+
assert.match(widget.render(120).at(-1), /^2 shells/);
|
|
34
|
+
f.calls[1].resolve(3); await flush();
|
|
35
|
+
assert.match(widget.render(120).at(-1), /^1 shell · 1 done/);
|
|
36
|
+
f.clock.advance(5000);
|
|
37
|
+
assert.equal(widget.render(120).at(-1), "1 shell · Alt+J");
|
|
38
|
+
status = "editor: apply_patch";
|
|
39
|
+
assert.equal(widget.render(120).at(-1), `${status} · 1 shell · Alt+J`);
|
|
40
|
+
assert.equal(widget.handleMouse(click(2, 2)), undefined, "editor status is not a shell click");
|
|
41
|
+
assert.equal(widget.handleMouse(click(23, 2)).handled, true);
|
|
42
|
+
panelOpen = true;
|
|
43
|
+
assert.deepEqual(widget.render(120), []);
|
|
44
|
+
assert.equal(widget.handleMouse(click(23, 2)), undefined);
|
|
45
|
+
panelOpen = false;
|
|
46
|
+
status = "中文状态".repeat(20);
|
|
47
|
+
for (const width of [0, 1, 8, 40]) {
|
|
48
|
+
const row = widget.render(width).at(-1);
|
|
49
|
+
assert.ok(visibleWidth(row) <= width);
|
|
50
|
+
if (width >= 8) assert.match(row, /1 shell/, "keep the count visible even if other statuses are long");
|
|
51
|
+
}
|
|
52
|
+
widget.invalidate();
|
|
53
|
+
assert.equal(widget.handleMouse(click(2, 2)), undefined, "resize/theme invalidation clears stale hit regions");
|
|
54
|
+
f.calls[0].resolve(); await flush();
|
|
55
|
+
f.clock.advance(5000);
|
|
56
|
+
assert.deepEqual(widget.render(120), native.render(120), "expired count leaves the native footer untouched");
|
|
57
|
+
} finally { await f.close(); }
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("single shell opens aligned details; full original multiline command is separate from metadata", async () => {
|
|
61
|
+
const f = fixture(); let p;
|
|
62
|
+
try {
|
|
63
|
+
const command = 'printf "hello"\nprintf "中文"';
|
|
64
|
+
const task = f.tasks.start({ command, description: "Short label" }, f.root);
|
|
65
|
+
assert.equal(f.tasks.command(task.id), command);
|
|
66
|
+
assert.equal(task.command, undefined);
|
|
67
|
+
p = panel(f);
|
|
68
|
+
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/);
|
|
69
|
+
f.clock.advance(209000);
|
|
70
|
+
assert.match(p.text(), /Runtime: 3m 29s/);
|
|
71
|
+
assert.ok(p.renders > 0);
|
|
72
|
+
p.view.handleInput("\x1b[D");
|
|
73
|
+
assert.match(p.text(), /Background\n 1 active shell/);
|
|
74
|
+
p.view.handleInput("\r");
|
|
75
|
+
assert.match(p.text(), /Shell details/);
|
|
76
|
+
p.view.handleInput(" ");
|
|
77
|
+
assert.equal(p.closed, 1);
|
|
78
|
+
assert.equal(f.calls[0].signal.aborted, false, "closing only dismisses the view");
|
|
79
|
+
assert.equal(f.clock.timers.size, 1, "only the job deadline remains");
|
|
80
|
+
} finally { p?.view.dispose(); await f.close(); }
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("multiple shells: arrow selection, click, identity across completion, x stops only selected job", async () => {
|
|
84
|
+
const f = fixture(); let p;
|
|
85
|
+
try {
|
|
86
|
+
const a = f.tasks.start({ command: "first" }, f.root);
|
|
87
|
+
const b = f.tasks.start({ command: "second" }, f.root);
|
|
88
|
+
p = panel(f);
|
|
89
|
+
assert.match(p.text(), /Background\n 2 active shells/);
|
|
90
|
+
assert.match(p.text(), /❯ ●first/);
|
|
91
|
+
p.view.handleInput("\x1b[B");
|
|
92
|
+
assert.match(p.text(), /❯ ●second/);
|
|
93
|
+
f.calls[0].resolve(); await flush();
|
|
94
|
+
assert.match(p.text(), /❯ ●second/);
|
|
95
|
+
p.view.handleInput("\r");
|
|
96
|
+
assert.match(p.text(), /Command: second/);
|
|
97
|
+
p.view.handleInput("x"); p.view.handleInput("x");
|
|
98
|
+
assert.equal(f.calls[1].signal.aborted, true);
|
|
99
|
+
assert.equal(f.calls[0].signal.aborted, false);
|
|
100
|
+
assert.match(p.text(), /Status: stopping/);
|
|
101
|
+
f.calls[1].reject(new Error("cancelled")); await flush();
|
|
102
|
+
assert.equal(f.tasks.get(b.id).status, "cancelled");
|
|
103
|
+
assert.doesNotMatch(p.text(), /x to stop/);
|
|
104
|
+
p.view.handleInput("\x1b[D");
|
|
105
|
+
const lines = p.view.render(120);
|
|
106
|
+
assert.match(lines.join("\n"), /Earlier in this session \(2\)/);
|
|
107
|
+
const row = lines.findIndex((line) => line.includes("●first"));
|
|
108
|
+
assert.equal(p.view.handleMouse(click(4, 1)), undefined);
|
|
109
|
+
assert.equal(p.view.handleMouse(click(4, row)).handled, true);
|
|
110
|
+
assert.match(p.text(), /Command: first/);
|
|
111
|
+
assert.equal(f.tasks.get(a.id).status, "succeeded");
|
|
112
|
+
} finally { p?.view.dispose(); await f.close(); }
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("bounded, sanitized output, long command wrapping, error states and narrow/CJK widths", async () => {
|
|
116
|
+
const f = fixture(); let p;
|
|
117
|
+
try {
|
|
118
|
+
const task = f.tasks.start({ command: "echo 中文".repeat(1000) }, f.root);
|
|
119
|
+
p = panel(f);
|
|
120
|
+
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")));
|
|
121
|
+
const text = p.text();
|
|
122
|
+
assert.match(text, /…/);
|
|
123
|
+
assert.match(text, /line 119/);
|
|
124
|
+
assert.doesNotMatch(text, /line 109|\x1b|\uFFF9/);
|
|
125
|
+
assert.match(text, /Tail only/);
|
|
126
|
+
for (const width of [0, 1, 8, 20, 40, 80, 120]) assert.ok(p.view.render(width).every((line) => visibleWidth(line) <= width), `width ${width}`);
|
|
127
|
+
f.calls[0].resolve(4); await flush();
|
|
128
|
+
assert.match(p.text(), /Status: failed/);
|
|
129
|
+
assert.match(p.text(), /Exit: 4/);
|
|
130
|
+
assert.match(p.text(), /Reason: Command exited with code 4/);
|
|
131
|
+
unlinkSync(task.log_path);
|
|
132
|
+
assert.match(p.text(), /Cannot read task log/);
|
|
133
|
+
} finally { p?.view.dispose(); await f.close(); }
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test("empty state, history paging, stable selected completed ID, timer disposal", async () => {
|
|
137
|
+
const f = fixture(); let p;
|
|
138
|
+
try {
|
|
139
|
+
p = panel(f);
|
|
140
|
+
assert.match(p.text(), /No shells in this session/);
|
|
141
|
+
p.view.handleInput("x"); p.view.handleInput("\r");
|
|
142
|
+
for (let i = 0; i < 25; i++) {
|
|
143
|
+
f.tasks.start({ command: `job ${i}` }, f.root);
|
|
144
|
+
f.calls.at(-1).resolve(); await flush();
|
|
145
|
+
}
|
|
146
|
+
assert.match(p.text(), /Earlier in this session \(25\)/);
|
|
147
|
+
for (let i = 0; i < 19; i++) p.view.handleInput("\x1b[B");
|
|
148
|
+
assert.match(p.text(), /❯ ●job 5/);
|
|
149
|
+
assert.match(p.text(), /5 older tasks omitted/);
|
|
150
|
+
p.view.handleInput("\r");
|
|
151
|
+
assert.match(p.text(), /Command: job 5/);
|
|
152
|
+
p.view.handleInput("\r");
|
|
153
|
+
assert.equal(p.closed, 1);
|
|
154
|
+
assert.equal(f.clock.timers.size, 0);
|
|
155
|
+
const renders = p.renders;
|
|
156
|
+
f.clock.advance(3000);
|
|
157
|
+
assert.equal(p.renders, renders);
|
|
158
|
+
} finally { p?.view.dispose(); await f.close(); }
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test("production extension registers no slash command and has no Herdr execution dependency", () => {
|
|
162
|
+
const source = readFileSync(new URL("../extensions/background-tasks.ts", import.meta.url), "utf8");
|
|
163
|
+
assert.doesNotMatch(source, /registerCommand|Herdr|herdr|\/bg/);
|
|
164
|
+
});
|
package/tests/tui-smoke.py
CHANGED
|
@@ -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
|
-
|
|
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('
|
|
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', '/
|
|
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
|
package/docs/task-panes.png
DELETED
|
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,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
|
-
}
|