@maxiaochao/pi-background-tasks 0.4.0 → 0.4.2

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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-11-17 - v0.4.2
4
+
5
+ - Keep multiline shell previews compact without changing script execution
6
+ - Fold script line breaks and indentation into a compact, width-wrapped command preview, so setup lines do not hide the actual command. Keep the executed script unchanged.
7
+
8
+ ## 2026-11-16 - v0.4.1
9
+
10
+ - Fix bottom-footer shell controls and hide the footer during task inspection
11
+ - Move the clickable shell count to the bottom footer status row, beside editor status when present; preserve Pi's native path, usage and model rendering.
12
+ - Hide the entire footer while the shell list or details panel is open, and restore it on close.
13
+ - Verify bottom-row placement and clean panels with real Chrome clicks, both with and without Codex Edit. Keep capture browsers isolated from existing browser sessions.
14
+
3
15
  ## 2026-11-13 - v0.4.0
4
16
 
5
17
  - Replace Herdr task views and /bg commands with a local shell counter and details panel
package/README.md CHANGED
@@ -70,16 +70,18 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
70
70
 
71
71
  ## User controls and status
72
72
 
73
- A compact **`1 shell` / `N shells`** counter sits below the editor without replacing Pi's footer. 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.
73
+ 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.
74
74
 
75
75
  - **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).
76
- - **Details:** `Status:`, `Runtime:` and `Command:` share a fixed value column. Long commands wrap for up to three lines with an ellipsis. **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.
77
- - **Controls:** ← returns to the list. Esc closes either view; Enter or Space also closes details. `x` stops only the selected running shell. Closing the panel leaves the task running. Inspecting output in the panel does not add model messages or consume a pending completion reminder.
76
+ - **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.
77
+ - **Controls:** ← returns to the list. Esc closes either view; Enter or Space also closes details. `x` stops only the selected running shell. While either panel is open, the entire footer is hidden: path, usage, model, extension statuses and shell count. Closing restores the current footer and leaves the task running. Inspecting output in the panel does not add model messages or consume a pending completion reminder.
78
78
  - **Counter:** recently finished tasks add `N done` for five seconds. Hiding the counter does not delete history. RPC receives an active count; print/JSON mode has no UI timer.
79
79
  - **No `/bg` commands or Herdr integration:** the extension creates no tabs, panes or log-following processes, including when Pi itself runs inside Herdr. Task execution always uses the same local backend.
80
80
 
81
81
  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.
82
82
 
83
+ 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.
84
+
83
85
  ## Completion delivery
84
86
 
85
87
  Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
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, below-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks fixed `model-only` exposure and separate concise declaration and task-specific start guidance, no start-text log path or redundant structured guidance field, and explicit running-task `list`/`output` availability; verifies 24-hour retention after an interrupt, output consumption while stopped, custom-wake isolation and restoration of automatic delivery by a new user-message run.
17
- - `panel.mjs`: singular/plural counter, mouse hit region, screenshot-style field alignment, original multiline command, 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. Checks explicit failure for an incompatible replacement footer and cleanup of the temporary zero-line capture widget. Checks fixed `model-only` exposure and separate concise declaration and task-specific start guidance, no start-text log path or redundant structured guidance field, and explicit running-task `list`/`output` availability; verifies 24-hour retention after an interrupt, output consumption while stopped, custom-wake isolation and restoration of automatic delivery by a new user-message run.
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.
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. Complete pending-batch consumption remains covered by the deterministic extension tests. Also verifies that the model receives distinct declaration/start guidance without a Codemode suffix, and that the next request receives status/log locations without command output, and that native Codemode cannot discover or call `background_task`. The blocking tool is a fixture, not a real Herdr child. `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.
@@ -55,12 +55,13 @@ It relays the real PTY output, captures only the test window, then closes it. In
55
55
 
56
56
  ```bash
57
57
  node scripts/capture-background-tasks-media.mjs .cache/background-ui
58
+ BG_MEDIA_EDITOR=none node scripts/capture-background-tasks-media.mjs .cache/background-ui-no-editor
58
59
  node scripts/capture-package-media.mjs background-tasks
