@maxiaochao/pi-background-tasks 0.5.0 → 0.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-11-26 - v0.5.1
4
+
5
+ - Compose footer statuses safely and prevent foreground waiting after background starts
6
+ - Restore an explicit post-start guard: automatic completion resumes the agent, while Bash sleeps, log tails, and `list`/`output` calls used only to wait are prohibited.
7
+ - Publish shell counts through Pi's keyed status interface and keep the clickable footer as a best-effort decorator.
8
+ - Compose arbitrary peer statuses without extension-specific rules, drop the shortcut hint before truncating peer state, and keep shell counts visible on narrow rows.
9
+ - Degrade safely when another extension owns or replaces the footer; preserve Alt+J access and never clear a later footer during reload or shutdown.
10
+ - Remove the unnecessary one-second TUI repaint timer while tasks are only running.
11
+
3
12
  ## 2026-11-25 - v0.5.0
4
13
 
5
14
  - Add 30-minute aggregate progress turns and concise automatic-completion guidance
package/README.md CHANGED
@@ -43,7 +43,7 @@ The model-visible tool description is:
43
43
 
44
44
  Each accepted start returns only its task data and this short, task-specific reminder:
45
45
 
46
- > Completion is reported automatically. Continue independent work, or end the turn if none remains.
46
+ > Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.
47
47
 
48
48
  The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
49
49
 
@@ -74,7 +74,7 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
74
74
 
75
75
  ## User controls and status
76
76
 
77
- A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status row**, beside `editor: apply_patch` or other extension statuses. Without another status, it occupies that row alone. The existing native path, usage and model rows stay unchanged. Click the count in fullscreen mode, or press **Alt+J** in either terminal mode. One active task opens **Shell details** directly; multiple tasks open **Background**. With no active tasks, Alt+J still opens retained history.
77
+ A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status row**, beside `editor: apply_patch` or any other extension statuses. The counter is always published through Pi's keyed status interface. A best-effort footer decorator keeps peer statuses in stable key order, pins the shell count after them, and adds click handling without naming specific extensions. Without another status, the count occupies that row alone. The existing native path, usage and model rows stay unchanged. Click the count in fullscreen mode, or press **Alt+J** in either terminal mode. One active task opens **Shell details** directly; multiple tasks open **Background**. With no active tasks, Alt+J still opens retained history.
78
78
 
79
79
  - **List:** ↑/↓ selects a shell, Enter opens its details, and clicking a task row opens that task. Running tasks appear first, followed by **Earlier in this session**. At most eight task rows are visible; selection scrolls the retained history (latest 20 finished tasks).
80
80
  - **Details:** `Status:`, `Runtime:` and `Command:` share a fixed value column. The command preview folds script line breaks and indentation into spaces, then wraps continuously to the panel width, up to three visual lines with an ellipsis. This is a display-only summary; the executed script is unchanged. **Output:** shows the last ten captured lines, clipped to the current width, refreshed every second. Empty output says `No output available`; truncated tails show the log path for further inspection. Finished tasks also show their exit code, reason and incomplete-capture warning when applicable.
@@ -84,7 +84,7 @@ A compact **`1 shell` / `N shells`** counter sits on the **bottom footer status
84
84
 
85
85
  The preview is intentionally bounded, not a full log viewer. Use the retained log path for earlier output or long lines. Commands have no TTY, so TTY-only colour and progress rendering may be absent. Other extensions' widgets remain intact.
86
86
 
87
- The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter. Extensions that also replace the entire footer are therefore not composable: a replacement present at startup produces an explicit extension error, and one installed later can replace this footer. Use the built-in footer with `setStatus()` extensions such as Codex Edit. A host-provided composable/clickable status API would remove this constraint.
87
+ The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter, so the decorator is optional rather than authoritative. If another extension already owns the footer, Background Tasks keeps publishing its keyed status and leaves that footer untouched. If another extension replaces the decorator later, disposal releases ownership so reload or shutdown cannot clobber the new footer. `Alt+J` remains available in both cases. Click handling and hiding the whole footer while the panel is open require the decorator; a foreign footer that ignores Pi extension statuses may also omit the counter. A host-provided OMP-style keyed status-item interface with priority and click actions would remove this remaining constraint.
88
88
 
89
89
  ## Progress turns
90
90
 
