@maxiaochao/pi-background-tasks 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
- import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
1
+ import { FooterComponent, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, type Component, 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,52 +16,61 @@ export function duration(seconds: number): string {
16
16
  return `${value}s`;
17
17
  }
18
18
 
19
- export class BackgroundWidget {
20
- private lines?: string[];
21
- private width?: number;
19
+ /** Locate the exported native component through the public TUI container tree. */
20
+ export function findNativeFooter(children: Component[]): FooterComponent | undefined {
21
+ for (const child of children) {
22
+ if (child instanceof FooterComponent) return child;
23
+ if ("children" in child && Array.isArray(child.children)) {
24
+ const footer = findNativeFooter(child.children);
25
+ if (footer) return footer;
26
+ }
27
+ }
28
+ }
29
+
30
+ /** Keep native usage/model rendering; add a clickable count to its final status row. */
31
+ export class BackgroundFooter {
32
+ private hit?: { x: number; y: number; width: number };
33
+ private readonly native: Component;
22
34
  private readonly getTasks: () => TaskSnapshot[];
23
35
  private readonly clock: Clock;
24
36
  private readonly theme: Theme;
25
- private readonly onSelect?: (id: string) => void;
26
- private rows: string[] = [];
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) {
37
+ private readonly hasStatuses: () => boolean;
38
+ private readonly panelOpen: () => boolean;
39
+ private readonly onSelect: () => void;
40
+ constructor(native: Component, getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, hasStatuses: () => boolean, panelOpen: () => boolean, onSelect: () => void) {
41
+ this.native = native;
30
42
  this.getTasks = getTasks;
31
43
  this.clock = clock;
32
44
  this.theme = theme;
45
+ this.hasStatuses = hasStatuses;
46
+ this.panelOpen = panelOpen;
33
47
  this.onSelect = onSelect;
34
48
  }
35
49
 
36
50
  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);
51
+ const hit = this.hit;
52
+ if (this.panelOpen() || !hit || event.type !== "click" || event.button !== "left" || event.y !== hit.y || event.x < hit.x || event.x >= hit.x + hit.width) return;
53
+ this.onSelect();
41
54
  return { handled: true, render: false };
42
55
  }
43
56
 
44
57
  render(width: number): string[] {
45
- if (this.lines && this.width === width) return this.lines;
58
+ this.hit = undefined;
59
+ if (this.panelOpen()) return [];
60
+ const lines = this.native.render(width);
46
61
  const tasks = visibleTasks(this.getTasks(), this.clock.now());
62
+ if (!tasks.length) return lines;
47
63
  const active = tasks.filter((task) => task.status === "running").length;
48
- const { theme } = this;
49
- this.rows = tasks.map((task) => task.id);
50
- this.lines = [
51
- truncateToWidth(theme.fg("accent", `Background tasks ${active}/2`), width),
52
- ...tasks.map((task) => {
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;
64
+ const ended = tasks.length - active;
65
+ const label = `${active} ${active === 1 ? "shell" : "shells"}${ended ? ` · ${ended} done` : ""}`;
66
+ const hint = width >= visibleWidth(label) + 8 ? this.theme.fg("dim", " · Alt+J") : "";
67
+ const text = truncateToWidth(this.theme.fg("accent", label) + hint, width, "");
68
+ const status = this.hasStatuses() ? lines.pop()! : "";
69
+ const available = width - visibleWidth(text) - 3;
70
+ const prefix = status && available > 0 ? truncateToWidth(status, available, "…") + " · " : "";
71
+ this.hit = { x: visibleWidth(prefix), y: lines.length, width: Math.min(visibleWidth(label), visibleWidth(text)) };
72
+ return [...lines, prefix + text];
61
73
  }
62
74
 
63
- invalidate(): void {
64
- this.lines = undefined;
65
- this.width = undefined;
66
- }
75
+ invalidate(): void { this.hit = undefined; this.native.invalidate(); }
67
76
  }
@@ -1,29 +1,52 @@
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
+ import { FooterComponent } from "@earendil-works/pi-coding-agent";
5
6
  import register from "../extensions/background-tasks.ts";
6
7
  import { fixture, flush } from "./helpers.mjs";
7
8
 
9
+ const keys = new KeybindingsManager(TUI_KEYBINDINGS);
10
+
8
11
  function harness(mode = "tui", hasUI = true) {
9
12
  const f = fixture();
10
13
  const handlers = new Map();
11
14
  const commands = new Map();
15
+ const shortcuts = new Map();
16
+ let panel, footer;
12
17
  const messages = [];
13
18
  const notices = [];
14
19
  const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
15
- const placements = new Map();
16
20
  const statuses = new Map();
17
21
  const idleChecks = [];
18
22
  let tool, renders = 0, idle = true, failSend = false;
19
23
  const theme = { fg: (_color, text) => text, bold: (text) => text };
24
+ const native = Object.assign(Object.create(FooterComponent.prototype), {
25
+ render: (width) => ["fixture/path (main)", "↑42k fixture-model", ...(
26
+ statuses.size ? [Array.from(statuses.values()).join(" ")] : []
27
+ )].map((line) => line.slice(0, width)),
28
+ invalidate() {},
29
+ });
30
+ const container = { children: [native] };
31
+ const tui = { children: [container], requestRender() { renders++; } };
20
32
  const ctx = {
21
33
  cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
22
34
  ui: {
23
- setWidget(key, factory, options) {
35
+ setWidget(key, factory) {
24
36
  if (!factory) { widgets.delete(key); return; }
25
- widgets.set(key, factory({ requestRender() { renders++; } }, theme));
26
- placements.set(key, options);
37
+ widgets.set(key, factory(tui, theme));
38
+ },
39
+ setFooter(factory) {
40
+ footer = undefined;
41
+ container.children = [];
42
+ if (factory) footer = factory(tui, theme, { getExtensionStatuses: () => statuses });
43
+ container.children = [footer ?? native];
44
+ tui.requestRender();
45
+ },
46
+ custom(factory) {
47
+ return new Promise((resolve) => {
48
+ panel = factory({ requestRender() { renders++; } }, theme, keys, () => { panel?.dispose(); panel = undefined; resolve(); });
49
+ });
27
50
  },
28
51
  setStatus(key, value) { if (value === undefined) statuses.delete(key); else statuses.set(key, value); },
29
52
  notify(message, level) { notices.push({ message, level }); },
@@ -32,17 +55,21 @@ function harness(mode = "tui", hasUI = true) {
32
55
  const pi = {
33
56
  on(name, handler) { handlers.set(name, handler); },
34
57
  registerTool(value) { tool = value; },
58
+ registerShortcut(name, value) { shortcuts.set(name, value); },
35
59
  registerCommand(name, value) { commands.set(name, value); },
36
60
  sendMessage(message, options) {
37
61
  if (failSend) { failSend = false; throw new Error("Fixture delivery rejected"); }
38
62
  messages.push({ message, options });
39
63
  },
40
64
  };
41
- register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, env: {} });
65
+ register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
42
66
  return {
43
- ...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
67
+ ...f, handlers, commands, messages, notices, widgets, statuses, idleChecks, ctx, tui, native,
44
68
  setIdle(value) { idle = value; },
45
69
  failNextSend() { failSend = true; },
70
+ get panel() { return panel; },
71
+ get footer() { return footer; },
72
+ open() { void shortcuts.get("alt+j").handler(ctx); },
46
73
  get tool() { return tool; }, get renders() { return renders; },
47
74
  async close() {
48
75
  const closing = handlers.get("session_shutdown")({}, ctx);
@@ -63,7 +90,7 @@ test("completions during a synchronous tool are merged before the next model req
63
90
  h.calls[1].resolve(2);
64
91
  await flush();
65
92
  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"), /failed/);
93
+ assert.match(h.footer.render(140).join("\n"), /done/);
67
94
  const existing = { type: "custom", customType: "other-extension", data: { preserved: true } };
68
95
  const boundary = h.handlers.get("turn_end")({ entries: [existing], continue: true, outcome: "completed" }, h.ctx);
69
96
  assert.equal(boundary.continue, true);
@@ -344,12 +371,16 @@ test("terminal output consumed by the agent removes only that pending reminder",
344
371
  h.calls[1].resolve();
345
372
  await flush();
346
373
  await h.tool.execute("list", { action: "list" });
347
- await h.commands.get("bg").handler(`output ${b.id}`, h.ctx);
374
+ h.open();
375
+ h.panel.handleInput("\r");
376
+ assert.match(h.panel.render(140).join("\n"), /Command: second/);
377
+ h.panel.handleInput("\x1b");
378
+ await flush();
348
379
  const output = await h.tool.execute("read", { action: "output", id: a.id });
349
380
  assert.equal(output.isError, true, "a nonzero command is still a successful log read");
350
381
  const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
351
382
  assert.deepEqual(boundary.entries[0].details.tasks.map((task) => task.id), [b.id]);
352
- assert.equal(h.messages.length, 1, "only the user's inspection message was sent");
383
+ assert.equal(h.messages.length, 0, "panel inspection never adds a model message");
353
384
  } finally { await h.close(); }
354
385
  });
355
386
 
@@ -508,7 +539,7 @@ test("start keeps only task-specific guidance while the declaration describes li
508
539
  } finally { await h.close(); }
509
540
  });
510
541
 
511
- test("tools, commands, widget and idle notifications share the same session jobs", async () => {
542
+ test("tools, clean panel, bottom footer and idle notifications share the same session jobs", async () => {
512
543
  const h = harness();
513
544
  try {
514
545
  await h.handlers.get("session_start")({}, h.ctx);
@@ -519,17 +550,23 @@ test("tools, commands, widget and idle notifications share the same session jobs
519
550
  assert.equal(job.status, "running");
520
551
  parentSignal.abort();
521
552
  assert.equal(h.calls[0].signal.aborted, false, "parent turn cancellation does not own the accepted background job");
522
- assert.deepEqual(h.placements.get("background-tasks"), { placement: "aboveEditor" });
553
+ assert.equal(h.widgets.has("background-tasks"), false, "no counter above the native footer");
523
554
  h.clock.advance(1000);
524
- const widget = h.widgets.get("background-tasks");
525
- assert.match(widget.render(140).join("\n"), /1s \/ 1m/);
526
- for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
555
+ const footer = h.footer;
556
+ h.statuses.set("codex-edit", "editor: apply_patch");
557
+ assert.equal(footer.render(140).at(-1), "editor: apply_patch · 1 shell · Alt+J");
558
+ for (const width of [1, 8, 40, 80]) assert.ok(footer.render(width).every((line) => visibleWidth(line) <= width));
527
559
  assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
528
560
 
529
561
  h.calls[0].onData(Buffer.from("captured build output\n"));
530
- await h.commands.get("bg").handler(`output ${job.id}`, h.ctx);
531
- assert.match(h.messages.at(-1).message.content, /captured build output/);
532
- assert.equal(h.messages.at(-1).options.triggerTurn, false);
562
+ h.open();
563
+ assert.deepEqual(footer.render(140), [], "hide path, usage, model, editor status and shell count while inspecting");
564
+ assert.match(h.panel.render(140).join("\n"), /captured build output/);
565
+ assert.match(h.panel.render(140).join("\n"), /Runtime: 1s/);
566
+ h.panel.handleInput("\x1b");
567
+ await flush();
568
+ assert.match(footer.render(140).at(-1), /editor: apply_patch · 1 shell/);
569
+ assert.equal(h.messages.length, 0);
533
570
  const output = await h.tool.execute("output", { action: "output", id: job.id });
534
571
  assert.equal(output.structuredContent.output, "captured build output\n");
535
572
  assert.equal(output.details.output, undefined);
@@ -544,11 +581,11 @@ test("tools, commands, widget and idle notifications share the same session jobs
544
581
  assert.doesNotMatch(completed[0].message.content, /captured build output/);
545
582
  assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
546
583
  assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
547
- assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
584
+ assert.match(footer.render(140).join("\n"), /done/);
548
585
  h.clock.advance(4999);
549
- assert.ok(h.widgets.has("background-tasks"));
586
+ assert.match(footer.render(140).at(-1), /done/);
550
587
  h.clock.advance(1);
551
- assert.equal(h.widgets.has("background-tasks"), false);
588
+ assert.deepEqual(footer.render(140), h.native.render(140));
552
589
  assert.equal(h.clock.timers.size, 0);
553
590
  assert.equal((await h.tool.execute("history", { action: "output", id: job.id })).structuredContent.task.status, "failed");
554
591
  assert.ok(h.renders > 0);
@@ -567,9 +604,9 @@ test("cancel and shutdown are idempotent; new sessions cannot receive old comple
567
604
  assert.equal((await cancel).structuredContent.task.status, "cancelled");
568
605
  h.clock.advance(0);
569
606
  const count = h.messages.length;
570
- await h.commands.get("bg").handler(`cancel ${a.id}`, h.ctx);
607
+ await h.tool.execute("again", { action: "cancel", id: a.id });
571
608
  assert.equal(h.messages.filter((m) => m.message.customType === "background-task-finished").length, 1);
572
- assert.equal(h.messages.length, count + 1, "only the explicit command acknowledgement is added");
609
+ assert.equal(h.messages.length, count, "repeated cancel adds no notification");
573
610
  const shutdown = h.handlers.get("session_shutdown")({ reason: "reload" }, h.ctx);
574
611
  assert.equal(h.calls[1].signal.aborted, true);
575
612
  h.calls[1].resolve();
@@ -591,7 +628,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
591
628
  assert.equal(result.structuredContent.task.status, "running");
592
629
  assert.equal(h.widgets.has("background-tasks"), false);
593
630
  assert.equal(h.clock.timers.size, 1, "only the execution deadline exists");
594
- if (hasUI) assert.match(h.statuses.get("background-tasks"), /1\/2/);
631
+ if (hasUI) assert.match(h.statuses.get("background-tasks"), /1 shell/);
595
632
  h.calls[0].resolve();
596
633
  await flush();
597
634
  h.clock.advance(0);
@@ -602,7 +639,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
602
639
  });
603
640
  }
604
641
 
605
- test("bad actions, irrelevant fields, aborted acceptance and command syntax fail visibly", async () => {
642
+ test("bad actions, irrelevant fields and aborted acceptance fail visibly; no slash commands", async () => {
606
643
  const h = harness();
607
644
  try {
608
645
  await h.handlers.get("session_start")({}, h.ctx);
@@ -617,8 +654,7 @@ test("bad actions, irrelevant fields, aborted acceptance and command syntax fail
617
654
  }
618
655
  const abort = new AbortController(); abort.abort();
619
656
  assert.equal((await h.tool.execute("abort", { action: "start", command: "x" }, abort.signal)).isError, true);
620
- await h.commands.get("bg").handler("start echo hello", h.ctx);
621
- assert.equal(h.notices.at(-1).level, "error");
657
+ assert.equal(h.commands.size, 0);
622
658
  assert.equal(h.calls.length, 0);
623
659
  } finally { await h.close(); }
624
660
  });
@@ -640,3 +676,36 @@ for (const reason of ["new", "resume", "fork", "quit"]) {
640
676
  } finally { await h.close(); }
641
677
  });
642
678
  }
679
+
680
+ test("footer count opens one local panel; shutdown closes it and clears refresh timers", async () => {
681
+ const h = harness();
682
+ try {
683
+ await h.handlers.get("session_start")({}, h.ctx);
684
+ await h.tool.execute("a", { action: "start", command: "first" });
685
+ const footer = h.footer;
686
+ const lines = footer.render(140);
687
+ footer.handleMouse({ type: "click", button: "left", x: 1, y: lines.length - 1 });
688
+ const original = h.panel;
689
+ assert.ok(original);
690
+ h.open();
691
+ assert.equal(h.panel, original, "repeated open cannot stack interactions");
692
+ assert.match(original.render(140).join("\n"), /Command: first/);
693
+ const shutdown = h.handlers.get("session_shutdown")({}, h.ctx);
694
+ assert.equal(h.panel, undefined);
695
+ assert.equal(h.calls[0].signal.aborted, true);
696
+ h.calls[0].resolve();
697
+ await shutdown;
698
+ assert.equal(h.clock.timers.size, 0);
699
+ assert.equal(h.footer, undefined);
700
+ } finally { await h.close(); }
701
+ });
702
+
703
+ test("a pre-existing replacement footer fails visibly instead of silently losing the count", async () => {
704
+ const h = harness();
705
+ try {
706
+ h.tui.children = [{ render: () => ["another footer"], invalidate() {} }];
707
+ await assert.rejects(h.handlers.get("session_start")({}, h.ctx), /requires Pi's built-in footer/);
708
+ assert.equal(h.footer, undefined);
709
+ assert.equal(h.widgets.has("background-tasks"), false, "temporary capture widget is cleaned on failure");
710
+ } finally { await h.close(); }
711
+ });
@@ -64,9 +64,9 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
64
64
  stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
65
65
  }
66
66
  } else {
67
- const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with /bg." : "BACKGROUND_NOTIFICATION_RECEIVED")
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")
68
68
  : media
69
- ? `${tasks.size === 1 ? "One demo job is" : "Both demo jobs are"} running. Click a task row below to open its live Herdr pane; closing the pane does not stop the job.`
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.`
70
70
  : "Main agent is ready; accepted background tasks keep running.";
71
71
  message.content.push({ type: "text", text: reply });
72
72
  stream.push({ type: "text_start", contentIndex: 0, partial: message });
@@ -79,7 +79,7 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
79
79
  },
80
80
  });
81
81
  pi.on("session_start", (_event, ctx) => {
82
- 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) });
83
83
  if (ctx.hasUI) ctx.ui.setTitle("Pi Background Tasks Smoke");
84
84
  });
85
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,14 +50,14 @@ 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 a task row/);
53
+ assert.match(next.find((event) => event.type === "text_end").content, /Click the shell count/);
54
54
  });
55
55
 
56
56
  for (const [prompt, kind] of [
57
57
  ["Start one background demo job: build progress.", "build"],
58
58
  ["Start the second background demo job: a test suite.", "tests"],
59
59
  ]) {
60
- test(`offline media provider can start the ${kind} job separately for single-pane verification`, async () => {
60
+ test(`offline media provider can start the ${kind} job separately for single-shell verification`, async () => {
61
61
  let provider;
62
62
  register({ registerProvider(_name, value) { provider = value; }, on() {} });
63
63
  const events = [];