@maxiaochao/pi-background-tasks 0.1.2 → 0.3.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/output.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { closeSync, openSync, readSync, writeSync } from "node:fs";
2
- import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
2
+ import { formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
3
3
 
4
- const PROGRAM_BYTES = 1024 * 1024;
4
+ const OUTPUT_MAX_BYTES = 8 * 1024;
5
+ const OUTPUT_MAX_LINES = 100;
5
6
  export type LogWrite = (fd: number, data: Buffer) => number;
6
7
 
7
8
  export interface OutputView {
@@ -23,6 +24,7 @@ export class TaskLog {
23
24
  private lines = 0;
24
25
  private openLine = false;
25
26
  private lastLineBytes = 0;
27
+ private lastCompletedLineBytes = 0;
26
28
 
27
29
  constructor(path: string, write: LogWrite = (fd, data) => writeSync(fd, data)) {
28
30
  this.path = path;
@@ -55,7 +57,7 @@ export class TaskLog {
55
57
  try {
56
58
  // Keep a bounded working window comparable to Bash's rolling tail. This
57
59
  // preserves an oversized last line that ends with a newline before trimming.
58
- const start = Math.max(0, this.bytes - DEFAULT_MAX_BYTES * 4 - 4);
60
+ const start = Math.max(0, this.bytes - OUTPUT_MAX_BYTES * 4 - 4);
59
61
  const tail = this.range(fd, start, this.bytes - start);
60
62
  let first = 0;
61
63
  while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
@@ -64,14 +66,14 @@ export class TaskLog {
64
66
  const previous = this.range(fd, start - 1, 1)[0];
65
67
  if (first > 0 || previous !== 0x0a) {
66
68
  const newline = snapshot.indexOf("\n");
67
- if (newline !== -1) snapshot = snapshot.slice(newline + 1);
69
+ if (newline !== -1 && newline < snapshot.length - 1) snapshot = snapshot.slice(newline + 1);
68
70
  }
69
71
  }
70
- const truncation = truncateTail(snapshot);
72
+ const truncation = truncateTail(snapshot, { maxLines: OUTPUT_MAX_LINES, maxBytes: OUTPUT_MAX_BYTES });
71
73
  const totalLines = this.lines + (this.openLine ? 1 : 0);
72
- truncation.truncated = totalLines > DEFAULT_MAX_LINES || this.decodedBytes > DEFAULT_MAX_BYTES;
74
+ truncation.truncated = totalLines > OUTPUT_MAX_LINES || this.decodedBytes > OUTPUT_MAX_BYTES;
73
75
  truncation.truncatedBy = truncation.truncated
74
- ? (truncation.truncatedBy ?? (this.decodedBytes > DEFAULT_MAX_BYTES ? "bytes" : "lines")) : null;
76
+ ? (truncation.truncatedBy ?? (this.decodedBytes > OUTPUT_MAX_BYTES ? "bytes" : "lines")) : null;
75
77
  truncation.totalLines = totalLines;
76
78
  truncation.totalBytes = this.decodedBytes;
77
79
  let text = truncation.content || "(no output)";
@@ -79,29 +81,14 @@ export class TaskLog {
79
81
  const end = totalLines;
80
82
  const begin = end - truncation.outputLines + 1;
81
83
  const detail = truncation.lastLinePartial
82
- ? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.lastLineBytes)})`
83
- : `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(DEFAULT_MAX_BYTES)} limit)` : ""}`;
84
+ ? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.openLine ? this.lastLineBytes : this.lastCompletedLineBytes)})`
85
+ : `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(OUTPUT_MAX_BYTES)} limit)` : ""}`;
84
86
  text += `\n\n[Showing ${detail}. Full output: ${this.path}]`;
85
87
  }
86
- const program = this.readProgram(fd);
87
- return { text, output: program.content, truncated: program.truncated, truncation };
88
+ return { text, output: truncation.content, truncated: truncation.truncated, truncation };
88
89
  } finally { closeSync(fd); }
89
90
  }
90
91
 