package/TESTING.md CHANGED
@@ -13,8 +13,8 @@ Tests use Node's built-in test runner. They resolve host peers from the installe
13
13
  - `tasks.mjs`: fake execution and clock at the task-manager interface; immediate return, two slots, validation, timeout/cancel races, final failure, disk budgets, write errors, bounded history and shutdown.
14
14
  - `output.mjs`: compares the shared 100-line/8-KiB preview with the real host Bash tool’s output, retaining unchanged small-output display parity and deliberately tighter truncation for large output. Covers line/byte limits, long lines, empty output, missing final newline, UTF-8 split across chunks, invalid UTF-8 and logs larger than 1 MiB. Checks both return paths carry the same tail, omission metadata reports total size, and full captured bytes remain on disk. The former Bash-sized display/1-MiB structured contract is retired; each retained fixture now verifies the bounded replacement.
15
15
  - `processes.mjs`: the native backend, a multi-line Python log check, non-blocking concurrency, PID-observed process-tree cleanup, silent busy-loop timeout and the default 32 MiB disk limit.
16
- - `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks one aggregate progress turn after 30 fake minutes, byte deltas without log contents, timer reset by a new parent run, completion precedence, interruption cleanup, the exact three-sentence tool description, fixed `model-only` exposure, no prompt guidelines, and explicit running-task `list`/`output` availability.
17
- - `panel.mjs`: singular/plural counter, mouse hit region, screenshot-style field alignment, compact continuous command previews, unchanged execution of original multiline scripts, CR/LF and indentation folding, preserved inline spaces, post-folding length limits, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
16
+ - `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. It verifies keyed-status fallback with a pre-existing foreign footer, safe self-detachment when a later footer replaces the decorator, and no running-task repaint timer. Checks one aggregate progress turn after 30 fake minutes, byte deltas without log contents, timer reset by a new parent run, completion precedence, interruption cleanup, the exact three-sentence tool description, the explicit end-turn/no-sleep start reminder, fixed `model-only` exposure, no prompt guidelines, and running-task `list`/`output` availability when inspection is actually needed.
17
+ - `panel.mjs`: singular/plural counter, arbitrary peer-status ordering and sanitization, narrow-width priority, mouse hit region, screenshot-style field alignment, compact continuous command previews, unchanged execution of original multiline scripts, CR/LF and indentation folding, preserved inline spaces, post-folding length limits, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
18
18
  - `media.mjs`: actual demo Python jobs stream in-place/line output and exit with 0/3 only after explicit release files; the offline provider issues exactly two direct starts, then returns without polling. This tests the fixtures used by the real recorder, not an invented screen.
19
19
  - `notifications.mjs`: isolated real Pi with model-issued background calls, default one-at-a-time queues and an offline provider. Sequential blocking fixtures hold one native tool batch open across two waves of actual failing shell jobs. The blocking fixture runs directly or through native Codemode, but background calls always come from the model. The next model request gets one merged notification for four completions, excluding reminders for zero, one or two first-wave terminal outputs read directly by the model before the boundary; no output bodies are attached to any completion notice; no extra requests follow the final report. An accelerated production registration also proves that real Pi receives repeated idle progress turns before the real shell completes, then receives one completion turn. Also verifies distinct declaration/start guidance without a Codemode suffix and that native Codemode cannot discover or call `background_task`. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
20
20
  - `compaction.mjs`: isolated native Pi SDK sessions call `session.compact()`, the same manual-compaction entry point used by `/compact` and RPC. Real shell jobs exit during a held offline summary request. Covers successful native compaction, a provider summary error and `abortCompaction()` cancellation; each must retain the pending completion while busy and automatically deliver status/log-location metadata once afterward, without another user prompt. Checks actual compaction lifecycle/events, saved compaction entries, completion timestamps/logs and exactly one automatic conversation request. Uses real timers and native `isIdle`/`isCompacting`, not injected busy state or replacement compaction results; no paid model call or TUI keyboard invocation of `/compact`. `BG_TEST_EXTENSION` also supports a negative-control extension.
@@ -5,10 +5,10 @@ import { stripVTControlCharacters } from "node:util";
5
5
  import { Type } from "typebox";
6
6
  import { BackgroundTasks, errorText, summary, systemClock, type Clock, type TaskSnapshot } from "../src/background-tasks.ts";
7
7
  import { BackgroundPanel } from "../src/panel.ts";
8
- import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
8
+ import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, taskStatusLabel, visibleTasks } from "../src/widget.ts";
9
9
 
