@maxiaochao/pi-background-tasks 0.3.1 → 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/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 lines?: string[];
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?: (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) {
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 (!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);
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 { 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;
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
  }
@@ -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, env: {} });
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"), /failed/);
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
- await h.commands.get("bg").handler(`output ${b.id}`, h.ctx);
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, 1, "only the user's inspection message was sent");
368
+ assert.equal(h.messages.length, 0, "panel inspection never adds a model message");
353
369
  } finally { await h.close(); }
354
370
  });
355
371
 
@@ -508,7 +524,7 @@ test("start keeps only task-specific guidance while the declaration describes li
508
524
  } finally { await h.close(); }
509
525
  });
510
526
 
511
- test("tools, commands, widget and idle notifications share the same session jobs", async () => {
527
+ test("tools, panel, widget and idle notifications share the same session jobs", async () => {
512
528
  const h = harness();
513
529
  try {
514
530
  await h.handlers.get("session_start")({}, h.ctx);
@@ -519,17 +535,20 @@ test("tools, commands, widget and idle notifications share the same session jobs
519
535
  assert.equal(job.status, "running");
520
536
  parentSignal.abort();
521
537
  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" });
538
+ assert.deepEqual(h.placements.get("background-tasks"), { placement: "belowEditor" });
523
539
  h.clock.advance(1000);
524
540
  const widget = h.widgets.get("background-tasks");
525
- assert.match(widget.render(140).join("\n"), /1s \/ 1m/);
541
+ assert.match(widget.render(140).join("\n"), /1 shell/);
526
542
  for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
527
543
  assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
528
544
 
529
545
  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);
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);
533
552
  const output = await h.tool.execute("output", { action: "output", id: job.id });
534
553
  assert.equal(output.structuredContent.output, "captured build output\n");
535
554
  assert.equal(output.details.output, undefined);
@@ -544,7 +563,7 @@ test("tools, commands, widget and idle notifications share the same session jobs
544
563
  assert.doesNotMatch(completed[0].message.content, /captured build output/);
545
564
  assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
546
565
  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/);
566
+ assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /done/);
548
567
  h.clock.advance(4999);
549
568
  assert.ok(h.widgets.has("background-tasks"));
550
569
  h.clock.advance(1);
@@ -567,9 +586,9 @@ test("cancel and shutdown are idempotent; new sessions cannot receive old comple
567
586
  assert.equal((await cancel).structuredContent.task.status, "cancelled");
568
587
  h.clock.advance(0);
569
588
  const count = h.messages.length;
570
- await h.commands.get("bg").handler(`cancel ${a.id}`, h.ctx);
589
+ await h.tool.execute("again", { action: "cancel", id: a.id });
571
590
  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");
591
+ assert.equal(h.messages.length, count, "repeated cancel adds no notification");
573
592
  const shutdown = h.handlers.get("session_shutdown")({ reason: "reload" }, h.ctx);
574
593
  assert.equal(h.calls[1].signal.aborted, true);
575
594
  h.calls[1].resolve();
@@ -591,7 +610,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
591
610
  assert.equal(result.structuredContent.task.status, "running");
592
611
  assert.equal(h.widgets.has("background-tasks"), false);
593
612
  assert.equal(h.clock.timers.size, 1, "only the execution deadline exists");
594
- if (hasUI) assert.match(h.statuses.get("background-tasks"), /1\/2/);
613
+ if (hasUI) assert.match(h.statuses.get("background-tasks"), /1 shell/);
595
614
  h.calls[0].resolve();
596
615
  await flush();
597
616
  h.clock.advance(0);
@@ -602,7 +621,7 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
602
621
  });
603
622
  }
604
623
 
605
- test("bad actions, irrelevant fields, aborted acceptance and command syntax fail visibly", async () => {
624
+ test("bad actions, irrelevant fields and aborted acceptance fail visibly; no slash commands", async () => {
606
625
  const h = harness();
607
626
  try {
608
627
  await h.handlers.get("session_start")({}, h.ctx);
@@ -617,8 +636,7 @@ test("bad actions, irrelevant fields, aborted acceptance and command syntax fail
617
636
  }
618
637
  const abort = new AbortController(); abort.abort();
619
638
  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");
639
+ assert.equal(h.commands.size, 0);
622
640
  assert.equal(h.calls.length, 0);
623
641
  } finally { await h.close(); }
624
642
  });
@@ -640,3 +658,26 @@ for (const reason of ["new", "resume", "fork", "quit"]) {
640
658
  } finally { await h.close(); }
641
659
  });
642
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
+ });
@@ -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 = [];
@@ -0,0 +1,144 @@
1
+ import assert from "node:assert/strict";
2
+ import { unlinkSync, readFileSync } from "node:fs";
3
+ import { test } from "node:test";
4
+ import { KeybindingsManager, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { BackgroundPanel } from "../src/panel.ts";
6
+ import { BackgroundWidget } from "../src/widget.ts";
7
+ import { fixture, flush } from "./helpers.mjs";
8
+
9
+ const keys = new KeybindingsManager(TUI_KEYBINDINGS);
10
+ const theme = { fg: (_color, text) => text, bold: (text) => text };
11
+ const click = (x, y, button = "left") => ({ type: "click", button, x, y });
12
+ function panel(f) {
13
+ let renders = 0, closed = 0;
14
+ const view = new BackgroundPanel(f.tasks, f.clock, theme, keys, () => renders++, () => closed++);
15
+ return { view, text: (width = 120) => view.render(width).join("\n"), get renders() { return renders; }, get closed() { return closed; } };
16
+ }
17
+
18
+ test("compact count, singular/plural, five-second retention and bounded mouse hit region", async () => {
19
+ const f = fixture();
20
+ try {
21
+ f.tasks.start({ command: "first" }, f.root);
22
+ let opened = 0;
23
+ const widget = new BackgroundWidget(() => f.tasks.list().tasks, f.clock, theme, () => opened++);
24
+ assert.deepEqual(widget.render(120), ["1 shell · Alt+J"]);
25
+ assert.equal(widget.handleMouse(click(7, 0)), undefined);
26
+ assert.equal(widget.handleMouse(click(2, 1)), undefined);
27
+ assert.equal(widget.handleMouse(click(2, 0, "right")), undefined);
28
+ assert.equal(widget.handleMouse(click(2, 0)).handled, true);
29
+ assert.equal(opened, 1);
30
+ f.tasks.start({ command: "second" }, f.root);
31
+ assert.match(widget.render(120)[0], /^2 shells/);
32
+ f.calls[1].resolve(3); await flush();
33
+ assert.match(widget.render(120)[0], /^1 shell · 1 done/);
34
+ f.clock.advance(5000);
35
+ assert.equal(widget.render(120)[0], "1 shell · Alt+J");
36
+ for (const width of [0, 1, 8, 40]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
37
+ } finally { await f.close(); }
38
+ });
39
+
40
+ test("single shell opens aligned details; full original multiline command is separate from metadata", async () => {
41
+ const f = fixture(); let p;
42
+ try {
43
+ const command = 'printf "hello"\nprintf "中文"';
44
+ const task = f.tasks.start({ command, description: "Short label" }, f.root);
45
+ assert.equal(f.tasks.command(task.id), command);
46
+ assert.equal(task.command, undefined);
47
+ p = panel(f);
48
+ assert.match(p.text(), /Shell details\n\n Status: running\n Runtime: 0s\n Command: printf "hello"\n printf "中文"\n\n Output:\n No output available/);
49
+ f.clock.advance(209000);
50
+ assert.match(p.text(), /Runtime: 3m 29s/);
51
+ assert.ok(p.renders > 0);
52
+ p.view.handleInput("\x1b[D");
53
+ assert.match(p.text(), /Background\n 1 active shell/);
54
+ p.view.handleInput("\r");
55
+ assert.match(p.text(), /Shell details/);
56
+ p.view.handleInput(" ");
57
+ assert.equal(p.closed, 1);
58
+ assert.equal(f.calls[0].signal.aborted, false, "closing only dismisses the view");
59
+ assert.equal(f.clock.timers.size, 1, "only the job deadline remains");
60
+ } finally { p?.view.dispose(); await f.close(); }
61
+ });
62
+
63
+ test("multiple shells: arrow selection, click, identity across completion, x stops only selected job", async () => {
64
+ const f = fixture(); let p;
65
+ try {
66
+ const a = f.tasks.start({ command: "first" }, f.root);
67
+ const b = f.tasks.start({ command: "second" }, f.root);
68
+ p = panel(f);
69
+ assert.match(p.text(), /Background\n 2 active shells/);
70
+ assert.match(p.text(), /❯ ●first/);
71
+ p.view.handleInput("\x1b[B");
72
+ assert.match(p.text(), /❯ ●second/);
73
+ f.calls[0].resolve(); await flush();
74
+ assert.match(p.text(), /❯ ●second/);
75
+ p.view.handleInput("\r");
76
+ assert.match(p.text(), /Command: second/);
77
+ p.view.handleInput("x"); p.view.handleInput("x");
78
+ assert.equal(f.calls[1].signal.aborted, true);
79
+ assert.equal(f.calls[0].signal.aborted, false);
80
+ assert.match(p.text(), /Status: stopping/);
81
+ f.calls[1].reject(new Error("cancelled")); await flush();
82
+ assert.equal(f.tasks.get(b.id).status, "cancelled");
83
+ assert.doesNotMatch(p.text(), /x to stop/);
84
+ p.view.handleInput("\x1b[D");
85
+ const lines = p.view.render(120);
86
+ assert.match(lines.join("\n"), /Earlier in this session \(2\)/);
87
+ const row = lines.findIndex((line) => line.includes("●first"));
88
+ assert.equal(p.view.handleMouse(click(4, 1)), undefined);
89
+ assert.equal(p.view.handleMouse(click(4, row)).handled, true);
90
+ assert.match(p.text(), /Command: first/);
91
+ assert.equal(f.tasks.get(a.id).status, "succeeded");
92
+ } finally { p?.view.dispose(); await f.close(); }
93
+ });
94
+
95
+ test("bounded, sanitized output, long command wrapping, error states and narrow/CJK widths", async () => {
96
+ const f = fixture(); let p;
97
+ try {
98
+ const task = f.tasks.start({ command: "echo 中文".repeat(1000) }, f.root);
99
+ p = panel(f);
100
+ f.calls[0].onData(Buffer.from("\x1b]52;c;c2VjcmV0\x07\x1b[31mRED\x1b[0m\uFFF9\n" + Array.from({ length: 120 }, (_, i) => `line ${i}`).join("\n")));
101
+ const text = p.text();
102
+ assert.match(text, /…/);
103
+ assert.match(text, /line 119/);
104
+ assert.doesNotMatch(text, /line 109|\x1b|\uFFF9/);
105
+ assert.match(text, /Tail only/);
106
+ for (const width of [0, 1, 8, 20, 40, 80, 120]) assert.ok(p.view.render(width).every((line) => visibleWidth(line) <= width), `width ${width}`);
107
+ f.calls[0].resolve(4); await flush();
108
+ assert.match(p.text(), /Status: failed/);
109
+ assert.match(p.text(), /Exit: 4/);
110
+ assert.match(p.text(), /Reason: Command exited with code 4/);
111
+ unlinkSync(task.log_path);
112
+ assert.match(p.text(), /Cannot read task log/);
113
+ } finally { p?.view.dispose(); await f.close(); }
114
+ });
115
+
116
+ test("empty state, history paging, stable selected completed ID, timer disposal", async () => {
117
+ const f = fixture(); let p;
118
+ try {
119
+ p = panel(f);
120
+ assert.match(p.text(), /No shells in this session/);
121
+ p.view.handleInput("x"); p.view.handleInput("\r");
122
+ for (let i = 0; i < 25; i++) {
123
+ f.tasks.start({ command: `job ${i}` }, f.root);
124
+ f.calls.at(-1).resolve(); await flush();
125
+ }
126
+ assert.match(p.text(), /Earlier in this session \(25\)/);
127
+ for (let i = 0; i < 19; i++) p.view.handleInput("\x1b[B");
128
+ assert.match(p.text(), /❯ ●job 5/);
129
+ assert.match(p.text(), /5 older tasks omitted/);
130
+ p.view.handleInput("\r");
131
+ assert.match(p.text(), /Command: job 5/);
132
+ p.view.handleInput("\r");
133
+ assert.equal(p.closed, 1);
134
+ assert.equal(f.clock.timers.size, 0);
135
+ const renders = p.renders;
136
+ f.clock.advance(3000);
137
+ assert.equal(p.renders, renders);
138
+ } finally { p?.view.dispose(); await f.close(); }
139
+ });
140
+
141
+ test("production extension registers no slash command and has no Herdr execution dependency", () => {
142
+ const source = readFileSync(new URL("../extensions/background-tasks.ts", import.meta.url), "utf8");
143
+ assert.doesNotMatch(source, /registerCommand|Herdr|herdr|\/bg/);
144
+ });
@@ -28,12 +28,12 @@ render = os.environ.get('BG_SMOKE_RENDER') == '1'
28
28
  capture = os.environ.get('BG_SMOKE_CAPTURE') == '1'
29
29
  env = dict(os.environ, PI_CODING_AGENT_DIR=str(work), PI_OFFLINE='1', BG_SMOKE_EVENTS=str(events_path), TERM='xterm-256color', COLORTERM='truecolor')
30
30
  env.pop('PI_HERDR_SUBAGENTS_CHILD', None)
31
- env.pop('HERDR_ENV', None) # Keep this smoke run's widget-only path; Herdr views are covered by viewer.mjs.
31
+ # Task UI is local and independent of terminal host.
32
32
  (work / 'settings.json').write_text(json.dumps({'quietStartup': True}))
33
33
  args = ['--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session', '--offline',
34
34
  '-e', 'builtin:codemode', '-e', str(PKG / 'extensions/background-tasks.ts'),
35
35
  '-e', str(ROOT / 'packages/scheduler/extensions/scheduler.ts'), '-e', str(PKG / 'tests/fixtures/provider.ts'),
36
- '--tools', 'codemode,background_task,schedule', '--model', 'bg-fixture/deterministic', '--tui-mode', 'fullscreen']
36
+ '--tools', 'codemode,background_task,schedule', '--model', 'bg-fixture/deterministic', '--tui-mode', os.environ.get('BG_SMOKE_TUI_MODE', 'fullscreen')]
37
37
  size = os.get_terminal_size(sys.stdout.fileno()) if render else os.terminal_size((140, 42))
38
38
  terminal_settings = termios.tcgetattr(sys.stdin.fileno()) if render else None
39
39
  if render:
@@ -143,7 +143,13 @@ try:
143
143
  wait(lambda: len([e for e in events() if e.get('event') == 'settled']) > settled_count, 'foreground turn completion')
144
144
  assert not finished('succeeded'), 'Sleeping job must survive foreground turn completion'
145
145
  shot('running')
146
- send('/bg output ' + first['id'])
146
+ child.send('\x1bj')
147
+ wait(lambda: 'active shells' in raw, 'shell list')
148
+ child.send('\r')
149
+ wait(lambda: 'Shell details' in raw, 'shell details')
150
+ shot('details')
151
+ child.send('\x1b')
152
+ pump(0.2)
147
153
  send('SMOKE_CANCEL')
148
154
  wait(lambda: bool(finished('cancelled')), 'cancel notification')
149
155
  wait(lambda: bool(finished('succeeded')), 'successful background notification')
@@ -183,7 +189,7 @@ try:
183
189
  assert all(not Path(path).exists() for path in logs), 'Session logs were not removed'
184
190
  (OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
185
191
  (OUT / 'result.json').write_text(json.dumps({'passed': True, 'screenshots': screens,
186
- 'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', '/bg output',
192
+ 'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', 'Alt+J list/details',
187
193
  'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
188
194
  '5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
189
195
  except Exception:
package/docs/demo.webm DELETED
Binary file
Binary file
package/src/herdr.ts DELETED
@@ -1,38 +0,0 @@
1
- import { spawn } from "node:child_process";
2
-
3
- /** One Herdr CLI call: arguments in, parsed `result` object out. */
4
- export type HerdrCall = (args: string[]) => Promise<Record<string, any>>;
5
-
6
- export class HerdrError extends Error {
7
- readonly code?: string;
8
- constructor(message: string, code?: string) {
9
- super(message);
10
- this.name = "HerdrError";
11
- this.code = code;
12
- }
13
- }
14
-
15
- export function isMissing(error: unknown): boolean {
16
- return error instanceof HerdrError && /^(tab|pane)_not_found$/.test(error.code ?? "");
17
- }
18
-
19
- /** Spawns the Herdr CLI without a shell. A hung call fails after `timeoutMs`. */
20
- export function cliHerdr(binary = "herdr", timeoutMs = 10_000): HerdrCall {
21
- return (args) => new Promise((resolve, reject) => {
22
- let stdout = "";
23
- let stderr = "";
24
- const child = spawn(binary, args, { stdio: ["ignore", "pipe", "pipe"], shell: false, signal: AbortSignal.timeout(timeoutMs) });
25
- child.stdout.on("data", (chunk) => { stdout += chunk; });
26
- child.stderr.on("data", (chunk) => { stderr += chunk; });
27
- child.once("error", (error) => reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${error.message}`)));
28
- child.once("close", (code) => {
29
- let parsed: { result?: Record<string, any>; error?: { code?: string; message?: string } } | undefined;
30
- try { parsed = JSON.parse(stdout); } catch { /* Reported below. */ }
31
- if (code === 0 && parsed?.result) return resolve(parsed.result);
32
- // Some commands, such as `pane run`, succeed without printing a response.
33
- if (code === 0 && !stdout.trim()) return resolve({});
34
- const detail = parsed?.error?.message ?? (stderr.trim() || stdout.trim() || `exit code ${code}`);
35
- reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${detail}`, parsed?.error?.code));
36
- });
37
- });
38
- }