91
- private readProgram(fd: number): { content: string; truncated: boolean } {
92
- if (this.bytes <= PROGRAM_BYTES) {
93
- return { content: new TextDecoder().decode(this.range(fd, 0, this.bytes), { stream: !this.closed }), truncated: false };
94
- }
95
- const half = PROGRAM_BYTES / 2;
96
- const head = this.range(fd, 0, half);
97
- const tail = this.range(fd, this.bytes - half, half);
98
- const headText = new TextDecoder().decode(head, { stream: true });
99
- let first = 0;
100
- while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
101
- const tailText = new TextDecoder().decode(tail.subarray(first), { stream: !this.closed });
102
- return { content: `${headText}\n\n[... ${this.bytes - PROGRAM_BYTES} bytes omitted ...]\n\n${tailText}`, truncated: true };
103
- }
104
-
105
92
  private range(fd: number, position: number, length: number): Buffer {
106
93
  const data = Buffer.alloc(length);
107
94
  let offset = 0;
@@ -120,6 +107,8 @@ export class TaskLog {
120
107
  if (text.length) this.openLine = true;
121
108
  this.lastLineBytes += Buffer.byteLength(text);
122
109
  } else {
110
+ const previous = last === 0 ? -1 : text.lastIndexOf("\n", last - 1);
111
+ this.lastCompletedLineBytes = Buffer.byteLength(text.slice(previous + 1, last)) + (previous === -1 ? this.lastLineBytes : 0);
123
112
  for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) this.lines++;
124
113
  this.lastLineBytes = Buffer.byteLength(text.slice(last + 1));
125
114
  this.openLine = last < text.length - 1;
package/src/viewer.ts ADDED
@@ -0,0 +1,201 @@
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
+ }
package/src/widget.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth } from "@earendil-works/pi-tui";
2
+ import { truncateToWidth, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
3
3
  import type { Clock, TaskSnapshot } from "./background-tasks.ts";
4
4
 
5
5
  export const WIDGET_KEY = "background-tasks";
@@ -22,11 +22,23 @@ export class BackgroundWidget {
22
22
  private readonly getTasks: () => TaskSnapshot[];
23
23
  private readonly clock: Clock;
24
24
  private readonly theme: Theme;
25
+ private readonly onSelect?: (id: string) => void;
26
+ private rows: string[] = [];
25
27
 
26
- constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme) {
28
+ /** With `onSelect`, a primary click on a task row selects it (fullscreen mode only). */
29
+ constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, onSelect?: (id: string) => void) {
27
30
  this.getTasks = getTasks;
28
31
  this.clock = clock;
29
32
  this.theme = theme;
33
+ this.onSelect = onSelect;
34
+ }
35
+
36
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
37
+ if (!this.onSelect || event.type !== "click" || event.button !== "left") return;
38
+ const id = this.rows[event.y - 1];
39
+ if (!id) return;
40
+ this.onSelect(id);
41
+ return { handled: true, render: false };
30
42
  }
31
43
 