59
60
  ```
60
61
 
61
62
  Requires Python 3, Chrome, the web-browser skill launcher, Pillow and an installed `@xterm/xterm` package. Set `XTERM_DIR` to its package directory if it is not under `~/.pi/agent/npm/node_modules/@xterm/xterm`. No Herdr or graphical desktop is required.
62
63
 
63
- The recorder starts a real Pi PTY with the production extension and offline provider. Chrome renders the actual ANSI stream through xterm.js. CDP sends real mouse press/release events to the shell counter and task rows, and keyboard events for selection, return, close, stop and Alt+J. It verifies single-shell details, two-shell list, aligned fields, live output, completion, cancellation, retained history and session-log cleanup. The Python bridge only transports PTY bytes; it does not draw replacement UI. Its local HTTP/WebSocket server uses a random path token and same-origin upgrade checks and is closed after the run.
64
+ The recorder starts a real Pi PTY with the production extension and offline provider. By default it also loads the production Codex Edit extension; that offline model correctly selects `editor: edit`. Deterministic tests additionally cover `editor: apply_patch`. `BG_MEDIA_EDITOR=none` verifies the same flow without an editor extension. Chrome renders the actual ANSI stream through xterm.js in a recorder-owned temporary browser profile, without touching an existing skill browser. CDP sends real mouse press/release events to the shell counter and task rows, and keyboard events for selection, return, close, stop and Alt+J. It asserts that the count is on the last nonempty row beside editor status when present, with no duplicate above the footer. Both list and details hide path, usage, model and status rows; closing restores them. A real four-line script with two exports must preview continuously, with the actual job command visible on the same row. It also verifies aligned fields, live output, completion, cancellation, retained history and session-log cleanup. The Python bridge only transports PTY bytes; it does not draw replacement UI. Its local HTTP/WebSocket server uses a random path token and same-origin upgrade checks and is closed after the run.
64
65
 
65
66
  The unified media entry first runs `tests/tui-smoke.py`, then the browser/TUI recorder. `result.json`, tool events and raw screen text/screenshots are saved under `.cache/package-media/background-terminal`. The renderer builds `docs/screenshot.png`, `docs/shell-list.png` and `docs/demo.gif` from real captured states. The old Herdr pane screenshot and WebM are retired.
66
67
 
package/docs/demo.gif CHANGED
Binary file
Binary file
Binary file
@@ -5,7 +5,7 @@ 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 { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
8
+ import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
9
9
 
10
10
  const actions = ["start", "list", "output", "cancel"] as const;
11
11
  const startNotice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
@@ -72,7 +72,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
72
72
  let completedNormally = true;
73
73
  let interrupted = false;
74
74
  const pending = new Map<string, TaskSnapshot>();
75
- let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
75
+ let mounted: { footer: BackgroundFooter; tui: { requestRender(): void } } | undefined;
76
76
  let panel: { close(): void } | undefined;
77
77
 
78
78
  const clearNotificationTimer = () => {
@@ -158,6 +158,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
158
158
  if (!current?.hasUI || current.mode !== "tui" || !tasks || panel) return;
159
159
  const interaction = { close: () => {} };
160
160
  panel = interaction;
161
+ mounted?.tui.requestRender();
161
162
  try {
162
163
  await current.ui.custom<void>((tui, theme, keybindings, done) => {
163
164
  const component = new BackgroundPanel(tasks, clock, theme, keybindings, () => tui.requestRender(), () => done());
@@ -168,6 +169,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
168
169
  if (context === current) current.ui.notify(`Cannot show shells: ${errorText(error)}`, "error");
169
170
  } finally {
170
171
  if (panel === interaction) panel = undefined;
172
+ mounted?.tui.requestRender();
171
173
  }
172
174
  };
173
175
  pi.registerShortcut("alt+j", { description: "Show background shells", handler: openPanel });
@@ -183,25 +185,12 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
183
185
  return;
184
186
  }
185
187
  const visible = visibleTasks(list.tasks, clock.now());
188
+ mounted?.footer.invalidate();
189
+ mounted?.tui.requestRender();
186
190
  if (visible.length === 0) {
187
191
  clearTimer();
188
- if (mounted) {
189
- context.ui.setWidget(WIDGET_KEY, undefined);
190
- mounted.tui.requestRender();
191
- mounted = undefined;
192
- }
193
192
  return;
194
193
  }
195
- if (mounted) {
196
- mounted.widget.invalidate();
197
- mounted.tui.requestRender();
198
- } else {
199
- context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
200
- const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, () => { void openPanel(); });
201
- mounted = { widget, tui };
202
- return widget;
203
- }, { placement: "belowEditor" });
204
- }
205
194
  if (timer === undefined) {
206
195
  const delay = Math.min(1000, ...visible.filter((task) => task.ended_at !== undefined).map((task) => task.ended_at! + FINISHED_VISIBLE_MS - clock.now()));
207
196
  timer = clock.setTimeout(() => { timer = undefined; refresh(); }, Math.max(1, delay));
@@ -223,7 +212,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
223
212
  try {
224
213
  if (previousContext?.hasUI) {
225
214
  previousContext.ui.setStatus(WIDGET_KEY, undefined);
226
- if (previousContext.mode === "tui") previousContext.ui.setWidget(WIDGET_KEY, undefined);
215
+ if (previousContext.mode === "tui" && mounted) previousContext.ui.setFooter(undefined);
227
216
  }
228
217
  mounted = undefined;
229
218
  } finally {
@@ -243,6 +232,25 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
243
232
  scheduleNotification();
244
233
  },
245
234
  });
235
+ if (ctx.hasUI && ctx.mode === "tui") {
236
+ // setFooter clears its container before invoking the factory. Capture the
237
+ // native component first, using a temporary, zero-line widget factory.
238
+ try {
239
+ ctx.ui.setWidget(WIDGET_KEY, (tui) => {
240
+ const native = findNativeFooter(tui.children);
241
+ if (!native) throw new Error("Background Tasks requires Pi's built-in footer; another extension has replaced it.");
242
+ ctx.ui.setFooter((footerTui, theme, data) => {
243
+ const footer = new BackgroundFooter(native, () => manager?.list().tasks ?? [], clock, theme,
244
+ () => data.getExtensionStatuses().size > 0, () => panel !== undefined, () => { void openPanel(); });
245
+ mounted = { footer, tui: footerTui };
246
+ return footer;
247
+ });
248
+ return { render: () => [], invalidate() {} };
249
+ });
250
+ } finally {
251
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
252
+ }
253
+ }
246
254
  });
247
255
  pi.on("session_shutdown", dispose);
248
256
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxiaochao/pi-background-tasks",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Session-scoped background shell tasks with completion notifications for Pi.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/panel.ts CHANGED
@@ -143,9 +143,10 @@ export class BackgroundPanel {
143
143
  private details(width: number, task: TaskSnapshot): string[] {
144
144
  const { theme } = this;
145
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));
146
+ const preview = clean(this.tasks.command(task.id)).split("\n").map((line) => line.trim()).filter(Boolean).join(" ");
147
+ const commandLines = wrapTextWithAnsi(preview.slice(0, 8192), Math.max(1, width - 10));
147
148
  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
+ if (commandLines.length > 3 || preview.length > 8192) command[command.length - 1] = truncateToWidth(command.at(-1)! + "…", Math.max(1, width - 10), "…");
149
150
  const lines = [theme.fg("accent", theme.bold("Shell details")), "",
150
151
  field("Status:", theme.fg(color(task), this.stopping.has(task.id) ? "stopping" : task.status)),
151
152
  field("Runtime:", duration(task.elapsed_seconds)),
package/src/widget.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, visibleWidth, 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,35 +16,61 @@ 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. */
20
- export class BackgroundWidget {
21
- private hitWidth = 0;
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;
37
+ private readonly hasStatuses: () => boolean;
38
+ private readonly panelOpen: () => boolean;
25
39
  private readonly onSelect: () => void;
26
- constructor(getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, onSelect: () => void) {
40
+ constructor(native: Component, getTasks: () => TaskSnapshot[], clock: Clock, theme: Theme, hasStatuses: () => boolean, panelOpen: () => boolean, onSelect: () => void) {
41
+ this.native = native;
27
42
  this.getTasks = getTasks;
28
43
  this.clock = clock;
29
44
  this.theme = theme;
45
+ this.hasStatuses = hasStatuses;
46
+ this.panelOpen = panelOpen;
30
47
  this.onSelect = onSelect;
31
48
  }
32
49
 
33
50
  handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
34
- if (event.type !== "click" || event.button !== "left" || event.y !== 0 || event.x < 0 || event.x >= this.hitWidth) return;
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;
35
53
  this.onSelect();
36
54
  return { handled: true, render: false };
37
55
  }
38
56
 
39
57
  render(width: number): string[] {
58
+ this.hit = undefined;
59
+ if (this.panelOpen()) return [];
60
+ const lines = this.native.render(width);
40
61
  const tasks = visibleTasks(this.getTasks(), this.clock.now());
62
+ if (!tasks.length) return lines;
41
63
  const active = tasks.filter((task) => task.status === "running").length;
42
64
  const ended = tasks.length - active;
43
65
  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)];
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];
47
73
  }
48
74
 
49
- invalidate(): void { this.hitWidth = 0; }
75
+ invalidate(): void { this.hit = undefined; this.native.invalidate(); }
50
76
  }
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import { unlinkSync } from "node:fs";
3
3
  import { test } from "node:test";
4
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
 
@@ -12,22 +13,35 @@ function harness(mode = "tui", hasUI = true) {
12
13
  const handlers = new Map();
13
14
  const commands = new Map();
14
15
  const shortcuts = new Map();
15
- let panel;
16
+ let panel, footer;
16
17
  const messages = [];
17
18
  const notices = [];
18
19
  const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
19
- const placements = new Map();
20
20
  const statuses = new Map();
21
21
  const idleChecks = [];
22
22
  let tool, renders = 0, idle = true, failSend = false;
23
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++; } };
24
32
  const ctx = {
25
33
  cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
26
34
  ui: {
27
- setWidget(key, factory, options) {
35
+ setWidget(key, factory) {
28
36
  if (!factory) { widgets.delete(key); return; }
29
- widgets.set(key, factory({ requestRender() { renders++; } }, theme));
30
- 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();
31
45
  },
32
46
  custom(factory) {
33
47
  return new Promise((resolve) => {
@@ -50,10 +64,11 @@ function harness(mode = "tui", hasUI = true) {
50
64
  };
51
65
  register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
52
66
  return {
53
- ...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
67
+ ...f, handlers, commands, messages, notices, widgets, statuses, idleChecks, ctx, tui, native,
54
68
  setIdle(value) { idle = value; },
55
69
  failNextSend() { failSend = true; },
56
70
  get panel() { return panel; },
71
+ get footer() { return footer; },
57
72
  open() { void shortcuts.get("alt+j").handler(ctx); },
58
73
  get tool() { return tool; }, get renders() { return renders; },
59
74
  async close() {
@@ -75,7 +90,7 @@ test("completions during a synchronous tool are merged before the next model req
75
90
  h.calls[1].resolve(2);
76
91
  await flush();
77
92
  assert.equal(h.messages.length, 0, "busy completions must not enter an irrevocable host queue");
78
- assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /done/);
93
+ assert.match(h.footer.render(140).join("\n"), /done/);
79
94
  const existing = { type: "custom", customType: "other-extension", data: { preserved: true } };
80
95
  const boundary = h.handlers.get("turn_end")({ entries: [existing], continue: true, outcome: "completed" }, h.ctx);
81
96
  assert.equal(boundary.continue, true);
@@ -524,7 +539,7 @@ test("start keeps only task-specific guidance while the declaration describes li
524
539
  } finally { await h.close(); }
525
540
  });
526
541
 
527
- test("tools, panel, 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 () => {
528
543
  const h = harness();
529
544
  try {
530
545
  await h.handlers.get("session_start")({}, h.ctx);
@@ -535,19 +550,22 @@ test("tools, panel, widget and idle notifications share the same session jobs",
535
550
  assert.equal(job.status, "running");
536
551
  parentSignal.abort();
537
552
  assert.equal(h.calls[0].signal.aborted, false, "parent turn cancellation does not own the accepted background job");
538
- assert.deepEqual(h.placements.get("background-tasks"), { placement: "belowEditor" });
553
+ assert.equal(h.widgets.has("background-tasks"), false, "no counter above the native footer");
539
554
  h.clock.advance(1000);
540
- const widget = h.widgets.get("background-tasks");
541
- assert.match(widget.render(140).join("\n"), /1 shell/);
542
- 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));
543
559
  assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
544
560
 
545
561
  h.calls[0].onData(Buffer.from("captured build output\n"));
546
562
  h.open();
563
+ assert.deepEqual(footer.render(140), [], "hide path, usage, model, editor status and shell count while inspecting");
547
564
  assert.match(h.panel.render(140).join("\n"), /captured build output/);
548
565
  assert.match(h.panel.render(140).join("\n"), /Runtime: 1s/);
549
566
  h.panel.handleInput("\x1b");
550
567
  await flush();
568
+ assert.match(footer.render(140).at(-1), /editor: apply_patch · 1 shell/);
551
569
  assert.equal(h.messages.length, 0);
552
570
  const output = await h.tool.execute("output", { action: "output", id: job.id });
553
571
  assert.equal(output.structuredContent.output, "captured build output\n");
@@ -563,11 +581,11 @@ test("tools, panel, widget and idle notifications share the same session jobs",
563
581
  assert.doesNotMatch(completed[0].message.content, /captured build output/);
564
582
  assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
565
583
  assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
566
- assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /done/);
584
+ assert.match(footer.render(140).join("\n"), /done/);
567
585
  h.clock.advance(4999);
568
- assert.ok(h.widgets.has("background-tasks"));
586
+ assert.match(footer.render(140).at(-1), /done/);
569
587
  h.clock.advance(1);
570
- assert.equal(h.widgets.has("background-tasks"), false);
588
+ assert.deepEqual(footer.render(140), h.native.render(140));
571
589
  assert.equal(h.clock.timers.size, 0);
572
590
  assert.equal((await h.tool.execute("history", { action: "output", id: job.id })).structuredContent.task.status, "failed");
573
591
  assert.ok(h.renders > 0);
@@ -659,14 +677,14 @@ for (const reason of ["new", "resume", "fork", "quit"]) {
659
677
  });
660
678
  }
661
679
 
662
- test("widget opens one local panel; shutdown closes it and clears refresh timers", async () => {
680
+ test("footer count opens one local panel; shutdown closes it and clears refresh timers", async () => {
663
681
  const h = harness();
664
682
  try {
665
683
  await h.handlers.get("session_start")({}, h.ctx);
666
684
  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 });
685
+ const footer = h.footer;
686
+ const lines = footer.render(140);
687
+ footer.handleMouse({ type: "click", button: "left", x: 1, y: lines.length - 1 });
670
688
  const original = h.panel;
671
689
  assert.ok(original);
672
690
  h.open();
@@ -678,6 +696,16 @@ test("widget opens one local panel; shutdown closes it and clears refresh timers
678
696
  h.calls[0].resolve();
679
697
  await shutdown;
680
698
  assert.equal(h.clock.timers.size, 0);
681
- assert.equal(h.widgets.has("background-tasks"), false);
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");
682
710
  } finally { await h.close(); }
683
711
  });
@@ -28,12 +28,12 @@ export default function (pi: ExtensionAPI) {
28
28
  const call = (args: any) => calls.push({ name: "background_task", arguments: args });
29
29
  if (last?.role !== "toolResult") {
30
30
  if (text.includes("Start two background demo jobs")) {
31
- call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
32
- call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
31
+ call({ action: "start", command: "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py build", description: "Build progress", timeout: 120 });
32
+ call({ action: "start", command: "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py tests", description: "Test suite", timeout: 120 });
33
33
  } else if (text.includes("Start one background demo job")) {
34
- call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
34
+ call({ action: "start", command: "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py build", description: "Build progress", timeout: 120 });
35
35
  } else if (text.includes("Start the second background demo job")) {
36
- call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
36
+ call({ action: "start", command: "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py tests", description: "Test suite", timeout: 120 });
37
37
  } else if (text.includes("SMOKE_START")) {
38
38
  call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
39
39
  call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
package/tests/media.mjs CHANGED
@@ -44,8 +44,8 @@ test("offline media provider issues exactly two direct background starts, then r
44
44
  for await (const event of provider.streamSimple(model, { messages: [user] })) events.push(event);
45
45
  const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
46
46
  assert.deepEqual(calls.map((call) => [call.name, call.arguments.command, call.arguments.description]), [
47
- ["background_task", "python3 demo-job.py build", "Build progress"],
48
- ["background_task", "python3 demo-job.py tests", "Test suite"],
47
+ ["background_task", "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py build", "Build progress"],
48
+ ["background_task", "set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py tests", "Test suite"],
49
49
  ]);
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);
@@ -65,6 +65,6 @@ for (const [prompt, kind] of [
65
65
  const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
66
66
  assert.equal(calls.length, 1);
67
67
  assert.equal(calls[0].name, "background_task");
68
- assert.equal(calls[0].arguments.command, `python3 demo-job.py ${kind}`);
68
+ assert.equal(calls[0].arguments.command, `set -e\nexport BG_DEMO=1\nexport CI=1\npython3 demo-job.py ${kind}`);
69
69
  });
70
70
  }
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 { BackgroundWidget } from "../src/widget.ts";
6
+ import { BackgroundFooter } from "../src/widget.ts";
7
7
  import { fixture, flush } from "./helpers.mjs";
8
8
 
9
9
  const keys = new KeybindingsManager(TUI_KEYBINDINGS);
@@ -20,24 +20,44 @@ test("compact count, singular/plural, five-second retention and bounded mouse hi
20
20
  try {
21
21
  f.tasks.start({ command: "first" }, f.root);
22
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);
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);
26
28
  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(widget.handleMouse(click(2, 2, "right")), undefined);
30
+ assert.equal(widget.handleMouse(click(2, 2)).handled, true);
29
31
  assert.equal(opened, 1);
30
32
  f.tasks.start({ command: "second" }, f.root);
31
- assert.match(widget.render(120)[0], /^2 shells/);
33
+ assert.match(widget.render(120).at(-1), /^2 shells/);
32
34
  f.calls[1].resolve(3); await flush();
33
- assert.match(widget.render(120)[0], /^1 shell · 1 done/);
35
+ assert.match(widget.render(120).at(-1), /^1 shell · 1 done/);
34
36
  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
+ 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");
37
57
  } finally { await f.close(); }
38
58
  });
39
59
 
40
- test("single shell opens aligned details; full original multiline command is separate from metadata", async () => {
60
+ test("single shell opens aligned, compact details without changing the original script", async () => {
41
61
  const f = fixture(); let p;
42
62
  try {
43
63
  const command = 'printf "hello"\nprintf "中文"';
@@ -45,7 +65,8 @@ test("single shell opens aligned details; full original multiline command is sep
45
65
  assert.equal(f.tasks.command(task.id), command);
46
66
  assert.equal(task.command, undefined);
47
67
  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/);
68
+ assert.match(p.text(), /Shell details\n\n Status: running\n Runtime: 0s\n Command: printf "hello" printf "中文"\n\n Output:\n No output available/);
69
+ assert.equal(f.calls[0].command, command);
49
70
  f.clock.advance(209000);
50
71
  assert.match(p.text(), /Runtime: 3m 29s/);
51
72
  assert.ok(p.renders > 0);
@@ -60,6 +81,36 @@ test("single shell opens aligned details; full original multiline command is sep
60
81
  } finally { p?.view.dispose(); await f.close(); }
61
82
  });
62
83
 
84
+ test("command preview folds line breaks and indentation before width wrapping", async () => {
85
+ const f = fixture(); let p;
86
+ try {
87
+ const command = '\nset -e\r\n export JAVA_HOME=/opt/jdk-11.0.32\r\t export PATH="$JAVA_HOME/bin:$PATH"\n\n ./gradlew test\n';
88
+ const task = f.tasks.start({ command }, f.root);
89
+ p = panel(f);
90
+ assert.match(p.text(), /Command: set -e export JAVA_HOME=\/opt\/jdk-11\.0\.32 export PATH="\$JAVA_HOME\/bin:\$PATH" \.\/gradlew test\n\n Output:/);
91
+ assert.doesNotMatch(p.text(), /…/);
92
+ const narrow = p.text(64);
93
+ assert.match(narrow, /\.\/gradlew test/);
94
+ assert.doesNotMatch(narrow, /…/);
95
+ assert.ok(p.view.render(64).every((line) => visibleWidth(line) <= 64));
96
+ assert.equal(f.tasks.command(task.id), command);
97
+ assert.equal(f.calls[0].command, command);
98
+ } finally { p?.view.dispose(); await f.close(); }
99
+ });
100
+
101
+ test("compact preview preserves inline spaces and applies its length guard after folding", async () => {
102
+ const f = fixture(); let p;
103
+ try {
104
+ const command = 'printf "hello 中文"\n' + " \n\t".repeat(3000) + 'printf "done"';
105
+ const task = f.tasks.start({ command }, f.root);
106
+ p = panel(f);
107
+ assert.match(p.text(), /Command: printf "hello 中文" printf "done"\n\n Output:/);
108
+ assert.doesNotMatch(p.text(), /…/);
109
+ assert.equal(f.tasks.command(task.id), command);
110
+ assert.equal(f.calls[0].command, command);
111
+ } finally { p?.view.dispose(); await f.close(); }
112
+ });
113
+
63
114
  test("multiple shells: arrow selection, click, identity across completion, x stops only selected job", async () => {
64
115
  const f = fixture(); let p;
65
116
  try {