@maxiaochao/pi-background-tasks 0.0.0-stage → 0.1.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.
@@ -0,0 +1,201 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { existsSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { BackgroundTasks } from "../src/background-tasks.ts";
6
+ import { fixture, flush } from "./helpers.mjs";
7
+
8
+ test("start returns while execution is pending; two tasks own independent slots", async () => {
9
+ const f = fixture();
10
+ try {
11
+ const first = f.tasks.start({ command: "sleep 60; printf done" }, f.root);
12
+ const second = f.tasks.start({ command: "other", timeout: 60 }, f.root);
13
+ assert.equal(first.status, "running");
14
+ assert.equal(first.timeout, 1800);
15
+ assert.notEqual(first.id, second.id);
16
+ assert.equal(f.calls.length, 2);
17
+ assert.throws(() => f.tasks.start({ command: "third" }, f.root), /two|2.*running/i);
18
+ f.calls[0].onData(Buffer.from("hello\n"));
19
+ assert.equal(f.tasks.output(first.id).output, "hello\n");
20
+ f.calls[0].resolve();
21
+ await flush();
22
+ assert.equal(f.tasks.get(first.id).status, "succeeded");
23
+ assert.equal(f.completed.length, 1);
24
+ assert.equal(f.tasks.list().running, 1);
25
+ assert.equal(f.tasks.get(first.id).capture_complete, true);
26
+ assert.equal(readFileSync(first.log_path, "utf8"), "hello\n");
27
+ } finally { await f.close(); }
28
+ });
29
+
30
+ test("timeout records its cause, aborts without a model, and retains the slot until cleanup", async () => {
31
+ const f = fixture();
32
+ try {
33
+ const a = f.tasks.start({ command: "loop", timeout: 1 }, f.root);
34
+ f.tasks.start({ command: "second" }, f.root);
35
+ f.clock.advance(1000);
36
+ assert.equal(f.calls[0].signal.aborted, true);
37
+ assert.equal(f.tasks.get(a.id).status, "running");
38
+ assert.throws(() => f.tasks.start({ command: "third" }, f.root), /two|2.*running/i);
39
+ const cancel = f.tasks.cancel(a.id);
40
+ f.calls[0].reject(new Error("aborted"));
41
+ await cancel;
42
+ assert.equal(f.tasks.get(a.id).status, "timed_out");
43
+ assert.equal(f.completed.length, 1);
44
+ await f.tasks.cancel(a.id);
45
+ assert.equal(f.completed.length, 1);
46
+ } finally { await f.close(); }
47
+ });
48
+
49
+ test("invalid inputs have no execution or log side effects", async () => {
50
+ const f = fixture();
51
+ try {
52
+ for (const timeout of [0, -1, 1.5, 7201, Infinity, NaN, "30"]) {
53
+ assert.throws(() => f.tasks.start({ command: "x", timeout }, f.root), /timeout/i);
54
+ }
55
+ assert.throws(() => f.tasks.start({ command: " " }, f.root), /command/i);
56
+ assert.throws(() => f.tasks.start({ command: "x", cwd: "missing" }, f.root), /directory/i);
57
+ assert.throws(() => f.tasks.get("not-mine"), /unknown/i);
58
+ assert.equal(f.calls.length, 0);
59
+ assert.equal(f.tasks.list().total, 0);
60
+ } finally { await f.close(); }
61
+ });
62
+
63
+ test("shutdown is idempotent, suppresses notifications and removes only owned logs", async () => {
64
+ const f = fixture();
65
+ const task = f.tasks.start({ command: "pending" }, f.root);
66
+ const shutdown = f.tasks.shutdown();
67
+ assert.equal(f.calls[0].signal.aborted, true);
68
+ f.calls[0].resolve();
69
+ await shutdown;
70
+ assert.equal(f.completed.length, 0);
71
+ assert.equal(f.clock.timers.size, 0);
72
+ assert.equal(existsSync(task.log_path), false);
73
+ assert.equal(existsSync(f.root), true);
74
+ assert.throws(() => f.tasks.start({ command: "x" }, f.root), /closed/i);
75
+ await f.close();
76
+ });
77
+
78
+ for (const mode of ["task", "session"]) {
79
+ test(`${mode} byte budget stops only the overflowing task and marks captured output incomplete`, async () => {
80
+ const f = fixture({ limits: { taskBytes: mode === "task" ? 4 : 100, sessionBytes: mode === "session" ? 4 : 100 } });
81
+ try {
82
+ const job = f.tasks.start({ command: "large" }, f.root);
83
+ f.calls[0].onData(Buffer.from("1234567"));
84
+ assert.equal(f.calls[0].signal.aborted, true);
85
+ f.calls[0].reject(new Error("aborted"));
86
+ await flush();
87
+ const result = f.tasks.output(job.id);
88
+ assert.equal(result.status, "output_limit");
89
+ assert.equal(result.output, "1234");
90
+ assert.equal(result.bytes, 4);
91
+ assert.equal(result.capture_complete, false);
92
+ assert.equal(f.completed.length, 1);
93
+ if (mode === "session") assert.throws(() => f.tasks.start({ command: "more" }, f.root), /budget/i);
94
+ else assert.equal(f.tasks.start({ command: "more" }, f.root).status, "running");
95
+ } finally { await f.close(); }
96
+ });
97
+ }
98
+
99
+ test("log write failure aborts the job and reports bounded failure without escaping onData", async () => {
100
+ const f = fixture({ logWrite() { throw new Error("disk full " + "x".repeat(10000)); } });
101
+ try {
102
+ const job = f.tasks.start({ command: "write" }, f.root);
103
+ assert.doesNotThrow(() => f.calls[0].onData(Buffer.from("hello")));
104
+ assert.equal(f.calls[0].signal.aborted, true);
105
+ f.calls[0].reject(new Error("aborted"));
106
+ await flush();
107
+ assert.equal(f.tasks.get(job.id).status, "failed");
108
+ assert.match(f.tasks.get(job.id).reason, /disk full/);
109
+ assert.ok(f.tasks.get(job.id).reason.length <= 500);
110
+ assert.equal(f.tasks.get(job.id).capture_complete, false);
111
+ } finally { await f.close(); }
112
+ });
113
+
114
+ test("nonzero exit, null exit and spawn errors are final failures; first stop reason wins", async () => {
115
+ const f = fixture();
116
+ try {
117
+ for (const outcome of [12, null, "spawn failed"]) {
118
+ const task = f.tasks.start({ command: "failure" }, f.root);
119
+ const call = f.calls.at(-1);
120
+ if (typeof outcome === "string") call.reject(new Error(outcome));
121
+ else call.resolve(outcome);
122
+ await flush();
123
+ assert.equal(f.tasks.get(task.id).status, "failed");
124
+ }
125
+ const job = f.tasks.start({ command: "cancel race", timeout: 1 }, f.root);
126
+ const cancelled = f.tasks.cancel(job.id);
127
+ f.clock.advance(1000);
128
+ f.calls.at(-1).resolve(0);
129
+ assert.equal((await cancelled).status, "cancelled");
130
+ assert.equal(f.completed.length, 4);
131
+ } finally { await f.close(); }
132
+ });
133
+
134
+ test("history is bounded in list, but older task outputs remain addressable; previews are safe", async () => {
135
+ const f = fixture();
136
+ try {
137
+ let first;
138
+ for (let i = 0; i < 25; i++) {
139
+ const job = f.tasks.start({ command: "x".repeat(10000), description: "\u001b]0;bad\u0007hello\n" + "中".repeat(300), timeout: 7200 }, f.root);
140
+ first ??= job;
141
+ assert.ok(Array.from(job.description).length <= 200);
142
+ assert.ok(!/[\x00-\x1f]/.test(job.description));
143
+ f.calls.at(-1).resolve();
144
+ await flush();
145
+ }
146
+ assert.equal(f.tasks.list().tasks.length, 20);
147
+ assert.equal(f.tasks.list().total, 25);
148
+ assert.equal(f.tasks.list().omitted, 5);
149
+ assert.equal(f.tasks.output(first.id).status, "succeeded");
150
+ } finally { await f.close(); }
151
+ });
152
+
153
+ test("explicit null timeout is not an unlimited/default timeout", async () => {
154
+ const f = fixture();
155
+ try { assert.throws(() => f.tasks.start({ command: "x", timeout: null }, f.root), /timeout/i); }
156
+ finally { await f.close(); }
157
+ });
158
+
159
+ test("a log failure while cancellation drains output preserves the stop cause and reports lost capture", async () => {
160
+ const f = fixture({ logWrite() { throw new Error("disk full while draining"); } });
161
+ try {
162
+ const job = f.tasks.start({ command: "write" }, f.root);
163
+ const cancel = f.tasks.cancel(job.id);
164
+ f.calls[0].onData(Buffer.from("buffered output"));
165
+ f.calls[0].reject(new Error("aborted"));
166
+ const result = await cancel;
167
+ assert.equal(result.status, "cancelled");
168
+ assert.equal(result.capture_complete, false);
169
+ assert.match(result.reason, /disk full while draining/);
170
+ } finally { await f.close(); }
171
+ });
172
+
173
+ test("short OS writes preserve all UTF-8 output in owner-only logs", async () => {
174
+ const f = fixture({ logWrite: (fd, data) => writeSync(fd, data.subarray(0, 2)) });
175
+ try {
176
+ const job = f.tasks.start({ command: "unicode" }, f.root);
177
+ f.calls[0].onData(Buffer.from("中文🙂\n"));
178
+ f.calls[0].resolve();
179
+ await flush();
180
+ assert.equal(f.tasks.output(job.id).output, "中文🙂\n");
181
+ assert.equal(statSync(job.log_path).mode & 0o777, 0o600);
182
+ assert.equal(statSync(dirname(job.log_path)).mode & 0o777, 0o700);
183
+ } finally { await f.close(); }
184
+ });
185
+
186
+ test("log creation failure rejects before execution; missing active logs abort visibly", async () => {
187
+ const f = fixture();
188
+ const invalid = new BackgroundTasks({ operations: f.operations, logRoot: join(f.root, "missing") });
189
+ try {
190
+ assert.throws(() => invalid.start({ command: "x" }, f.root), /ENOENT/);
191
+ assert.equal(f.calls.length, 0);
192
+ const job = f.tasks.start({ command: "pending" }, f.root);
193
+ unlinkSync(job.log_path);
194
+ assert.throws(() => f.tasks.output(job.id), /Cannot read/);
195
+ assert.equal(f.calls[0].signal.aborted, true);
196
+ f.calls[0].reject(new Error("aborted"));
197
+ await flush();
198
+ assert.equal(f.tasks.get(job.id).status, "failed");
199
+ assert.equal(f.tasks.get(job.id).capture_complete, false);
200
+ } finally { await invalid.shutdown(); await f.close(); }
201
+ });
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """Exercise a real Pi TUI through a PTY and an offline fixture provider.
3
+
4
+ BG_SMOKE_RENDER=1 relays the actual ANSI stream into an isolated terminal window.
5
+ BG_SMOKE_CAPTURE=1 captures only that named window (requires X11 + ImageMagick).
6
+ """
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import traceback
16
+ import termios
17
+ import tty
18
+
19
+ import pexpect
20
+
21
+ PKG = Path(__file__).resolve().parents[1]
22
+ ROOT = PKG.parents[1]
23
+ OUT = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else ROOT / '.cache/verification/background-tui'
24
+ OUT.mkdir(parents=True, exist_ok=True)
25
+ work = Path(tempfile.mkdtemp(prefix='pi-bg-tui-'))
26
+ events_path = work / 'events.jsonl'
27
+ render = os.environ.get('BG_SMOKE_RENDER') == '1'
28
+ capture = os.environ.get('BG_SMOKE_CAPTURE') == '1'
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
+ env.pop('PI_HERDR_SUBAGENTS_CHILD', None)
31
+ (work / 'settings.json').write_text(json.dumps({'quietStartup': True}))
32
+ args = ['--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session', '--offline',
33
+ '-e', 'builtin:codemode', '-e', str(PKG / 'extensions/background-tasks.ts'),
34
+ '-e', str(ROOT / 'packages/scheduler/extensions/scheduler.ts'), '-e', str(PKG / 'tests/fixtures/provider.ts'),
35
+ '--tools', 'codemode,background_task,schedule', '--model', 'bg-fixture/deterministic', '--tui-mode', 'fullscreen']
36
+ size = os.get_terminal_size(sys.stdout.fileno()) if render else os.terminal_size((140, 42))
37
+ terminal_settings = termios.tcgetattr(sys.stdin.fileno()) if render else None
38
+ if render:
39
+ tty.setraw(sys.stdin.fileno())
40
+ child = pexpect.spawn(os.environ.get('PI_TEST_BINARY', shutil.which('pi')), args, cwd=str(work), env=env,
41
+ encoding='utf-8', codec_errors='replace', dimensions=(size.lines, size.columns), timeout=20)
42
+ child.linesep = '\r'
43
+ raw = ''
44
+ raw_file = (OUT / 'terminal.ansi').open('w')
45
+ screens = []
46
+
47
+
48
+ def pump(seconds=0.1):
49
+ global raw
50
+ deadline = time.monotonic() + seconds
51
+ while time.monotonic() < deadline:
52
+ try:
53
+ data = child.read_nonblocking(65536, timeout=min(0.05, max(0.001, deadline - time.monotonic())))
54
+ raw += data
55
+ raw_file.write(data)
56
+ raw_file.flush()
57
+ if render:
58
+ sys.stdout.write(data)
59
+ sys.stdout.flush()
60
+ except pexpect.TIMEOUT:
61
+ pass
62
+ except pexpect.EOF:
63
+ break
64
+
65
+
66
+ def events():
67
+ if not events_path.exists():
68
+ return []
69
+ return [json.loads(line) for line in events_path.read_text().splitlines() if line]
70
+
71
+
72
+ def wait(check, label, timeout=20):
73
+ deadline = time.monotonic() + timeout
74
+ while not check():
75
+ pump()
76
+ if not child.isalive():
77
+ raise AssertionError('Pi exited before ' + label)
78
+ if time.monotonic() > deadline:
79
+ raise AssertionError('Timeout waiting for ' + label + '\n' + raw[-4000:])
80
+ pump(0.15)
81
+
82
+
83
+ def send(text):
84
+ child.sendline(text)
85
+ pump(0.1)
86
+
87
+
88
+ def tools(name='background_task'):
89
+ return [e for e in events() if e.get('event') == 'tool_end' and e.get('name') == name]
90
+
91
+
92
+ def finished(status):
93
+ return [e for e in events() if e.get('event') == 'custom' and e.get('type') == 'background-task-finished'
94
+ and e.get('details', {}).get('task', {}).get('status') == status]
95
+
96
+
97
+ def shot(name):
98
+ pump(0.2)
99
+ if capture:
100
+ info = subprocess.check_output(['xwininfo', '-name', 'π - ' + work.name], text=True)
101
+ window = next(line.split()[3] for line in info.splitlines() if 'Window id:' in line)
102
+ path = OUT / (name + '.png')
103
+ subprocess.run(['import', '-window', window, str(path)], check=True)
104
+ screens.append(str(path))
105
+
106
+
107
+ def alive(pid):
108
+ try:
109
+ os.kill(pid, 0)
110
+ stat = Path(f'/proc/{pid}/stat')
111
+ return not (stat.exists() and stat.read_text().split(') ', 1)[1].startswith('Z '))
112
+ except ProcessLookupError:
113
+ return False
114
+
115
+
116
+ def start_long():
117
+ before = len(tools())
118
+ send('SMOKE_LONG')
119
+ wait(lambda: len(tools()) > before and (work / 'child.pid').exists(), 'lifecycle task')
120
+ return [int((work / file).read_text()) for file in ['shell.pid', 'child.pid']]
121
+
122
+
123
+ try:
124
+ wait(lambda: any(e.get('event') == 'loaded' for e in events()), 'extension startup')
125
+ loaded = next(e for e in events() if e.get('event') == 'loaded')
126
+ assert loaded['tools'].count('background_task') == 1
127
+ send('/schedule add 1h Check release status')
128
+ wait(lambda: 'active schedule' in raw, 'Scheduler widget')
129
+ send('SMOKE_START')
130
+ wait(lambda: len(tools()) >= 3 and any(e.get('name') == 'codemode' for e in tools('codemode')), 'Codemode startup batch')
131
+ starts = tools()[:3]
132
+ assert not starts[0]['isError'] and not starts[1]['isError'] and starts[2]['isError'], starts
133
+ first = starts[0]['result']['structuredContent']['task']
134
+ second = starts[1]['result']['structuredContent']['task']
135
+ assert first['status'] == second['status'] == 'running'
136
+ assert any('Script completed' in str(e.get('result')) for e in tools('codemode')), tools('codemode')
137
+ assert not finished('succeeded'), 'Sleeping job must survive Codemode completion'
138
+ shot('running')
139
+ send('/bg output ' + first['id'])
140
+ send('SMOKE_CANCEL')
141
+ wait(lambda: bool(finished('cancelled')), 'cancel notification')
142
+ wait(lambda: bool(finished('succeeded')), 'successful background notification')
143
+ shot('completed')
144
+ send('SMOKE_OUTPUT')
145
+ wait(lambda: any(e.get('result', {}).get('structuredContent', {}).get('output') == 'BUILD SUCCESSFUL\n' for e in tools()), 'explicit output query')
146
+ wait(lambda: 'BACKGROUND_NOTIFICATION_RECEIVED' in raw, 'main agent automatic response')
147
+ pump(0.5)
148
+ notifications = [e for e in events() if e.get('event') == 'custom' and e.get('type') == 'background-task-finished']
149
+ assert len(notifications) == 2, 'Duplicate persisted busy/idle notifications'
150
+ pump(5.3)
151
+ shot('history')
152
+
153
+ pids = start_long()
154
+ loaded_count = len([e for e in events() if e.get('event') == 'loaded'])
155
+ send('/reload')
156
+ wait(lambda: len([e for e in events() if e.get('event') == 'loaded']) > loaded_count, 'reload')
157
+ wait(lambda: all(not alive(pid) for pid in pids), 'reload process cleanup')
158
+ (work / 'child.pid').unlink(missing_ok=True)
159
+ pids = start_long()
160
+ send('/new')
161
+ wait(lambda: all(not alive(pid) for pid in pids), 'new-session process cleanup')
162
+ (work / 'child.pid').unlink(missing_ok=True)
163
+ pids = start_long()
164
+ child.sendcontrol('d')
165
+ pump(0.15)
166
+ if child.isalive():
167
+ child.sendcontrol('d')
168
+ deadline = time.monotonic() + 10
169
+ while child.isalive() and time.monotonic() < deadline:
170
+ pump()
171
+ assert not child.isalive(), 'Pi did not exit cleanly'
172
+ assert all(not alive(pid) for pid in pids), 'Quit leaked a shell or child process'
173
+ records = events()
174
+ logs = [e['result']['structuredContent']['task']['log_path'] for e in tools()
175
+ if e.get('result', {}).get('structuredContent', {}).get('task')]
176
+ assert all(not Path(path).exists() for path in logs), 'Session logs were not removed'
177
+ (OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
178
+ (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',
180
+ 'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
181
+ '5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
182
+ except Exception:
183
+ (OUT / 'error.txt').write_text(traceback.format_exc())
184
+ raise
185
+ finally:
186
+ if child.isalive():
187
+ child.sendcontrol('d')
188
+ pump(0.1)
189
+ if child.isalive():
190
+ child.sendcontrol('d')
191
+ pump(0.5)
192
+ if child.isalive():
193
+ child.terminate(force=True)
194
+ raw_file.close()
195
+ if terminal_settings is not None:
196
+ termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, terminal_settings)
197
+ if events_path.exists() and not (OUT / 'events.jsonl').exists():
198
+ shutil.copyfile(events_path, OUT / 'events.jsonl')
199
+ shutil.rmtree(work)