32
44
  render(width: number): string[] {
@@ -34,6 +46,7 @@ export class BackgroundWidget {
34
46
  const tasks = visibleTasks(this.getTasks(), this.clock.now());
35
47
  const active = tasks.filter((task) => task.status === "running").length;
36
48
  const { theme } = this;
49
+ this.rows = tasks.map((task) => task.id);
37
50
  this.lines = [
38
51
  truncateToWidth(theme.fg("accent", `Background tasks ${active}/2`), width),
39
52
  ...tasks.map((task) => {
@@ -97,7 +97,9 @@ for (const outcome of ["success", "failure", "cancel"]) {
97
97
  });
98
98
  await session.bindExtensions({});
99
99
  await session.prompt("Earlier context to summarize: " + "background verification history ".repeat(200));
100
- await session.prompt("START_COMPACTION_JOB");
100
+ // Keep a complete earlier turn summarizable independently of the
101
+ // background tool's start-result length.
102
+ await session.prompt("START_COMPACTION_JOB " + "Recent context to keep. ".repeat(200));
101
103
  assert.equal(startedTask?.status, "running");
102
104
  assert.equal(session.isIdle, true);
103
105
  const notifications = () => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
@@ -134,6 +136,8 @@ for (const outcome of ["success", "failure", "cancel"]) {
134
136
  assert.equal(notifications().length, 1);
135
137
  assert.equal(conversationRequests().length, before + 1, "no user prompt is submitted after compact()");
136
138
  const notification = notifications()[0];
139
+ assert.doesNotMatch(notification.content, /finished during compaction/);
140
+ assert.ok(notification.content.includes(notification.details.tasks[0].log_path));
137
141
  const task = notification.details.tasks[0];
138
142
  assert.equal(task.id, startedTask.id);
139
143
  assert.equal(task.status, "failed");
@@ -15,7 +15,7 @@ function harness(mode = "tui", hasUI = true) {
15
15
  const placements = new Map();
16
16
  const statuses = new Map();
17
17
  const idleChecks = [];
18
- let tool, renders = 0, idle = true;
18
+ let tool, renders = 0, idle = true, failSend = false;
19
19
  const theme = { fg: (_color, text) => text, bold: (text) => text };
20
20
  const ctx = {
21
21
  cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
@@ -33,12 +33,16 @@ function harness(mode = "tui", hasUI = true) {
33
33
  on(name, handler) { handlers.set(name, handler); },
34
34
  registerTool(value) { tool = value; },
35
35
  registerCommand(name, value) { commands.set(name, value); },
36
- sendMessage(message, options) { messages.push({ message, options }); },
36
+ sendMessage(message, options) {
37
+ if (failSend) { failSend = false; throw new Error("Fixture delivery rejected"); }
38
+ messages.push({ message, options });
39
+ },
37
40
  };
38
- register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
41
+ register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, env: {} });
39
42
  return {
40
43
  ...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
41
44
  setIdle(value) { idle = value; },
45
+ failNextSend() { failSend = true; },
42
46
  get tool() { return tool; }, get renders() { return renders; },
43
47
  async close() {
44
48
  const closing = handlers.get("session_shutdown")({}, ctx);
@@ -71,6 +75,139 @@ test("completions during a synchronous tool are merged before the next model req
71
75
  } finally { await h.close(); }
72
76
  });
73
77
 
78
+ test("completion sends only status and log location with progressive-inspection guidance", async () => {
79
+ const h = harness("print", false);
80
+ try {
81
+ await h.handlers.get("session_start")({}, h.ctx);
82
+ h.setIdle(false);
83
+ const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
84
+ h.calls[0].onData(Buffer.from("BUILD RESULT: done\n"));
85
+ h.calls[0].resolve();
86
+ await flush();
87
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
88
+ assert.doesNotMatch(message.content, /BUILD RESULT: done|Untrusted shell output/);
89
+ assert.ok(message.content.includes(`Captured log: ${task.log_path}`));
90
+ assert.match(message.content, /Inspect logs progressively as needed/);
91
+ assert.match(message.content, /search for relevant terms or read bounded ranges/);
92
+ assert.doesNotMatch(message.content, /do not repeatedly|Do not sleep|Inspect:/);
93
+ const inspected = await h.tool.execute("inspect", { action: "output", id: task.id });
94
+ assert.equal(inspected.structuredContent.output, "BUILD RESULT: done\n");
95
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
96
+ } finally { await h.close(); }
97
+ });
98
+
99
+ test("status-only completion batches stay bounded without reading or injecting large UTF-8 logs", async () => {
100
+ const h = harness("print", false);
101
+ try {
102
+ await h.handlers.get("session_start")({}, h.ctx);
103
+ h.setIdle(false);
104
+ const ids = [];
105
+ const data = Buffer.from("🙂".repeat(3000));
106
+ for (let i = 0; i < 10; i++) {
107
+ const task = (await h.tool.execute(`start-${i}`, { action: "start", command: `build-${i}`, description: "界".repeat(200) })).structuredContent.task;
108
+ ids.push(task.id);
109
+ h.calls[i].onData(data);
110
+ h.calls[i].reject(new Error("错".repeat(500)));
111
+ await flush();
112
+ }
113
+ const delivered = [];
114
+ let batches = 0;
115
+ for (;;) {
116
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
117
+ if (!boundary) break;
118
+ assert.ok(++batches <= ids.length, "every batch must make progress");
119
+ const message = boundary.entries[0];
120
+ assert.ok(Buffer.byteLength(message.content) <= 16384);
121
+ assert.ok(!message.content.includes("\uFFFD"), "budget cuts must preserve UTF-8");
122
+ assert.ok(!message.content.includes("🙂"), "captured log bodies must not enter notifications");
123
+ assert.doesNotMatch(message.content, /Untrusted shell output|Output preview/);
124
+ delivered.push(...message.details.tasks.map((task) => task.id));
125
+ }
126
+ assert.ok(batches > 1, "long metadata must split the pending batch");
127
+ assert.deepEqual(delivered, ids);
128
+ assert.equal(h.messages.length, 0);
129
+ const inspected = await h.tool.execute("inspect", { action: "output", id: ids[0] });
130
+ assert.equal(inspected.structuredContent.task.bytes, data.length);
131
+ assert.equal(inspected.structuredContent.task.capture_complete, true);
132
+ } finally { await h.close(); }
133
+ });
134
+
135
+ test("notification does not open missing logs; later explicit inspections report errors independently", async () => {
136
+ const h = harness("print", false);
137
+ try {
138
+ await h.handlers.get("session_start")({}, h.ctx);
139
+ h.setIdle(false);
140
+ const broken = (await h.tool.execute("broken", { action: "start", command: "broken" })).structuredContent.task;
141
+ const healthy = (await h.tool.execute("healthy", { action: "start", command: "healthy" })).structuredContent.task;
142
+ h.calls[0].onData(Buffer.from("unavailable log\n"));
143
+ h.calls[1].onData(Buffer.from("healthy result\n"));
144
+ h.calls[0].resolve(7);
145
+ h.calls[1].resolve();
146
+ await flush();
147
+ unlinkSync(broken.log_path);
148
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
149
+ assert.deepEqual(message.details.tasks.map((task) => task.id), [broken.id, healthy.id]);
150
+ assert.equal(message.details.tasks[0].status, "failed");
151
+ assert.equal(message.details.tasks[0].capture_complete, true, "notification must not inspect the file or mutate capture state");
152
+ assert.ok(message.content.includes(broken.log_path));
153
+ assert.ok(message.content.includes(healthy.log_path));
154
+ assert.doesNotMatch(message.content, /healthy result|unavailable log|Output unavailable/);
155
+ const missing = await h.tool.execute("read-broken", { action: "output", id: broken.id });
156
+ assert.equal(missing.isError, true);
157
+ assert.match(missing.structuredContent.error, /Cannot read task log/);
158
+ const present = await h.tool.execute("read-healthy", { action: "output", id: healthy.id });
159
+ assert.equal(present.structuredContent.output, "healthy result\n");
160
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
161
+ } finally { await h.close(); }
162
+ });
163
+
164
+ test("a rejected idle delivery retains its result for the next safe boundary", async () => {
165
+ const h = harness("print", false);
166
+ try {
167
+ await h.handlers.get("session_start")({}, h.ctx);
168
+ const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
169
+ h.calls[0].onData(Buffer.from("retained result\n"));
170
+ h.calls[0].resolve();
171
+ await flush();
172
+ h.failNextSend();
173
+ h.clock.advance(0);
174
+ assert.equal(h.messages.length, 0);
175
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
176
+ assert.equal(message.details.tasks[0].id, task.id);
177
+ assert.ok(message.content.includes(task.log_path));
178
+ assert.doesNotMatch(message.content, /retained result/);
179
+ assert.equal((await h.tool.execute("inspect", { action: "output", id: task.id })).structuredContent.output, "retained result\n");
180
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
181
+ } finally { await h.close(); }
182
+ });
183
+
184
+ test("timeout and empty-result notifications contain status and paths, not captured output", async () => {
185
+ const h = harness("print", false);
186
+ try {
187
+ await h.handlers.get("session_start")({}, h.ctx);
188
+ h.setIdle(false);
189
+ await h.tool.execute("slow", { action: "start", command: "slow", timeout: 1 });
190
+ h.calls[0].onData(Buffer.from("partial before deadline\n"));
191
+ h.clock.advance(1000);
192
+ h.calls[0].reject(new Error("aborted"));
193
+ await flush();
194
+ const timedOut = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
195
+ assert.equal(timedOut.details.tasks[0].status, "timed_out");
196
+ assert.match(timedOut.content, /Runtime limit of 1 seconds reached/);
197
+ assert.doesNotMatch(timedOut.content, /partial before deadline/);
198
+ assert.ok(timedOut.content.includes(timedOut.details.tasks[0].log_path));
199
+ assert.equal((await h.tool.execute("read-slow", { action: "output", id: timedOut.details.tasks[0].id })).structuredContent.output, "partial before deadline\n");
200
+ await h.tool.execute("empty", { action: "start", command: "empty" });
201
+ h.calls[1].resolve();
202
+ await flush();
203
+ const empty = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
204
+ assert.ok(empty.content.includes(empty.details.tasks[0].log_path));
205
+ assert.doesNotMatch(empty.content, /\(no output\)/);
206
+ assert.equal((await h.tool.execute("read-empty", { action: "output", id: empty.details.tasks[0].id })).structuredContent.output, "");
207
+ assert.doesNotMatch(empty.content, /For logs:|For more logs:/);
208
+ } finally { await h.close(); }
209
+ });
210
+
74
211
  test("a completion during manual compaction wakes after idle without another agent boundary", async () => {
75
212
  const h = harness("print", false);
76
213
  try {
@@ -326,7 +463,8 @@ test("registration is compact, does not inject prompt rules or start session res
326
463
  try {
327
464
  assert.equal(h.tool.name, "background_task");
328
465
  assert.equal(h.tool.exposure, "model-only");
329
- assert.match(h.tool.description, /return task IDs immediately/);
466
+ assert.match(h.tool.description, /up to two concurrent background shell tasks/);
467
+ assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
330
468
  assert.ok(h.tool.description.length < 500);
331
469
  assert.equal(h.tool.promptGuidelines, undefined);
332
470
  assert.ok(h.tool.outputSchema);
@@ -338,20 +476,28 @@ test("registration is compact, does not inject prompt rules or start session res
338
476
  } finally { await h.close(); }
339
477
  });
340
478
 
341
- test("start provides non-blocking next steps in both model text and structured results", async () => {
479
+ test("start keeps only task-specific guidance while the declaration describes lifecycle and running queries", async () => {
342
480
  const h = harness();
343
481
  try {
344
482
  await h.handlers.get("session_start")({}, h.ctx);
345
483
  const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
346
- const { task, guidance } = started.structuredContent;
484
+ const { task } = started.structuredContent;
485
+ const notice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
347
486
  assert.equal(task.status, "running");
348
- assert.equal(guidance, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
349
- assert.ok(started.content[0].text.includes(guidance), "the start result must include the guidance");
350
- assert.ok(h.tool.description.includes(guidance), "the tool description must include the same guidance");
351
- assert.equal(h.tool.outputSchema.properties.guidance.type, "string");
352
- assert.equal(h.tool.outputSchema.required?.includes("guidance") ?? false, false);
487
+ assert.ok(started.content[0].text.includes(notice));
488
+ assert.ok(!started.content[0].text.includes(task.log_path));
489
+ assert.ok(!started.content[0].text.includes("session changes"));
490
+ assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
491
+ assert.match(h.tool.description, /automatic completion notifications/);
492
+ assert.match(h.tool.description, /session changes, reload, or exit/);
493
+ assert.match(h.tool.parameters.properties.action.description, /list and output also work while tasks are running/);
494
+ assert.equal(started.structuredContent.guidance, undefined);
495
+ assert.equal(h.tool.outputSchema.properties.guidance, undefined);
353
496
  const list = await h.tool.execute("list", { action: "list" });
354
497
  const output = await h.tool.execute("output", { action: "output", id: task.id });
498
+ assert.equal(list.structuredContent.tasks[0].status, "running", "status inspection does not require a completion notification");
499
+ assert.equal(output.structuredContent.task.status, "running", "log inspection is allowed before completion");
500
+ assert.equal(h.messages.length, 0, "running-task inspection does not wait for or create a notification");
355
501
  assert.equal(list.structuredContent.guidance, undefined);
356
502
  assert.equal(output.structuredContent.guidance, undefined);
357
503
  h.calls[0].resolve();
@@ -379,12 +525,12 @@ test("tools, commands, widget and idle notifications share the same session jobs
379
525
  for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
380
526
  assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
381
527
 
382
- h.calls[0].onData(Buffer.from("logs only on explicit read\n"));
528
+ h.calls[0].onData(Buffer.from("captured build output\n"));
383
529
  await h.commands.get("bg").handler(`output ${job.id}`, h.ctx);
384
- assert.match(h.messages.at(-1).message.content, /logs only on explicit read/);
530
+ assert.match(h.messages.at(-1).message.content, /captured build output/);
385
531
  assert.equal(h.messages.at(-1).options.triggerTurn, false);
386
532
  const output = await h.tool.execute("output", { action: "output", id: job.id });
387
- assert.equal(output.structuredContent.output, "logs only on explicit read\n");
533
+ assert.equal(output.structuredContent.output, "captured build output\n");
388
534
  assert.equal(output.details.output, undefined);
389
535
 
390
536
  h.calls[0].resolve(7);
@@ -394,7 +540,9 @@ test("tools, commands, widget and idle notifications share the same session jobs
394
540
  assert.equal(completed.length, 1);
395
541
  assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "steer" });
396
542
  assert.match(completed[0].message.content, /failed.*exit 7/);
397
- assert.ok(!completed[0].message.content.includes("logs only"));
543
+ assert.doesNotMatch(completed[0].message.content, /captured build output/);
544
+ assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
545
+ assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
398
546
  assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
399
547
  h.clock.advance(4999);
400
548
  assert.ok(h.widgets.has("background-tasks"));
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env python3
2
+ """Real demo jobs. Explicit release files control completion for screen recording."""
3
+ from pathlib import Path
4
+ import sys
5
+ import time
6
+
7
+ kind = sys.argv[1]
8
+ if kind not in ("build", "tests"):
9
+ raise SystemExit("expected build or tests")
10
+
11
+ print(f"Starting {kind} demo job (real local process)", flush=True)
12
+ count = 0
13
+ while not Path(f"release-{kind}").exists():
14
+ count += 1
15
+ if kind == "build":
16
+ print(f"\rCompiling module {count:03d} ...", end="", flush=True)
17
+ else:
18
+ print(f"test_{count:03d} ... passed", flush=True)
19
+ time.sleep(0.5) # Output cadence only; completion is controlled by the release file.
20
+
21
+ print("\nBUILD SUCCESSFUL" if kind == "build" else "TEST SUITE COMPLETE: one demo failure", flush=True)
22
+ raise SystemExit(0 if kind == "build" else 3)
@@ -60,7 +60,7 @@ export default function (pi: ExtensionAPI) {
60
60
  const wave = requests - 1;
61
61
  if (requests === 2) message.content.push({ type: "toolCall", id: "wait-first-wave", name: "synchronous_subagent_fixture", arguments: { wave: 0 } });
62
62
  for (let i = 0; i < 2; i++) message.content.push({ type: "toolCall", id: `start-${wave}-${i}`, name: "background_task", arguments: {
63
- action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'wave ${wave}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
63
+ action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'RESULT wave ${wave} job ${i}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
64
64
  } });
65
65
  if (requests === 2) {
66
66
  if (process.env.BG_NOTIFICATION_MODE === "codemode") message.content.push({ type: "toolCall", id: "wait-second-wave", name: "codemode", arguments: { code: "text(await tools.synchronous_subagent_fixture({ wave: 1 }));" } });
@@ -19,13 +19,17 @@ export default function (pi: ExtensionAPI) {
19
19
  queueMicrotask(() => {
20
20
  const last = context.messages.at(-1) as any;
21
21
  const text = typeof last?.content === "string" ? last.content : (last?.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n");
22
+ const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("Start two background demo jobs"));
22
23
  const tools = getCurrentTools(context.messages);
23
24
  record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
24
25
  backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description });
25
26
  const calls: { name: string; arguments: any }[] = [];
26
27
  const call = (args: any) => calls.push({ name: "background_task", arguments: args });
27
28
  if (last?.role !== "toolResult") {
28
- if (text.includes("SMOKE_START")) {
29
+ if (text.includes("Start two background demo jobs")) {
30
+ call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
31
+ call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
32
+ } else if (text.includes("SMOKE_START")) {
29
33
  call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
30
34
  call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
31
35
  call({ action: "start", command: "printf third" });
@@ -55,7 +59,10 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
55
59
  stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
56
60
  }
57
61
  } else {
58
- const reply = text.includes("[Background task finished]") ? "BACKGROUND_NOTIFICATION_RECEIVED" : "Main agent is ready; accepted background tasks keep running.";
62
+ const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with /bg." : "BACKGROUND_NOTIFICATION_RECEIVED")
63
+ : media
64
+ ? "Both demo jobs are running. Click a task row below to open its live Herdr pane; closing the pane does not stop the job."
65
+ : "Main agent is ready; accepted background tasks keep running.";
59
66
  message.content.push({ type: "text", text: reply });
60
67
  stream.push({ type: "text_start", contentIndex: 0, partial: message });
61
68
  stream.push({ type: "text_delta", contentIndex: 0, delta: reply, partial: message });