10
10
  const actions = ["start", "list", "output", "cancel"] as const;
11
- const startNotice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
11
+ const startNotice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
12
12
  const PROGRESS_INTERVAL_MS = 30 * 60_000;
13
13
  // Bound model-visible status text when many completions accumulate.
14
14
  const NOTIFICATION_MAX_BYTES = 16 * 1024;
@@ -238,14 +238,16 @@ export default function (pi: ExtensionAPI, dependencies: {
238
238
  return;
239
239
  }
240
240
  const visible = visibleTasks(list.tasks, clock.now());
241
+ context.ui.setStatus(WIDGET_KEY, taskStatusLabel(visible));
241
242
  mounted?.footer.invalidate();
242
243
  mounted?.tui.requestRender();
243
- if (visible.length === 0) {
244
+ const finished = visible.filter((task) => task.ended_at !== undefined);
245
+ if (finished.length === 0) {
244
246
  clearTimer();
245
247
  return;
246
248
  }
247
249
  if (timer === undefined) {
248
- const delay = Math.min(1000, ...visible.filter((task) => task.ended_at !== undefined).map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
250
+ const delay = Math.min(...finished.map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
249
251
  timer = clock.setTimeout(() => { timer = undefined; refresh(); }, Math.max(1, delay));
250
252
  }
251
253
  };
@@ -264,12 +266,13 @@ export default function (pi: ExtensionAPI, dependencies: {
264
266
  progressBytes.clear();
265
267
  completedNormally = true;
266
268
  interrupted = false;
269
+ const activeFooter = mounted;
270
+ mounted = undefined;
267
271
  try {
268
272
  if (previousContext?.hasUI) {
269
273
  previousContext.ui.setStatus(WIDGET_KEY, undefined);
270
- if (previousContext.mode === "tui" && mounted) previousContext.ui.setFooter(undefined);
274
+ if (activeFooter) previousContext.ui.setFooter(undefined);
271
275
  }
272
- mounted = undefined;
273
276
  } finally {
274
277
  await previous?.shutdown();
275
278
  }
@@ -302,10 +305,13 @@ export default function (pi: ExtensionAPI, dependencies: {
302
305
  try {
303
306
  ctx.ui.setWidget(WIDGET_KEY, (tui) => {
304
307
  const native = findNativeFooter(tui.children);
305
- if (!native) throw new Error("Background Tasks requires Pi's built-in footer; another extension has replaced it.");
308
+ if (!native) return { render: () => [], invalidate() {} };
306
309
  ctx.ui.setFooter((footerTui, theme, data) => {
307
- const footer = new BackgroundFooter(native, () => manager?.list().tasks ?? [], clock, theme,
308
- () => data.getExtensionStatuses().size > 0, () => panel !== undefined, () => { void openPanel(); });
310
+ let footer: BackgroundFooter;
311
+ footer = new BackgroundFooter(native, theme, () => data.getExtensionStatuses(),
312
+ () => panel !== undefined, () => { void openPanel(); }, () => {
313
+ if (mounted?.footer === footer) mounted = undefined;
314
+ });
309
315
  mounted = { footer, tui: footerTui };
310
316
  return footer;
311
317
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxiaochao/pi-background-tasks",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Session-scoped background shell tasks with progress and completion notifications for Pi.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/widget.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { FooterComponent, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth, visibleWidth, type Component, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
3
- import type { Clock, TaskSnapshot } from "./background-tasks.ts";
3
+ import type { TaskSnapshot } from "./background-tasks.ts";
4
4
 
5
5
  export const WIDGET_KEY = "background-tasks";
6
6
  export const FINISHED_VISIBLE_MS = 5000;
@@ -9,6 +9,13 @@ export function visibleTasks(tasks: TaskSnapshot[], now: number): TaskSnapshot[]
9
9
  return tasks.filter((task) => task.status === "running" || (task.ended_at !== undefined && now < task.ended_at + FINISHED_VISIBLE_MS));
10
10
  }
11
11
 
12
+ export function taskStatusLabel(tasks: TaskSnapshot[]): string | undefined {
13
+ if (!tasks.length) return undefined;
14
+ const active = tasks.filter((task) => task.status === "running").length;
15
+ const ended = tasks.length - active;
16
+ return `${active} ${active === 1 ? "shell" : "shells"}${ended ? ` · ${ended} done` : ""}`;
17
+ }
18
+
12
19
  export function duration(seconds: number): string {
13
20
  const value = Math.max(0, Math.floor(seconds));
14
21
  if (value >= 3600) return `${Math.floor(value / 3600)}h${value % 3600 ? ` ${Math.floor(value % 3600 / 60)}m` : ""}`;
@@ -27,24 +34,27 @@ export function findNativeFooter(children: Component[]): FooterComponent | undef
27
34
  }
28
35
  }
29
36
 
37
+ function sanitizeStatusText(text: string): string {
38
+ return text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim();
39
+ }
40
+
30
41
  /** Keep native usage/model rendering; add a clickable count to its final status row. */
31
42
  export class BackgroundFooter {
32
43
  private hit?: { x: number; y: number; width: number };
33
44
  private readonly native: Component;
34
- private readonly getTasks: () => TaskSnapshot[];
35
- private readonly clock: Clock;
36
45
  private readonly theme: Theme;
37
- private readonly hasStatuses: () => boolean;
46
+ private readonly getStatuses: () => ReadonlyMap<string, string>;
38
47
  private readonly panelOpen: () => boolean;
39
48
  private readonly onSelect: () => void;
40
- constructor(native: Component, getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, hasStatuses: () => boolean, panelOpen: () => boolean, onSelect: () => void) {
49
+ private readonly onDispose: () => void;
50
+ private disposed = false;
51
+ constructor(native: Component, theme: Theme, getStatuses: () => ReadonlyMap<string, string>, panelOpen: () => boolean, onSelect: () => void, onDispose: () => void = () => {}) {
41
52
  this.native = native;
42
- this.getTasks = getTasks;
43
- this.clock = clock;
44
53
  this.theme = theme;
45
- this.hasStatuses = hasStatuses;
54
+ this.getStatuses = getStatuses;
46
55
  this.panelOpen = panelOpen;
47
56
  this.onSelect = onSelect;
57
+ this.onDispose = onDispose;
48
58
  }
49
59
 
50
60
  handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
@@ -58,19 +68,53 @@ export class BackgroundFooter {
58
68
  this.hit = undefined;
59
69
  if (this.panelOpen()) return [];
60
70
  const lines = this.native.render(width);
61
- const tasks = visibleTasks(this.getTasks(), this.clock.now());
62
- if (!tasks.length) return lines;
63
- const active = tasks.filter((task) => task.status === "running").length;
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];
71
+ const statuses = this.getStatuses();
72
+ const label = sanitizeStatusText(statuses.get(WIDGET_KEY) ?? "");
73
+ if (visibleWidth(label) === 0) return lines;
74
+ lines.pop();
75
+
76
+ const separator = this.theme.fg("dim", " · ");
77
+ const peers = [...statuses.entries()]
78
+ .filter(([key]) => key !== WIDGET_KEY)
79
+ .sort(([left], [right]) => left.localeCompare(right))
80
+ .map(([, text]) => sanitizeStatusText(text))
81
+ .filter((text) => visibleWidth(text) > 0)
82
+ .join(separator);
83
+ const styledLabel = this.theme.fg("accent", label);
84
+ const hint = this.theme.fg("dim", " · Alt+J");
85
+ let prefix = "";
86
+ const renderedLabel = truncateToWidth(styledLabel, width, "");
87
+ let suffix = renderedLabel;
88
+
89
+ if (visibleWidth(renderedLabel) === visibleWidth(label)) {
90
+ if (peers) {
91
+ const withoutHint = peers + separator + renderedLabel;
92
+ if (visibleWidth(withoutHint + hint) <= width) {
93
+ prefix = peers + separator;
94
+ suffix = renderedLabel + hint;
95
+ } else if (visibleWidth(withoutHint) <= width) {
96
+ prefix = peers + separator;
97
+ } else {
98
+ const available = width - visibleWidth(renderedLabel) - visibleWidth(separator);
99
+ const truncatedPeers = truncateToWidth(peers, available, "…");
100
+ if (visibleWidth(truncatedPeers) > 1) prefix = truncatedPeers + separator;
101
+ }
102
+ } else if (visibleWidth(renderedLabel + hint) <= width) {
103
+ suffix = renderedLabel + hint;
104
+ }
105
+ }
106
+
107
+ const hitWidth = visibleWidth(renderedLabel);
108
+ if (hitWidth > 0) this.hit = { x: visibleWidth(prefix), y: lines.length, width: hitWidth };
109
+ return [...lines, prefix + suffix];
73
110
  }
74
111
 
75
112
  invalidate(): void { this.hit = undefined; this.native.invalidate(); }
113
+
114
+ dispose(): void {
115
+ if (this.disposed) return;
116
+ this.disposed = true;
117
+ this.hit = undefined;
118
+ this.onDispose();
119
+ }
76
120
  }
@@ -19,11 +19,11 @@ function harness(mode = "tui", hasUI = true, dependencies = {}) {
19
19
  const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
20
20
  const statuses = new Map();
21
21
  const idleChecks = [];
22
- let tool, renders = 0, idle = true, failSend = false;
22
+ let tool, renders = 0, footerChanges = 0, idle = true, failSend = false;
23
23
  const theme = { fg: (_color, text) => text, bold: (text) => text };
24
24
  const native = Object.assign(Object.create(FooterComponent.prototype), {
25
25
  render: (width) => ["fixture/path (main)", "↑42k fixture-model", ...(
26
- statuses.size ? [Array.from(statuses.values()).join(" ")] : []
26
+ statuses.size ? [[...statuses.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, text]) => text).join(" ")] : []
27
27
  )].map((line) => line.slice(0, width)),
28
28
  invalidate() {},
29
29
  });
@@ -37,10 +37,12 @@ function harness(mode = "tui", hasUI = true, dependencies = {}) {
37
37
  widgets.set(key, factory(tui, theme));
38
38
  },
39
39
  setFooter(factory) {
40
+ footer?.dispose?.();
40
41
  footer = undefined;
41
42
  container.children = [];
42
43
  if (factory) footer = factory(tui, theme, { getExtensionStatuses: () => statuses });
43
44
  container.children = [footer ?? native];
45
+ footerChanges++;
44
46
  tui.requestRender();
45
47
  },
46
48
  custom(factory) {
@@ -69,6 +71,7 @@ function harness(mode = "tui", hasUI = true, dependencies = {}) {
69
71
  failNextSend() { failSend = true; },
70
72
  get panel() { return panel; },
71
73
  get footer() { return footer; },
74
+ get footerChanges() { return footerChanges; },
72
75
  open() { void shortcuts.get("alt+j").handler(ctx); },
73
76
  get tool() { return tool; }, get renders() { return renders; },
74
77
  async close() {
@@ -620,9 +623,12 @@ test("start keeps concise task-specific guidance while the declaration describes
620
623
  await h.handlers.get("session_start")({}, h.ctx);
621
624
  const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
622
625
  const { task } = started.structuredContent;
623
- const notice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
626
+ const notice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
624
627
  assert.equal(task.status, "running");
625
628
  assert.ok(started.content[0].text.includes(notice));
629
+ assert.match(started.content[0].text, /end the turn now/);
630
+ assert.match(started.content[0].text, /Do not call Bash sleep/);
631
+ assert.match(started.content[0].text, /list\/output solely to wait/);
626
632
  assert.ok(!started.content[0].text.includes(task.log_path));
627
633
  assert.ok(!started.content[0].text.includes("session changes"));
628
634
  assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
@@ -657,6 +663,7 @@ test("tools, clean panel, bottom footer and idle notifications share the same se
657
663
  parentSignal.abort();
658
664
  assert.equal(h.calls[0].signal.aborted, false, "parent turn cancellation does not own the accepted background job");
659
665
  assert.equal(h.widgets.has("background-tasks"), false, "no counter above the native footer");
666
+ assert.equal(h.clock.timers.size, 1, "a running task needs only its execution deadline, not a footer repaint timer");
660
667
  h.clock.advance(1000);
661
668
  const footer = h.footer;
662
669
  h.statuses.set("codex-edit", "editor: apply_patch");
@@ -698,6 +705,34 @@ test("tools, clean panel, bottom footer and idle notifications share the same se
698
705
  } finally { await h.close(); }
699
706
  });
700
707
 
708
+ test("keyed TUI status follows staggered five-second completion expiry without running repaint timers", async () => {
709
+ const h = harness();
710
+ try {
711
+ await h.handlers.get("session_start")({}, h.ctx);
712
+ await h.tool.execute("first", { action: "start", command: "first" });
713
+ await h.tool.execute("second", { action: "start", command: "second" });
714
+ assert.equal(h.statuses.get("background-tasks"), "2 shells");
715
+ assert.equal(h.clock.timers.size, 2, "only the two execution deadlines run");
716
+ h.handlers.get("agent_settled")({ aborted: true });
717
+
718
+ h.calls[0].resolve();
719
+ await flush();
720
+ assert.equal(h.statuses.get("background-tasks"), "1 shell · 1 done");
721
+ h.clock.advance(3000);
722
+ h.calls[1].resolve();
723
+ await flush();
724
+ assert.equal(h.statuses.get("background-tasks"), "0 shells · 2 done");
725
+
726
+ h.clock.advance(2000);
727
+ assert.equal(h.statuses.get("background-tasks"), "0 shells · 1 done");
728
+ h.clock.advance(2999);
729
+ assert.equal(h.statuses.get("background-tasks"), "0 shells · 1 done");
730
+ h.clock.advance(1);
731
+ assert.equal(h.statuses.has("background-tasks"), false);
732
+ assert.equal(h.clock.timers.size, 0);
733
+ } finally { await h.close(); }
734
+ });
735
+
701
736
  test("cancel and shutdown are idempotent; new sessions cannot receive old completions", async () => {
702
737
  const h = harness();
703
738
  try {
@@ -806,12 +841,49 @@ test("footer count opens one local panel; shutdown closes it and clears refresh
806
841
  } finally { await h.close(); }
807
842
  });
808
843
 
809
- test("a pre-existing replacement footer fails visibly instead of silently losing the count", async () => {
844
+ test("a pre-existing replacement footer keeps native status and Alt+J without taking footer ownership", async () => {
810
845
  const h = harness();
811
846
  try {
812
- h.tui.children = [{ render: () => ["another footer"], invalidate() {} }];
813
- await assert.rejects(h.handlers.get("session_start")({}, h.ctx), /requires Pi's built-in footer/);
847
+ const foreign = { render: () => ["another footer"], invalidate() {} };
848
+ h.tui.children = [foreign];
849
+ await h.handlers.get("session_start")({}, h.ctx);
850
+ await h.tool.execute("start", { action: "start", command: "first" });
814
851
  assert.equal(h.footer, undefined);
815
852
  assert.equal(h.widgets.has("background-tasks"), false, "temporary capture widget is cleaned on failure");
853
+ assert.equal(h.statuses.get("background-tasks"), "1 shell");
854
+ h.open();
855
+ assert.match(h.panel.render(140).join("\n"), /Command: first/);
856
+ h.panel.handleInput("\x1b");
857
+ await flush();
858
+ const changes = h.footerChanges;
859
+ h.calls[0].resolve();
860
+ await h.handlers.get("session_shutdown")({}, h.ctx);
861
+ assert.equal(h.footerChanges, changes, "shutdown must not replace a footer it never owned");
862
+ assert.equal(h.statuses.has("background-tasks"), false);
863
+ assert.equal(h.tui.children[0], foreign);
864
+ } finally { await h.close(); }
865
+ });
866
+
867
+ test("a later replacement footer evicts the decorator without being clobbered on shutdown", async () => {
868
+ const h = harness();
869
+ try {
870
+ await h.handlers.get("session_start")({}, h.ctx);
871
+ await h.tool.execute("start", { action: "start", command: "first" });
872
+ const decorator = h.footer;
873
+ const foreign = { render: () => ["another footer"], invalidate() {} };
874
+ h.ctx.ui.setFooter(() => foreign);
875
+ assert.notEqual(h.footer, decorator);
876
+ assert.equal(h.footer, foreign);
877
+ assert.equal(h.statuses.get("background-tasks"), "1 shell");
878
+ h.open();
879
+ assert.match(h.panel.render(140).join("\n"), /Command: first/);
880
+ h.panel.handleInput("\x1b");
881
+ await flush();
882
+ const changes = h.footerChanges;
883
+ h.calls[0].resolve();
884
+ await h.handlers.get("session_shutdown")({}, h.ctx);
885
+ assert.equal(h.footerChanges, changes, "shutdown must not clear a later footer owner");
886
+ assert.equal(h.footer, foreign);
887
+ assert.equal(h.statuses.has("background-tasks"), false);
816
888
  } finally { await h.close(); }
817
889
  });
@@ -105,7 +105,9 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
105
105
  const interruptRequestedAt = Date.now();
106
106
  if (timing === "after active compaction") {
107
107
  await session.compact();
108
- assert.equal(summaries, 1, "manual compaction must run its native summary after interrupting the active agent");
108
+ // Native compaction may summarize history and a split turn separately.
109
+ // This contract needs a real summary without allowing a retry loop.
110
+ assert.ok(summaries >= 1 && summaries <= 2, "manual compaction must summarize after interrupting the active agent without looping");
109
111
  } else await session.abort();
110
112
  await prompting;
111
113
  const interruptedAt = Date.now();
@@ -36,7 +36,7 @@ test("native model receives distinct declaration and start guidance without Code
36
36
  const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
37
37
  const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
38
38
  assert.equal(started.isError, false);
39
- const notice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
39
+ const notice = "Completion will resume you automatically. Continue independent work if any remains; otherwise end the turn now. Do not call Bash sleep, tail logs, or use list/output solely to wait.";
40
40
  assert.equal(started.result.structuredContent.guidance, undefined);
41
41
  assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
42
42
  const requests = records.filter((entry) => entry.event === "request");
@@ -47,6 +47,7 @@ test("native model receives distinct declaration and start guidance without Code
47
47
  assert.ok(!requests[0].backgroundDescription.includes(notice));
48
48
  assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
49
49
  assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
50
+ assert.match(requests[1].text, /Do not call Bash sleep/);
50
51
  assert.ok(!started.result.content[0].text.includes(started.result.structuredContent.task.log_path));
51
52
  } finally { rmSync(directory, { recursive: true, force: true }); }
52
53
  });
package/tests/panel.mjs CHANGED
@@ -3,7 +3,7 @@ import { unlinkSync, readFileSync } from "node:fs";
3
3
  import { test } from "node:test";
4
4
  import { KeybindingsManager, TUI_KEYBINDINGS, visibleWidth } from "@earendil-works/pi-tui";
5
5
  import { BackgroundPanel } from "../src/panel.ts";
6
- import { BackgroundFooter } from "../src/widget.ts";
6
+ import { BackgroundFooter, WIDGET_KEY } from "../src/widget.ts";
7
7
  import { fixture, flush } from "./helpers.mjs";
8
8
 
9
9
  const keys = new KeybindingsManager(TUI_KEYBINDINGS);
@@ -15,46 +15,53 @@ function panel(f) {
15
15
  return { view, text: (width = 120) => view.render(width).join("\n"), get renders() { return renders; }, get closed() { return closed; } };
16
16
  }
17
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
- let status = "", panelOpen = false;
24
- const native = { render: () => ["path", "usage model", ...(status ? [status] : [])], invalidate() {} };
25
- const widget = new BackgroundFooter(native, () => f.tasks.list().tasks, f.clock, theme, () => !!status, () => panelOpen, () => opened++);
26
- assert.deepEqual(widget.render(120), ["path", "usage model", "1 shell · Alt+J"]);
27
- assert.equal(widget.handleMouse(click(7, 2)), undefined);
28
- assert.equal(widget.handleMouse(click(2, 1)), undefined);
29
- assert.equal(widget.handleMouse(click(2, 2, "right")), undefined);
30
- assert.equal(widget.handleMouse(click(2, 2)).handled, true);
31
- assert.equal(opened, 1);
32
- f.tasks.start({ command: "second" }, f.root);
33
- assert.match(widget.render(120).at(-1), /^2 shells/);
34
- f.calls[1].resolve(3); await flush();
35
- assert.match(widget.render(120).at(-1), /^1 shell · 1 done/);
36
- f.clock.advance(5000);
37
- assert.equal(widget.render(120).at(-1), "1 shell · Alt+J");
38
- status = "editor: apply_patch";
39
- assert.equal(widget.render(120).at(-1), `${status} · 1 shell · Alt+J`);
40
- assert.equal(widget.handleMouse(click(2, 2)), undefined, "editor status is not a shell click");
41
- assert.equal(widget.handleMouse(click(23, 2)).handled, true);
42
- panelOpen = true;
43
- assert.deepEqual(widget.render(120), []);
44
- assert.equal(widget.handleMouse(click(23, 2)), undefined);
45
- panelOpen = false;
46
- status = "中文状态".repeat(20);
47
- for (const width of [0, 1, 8, 40]) {
48
- const row = widget.render(width).at(-1);
49
- assert.ok(visibleWidth(row) <= width);
50
- if (width >= 8) assert.match(row, /1 shell/, "keep the count visible even if other statuses are long");
51
- }
52
- widget.invalidate();
53
- assert.equal(widget.handleMouse(click(2, 2)), undefined, "resize/theme invalidation clears stale hit regions");
54
- f.calls[0].resolve(); await flush();
55
- f.clock.advance(5000);
56
- assert.deepEqual(widget.render(120), native.render(120), "expired count leaves the native footer untouched");
57
- } finally { await f.close(); }
18
+ test("compact count, arbitrary peer statuses, narrow widths and bounded mouse hit region", () => {
19
+ let opened = 0;
20
+ let panelOpen = false;
21
+ const statuses = new Map([[WIDGET_KEY, "1 shell"]]);
22
+ const native = { render: () => ["path", "usage model", ...(statuses.size ? [[...statuses.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, text]) => text).join(" ")] : [])], invalidate() {} };
23
+ const widget = new BackgroundFooter(native, theme, () => statuses, () => panelOpen, () => opened++);
24
+ assert.deepEqual(widget.render(120), ["path", "usage model", "1 shell · Alt+J"]);
25
+ assert.equal(widget.handleMouse(click(7, 2)), undefined);
26
+ assert.equal(widget.handleMouse(click(2, 1)), undefined);
27
+ assert.equal(widget.handleMouse(click(2, 2, "right")), undefined);
28
+ assert.equal(widget.handleMouse(click(2, 2)).handled, true);
29
+ assert.equal(opened, 1);
30
+ statuses.set(WIDGET_KEY, "2 shells");
31
+ assert.match(widget.render(120).at(-1), /^2 shells/);
32
+ statuses.set(WIDGET_KEY, "1 shell · 1 done");
33
+ assert.match(widget.render(120).at(-1), /^1 shell · 1 done/);
34
+ statuses.set(WIDGET_KEY, "1 shell");
35
+ assert.equal(widget.render(120).at(-1), "1 shell · Alt+J");
36
+ statuses.set("codex-edit", "editor: apply_patch");
37
+ assert.equal(widget.render(120).at(-1), "editor: apply_patch · 1 shell · Alt+J");
38
+ assert.equal(widget.handleMouse(click(2, 2)), undefined, "editor status is not a shell click");
39
+ assert.equal(widget.handleMouse(click(23, 2)).handled, true);
40
+ assert.equal(widget.render(29).at(-1), "editor: apply_patch · 1 shell", "drop the shortcut before truncating a peer status");
41
+ statuses.set("scheduler", "2 schedules");
42
+ statuses.set("z-custom", "future\tstatus\nready");
43
+ statuses.set("zero-width", "\x1b[31m\x1b[0m");
44
+ assert.equal(widget.render(120).at(-1), "editor: apply_patch · 2 schedules · future status ready · 1 shell · Alt+J");
45
+ const compact = widget.render(30).at(-1);
46
+ assert.doesNotMatch(compact, /Alt\+J/, "drop the shortcut before peer statuses");
47
+ assert.match(compact, /1 shell$/, "keep the shell count visible after truncating peers");
48
+ const compactShell = visibleWidth(compact.slice(0, compact.indexOf("1 shell")));
49
+ assert.equal(widget.handleMouse(click(compactShell - 1, 2)), undefined);
50
+ assert.equal(widget.handleMouse(click(compactShell + 1, 2)).handled, true, "truncated peer text keeps the shell hit box aligned");
51
+ panelOpen = true;
52
+ assert.deepEqual(widget.render(120), []);
53
+ assert.equal(widget.handleMouse(click(23, 2)), undefined);
54
+ panelOpen = false;
55
+ statuses.set("z-custom", "中文状态".repeat(20));
56
+ for (const width of [0, 1, 8, 40]) {
57
+ const row = widget.render(width).at(-1);
58
+ assert.ok(visibleWidth(row) <= width);
59
+ if (width >= 8) assert.match(row, /1 shell/, "keep the count visible even if other statuses are long");
60
+ }
61
+ widget.invalidate();
62
+ assert.equal(widget.handleMouse(click(2, 2)), undefined, "resize/theme invalidation clears stale hit regions");
63
+ statuses.delete(WIDGET_KEY);
64
+ assert.deepEqual(widget.render(120), native.render(120), "missing shell status leaves the native footer untouched");
58
65
  });
59
66
 
60
67
  test("single shell opens aligned, compact details without changing the original script", async () => {