@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.
- package/CHANGELOG.md +15 -0
- package/README.md +19 -35
- package/TESTING.md +16 -21
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/shell-list.png +0 -0
- package/extensions/background-tasks.ts +29 -55
- package/package.json +2 -2
- package/src/background-tasks.ts +5 -0
- package/src/panel.ts +167 -0
- package/src/widget.ts +13 -30
- package/tests/extension.mjs +61 -19
- package/tests/fixtures/provider.ts +10 -5
- package/tests/fixtures/terminal.py +52 -0
- package/tests/load.mjs +1 -0
- package/tests/media.mjs +17 -1
- package/tests/notifications.mjs +2 -1
- package/tests/panel.mjs +144 -0
- package/tests/runtime.mjs +12 -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 -201
- package/tests/viewer.mjs +0 -252
package/src/panel.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { errorText, summary, type BackgroundTasks, type Clock, type TaskSnapshot } from "./background-tasks.ts";
|
|
5
|
+
import { duration } from "./widget.ts";
|
|
6
|
+
|
|
7
|
+
function clean(text: string): string {
|
|
8
|
+
return stripVTControlCharacters(text).replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\t/g, " ").replace(/[\x00-\x09\x0b-\x1f\x7f\uFFF9-\uFFFB]/g, "");
|
|
9
|
+
}
|
|
10
|
+
function color(task: TaskSnapshot): "accent" | "success" | "muted" | "error" {
|
|
11
|
+
return task.status === "running" ? "accent" : task.status === "succeeded" ? "success" : task.status === "cancelled" ? "muted" : "error";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** An editor-local interaction. Selection is by ID, so completion cannot retarget x. */
|
|
15
|
+
export class BackgroundPanel {
|
|
16
|
+
private readonly tasks: BackgroundTasks;
|
|
17
|
+
private readonly clock: Clock;
|
|
18
|
+
private readonly theme: Theme;
|
|
19
|
+
private readonly keys: KeybindingsManager;
|
|
20
|
+
private readonly requestRender: () => void;
|
|
21
|
+
private readonly done: () => void;
|
|
22
|
+
private selected?: string;
|
|
23
|
+
private detail = false;
|
|
24
|
+
private timer?: unknown;
|
|
25
|
+
private closed = false;
|
|
26
|
+
private stopping = new Set<string>();
|
|
27
|
+
private error?: string;
|
|
28
|
+
private rows = new Map<number, string>();
|
|
29
|
+
readonly capturesViewportInput = true;
|
|
30
|
+
|
|
31
|
+
constructor(tasks: BackgroundTasks, clock: Clock, theme: Theme, keys: KeybindingsManager, requestRender: () => void, done: () => void) {
|
|
32
|
+
this.tasks = tasks;
|
|
33
|
+
this.clock = clock;
|
|
34
|
+
this.theme = theme;
|
|
35
|
+
this.keys = keys;
|
|
36
|
+
this.requestRender = requestRender;
|
|
37
|
+
this.done = done;
|
|
38
|
+
const list = tasks.list();
|
|
39
|
+
this.selected = list.tasks[0]?.id;
|
|
40
|
+
this.detail = list.running === 1 || list.tasks.length === 1;
|
|
41
|
+
this.tick();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private tick(): void {
|
|
45
|
+
this.timer = this.clock.setTimeout(() => {
|
|
46
|
+
if (this.closed) return;
|
|
47
|
+
this.requestRender();
|
|
48
|
+
this.tick();
|
|
49
|
+
}, 1000);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
dispose(): void {
|
|
53
|
+
this.closed = true;
|
|
54
|
+
if (this.timer !== undefined) this.clock.clearTimeout(this.timer);
|
|
55
|
+
this.timer = undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private close(): void { this.dispose(); this.done(); }
|
|
59
|
+
invalidate(): void { this.rows.clear(); }
|
|
60
|
+
|
|
61
|
+
handleInput(data: string): void {
|
|
62
|
+
if (this.closed) return;
|
|
63
|
+
if (this.keys.matches(data, "tui.select.cancel") || matchesKey(data, "alt+j")) return this.close();
|
|
64
|
+
if (this.detail && (this.keys.matches(data, "tui.select.confirm") || matchesKey(data, "space"))) return this.close();
|
|
65
|
+
if (this.detail && matchesKey(data, "left")) {
|
|
66
|
+
this.detail = false;
|
|
67
|
+
} else if (matchesKey(data, "x")) {
|
|
68
|
+
void this.stop();
|
|
69
|
+
return;
|
|
70
|
+
} else if (!this.detail) {
|
|
71
|
+
const list = this.tasks.list().tasks;
|
|
72
|
+
const index = Math.max(0, list.findIndex((task) => task.id === this.selected));
|
|
73
|
+
if (this.keys.matches(data, "tui.select.up")) this.selected = list[Math.max(0, index - 1)]?.id;
|
|
74
|
+
else if (this.keys.matches(data, "tui.select.down")) this.selected = list[Math.min(list.length - 1, index + 1)]?.id;
|
|
75
|
+
else if (this.keys.matches(data, "tui.select.confirm") && this.selected) this.detail = true;
|
|
76
|
+
else return;
|
|
77
|
+
} else return;
|
|
78
|
+
this.error = undefined;
|
|
79
|
+
this.requestRender();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
83
|
+
if (this.closed || this.detail || event.type !== "click" || event.button !== "left") return;
|
|
84
|
+
const id = this.rows.get(event.y);
|
|
85
|
+
if (!id) return;
|
|
86
|
+
this.selected = id;
|
|
87
|
+
this.detail = true;
|
|
88
|
+
this.error = undefined;
|
|
89
|
+
return { handled: true, render: true };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private async stop(): Promise<void> {
|
|
93
|
+
const id = this.selected;
|
|
94
|
+
if (!id || this.stopping.has(id) || this.tasks.get(id).status !== "running") return;
|
|
95
|
+
this.stopping.add(id);
|
|
96
|
+
this.requestRender();
|
|
97
|
+
try { await this.tasks.cancel(id); }
|
|
98
|
+
catch (error) { this.error = errorText(error); }
|
|
99
|
+
finally {
|
|
100
|
+
this.stopping.delete(id);
|
|
101
|
+
if (!this.closed) this.requestRender();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
render(width: number): string[] {
|
|
106
|
+
this.rows.clear();
|
|
107
|
+
const inner = Math.max(1, width - 4);
|
|
108
|
+
const body = this.detail && this.selected ? this.details(inner, this.tasks.get(this.selected)) : this.list(inner);
|
|
109
|
+
if (this.error) body.push(this.theme.fg("error", this.error));
|
|
110
|
+
return [this.theme.fg("accent", "─".repeat(Math.max(0, width))), ...body.map((line) => line ? truncateToWidth(` ${line}`, width) : ""), ""];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private list(width: number): string[] {
|
|
114
|
+
const { theme } = this;
|
|
115
|
+
const list = this.tasks.list();
|
|
116
|
+
if (!list.tasks.some((task) => task.id === this.selected)) this.selected = list.tasks[0]?.id;
|
|
117
|
+
const lines = [theme.fg("accent", theme.bold("Background")), theme.fg("muted", `${list.running} active ${list.running === 1 ? "shell" : "shells"}`), ""];
|
|
118
|
+
// Bound history height, keeping the selected task visible without losing its ID.
|
|
119
|
+
const index = Math.max(0, list.tasks.findIndex((task) => task.id === this.selected));
|
|
120
|
+
const start = Math.max(0, index - 7);
|
|
121
|
+
const visible = list.tasks.slice(start, start + 8);
|
|
122
|
+
const labelWidth = Math.max(1, ...visible.map((task) => visibleWidth(summary(this.tasks.command(task.id)))));
|
|
123
|
+
let history = false;
|
|
124
|
+
for (const task of visible) {
|
|
125
|
+
if (task.status !== "running" && !history) {
|
|
126
|
+
lines.push("", ` Earlier in this session (${list.total - list.running})`);
|
|
127
|
+
history = true;
|
|
128
|
+
}
|
|
129
|
+
this.rows.set(lines.length + 1, task.id); // Top rule occupies row zero.
|
|
130
|
+
const label = summary(this.tasks.command(task.id));
|
|
131
|
+
const status = this.stopping.has(task.id) ? "stopping" : task.status;
|
|
132
|
+
const commandWidth = Math.max(1, Math.min(labelWidth, 64, width - status.length - 6));
|
|
133
|
+
lines.push(`${task.id === this.selected ? theme.fg("accent", "❯") : " "} ${theme.fg(color(task), "●")}${truncateToWidth(label, commandWidth, "…", true)} ${theme.fg(color(task), status)}`);
|
|
134
|
+
}
|
|
135
|
+
if (!history) lines.push("", ` Earlier in this session (${list.total - list.running})`);
|
|
136
|
+
if (!list.total) lines.push(theme.fg("muted", "No shells in this session"));
|
|
137
|
+
if (list.tasks.length > visible.length || list.omitted) lines.push(theme.fg("dim", `Showing ${start + 1}–${start + visible.length} of ${list.tasks.length}${list.omitted ? ` · ${list.omitted} older tasks omitted` : ""}`));
|
|
138
|
+
const selected = list.tasks.find((task) => task.id === this.selected);
|
|
139
|
+
lines.push("", theme.fg("dim", `↑/↓ to select · Enter to view${selected?.status === "running" ? " · x to stop" : ""} · Esc to close`));
|
|
140
|
+
return lines;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private details(width: number, task: TaskSnapshot): string[] {
|
|
144
|
+
const { theme } = this;
|
|
145
|
+
const field = (name: string, value: string) => `${theme.bold(name.padEnd(10))}${value}`;
|
|
146
|
+
const commandLines = wrapTextWithAnsi(clean(this.tasks.command(task.id)).slice(0, 8192), Math.max(1, width - 10));
|
|
147
|
+
const command = commandLines.slice(0, 3);
|
|
148
|
+
if (commandLines.length > 3 || this.tasks.command(task.id).length > 8192) command[command.length - 1] = truncateToWidth(command.at(-1)! + "…", Math.max(1, width - 10), "…");
|
|
149
|
+
const lines = [theme.fg("accent", theme.bold("Shell details")), "",
|
|
150
|
+
field("Status:", theme.fg(color(task), this.stopping.has(task.id) ? "stopping" : task.status)),
|
|
151
|
+
field("Runtime:", duration(task.elapsed_seconds)),
|
|
152
|
+
field("Command:", command[0] ?? ""), ...command.slice(1).map((line) => " " + line)];
|
|
153
|
+
if (task.exit_code !== undefined) lines.push(field("Exit:", String(task.exit_code)));
|
|
154
|
+
if (task.reason) lines.push(field("Reason:", clean(task.reason)));
|
|
155
|
+
lines.push("", theme.bold("Output:"));
|
|
156
|
+
try {
|
|
157
|
+
const view = this.tasks.output(task.id);
|
|
158
|
+
const output = clean(view.output).replace(/\n$/, "");
|
|
159
|
+
const tail = output ? output.split("\n") : [];
|
|
160
|
+
lines.push(...(tail.length ? tail.slice(-10).map((line) => truncateToWidth(line, width)) : [theme.fg("muted", "No output available")]));
|
|
161
|
+
if (view.truncated || tail.length > 10) lines.push(theme.fg("dim", `Tail only · ${task.log_path}`));
|
|
162
|
+
if (task.status !== "running" && !view.capture_complete) lines.push(theme.fg("error", "Output capture is incomplete."));
|
|
163
|
+
} catch (error) { lines.push(theme.fg("error", errorText(error))); }
|
|
164
|
+
lines.push("", theme.fg("dim", `← to go back · Esc/Enter/Space to close${task.status === "running" ? " · x to stop" : ""}`));
|
|
165
|
+
return lines;
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/widget.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { truncateToWidth, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
2
|
+
import { truncateToWidth, visibleWidth, 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";
|
|
@@ -16,17 +16,14 @@ export function duration(seconds: number): string {
|
|
|
16
16
|
return `${value}s`;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/** Compact, clickable shell count below the editor. The native footer stays intact. */
|
|
19
20
|
export class BackgroundWidget {
|
|
20
|
-
private
|
|
21
|
-
private width?: number;
|
|
21
|
+
private hitWidth = 0;
|
|
22
22
|
private readonly getTasks: () => TaskSnapshot[];
|
|
23
23
|
private readonly clock: Clock;
|
|
24
24
|
private readonly theme: Theme;
|
|
25
|
-
private readonly onSelect
|
|
26
|
-
|
|
27
|
-
|
|
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) {
|
|
25
|
+
private readonly onSelect: () => void;
|
|
26
|
+
constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, onSelect: () => void) {
|
|
30
27
|
this.getTasks = getTasks;
|
|
31
28
|
this.clock = clock;
|
|
32
29
|
this.theme = theme;
|
|
@@ -34,34 +31,20 @@ export class BackgroundWidget {
|
|
|
34
31
|
}
|
|
35
32
|
|
|
36
33
|
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
if (!id) return;
|
|
40
|
-
this.onSelect(id);
|
|
34
|
+
if (event.type !== "click" || event.button !== "left" || event.y !== 0 || event.x < 0 || event.x >= this.hitWidth) return;
|
|
35
|
+
this.onSelect();
|
|
41
36
|
return { handled: true, render: false };
|
|
42
37
|
}
|
|
43
38
|
|
|
44
39
|
render(width: number): string[] {
|
|
45
|
-
if (this.lines && this.width === width) return this.lines;
|
|
46
40
|
const tasks = visibleTasks(this.getTasks(), this.clock.now());
|
|
47
41
|
const active = tasks.filter((task) => task.status === "running").length;
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
this.
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const color = task.status === "running" ? "accent" : task.status === "succeeded" ? "success" : task.status === "cancelled" ? "muted" : "error";
|
|
54
|
-
const marker = task.status === "running" ? "●" : task.status === "succeeded" ? "✓" : task.status === "cancelled" ? "○" : "✗";
|
|
55
|
-
const elapsed = ((task.ended_at ?? this.clock.now()) - task.started_at) / 1000;
|
|
56
|
-
return truncateToWidth(` ${theme.fg(color, marker)} ${theme.fg("accent", task.id)} · ${duration(elapsed)} / ${duration(task.timeout)} · ${theme.fg(color, task.status)} · ${theme.fg("text", task.description)}`, width);
|
|
57
|
-
}),
|
|
58
|
-
];
|
|
59
|
-
this.width = width;
|
|
60
|
-
return this.lines;
|
|
42
|
+
const ended = tasks.length - active;
|
|
43
|
+
const label = `${active} ${active === 1 ? "shell" : "shells"}${ended ? ` · ${ended} done` : ""}`;
|
|
44
|
+
const text = truncateToWidth(this.theme.fg("accent", label), width);
|
|
45
|
+
this.hitWidth = tasks.length ? visibleWidth(text) : 0;
|
|
46
|
+
return [truncateToWidth(`${text}${this.theme.fg("dim", " · Alt+J")}`, width)];
|
|
61
47
|
}
|
|
62
48
|
|
|
63
|
-
invalidate(): void {
|
|
64
|
-
this.lines = undefined;
|
|
65
|
-
this.width = undefined;
|
|
66
|
-
}
|
|
49
|
+
invalidate(): void { this.hitWidth = 0; }
|
|
67
50
|
}
|
package/tests/extension.mjs
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { unlinkSync } from "node:fs";
|
|
3
3
|
import { test } from "node:test";
|
|
4
|
-
import { visibleWidth } from "@earendil-works/pi-tui";
|
|
4
|
+
import { KeybindingsManager, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
|
|
5
5
|
import register from "../extensions/background-tasks.ts";
|
|
6
6
|
import { fixture, flush } from "./helpers.mjs";
|
|
7
7
|
|
|
8
|
+
const keys = new KeybindingsManager(TUI_KEYBINDINGS);
|
|
9
|
+
|
|
8
10
|
function harness(mode = "tui", hasUI = true) {
|
|
9
11
|
const f = fixture();
|
|
10
12
|
const handlers = new Map();
|
|
11
13
|
const commands = new Map();
|
|
14
|
+
const shortcuts = new Map();
|
|
15
|
+
let panel;
|
|
12
16
|
const messages = [];
|
|
13
17
|
const notices = [];
|
|
14
18
|
const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
|
|
@@ -25,6 +29,11 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
25
29
|
widgets.set(key, factory({ requestRender() { renders++; } }, theme));
|
|
26
30
|
placements.set(key, options);
|
|
27
31
|
},
|
|
32
|
+
custom(factory) {
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
panel = factory({ requestRender() { renders++; } }, theme, keys, () => { panel?.dispose(); panel = undefined; resolve(); });
|
|
35
|
+
});
|
|
36
|
+
},
|
|
28
37
|
setStatus(key, value) { if (value === undefined) statuses.delete(key); else statuses.set(key, value); },
|
|
29
38
|
notify(message, level) { notices.push({ message, level }); },
|
|
30
39
|
},
|
|
@@ -32,17 +41,20 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
32
41
|
const pi = {
|
|
33
42
|
on(name, handler) { handlers.set(name, handler); },
|
|
34
43
|
registerTool(value) { tool = value; },
|
|
44
|
+
registerShortcut(name, value) { shortcuts.set(name, value); },
|
|
35
45
|
registerCommand(name, value) { commands.set(name, value); },
|
|
36
46
|
sendMessage(message, options) {
|
|
37
47
|
if (failSend) { failSend = false; throw new Error("Fixture delivery rejected"); }
|
|
38
48
|
messages.push({ message, options });
|
|
39
49
|
},
|
|
40
50
|
};
|
|
41
|
-
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root
|
|
51
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
|
|
42
52
|
return {
|
|
43
53
|
...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
|
|
44
54
|
setIdle(value) { idle = value; },
|
|
45
55
|
failNextSend() { failSend = true; },
|
|
56
|
+
get panel() { return panel; },
|
|
57
|
+
open() { void shortcuts.get("alt+j").handler(ctx); },
|
|
46
58
|
get tool() { return tool; }, get renders() { return renders; },
|
|
47
59
|
async close() {
|
|
48
60
|
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
@@ -63,7 +75,7 @@ test("completions during a synchronous tool are merged before the next model req
|
|
|
63
75
|
h.calls[1].resolve(2);
|
|
64
76
|
await flush();
|
|
65
77
|
assert.equal(h.messages.length, 0, "busy completions must not enter an irrevocable host queue");
|
|
66
|
-
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /
|
|
78
|
+
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /done/);
|
|
67
79
|
const existing = { type: "custom", customType: "other-extension", data: { preserved: true } };
|
|
68
80
|
const boundary = h.handlers.get("turn_end")({ entries: [existing], continue: true, outcome: "completed" }, h.ctx);
|
|
69
81
|
assert.equal(boundary.continue, true);
|
|
@@ -344,12 +356,16 @@ test("terminal output consumed by the agent removes only that pending reminder",
|
|
|
344
356
|
h.calls[1].resolve();
|
|
345
357
|
await flush();
|
|
346
358
|
await h.tool.execute("list", { action: "list" });
|
|
347
|
-
|
|
359
|
+
h.open();
|
|
360
|
+
h.panel.handleInput("\r");
|
|
361
|
+
assert.match(h.panel.render(140).join("\n"), /Command: second/);
|
|
362
|
+
h.panel.handleInput("\x1b");
|
|
363
|
+
await flush();
|
|
348
364
|
const output = await h.tool.execute("read", { action: "output", id: a.id });
|
|
349
365
|
assert.equal(output.isError, true, "a nonzero command is still a successful log read");
|
|
350
366
|
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
351
367
|
assert.deepEqual(boundary.entries[0].details.tasks.map((task) => task.id), [b.id]);
|
|
352
|
-
assert.equal(h.messages.length,
|
|
368
|
+
assert.equal(h.messages.length, 0, "panel inspection never adds a model message");
|
|
353
369
|
} finally { await h.close(); }
|
|
354
370
|
});
|
|
355
371
|
|
|
@@ -465,6 +481,7 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
465
481
|
assert.equal(h.tool.exposure, "model-only");
|
|
466
482
|
assert.match(h.tool.description, /up to two concurrent background shell tasks/);
|
|
467
483
|
assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
|
|
484
|
+
assert.equal(h.tool.parameters.properties.command.description, "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.");
|
|
468
485
|
assert.ok(h.tool.description.length < 500);
|
|
469
486
|
assert.equal(h.tool.promptGuidelines, undefined);
|
|
470
487
|
assert.ok(h.tool.outputSchema);
|
|
@@ -482,7 +499,7 @@ test("start keeps only task-specific guidance while the declaration describes li
|
|
|
482
499
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
483
500
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
484
501
|
const { task } = started.structuredContent;
|
|
485
|
-
const notice = "Completion is reported automatically. Continue other work or end the turn; do not
|
|
502
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
486
503
|
assert.equal(task.status, "running");
|
|
487
504
|
assert.ok(started.content[0].text.includes(notice));
|
|
488
505
|
assert.ok(!started.content[0].text.includes(task.log_path));
|
|
@@ -507,7 +524,7 @@ test("start keeps only task-specific guidance while the declaration describes li
|
|
|
507
524
|
} finally { await h.close(); }
|
|
508
525
|
});
|
|
509
526
|
|
|
510
|
-
test("tools,
|
|
527
|
+
test("tools, panel, widget and idle notifications share the same session jobs", async () => {
|
|
511
528
|
const h = harness();
|
|
512
529
|
try {
|
|
513
530
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
@@ -518,17 +535,20 @@ test("tools, commands, widget and idle notifications share the same session jobs
|
|
|
518
535
|
assert.equal(job.status, "running");
|
|
519
536
|
parentSignal.abort();
|
|
520
537
|
assert.equal(h.calls[0].signal.aborted, false, "parent turn cancellation does not own the accepted background job");
|
|
521
|
-
assert.deepEqual(h.placements.get("background-tasks"), { placement: "
|
|
538
|
+
assert.deepEqual(h.placements.get("background-tasks"), { placement: "belowEditor" });
|
|
522
539
|
h.clock.advance(1000);
|
|
523
540
|
const widget = h.widgets.get("background-tasks");
|
|
524
|
-
assert.match(widget.render(140).join("\n"), /
|
|
541
|
+
assert.match(widget.render(140).join("\n"), /1 shell/);
|
|
525
542
|
for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
|
|
526
543
|
assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
|
|
527
544
|
|
|
528
545
|
h.calls[0].onData(Buffer.from("captured build output\n"));
|
|
529
|
-
|
|
530
|
-
assert.match(h.
|
|
531
|
-
assert.
|
|
546
|
+
h.open();
|
|
547
|
+
assert.match(h.panel.render(140).join("\n"), /captured build output/);
|
|
548
|
+
assert.match(h.panel.render(140).join("\n"), /Runtime: 1s/);
|
|
549
|
+
h.panel.handleInput("\x1b");
|
|
550
|
+
await flush();
|
|
551
|
+
assert.equal(h.messages.length, 0);
|
|
532
552
|
const output = await h.tool.execute("output", { action: "output", id: job.id });
|
|
533
553
|
assert.equal(output.structuredContent.output, "captured build output\n");
|
|
534
554
|
assert.equal(output.details.output, undefined);
|
|
@@ -543,7 +563,7 @@ test("tools, commands, widget and idle notifications share the same session jobs
|
|
|
543
563
|
assert.doesNotMatch(completed[0].message.content, /captured build output/);
|
|
544
564
|
assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
|
|
545
565
|
assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
|
|
546
|
-
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /
|
|
566
|
+
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /done/);
|
|
547
567
|
h.clock.advance(4999);
|
|
548
568
|
assert.ok(h.widgets.has("background-tasks"));
|
|
549
569
|
h.clock.advance(1);
|
|
@@ -566,9 +586,9 @@ test("cancel and shutdown are idempotent; new sessions cannot receive old comple
|
|
|
566
586
|
assert.equal((await cancel).structuredContent.task.status, "cancelled");
|
|
567
587
|
h.clock.advance(0);
|
|
568
588
|
const count = h.messages.length;
|
|
569
|
-
await h.
|
|
589
|
+
await h.tool.execute("again", { action: "cancel", id: a.id });
|
|
570
590
|
assert.equal(h.messages.filter((m) => m.message.customType === "background-task-finished").length, 1);
|
|
571
|
-
assert.equal(h.messages.length, count
|
|
591
|
+
assert.equal(h.messages.length, count, "repeated cancel adds no notification");
|
|
572
592
|
const shutdown = h.handlers.get("session_shutdown")({ reason: "reload" }, h.ctx);
|
|
573
593
|
assert.equal(h.calls[1].signal.aborted, true);
|
|
574
594
|
h.calls[1].resolve();
|
|
@@ -590,7 +610,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
|
|
|
590
610
|
assert.equal(result.structuredContent.task.status, "running");
|
|
591
611
|
assert.equal(h.widgets.has("background-tasks"), false);
|
|
592
612
|
assert.equal(h.clock.timers.size, 1, "only the execution deadline exists");
|
|
593
|
-
if (hasUI) assert.match(h.statuses.get("background-tasks"), /1
|
|
613
|
+
if (hasUI) assert.match(h.statuses.get("background-tasks"), /1 shell/);
|
|
594
614
|
h.calls[0].resolve();
|
|
595
615
|
await flush();
|
|
596
616
|
h.clock.advance(0);
|
|
@@ -601,7 +621,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
|
|
|
601
621
|
});
|
|
602
622
|
}
|
|
603
623
|
|
|
604
|
-
test("bad actions, irrelevant fields
|
|
624
|
+
test("bad actions, irrelevant fields and aborted acceptance fail visibly; no slash commands", async () => {
|
|
605
625
|
const h = harness();
|
|
606
626
|
try {
|
|
607
627
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
@@ -616,8 +636,7 @@ test("bad actions, irrelevant fields, aborted acceptance and command syntax fail
|
|
|
616
636
|
}
|
|
617
637
|
const abort = new AbortController(); abort.abort();
|
|
618
638
|
assert.equal((await h.tool.execute("abort", { action: "start", command: "x" }, abort.signal)).isError, true);
|
|
619
|
-
|
|
620
|
-
assert.equal(h.notices.at(-1).level, "error");
|
|
639
|
+
assert.equal(h.commands.size, 0);
|
|
621
640
|
assert.equal(h.calls.length, 0);
|
|
622
641
|
} finally { await h.close(); }
|
|
623
642
|
});
|
|
@@ -639,3 +658,26 @@ for (const reason of ["new", "resume", "fork", "quit"]) {
|
|
|
639
658
|
} finally { await h.close(); }
|
|
640
659
|
});
|
|
641
660
|
}
|
|
661
|
+
|
|
662
|
+
test("widget opens one local panel; shutdown closes it and clears refresh timers", async () => {
|
|
663
|
+
const h = harness();
|
|
664
|
+
try {
|
|
665
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
666
|
+
await h.tool.execute("a", { action: "start", command: "first" });
|
|
667
|
+
const widget = h.widgets.get("background-tasks");
|
|
668
|
+
widget.render(140);
|
|
669
|
+
widget.handleMouse({ type: "click", button: "left", x: 1, y: 0 });
|
|
670
|
+
const original = h.panel;
|
|
671
|
+
assert.ok(original);
|
|
672
|
+
h.open();
|
|
673
|
+
assert.equal(h.panel, original, "repeated open cannot stack interactions");
|
|
674
|
+
assert.match(original.render(140).join("\n"), /Command: first/);
|
|
675
|
+
const shutdown = h.handlers.get("session_shutdown")({}, h.ctx);
|
|
676
|
+
assert.equal(h.panel, undefined);
|
|
677
|
+
assert.equal(h.calls[0].signal.aborted, true);
|
|
678
|
+
h.calls[0].resolve();
|
|
679
|
+
await shutdown;
|
|
680
|
+
assert.equal(h.clock.timers.size, 0);
|
|
681
|
+
assert.equal(h.widgets.has("background-tasks"), false);
|
|
682
|
+
} finally { await h.close(); }
|
|
683
|
+
});
|
|
@@ -19,16 +19,21 @@ 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("
|
|
22
|
+
const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("background demo job"));
|
|
23
23
|
const tools = getCurrentTools(context.messages);
|
|
24
24
|
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
25
|
-
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description
|
|
25
|
+
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description,
|
|
26
|
+
backgroundCommandDescription: tools.find((tool) => tool.name === "background_task")?.parameters?.properties?.command?.description });
|
|
26
27
|
const calls: { name: string; arguments: any }[] = [];
|
|
27
28
|
const call = (args: any) => calls.push({ name: "background_task", arguments: args });
|
|
28
29
|
if (last?.role !== "toolResult") {
|
|
29
30
|
if (text.includes("Start two background demo jobs")) {
|
|
30
31
|
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
31
32
|
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
33
|
+
} else if (text.includes("Start one background demo job")) {
|
|
34
|
+
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
35
|
+
} else if (text.includes("Start the second background demo job")) {
|
|
36
|
+
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
32
37
|
} else if (text.includes("SMOKE_START")) {
|
|
33
38
|
call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
|
|
34
39
|
call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
|
|
@@ -59,9 +64,9 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
|
59
64
|
stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
|
|
60
65
|
}
|
|
61
66
|
} else {
|
|
62
|
-
const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with
|
|
67
|
+
const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with Alt+J." : "BACKGROUND_NOTIFICATION_RECEIVED")
|
|
63
68
|
: media
|
|
64
|
-
? "Both demo jobs are running. Click
|
|
69
|
+
? `${tasks.size === 1 ? "One demo job is" : "Both demo jobs are"} running. Click the shell count below to inspect live output; closing the panel does not stop the job.`
|
|
65
70
|
: "Main agent is ready; accepted background tasks keep running.";
|
|
66
71
|
message.content.push({ type: "text", text: reply });
|
|
67
72
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
|
@@ -74,7 +79,7 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
|
74
79
|
},
|
|
75
80
|
});
|
|
76
81
|
pi.on("session_start", (_event, ctx) => {
|
|
77
|
-
record({ event: "loaded", tools: pi.getAllTools().map((tool) => tool.name) });
|
|
82
|
+
record({ event: "loaded", tools: pi.getAllTools().map((tool) => tool.name), commands: pi.getCommands().map((command) => command.name) });
|
|
78
83
|
if (ctx.hasUI) ctx.ui.setTitle("Pi Background Tasks Smoke");
|
|
79
84
|
});
|
|
80
85
|
pi.on("agent_settled", () => record({ event: "settled" }));
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""JSON-lines bridge between a real Pi PTY and the browser media recorder."""
|
|
3
|
+
import base64
|
|
4
|
+
import fcntl
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import pty
|
|
8
|
+
import select
|
|
9
|
+
import signal
|
|
10
|
+
import struct
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import termios
|
|
14
|
+
|
|
15
|
+
master, slave = pty.openpty()
|
|
16
|
+
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 36, 130, 0, 0))
|
|
17
|
+
child = subprocess.Popen(sys.argv[1:], stdin=slave, stdout=slave, stderr=slave, start_new_session=True)
|
|
18
|
+
os.close(slave)
|
|
19
|
+
pending = b''
|
|
20
|
+
try:
|
|
21
|
+
while child.poll() is None:
|
|
22
|
+
readable, _, _ = select.select([master, sys.stdin.buffer], [], [], 0.1)
|
|
23
|
+
if master in readable:
|
|
24
|
+
try:
|
|
25
|
+
data = os.read(master, 65536)
|
|
26
|
+
except OSError:
|
|
27
|
+
break
|
|
28
|
+
if not data:
|
|
29
|
+
break
|
|
30
|
+
print(json.dumps({'output': base64.b64encode(data).decode()}), flush=True)
|
|
31
|
+
if sys.stdin.buffer in readable:
|
|
32
|
+
chunk = os.read(sys.stdin.fileno(), 65536)
|
|
33
|
+
if not chunk:
|
|
34
|
+
break
|
|
35
|
+
pending += chunk
|
|
36
|
+
while b'\n' in pending:
|
|
37
|
+
line, pending = pending.split(b'\n', 1)
|
|
38
|
+
message = json.loads(line)
|
|
39
|
+
if 'input' in message:
|
|
40
|
+
os.write(master, message['input'].encode())
|
|
41
|
+
if 'size' in message:
|
|
42
|
+
cols, rows = message['size']
|
|
43
|
+
fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0))
|
|
44
|
+
finally:
|
|
45
|
+
if child.poll() is None:
|
|
46
|
+
child.send_signal(signal.SIGTERM)
|
|
47
|
+
try:
|
|
48
|
+
child.wait(timeout=10)
|
|
49
|
+
except subprocess.TimeoutExpired:
|
|
50
|
+
child.kill()
|
|
51
|
+
child.wait()
|
|
52
|
+
os.close(master)
|
package/tests/load.mjs
CHANGED
|
@@ -22,6 +22,7 @@ try {
|
|
|
22
22
|
const events = readFileSync(join(directory, "events.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
23
|
const loaded = events.find((entry) => entry.event === "loaded");
|
|
24
24
|
assert.equal(loaded.tools.filter((name) => name === "background_task").length, 1, "the real host registered exactly one background-task tool");
|
|
25
|
+
assert.ok(!loaded.commands.includes("bg"), "the host has no background-task slash command");
|
|
25
26
|
const request = events.find((entry) => entry.event === "request");
|
|
26
27
|
assert.equal(request.tools.filter((name) => name === "background_task").length, 1, "background_task is active in the model request without manual activation");
|
|
27
28
|
console.log(`Real Pi loaded ${toolkit ? "the toolkit default loadout" : "the standalone background-task extension"} with exactly one background-task tool and an offline fixture provider.`);
|
package/tests/media.mjs
CHANGED
|
@@ -50,5 +50,21 @@ test("offline media provider issues exactly two direct background starts, then r
|
|
|
50
50
|
const next = [];
|
|
51
51
|
for await (const event of provider.streamSimple(model, { messages: [user, { role: "toolResult", toolCallId: calls[1].id, toolName: "background_task", content: [{ type: "text", text: "Started" }] }] })) next.push(event);
|
|
52
52
|
assert.equal(next.filter((event) => event.type === "toolcall_end").length, 0);
|
|
53
|
-
assert.match(next.find((event) => event.type === "text_end").content, /Click
|
|
53
|
+
assert.match(next.find((event) => event.type === "text_end").content, /Click the shell count/);
|
|
54
54
|
});
|
|
55
|
+
|
|
56
|
+
for (const [prompt, kind] of [
|
|
57
|
+
["Start one background demo job: build progress.", "build"],
|
|
58
|
+
["Start the second background demo job: a test suite.", "tests"],
|
|
59
|
+
]) {
|
|
60
|
+
test(`offline media provider can start the ${kind} job separately for single-shell verification`, async () => {
|
|
61
|
+
let provider;
|
|
62
|
+
register({ registerProvider(_name, value) { provider = value; }, on() {} });
|
|
63
|
+
const events = [];
|
|
64
|
+
for await (const event of provider.streamSimple({ api: "bg-fixture", provider: "bg-fixture", id: "deterministic" }, { messages: [{ role: "user", content: prompt }] })) events.push(event);
|
|
65
|
+
const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
|
|
66
|
+
assert.equal(calls.length, 1);
|
|
67
|
+
assert.equal(calls[0].name, "background_task");
|
|
68
|
+
assert.equal(calls[0].arguments.command, `python3 demo-job.py ${kind}`);
|
|
69
|
+
});
|
|
70
|
+
}
|
package/tests/notifications.mjs
CHANGED
|
@@ -22,10 +22,11 @@ test("native model receives distinct declaration and start guidance without Code
|
|
|
22
22
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
23
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
24
|
assert.equal(started.isError, false);
|
|
25
|
-
const notice = "Completion is reported automatically. Continue other work or end the turn; do not
|
|
25
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
26
26
|
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
27
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
28
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
|
+
assert.match(requests[0].backgroundCommandDescription, /Stdout\/stderr are saved to a unique per-task log; its path is reported on completion\./);
|
|
29
30
|
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
30
31
|
assert.match(requests[0].backgroundDescription, /session changes, reload, or exit/);
|
|
31
32
|
assert.ok(!requests[0].backgroundDescription.includes(notice));
|