Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Session list marks conversations that still have background tasks (#585)

Yaowei Zheng50d5e0ef1506
diff --git a/changelog/unreleased/2026-09-02-session-background-indicator.md b/changelog/unreleased/2026-09-02-session-background-indicator.md
new file mode 100644
index 00000000..c58f8e2b
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-session-background-indicator.md
@@ -0,0 +1,47 @@
+# The Session list shows which conversations still have background tasks
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#585](https://github.com/Prism-Shadow/penguin-harness/pull/585)
+
+[中文版](2026-09-02-session-background-indicator.zh.md)
+
+A conversation that has started a dev server or a background subagent now says so in the
+sidebar: its row carries a small activity trace beside the usual status glyph, the chat
+header counts the same tasks in a small pill, and both follow the server live — the mark
+appears when a command is promoted past its yield window or launched in the background,
+and leaves the moment the last task ends, without a list refresh. The same mark sits on the
+tool row of a call made with `run_in_background`, so the transcript and the conversation
+list say the same thing about the same work.
+
+## Details
+
+- `SessionInfo` gained an optional `backgroundTasks: { processes, subagents }`, read from the
+ loaded runtime's in-memory registries — command sessions still running, and subagent
+ sessions that hold a `subagent_id` and are mid-round. The field is present only while at
+ least one count is non-zero; an unloaded Session and one with nothing running both omit it.
+ List rows and the single-session GET carry the same field.
+- A new user-level event, `session_background`, is published on `GET /api/events` whenever a
+ Session's counts move (a promotion, an exit, a stop, a subagent round starting or settling, a
+ release), carrying the counts as they now stand — zeros included — to the Project's owner
+ and members, the same audience as `session_state`.
+- Core's `Environment` gained a single background-state listener (`setBackgroundStateListener`,
+ forwarded by `Session.onBackgroundState`) fed by the background registries' membership
+ changes, the exit of a registered command process, and the subagent run-state pings, so a
+ host hears everything that changes "what is still running in the background" from one
+ subscription.
+- The sidebar row draws the mark in the `busy` tone with its count in the tooltip and accessible
+ name ("2 background tasks" / 「2 个后台任务」), beside the running / compacting / unread
+ glyph rather than instead of it: an idle, read conversation whose dev server is still up
+ keeps the mark. The chat header's former "running services" count became this pill; it now
+ includes background subagents and reads the row's live figure instead of the process poll,
+ and a count change also re-reads the process list at once.
+- A tool row whose call carries `run_in_background: true` draws the same mark right of its
+ duration, where it names one call rather than a count ("Runs in the background" / 「在后台
+ 运行」) — a backgrounded call returns at once, and its row otherwise looks like any settled
+ step.
+- The mark is an activity trace — a flat line with one tall beat — rather than the layered
+ stack first shipped in this branch, which read as "layers" instead of "still running" and
+ whose two parallelograms merged into a smudge at the row's 12px.
+- The Web App, server API and design docs describe the mark, the field and the event.
diff --git a/changelog/unreleased/2026-09-02-session-background-indicator.zh.md b/changelog/unreleased/2026-09-02-session-background-indicator.zh.md
new file mode 100644
index 00000000..1384f621
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-session-background-indicator.zh.md
@@ -0,0 +1,20 @@
+# 会话列表标出仍有后台任务的对话
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#585](https://github.com/Prism-Shadow/penguin-harness/pull/585)
+
+[English](2026-09-02-session-background-indicator.md)
+
+起了 dev server 或后台子智能体的对话,现在会在侧栏里说明这一点:会话行在原有状态字形旁多一枚小小的活动波形标记,对话页头部以一枚小胶囊显示同一数量,二者都随服务端实时变化——命令超过 yield 窗口转入后台或以后台方式启动时标记出现,最后一项后台任务结束的那一刻标记消失,无需刷新列表。以 `run_in_background` 发起的调用,其工具行上也带同一枚标记,消息流与会话列表就同一份工作说同一件事。
+
+## 细节
+
+- `SessionInfo` 新增可选字段 `backgroundTasks: { processes, subagents }`,读自已加载运行时的内存注册表——仍在运行的命令会话,以及持有 `subagent_id`、正在跑一轮的子会话。只在至少一项非零时出现;未加载的 Session 与没有任何后台任务的 Session 都省略该字段。列表行与单条查询携带同一字段。
+- 新增用户级事件 `session_background`:Session 的计数发生变化(转后台、退出、停止、子智能体开始或结束一轮、释放)时经 `GET /api/events` 推送,携带此刻的计数——归零同样推送——发往该 Project 的拥有者与成员,受众与 `session_state` 相同。
+- core 的 `Environment` 新增单一的后台状态监听器(`setBackgroundStateListener`,由 `Session.onBackgroundState` 转发),由后台注册表的成员变化、已登记命令进程的退出与子会话轮次状态共同触发,宿主只需一次订阅即可听到「后台还在跑什么」的全部变化。
+- 侧栏会话行以 `busy` 色调绘制该标记,数量放在悬停提示与可访问名里(「2 个后台任务」/ "2 background tasks"),与运行中 / 压缩中 / 未读字形**并存**而非替代:dev server 还开着的空闲、已读对话照样带着它。对话页头部原先的「运行中的服务」计数改为这枚胶囊:现在把后台子智能体一并计入,并读取会话行的实时数字而不是进程轮询结果;计数变化时也会立即重读一次进程列表。
+- 参数含 `run_in_background: true` 的工具行在用时右侧绘制同一枚标记,此处指的是这一次调用而非数量(「在后台运行」/ "Runs in the background")——后台调用立刻返回,其行在其他方面与任何已完成的步骤无异。
+- 该标记是一条带单个高峰的活动波形,取代本分支先前的层叠图形:层叠读起来是「层」而不是「还在跑」,且两片平行四边形在会话行的 12px 上会糊成一团。
+- Web App、服务端 API 与设计文档补充了该标记、字段与事件的说明。
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index 66aea3e7..6afc85f8 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -176,6 +176,16 @@ export class Environment implements EnvironmentInterface {
...(config.controlEnv !== undefined ? { controlEnv: config.controlEnv } : {}),
});
this.subagentSessions = new SubagentSessionManager();
+ // Background-task liveness fans in from both registries and from the subagent run-state
+ // pings: the host's background-state listener hears every change of "what is still
+ // running in the background", while its run-state listener hears only the rounds.
+ this.commandSessions.onChange(() => this.emitBackgroundState());
+ this.subagentSessions.onChange(() => this.emitBackgroundState());
+ this.subagentSessions.setStateListener(() => {
+ if (this.bgDisposed) return;
+ this.subagentStateListener?.();
+ this.emitBackgroundState();
+ });
this.subagentRunner = config.services?.subagentRunner ?? null;
this.services = {
...config.services,
@@ -265,6 +275,15 @@ export class Environment implements EnvironmentInterface {
private bgListener: ((event: BackgroundTaskDoneEvent) => void) | null = null;
private bgBuffer: BackgroundTaskDoneEvent[] = [];
private bgDisposed = false;
+ /** Host subagent run-state listener (see setSubagentStateListener); null until a host subscribes. */
+ private subagentStateListener: (() => void) | null = null;
+ /** Host background-task state listener (see setBackgroundStateListener); null until a host subscribes. */
+ private bgStateListener: (() => void) | null = null;
+
+ private emitBackgroundState(): void {
+ if (this.bgDisposed) return;
+ this.bgStateListener?.();
+ }
private emitBackgroundDone(event: BackgroundTaskDoneEvent): void {
if (this.bgDisposed) return;
@@ -411,11 +430,14 @@ export class Environment implements EnvironmentInterface {
return this.subagentSessions.bySessionId(childSessionId)?.setThinkingLevel(level) ?? false;
}
- /** Attaches the single subagent run-state listener (see EnvironmentInterface.setSubagentStateListener). */
+ /** Attaches the single subagent run-state listener (see EnvironmentInterface.setSubagentStateListener); the manager's own listener is installed at construction and fans out to it. */
setSubagentStateListener(listener: () => void): void {
- this.subagentSessions.setStateListener(() => {
- if (!this.bgDisposed) listener();
- });
+ this.subagentStateListener = listener;
+ }
+
+ /** Attaches the single background-task state listener (see EnvironmentInterface.setBackgroundStateListener). Not buffered: the ping carries nothing, and a host reads the registries when it attaches. */
+ setBackgroundStateListener(listener: () => void): void {
+ this.bgStateListener = listener;
}
/** Attaches the host's session-lifetime fallback approval sink for child sessions (see EnvironmentInterface.setSubagentApprovalFallback). */
diff --git a/packages/core/src/environment/tools/background/registry.ts b/packages/core/src/environment/tools/background/registry.ts
index 6d4937b6..1002c3a6 100644
--- a/packages/core/src/environment/tools/background/registry.ts
+++ b/packages/core/src/environment/tools/background/registry.ts
@@ -57,6 +57,8 @@ export class BackgroundRegistry<T extends BackgroundTask> {
private readonly maxTasks: number;
private readonly reapTimer: ReturnType<typeof setInterval>;
private disposed = false;
+ /** Single membership listener (see onChange); null until a manager subscribes. */
+ private changeListener: (() => void) | null = null;
constructor(opts: { idPrefix: string; maxTasks: number }) {
this.idPrefix = opts.idPrefix;
@@ -109,9 +111,21 @@ export class BackgroundRegistry<T extends BackgroundTask> {
while (this.tasks.has(id)) id = this.randomId();
task.lastUsed = Date.now();
this.tasks.set(id, task);
+ this.changeListener?.();
return id;
}
+ /**
+ * Attaches the single membership listener: pinged after a session enters the registry
+ * and after one leaves it — an explicit removal, a capacity eviction, an idle reap, or the
+ * clear-out of killAll/dispose (killAllHard fires nothing: the event loop is already
+ * gone). Payload-free; a subscriber re-reads `list()`. A later call replaces the earlier
+ * one.
+ */
+ onChange(listener: () => void): void {
+ this.changeListener = listener;
+ }
+
private randomId(): string {
return `${this.idPrefix}-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
}
@@ -140,12 +154,15 @@ export class BackgroundRegistry<T extends BackgroundTask> {
if (!t) return;
this.tasks.delete(id);
t.kill();
+ this.changeListener?.();
}
/** Kills and clears all sessions (called when the Session/Environment ends). */
killAll(): void {
+ const had = this.tasks.size > 0;
for (const t of this.tasks.values()) t.kill();
this.tasks.clear();
+ if (had) this.changeListener?.();
}
/** Synchronously hard-kills all sessions (process 'exit' fallback path). */
diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.ts
index c5fe805f..6ec9a67e 100644
--- a/packages/core/src/environment/tools/command/session-manager.ts
+++ b/packages/core/src/environment/tools/command/session-manager.ts
@@ -210,6 +210,8 @@ export class CommandSessionManager {
* A getter like `proxyEnv`, re-read at every spawn. Absent = nothing injected.
*/
private readonly controlEnv: (() => Record<string, string>) | undefined;
+ /** Single change listener (see onChange); null until the Environment subscribes. */
+ private changeListener: (() => void) | null = null;
constructor(opts?: {
vault?: Record<string, string>;
@@ -219,6 +221,17 @@ export class CommandSessionManager {
this.vault = opts?.vault ?? {};
this.proxyEnv = opts?.proxyEnv;
this.controlEnv = opts?.controlEnv;
+ this.registry.onChange(() => this.changeListener?.());
+ }
+
+ /**
+ * Attaches the single listener for changes to the set of running background commands: a
+ * session registered, one removed (kill, reap, eviction, dispose), and a registered
+ * process reaching its terminal state on its own. Payload-free; subscribers re-read
+ * `list()`. A later call replaces the earlier one.
+ */
+ onChange(listener: () => void): void {
+ this.changeListener = listener;
}
/**
@@ -269,7 +282,11 @@ export class CommandSessionManager {
/** Registers a still-running session as a background process, allocating and returning a unique `process_id`. */
register(session: ManagedSession): string {
this.registry.makeRoom(true);
- return this.registry.register(session);
+ const id = this.registry.register(session);
+ // A registered process that exits on its own leaves the running set without leaving the
+ // registry (its row stays listed as exited until removed), so the exit itself is reported.
+ session.setExitListener(() => this.changeListener?.());
+ return id;
}
/** Looks up a session by process_id and refreshes its access time; returns undefined if it doesn't exist. */
diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.ts
index 6ac92a86..58459906 100644
--- a/packages/core/src/environment/tools/command/session.ts
+++ b/packages/core/src/environment/tools/command/session.ts
@@ -191,10 +191,13 @@ export class ManagedSession {
// One-shot exit watchers (run_in_background completion reports). Consumed on fire; a
// watcher armed after exit fires on a microtask, so the caller never misses a fast command.
private exitWatchers: Array<() => void> = [];
+ /** Persistent exit listener (see setExitListener); null until the registry subscribes. */
+ private exitListener: (() => void) | null = null;
private fireExitWatchers(): void {
const watchers = this.exitWatchers;
this.exitWatchers = [];
for (const cb of watchers) cb();
+ this.exitListener?.();
}
/** Registers a one-shot callback for the foreground process's terminal state (exit or spawn failure); fires immediately (microtask) when already terminal. */
@@ -211,6 +214,18 @@ export class ManagedSession {
this.exitWatchers = [];
}
+ /**
+ * Attaches the single persistent exit listener: fires once when the foreground process
+ * reaches its terminal state, whatever ended it. Unlike the one-shot watchers above it is
+ * not disarmed by clearExitWatchers — a deliberate kill is still the process leaving the
+ * running set, which is what a registry's membership view has to hear. Fires on a
+ * microtask when the session is already terminal.
+ */
+ setExitListener(listener: () => void): void {
+ this.exitListener = listener;
+ if (this.exited) queueMicrotask(listener);
+ }
+
/** Synchronously drains the yet-undelivered output (the same buffer `collect` serves) — used to build completion reports without an async window. */
drainPending(): string {
return this.buffer.drain();
diff --git a/packages/core/src/environment/tools/subagent/session-manager.ts b/packages/core/src/environment/tools/subagent/session-manager.ts
index 5c613937..65d1fa42 100644
--- a/packages/core/src/environment/tools/subagent/session-manager.ts
+++ b/packages/core/src/environment/tools/subagent/session-manager.ts
@@ -37,6 +37,22 @@ export class SubagentSessionManager {
private stateListener: (() => void) | null = null;
/** Host fallback approval sink, applied to every tracked session (see EnvironmentInterface.setSubagentApprovalFallback). */
private approvalFallback: ApproveFn | null = null;
+ /** Single registry-membership listener (see onChange); null until the Environment subscribes. */
+ private changeListener: (() => void) | null = null;
+
+ constructor() {
+ this.registry.onChange(() => this.changeListener?.());
+ }
+
+ /**
+ * Attaches the single listener for registry membership changes — a session promoted to
+ * the background (register) or released from it (eviction, idle reap, dispose). Round
+ * start/settle rides the separate run-state listener (setStateListener). Payload-free;
+ * subscribers re-read `listLive()`. A later call replaces the earlier one.
+ */
+ onChange(listener: () => void): void {
+ this.changeListener = listener;
+ }
/** Whether the manager has been disposed (the host Session has ended). */
get isDisposed(): boolean {
diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.ts
index bb37863b..b22ad40c 100644
--- a/packages/core/src/interfaces/environment.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -462,6 +462,15 @@ export interface EnvironmentInterface {
* Optional, same single-listener pattern as setBackgroundTaskListener.
*/
setSubagentStateListener?(listener: () => void): void;
+ /**
+ * Attaches the single listener for background-task state changes: a command session
+ * promoted to the background, exited, stopped or removed; a subagent session promoted,
+ * starting or settling a round, or released. Payload-free — the host re-reads
+ * `listBackgroundCommands` / `listBackgroundSubagents` on each ping, and reads them once
+ * when it attaches (pings before that are not buffered). Optional, same single-listener
+ * pattern as setSubagentStateListener.
+ */
+ setBackgroundStateListener?(listener: () => void): void;
/**
* Attaches the host's session-lifetime fallback approval sink for child sessions: a child
* approval with no window sink (an active run_subagent/input_subagent call) and no
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index 7a8a021f..82439294 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -926,6 +926,11 @@ export class Session {
this.environment.setSubagentStateListener?.(listener);
}
+ /** Attaches the single listener for background-task state changes; the host re-reads `listBackgroundCommands` / `listBackgroundSubagents` on each ping (see EnvironmentInterface.setBackgroundStateListener). */
+ onBackgroundState(listener: () => void): void {
+ this.environment.setBackgroundStateListener?.(listener);
+ }
+
/** Queues a background completion event; a running Task delivers it at the next boundary, otherwise the host is signaled (see pendingNotices). */
private handleBackgroundDone(event: BackgroundTaskDoneEvent): void {
this.pendingNotices.push(event);
diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.ts
index d6846ef1..8f38602b 100644
--- a/packages/core/test/background-execution.test.ts
+++ b/packages/core/test/background-execution.test.ts
@@ -353,6 +353,79 @@ describe("exec_command run_in_background", () => {
});
});
+describe("background-state listener", () => {
+ it("pings on a background launch, again when the process exits, and on a kill", async () => {
+ const { env } = await makeEnv();
+ let pings = 0;
+ env.setBackgroundStateListener(() => {
+ pings += 1;
+ });
+ const res = await runTool(env, "exec_command", {
+ cmd: "printf done; exit 0",
+ run_in_background: true,
+ });
+ extractProcessId(res.output);
+ // Registration pinged synchronously, inside the launching call.
+ expect(pings).toBeGreaterThanOrEqual(1);
+ // The exit pings on its own: the row stays listed (exited) but leaves the running set.
+ await waitFor(() => env.listBackgroundCommands().every((p) => !p.running));
+ await waitFor(() => pings >= 2);
+
+ const settled = pings;
+ const long = await runTool(env, "exec_command", { cmd: "sleep 30", run_in_background: true });
+ const id = extractProcessId(long.output);
+ expect(pings).toBe(settled + 1);
+ // A deliberate kill disarms the completion report but not this: the registry removal
+ // pings synchronously, and the group's later exit adds nothing the host has to act on.
+ const killed = await runTool(env, "input_command", { process_id: id, kill: true });
+ expect(killed.stopReason).toBe("completed");
+ expect(pings).toBeGreaterThan(settled + 1);
+ expect(env.listBackgroundCommands().find((p) => p.processId === id)).toBeUndefined();
+ });
+
+ it("pings when a subagent is promoted to the background and when its round settles", async () => {
+ const gates = new Map<string, () => void>();
+ const runner = runnerOf(async function* ({ prompt }) {
+ await new Promise<void>((r) => gates.set(prompt, r));
+ yield withHop(assistantText(`answer to: ${prompt}`));
+ });
+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-bg-"));
+ const env = new Environment({
+ workspaceDir: dir,
+ toolConfig: { customTools: [SUB_DEF], mcpServers: [] },
+ services: { subagentRunner: runner },
+ });
+ cleanups.push(async () => {
+ env.dispose();
+ await rm(dir, { recursive: true, force: true });
+ });
+ let pings = 0;
+ env.setBackgroundStateListener(() => {
+ pings += 1;
+ });
+ const res = await runTool(env, "run_subagent", { prompt: "bg task", run_in_background: true });
+ expect(res.stopReason).toBe("completed");
+ expect(pings).toBeGreaterThanOrEqual(1);
+ // Promoted (it holds a subagent_id) and mid-round: what a host counts as a background subagent.
+ expect(env.listBackgroundSubagents()).toMatchObject([{ running: true }]);
+ expect(env.listBackgroundSubagents()[0]!.subagentId).not.toBeNull();
+
+ const launched = pings;
+ await waitFor(() => gates.has("bg task"));
+ gates.get("bg task")!();
+ await waitFor(() => !env.hasRunningBackgroundSubagents());
+ // The round settling rides the same listener as the registry changes: one subscription
+ // hears everything that moves the count.
+ expect(pings).toBeGreaterThan(launched);
+ expect(env.listBackgroundSubagents()).toMatchObject([{ running: false }]);
+
+ // Disposal is silent: the Session has ended, and its registries emptying is not news.
+ const beforeDispose = pings;
+ env.dispose();
+ expect(pings).toBe(beforeDispose);
+ });
+});
+
describe("input_command defaults", () => {
it("the default empty-poll wait is 120000ms", () => {
expect(DEFAULT_EMPTY_POLL_YIELD_MS).toBe(120_000);
diff --git a/packages/core/test/background-registry.test.ts b/packages/core/test/background-registry.test.ts
index 1396c172..2ee38136 100644
--- a/packages/core/test/background-registry.test.ts
+++ b/packages/core/test/background-registry.test.ts
@@ -1,5 +1,6 @@
/**
- * Behavior tests for BackgroundRegistry's idle reaping (a leak safety net).
+ * Behavior tests for BackgroundRegistry's idle reaping (a leak safety net) and its
+ * membership listener (what a host's background-task count is driven by).
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BackgroundRegistry } from "../src/environment/tools/background/index.js";
@@ -62,3 +63,41 @@ describe("BackgroundRegistry idle reaping", () => {
expect(() => vi.advanceTimersByTime(30 * 24 * 60 * 60_000)).not.toThrow();
});
});
+
+describe("BackgroundRegistry membership listener", () => {
+ it("pings on every entry and exit, and once for a clear-out that removed anything", () => {
+ const registry = new BackgroundRegistry<FakeTask>({ idPrefix: "proc", maxTasks: 4 });
+ let pings = 0;
+ registry.onChange(() => {
+ pings += 1;
+ });
+ const a = registry.register(fakeTask());
+ const b = registry.register(fakeTask());
+ expect(pings).toBe(2);
+ registry.remove(a);
+ expect(pings).toBe(3);
+ // An id no longer (or never) held changes nothing, so nothing is reported.
+ registry.remove(a);
+ registry.remove("proc-nope");
+ expect(pings).toBe(3);
+ // killAll reports once for the whole clear-out, and not at all when it was already empty.
+ registry.killAll();
+ expect(pings).toBe(4);
+ registry.killAll();
+ expect(pings).toBe(4);
+ expect(registry.get(b)).toBeUndefined();
+ registry.dispose();
+ expect(pings).toBe(4);
+ });
+
+ it("reports a capacity eviction as an exit before the newcomer's entry", () => {
+ const registry = new BackgroundRegistry<FakeTask>({ idPrefix: "proc", maxTasks: 1 });
+ const sizes: number[] = [];
+ registry.onChange(() => sizes.push(registry.size));
+ registry.register(fakeTask());
+ registry.makeRoom(true);
+ registry.register(fakeTask());
+ expect(sizes).toEqual([1, 0, 1]);
+ registry.dispose();
+ });
+});
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 5d50764d..b954e2cd 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -430,7 +430,7 @@ Real-time delivery uses Server-Sent Events, not WebSocket, on two channels (the
| Channel | Path | Contents |
| --- | --- | --- |
| Per Session | GET /api/sessions/:sessionId/stream | The Session's message stream and run events |
-| Per user | GET /api/events | `hello` handshake and cross-Session notifications (session_state / schedule_fired / schedule_queued / session_created) |
+| Per user | GET /api/events | `hello` handshake and cross-Session notifications (session_state / session_background / schedule_fired / schedule_queued / session_created) |
### Wire Format
@@ -442,6 +442,7 @@ export type ServerEvent =
| { type: "task_state"; state: "idle" | "running" | "compacting" }
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
+ | { type: "session_background"; sessionId: string; processes: number; subagents: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
@@ -456,6 +457,7 @@ export type ServerEvent =
| task_state | The Session's run state flips (idle / running / compacting) |
| session_title | The model-generated title after the first turn has been persisted |
| session_state | The user-channel counterpart of `task_state`: the same run-state flip, named by `sessionId`, so a Session list stays live for every row and not only the conversation a client has open. Carries the row fields needed to redraw it without refetching — `lastActiveAt` as just stamped, and `hasTrace` (true whenever the state is running or compacting, since a Session that is running has by definition started a Task). Published to the user channels of the Project's owner and members |
+| session_background | A Session's background-task counts changed — a command promoted past its yield window or launched with `run_in_background`, a process that exited or was stopped, a background subagent starting, settling or being released. Carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = promoted subagent sessions mid-round), zeros included so a list can clear its mark without refetching; the list row and the single-session GET omit the field at zero. Same audience as `session_state` |
| resync_required | The Last-Event-ID was evicted from the buffer; the client must refetch history |
| credentials_updated | The Project's model credentials changed (`PUT /models`, or a completed key-minting flow): cached runtimes were invalidated, so the client clears any auth-dead composer state |
| hello | Handshake on the user channel |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 2618c7b0..c80348e3 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -427,7 +427,7 @@ Web 的 `/model` 模型切换没有专用接口:它按 `/agent` 交接的方
| 通道 | 路径 | 内容 |
| --- | --- | --- |
| Session 级 | GET /api/sessions/:sessionId/stream | 该 Session 的消息流与运行事件 |
-| 用户级 | GET /api/events | `hello` 握手与跨 Session 通知(session_state / schedule_fired / schedule_queued / session_created) |
+| 用户级 | GET /api/events | `hello` 握手与跨 Session 通知(session_state / session_background / schedule_fired / schedule_queued / session_created) |
### 传输格式
@@ -439,6 +439,7 @@ export type ServerEvent =
| { type: "task_state"; state: "idle" | "running" | "compacting" }
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
+ | { type: "session_background"; sessionId: string; processes: number; subagents: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
@@ -453,6 +454,7 @@ export type ServerEvent =
| task_state | Session 运行状态翻转(idle / running / compacting) |
| session_title | 首轮后模型生成的标题已持久化 |
| session_state | `task_state` 在用户通道上的对应事件:同一次运行状态翻转,带上 `sessionId`,因此会话列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件还携带重绘该行所需的行字段,无需重新拉取列表 —— 刚刚写入的 `lastActiveAt`,以及 `hasTrace`(状态为 running 或 compacting 时必为 true,因为正在运行的会话必然已经启动过 Task)。仅发往该 Project 拥有者与成员的用户通道 |
+| session_background | 某个 Session 的后台任务计数发生变化——命令超过 yield 窗口转入后台或以 `run_in_background` 启动、进程退出或被停止、后台子智能体开始一轮、结束一轮或被释放。携带此刻的 `SessionInfo.backgroundTasks`(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转后台、正在跑一轮的子会话数),归零时同样推送,列表据此即可撤下标记而无需重新拉取;列表行与单条查询在计数为零时省略该字段。受众与 `session_state` 相同 |
| resync_required | Last-Event-ID 已被缓冲区淘汰,客户端须重新拉取历史 |
| credentials_updated | Project 模型凭据已变更(`PUT /models`,或一次完成的授权新建 key 流程):缓存运行时已失效,客户端应清除鉴权失败的输入框禁用态 |
| hello | 用户通道连接握手 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 6502ccf1..2e66077e 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -48,18 +48,20 @@ A row's actions come at two levels:
- **Hovering** a row replaces the trailing last-active time with two icon buttons — archive and delete. They are reachable from the keyboard too: tabbing onto either one reveals it;
- **Right-clicking** a row opens the full menu at the pointer: pin, rename, archive, delete. A **long press** on touch and **Shift+F10** on the keyboard open the same menu, since neither hover nor a secondary click exists there. Escape, a click elsewhere, or scrolling the list dismisses it; the browser's own context menu is taken over on conversation rows only, and stays as usual everywhere else on the page.
+Beside a row's title sit its status marks: a turning hourglass while the Session runs (a squeezing bar while it compacts), a green dot once a run finished that you have not looked at yet, and a small activity trace while the Session still owns **background tasks** — commands running on past their yield window and background subagents mid-round. Its tooltip counts them ("2 background tasks"). The mark is independent of the others: an idle conversation whose dev server is still up keeps it, and it disappears the moment the last task ends, pushed live without a refresh.
+
Pinning is offered only in the active list — the archived, subagent and scheduled folders leave it out — and a pinned conversation sorts to the top of its group. The choice is remembered per Project in the browser.
### Streaming Rendering
- Model text renders token by token; thinking blocks are collapsible;
-- Tool cards expand to show arguments and output, with a live timer while running;
+- Tool cards expand to show arguments and output, with a live timer while running; a call made with `run_in_background` carries the same activity trace as the conversation list, right of its duration ("Runs in the background") — the call returns at once, and the mark says its work did not;
- Subagents leave a full-width row in the stream, styled like the other collapsed step rows (agent avatar, name, short session id, running spinner, and an amber dot while one of their tool calls awaits approval); clicking it opens the agents side panel — a call graph of that row's Task on top (each node shows its elapsed time; click a node to switch) and the selected child's live conversation below — the child's own user prompts included — where nested tool cards and approvals work exactly as in the main chat. Panel visibility is task-scoped: sending a message that starts a new task closes it by default (entering a session starts closed too), and it comes back when you open it yourself or — on desktop — when the current task spawns a subagent (one auto-open per task; a manual close holds until the next task; never over an open files panel). Opening the panel from the toolbar, or switching sessions, shows the latest Task's graph; a row on an older turn brings back that turn's graph. The agents panel and the Workspace files panel never show together — opening one closes the other. Context compaction and the first-run MCP connect show a unified step row (the work-group header shell, sticky title bar included — running/success/failure only swap the icon and the one-line detail, with the wall time on the result; the MCP row leads with the discovered-tool count and names unavailable servers, and expands into one group per server — status, tool count and that server's connect time — each opening into its tool list or the failure detail);
- After each Task, a stats line shows tokens, TPS, elapsed time, cost, copy, and a **Fork** action to the right of copy. Fork asks for confirmation first — it duplicates the conversation into a new chat — and only then opens a new Session at that completed assistant reply with the same Agent, model, Workspace, approval mode, and retained transcript. Forks from different replies in one source chat share an increasing, language-neutral title sequence (`Source title (1)`, `Source title (2)`). Its Trace and scratchpad are independent snapshots: local images/files keep rendering even after the source chat is deleted;
### Header Stats and the Details Card
-The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. Below those:
+The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. Right of the elapsed time, while the conversation still owns background tasks, a small pill shows their count — the same figure the conversation list's mark carries. Below those:
- **Processes** — background processes the conversation started (`exec_command`s promoted past their yield window), one row each with the command, start time and pid — plus, on running rows, a link to the service the process serves when one was detected (the last local URL its output printed, else a listen-port probe of its process group). Running rows carry a **Stop** button (kills the whole process group and drops the row) — the conversation is told the process is down, as **stopped** rather than failed, so the model knows the dev server is gone without reading it as a crash to restart; exited rows keep their "exited" label and carry a **Remove** button that deletes the entry from the list. Removal is immediate and final: the entry leaves the runtime registry together with the output captured from that process, so afterwards the model can no longer be asked to read it — keep the row until you are done with its output.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 7d1b959f..950c6532 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -48,18 +48,20 @@ penguin web
- **悬停**一行时,行尾的最近活跃时间让位给两个图标按钮——归档与删除;键盘同样够得到:Tab 到其中任意一个,该按钮即显形;
- **右键点击**一行,在指针处打开完整菜单:置顶、重命名、归档、删除。触屏**长按**、键盘 **Shift+F10** 打开同一个菜单(触屏没有悬停,也没有右键)。按 Esc、点击别处或滚动列表都会关闭它;系统右键菜单只在会话行上被接管,页面其他位置照常。
+会话行标题旁是它的状态标记:Session 运行中是翻转的沙漏(压缩中是向中线合拢的压缩标),有一条你还没看过的回复时是一枚绿点,会话仍有**后台任务**——超过 yield 窗口继续运行的命令、正在跑一轮的后台子智能体——时另有一枚小小的活动波形标记,悬停显示数量(「2 个后台任务」)。这枚标记与其他标记互不影响:dev server 还开着的空闲对话照样带着它,最后一项后台任务结束的那一刻它即消失,由服务端实时推送、无需刷新。
+
置顶只在活跃列表里出现(已归档、子智能体与定时任务的折叠夹中没有这一项),置顶的会话排在所属分组的最前面,该状态按 Project 记在浏览器本地。
### 流式渲染
- 模型文本逐 Token 渲染,思考块可折叠;
-- 工具卡片可展开查看参数与输出,执行中显示实时计时;
+- 工具卡片可展开查看参数与输出,执行中显示实时计时;以 `run_in_background` 发起的调用在用时右侧带与会话列表同一枚活动波形标记(「在后台运行」)——调用本身立刻返回,标记说明它的工作没有;
- 子 Agent 在消息流中只留下一条通栏行,样式与其他折叠步骤行一致(头像、名称、短会话号、运行中转圈,子会话内有待审批时带琥珀色圆点);点击打开右侧智能体面板——上方是该行所属 Task 派生关系的调用图(节点上显示运行时长,点节点切换),下方是所选子会话的实时对话(含子会话自己的用户消息),嵌套工具卡片与审批与主对话完全一致;面板的显示以任务为界:发送消息开启新任务时默认关闭(进入会话时同样默认关闭),仅在手动打开、或(桌面端)当前任务派生子智能体时重新显示(每个任务自动打开一次,任务内手动关闭后保持关闭到下个任务,且不抢占已打开的工作区面板);从工具条打开面板或切换 Session 时默认展示最新 Task 的调用图,点旧轮次的行则回看那一轮的调用图;智能体面板与工作区面板不会同时显示,打开一个即关闭另一个;上下文压缩与首次 MCP 连接以统一样式的步骤行提示(与运行分组头同款外壳,含吸顶标题栏,连接中/成功/失败仅切换图标与单行详情,结果行含耗时;MCP 行主显发现的工具数并点名不可用的 Server,展开后按 Server 分组——每组一行状态、工具数与该 Server 的连接耗时,点开组内是工具列表或失败原因);
- 每个 Task 结束后显示统计行:Token 用量、TPS、耗时、费用、复制以及位于复制按钮右侧的**分叉**操作。分叉会先弹出确认框(该操作会把对话复制为一个新对话),确认后才在该条已完成的模型回复处新建 Session,沿用 Agent、模型、Workspace、审批模式和保留范围内的历史;同一源对话从不同回复分叉时,标题使用不依赖界面语言的编号后缀,按 `原标题 (1)`、`原标题 (2)` 递增。新旧会话的 Trace 与 scratchpad 是独立快照,即使删除源对话,本地图片和附件仍可显示;
### 头部统计与详情卡
-工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。其下还有一节:
+工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。会话仍有后台任务时,用时右侧有一枚小胶囊显示其数量——与会话列表行上那枚标记同一个数。其下还有一节:
- **会话进程**——对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`),逐行显示命令、启动时间与 pid;运行中的行在检测到进程所服务的地址时,还会附上可点击的服务链接(取其输出打印的最后一个本机 URL,否则对其进程组做监听端口探测)。运行中的行带「停止」按钮(杀停整个进程组并把该行从列表移除)——对话会收到该进程已结束的回报,措辞是「已停止」而非失败,模型因此知道 dev server 没了,却不会把它读成需要重启的崩溃;已退出的行保留「已退出」标注,并带「移除」按钮,可把该条目从列表删除。移除立即生效且不可撤销:条目连同该进程已捕获的输出一起离开运行时注册表,之后无法再让模型读取那段输出——输出还有用时请先留着这一行。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 10b332a9..d24ca830 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1234,6 +1234,24 @@ export interface SessionInfo {
tracePath?: string;
/** Present when the Session has an ENABLED messaging binding: its channel (the sidebar row's per-channel indicator). */
messagingChannel?: MessagingChannel;
+ /**
+ * Background work the Session's loaded runtime still owns: command sessions running past
+ * their yield window (`exec_command` promotions and `run_in_background` launches) and
+ * background subagent sessions mid-round. Read from the runtime's in-memory registries —
+ * no Trace is consulted — and present only while at least one count is non-zero, so a
+ * Session that is not loaded (a resumed entry starts with empty registries) and one with
+ * nothing running both omit it. Changes are pushed as `session_background` on the user
+ * channel; list rows and the single-session GET carry the same field.
+ */
+ backgroundTasks?: SessionBackgroundTasks;
+}
+
+/** The background-task counts of one Session (see SessionInfo.backgroundTasks). */
+export interface SessionBackgroundTasks {
+ /** Background command sessions whose process is still running. */
+ processes: number;
+ /** Background subagent sessions (promoted to a `subagent_id`) currently mid-round. */
+ subagents: number;
}
/**
@@ -2245,6 +2263,14 @@ export type ServerEvent =
lastActiveAt: string;
hasTrace: boolean;
}
+ /**
+ * A Session's background-task counts changed: a command promoted to the background, a
+ * process that exited or was stopped, a background subagent starting or settling a round,
+ * a released session. The counts are the row's `backgroundTasks` as they stand after the
+ * change — zeros included, so a list can clear its mark without refetching. Published to
+ * the user channels of the Project's owner and members, like `session_state`.
+ */
+ | { type: "session_background"; sessionId: string; processes: number; subagents: number }
/** Last-Event-ID has been evicted from the buffer: the frontend should re-fetch the history endpoint before continuing to consume this connection. */
| { type: "resync_required" }
/**
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index fc4f6440..768f9ab6 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -59,6 +59,7 @@ import type {
PendingFollowUpInfo,
PendingSteeringInfo,
ServerEvent,
+ SessionBackgroundTasks,
SessionStatus,
} from "../api/types.js";
import type { RecallableFile } from "../services/task-attachments.js";
@@ -196,6 +197,8 @@ export interface RuntimeSession {
setBackgroundSubagentThinkingLevel?(childSessionId: string, level: ThinkingLevelName): boolean;
/** Subscribes subagent run-state changes (core `Session.onSubagentState`): the manager republishes `task_state` with the fresh live listing. Optional. */
onSubagentState?(listener: () => void): void;
+ /** Subscribes background-task state changes (core `Session.onBackgroundState`): the manager re-counts the live registries and publishes `session_background` when the counts moved. Optional. */
+ onBackgroundState?(listener: () => void): void;
/** Releases environment resources — kills the remaining background processes (core `Session.dispose`). Optional, idempotent. */
dispose?(): void;
}
@@ -436,8 +439,15 @@ interface RuntimeEntry {
* idle eviction — removes one.
*/
returnedSteering: PendingSteeringEntry[];
- /** Timestamp of last activity (refreshed on load / status flip / drive completion), used for idle-eviction checks. */
+ /** Timestamp of last activity (refreshed on load / status flip / drive completion / background-task change), used for idle-eviction checks. */
lastActivityMs: number;
+ /**
+ * Background-task counts as last read from the runtime — at entry creation, then on every
+ * background-state ping. The baseline `session_background` is published against: a ping
+ * that leaves the counts where they were (a foreground-window child settling, an exited
+ * process being removed from the list) publishes nothing.
+ */
+ backgroundTasks: SessionBackgroundTasks;
}
/** Active-table idle eviction: same convention as the SSE channel (an idle entry with no activity for 30 minutes releases its memory). */
@@ -449,6 +459,22 @@ function agentKey(projectId: string, agentId: string): string {
return `${projectId}\0${agentId}`;
}
+/**
+ * The runtime's background-task counts, read live from its registries: command sessions
+ * whose process is still running (exited rows stay listed until removed and do not count),
+ * and subagent sessions that hold a `subagent_id` — promoted to the background by a yield
+ * window expiring or a `run_in_background` launch — and are mid-round. A child still inside
+ * a foreground collect window has no id yet and is the running Task's own work, not
+ * background work.
+ */
+function backgroundTaskCounts(session: RuntimeSession): SessionBackgroundTasks {
+ const processes = session.listBackgroundCommands?.().filter((p) => p.running).length ?? 0;
+ const subagents =
+ session.listBackgroundSubagents?.().filter((s) => s.running && s.subagentId !== null).length ??
+ 0;
+ return { processes, subagents };
+}
+
/** The `task_state` display info of one queued follow-up (see PendingFollowUpInfo). */
function followUpInfo(f: QueuedFollowUp): PendingFollowUpInfo {
return {
@@ -596,6 +622,18 @@ export class SessionManager {
return this.entries.get(sessionId)?.followUps.length ?? 0;
}
+ /**
+ * Background-task counts of a LOADED session, read live (see SessionInfo.backgroundTasks);
+ * undefined when the session is not in the active table or nothing is running — the list
+ * row and the single GET omit the field in both cases.
+ */
+ backgroundTasksOf(sessionId: string): SessionBackgroundTasks | undefined {
+ const entry = this.entries.get(sessionId);
+ if (!entry) return undefined;
+ const counts = backgroundTaskCounts(entry.session);
+ return counts.processes > 0 || counts.subagents > 0 ? counts : undefined;
+ }
+
/** Steering messages queued but not yet delivered to the model (display mirror; see RuntimeEntry.pendingSteering). */
pendingSteeringOf(sessionId: string): PendingSteeringInfo[] {
return (this.entries.get(sessionId)?.pendingSteering ?? []).map((p) => p.info);
@@ -732,6 +770,7 @@ export class SessionManager {
pendingSteering: [],
returnedSteering: [],
lastActivityMs: Date.now(),
+ backgroundTasks: backgroundTaskCounts(session),
});
// Same wiring as ensureEntry: adopt IS the entry path for a session created in this
// process (POST /sessions), and a listener registered only on the loader path left
@@ -748,7 +787,10 @@ export class SessionManager {
* same feed SSE relays) and recorded for usage — a background child streams to the
* frontend in real time past the launching turn's end, until its terminal state;
* - subagent run-state changes, republished as `task_state` so the panel's running
- * marks track child rounds structurally instead of parsing tool-output text.
+ * marks track child rounds structurally instead of parsing tool-output text;
+ * - background-task state changes (a command promoted or exited, a subagent promoted,
+ * settling or released), re-counted and published as `session_background` on the user
+ * channel so every Session list shows which rows still own background work.
*/
private registerNoticeListener(sessionId: string, session: RuntimeSession): void {
session.onBackgroundNotice?.(() => void this.startBackgroundNoticeTask(sessionId));
@@ -757,6 +799,7 @@ export class SessionManager {
const entry = this.entries.get(sessionId);
if (entry) this.publishState(entry, entry.status);
});
+ session.onBackgroundState?.(() => this.publishBackgroundTasks(sessionId));
// The entry-lifetime approve doubles as the children's fallback approval sink: a child
// approval with no window and no background-launch standing sink escalates to the user
// (SSE approval_request) instead of parking until the model's next poll — the parent
@@ -1572,6 +1615,8 @@ export class SessionManager {
/** get-or-resume-or-heal: use directly on an active-table hit; otherwise load via the loader, updating the index's primary key on self-heal. */
private async ensureEntry(sessionId: string): Promise<RuntimeEntry> {
const existing = this.entries.get(sessionId);
+ /** Background-task counts the discarded runtime last reported (see the publish below). */
+ let discardedBackgroundTasks: SessionBackgroundTasks | undefined;
if (existing) {
if (existing.generation === this.generationOf(existing.projectId, existing.agentId)) {
return existing;
@@ -1588,6 +1633,7 @@ export class SessionManager {
return existing;
}
this.entries.delete(sessionId);
+ discardedBackgroundTasks = existing.backgroundTasks;
}
const row = this.deps.sessions.findById(sessionId);
if (!row) {
@@ -1634,9 +1680,16 @@ export class SessionManager {
pendingSteering: [],
returnedSteering: [],
lastActivityMs: Date.now(),
+ // Baselined on the DISCARDED runtime's counts when there was one: the replacement
+ // resumes with empty registries, so a client that saw the old counts would keep its
+ // background-task mark with no ping left to clear it. Publishing against that baseline
+ // below reports whatever the fresh runtime actually owns — nothing, in every case the
+ // discard path produces today.
+ backgroundTasks: discardedBackgroundTasks ?? backgroundTaskCounts(session),
};
this.entries.set(currentId, entry);
this.registerNoticeListener(currentId, session);
+ if (discardedBackgroundTasks !== undefined) this.publishBackgroundTasks(currentId);
return entry;
}
@@ -2040,6 +2093,31 @@ export class SessionManager {
this.deps.channels.get(entry.sessionId).publish(event, "server_event");
}
+ /**
+ * Re-counts a loaded session's background tasks and, when the counts moved, publishes
+ * `session_background` on the user channel (the list's mark is a user-channel affair like
+ * `session_state`; the open conversation reads the same row). A change is Session
+ * activity for the idle sweep: the entry stays loaded for the usual idle window after its
+ * last background task ends, so the finished process list can still be read. An entry
+ * that already left the table (a delete disposing its runtime) publishes nothing — its
+ * row is gone as well.
+ */
+ private publishBackgroundTasks(sessionId: string): void {
+ const entry = this.entries.get(sessionId);
+ if (!entry) return;
+ const counts = backgroundTaskCounts(entry.session);
+ const last = entry.backgroundTasks;
+ if (counts.processes === last.processes && counts.subagents === last.subagents) return;
+ entry.backgroundTasks = counts;
+ entry.lastActivityMs = Date.now();
+ this.deps.notifyProjectUsers?.(entry.projectId, {
+ type: "session_background",
+ sessionId: entry.sessionId,
+ processes: counts.processes,
+ subagents: counts.subagents,
+ });
+ }
+
/** Serialize (mutually exclude) execution by sessionId; cleans up the lock-table entry once its chain drains (avoids unbounded growth). */
private async withLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
// What's stored in the chain is the already-caught version (used only for
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index c1fb0d23..3deb7e23 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -88,6 +88,7 @@ export class SessionService {
async toInfo(row: SessionRow, hasTrace: boolean): Promise<SessionInfo> {
const source = await this.sourceOf(row, hasTrace);
const messagingChannel = this.deps.messagingChannel?.(row.sessionId) ?? null;
+ const backgroundTasks = this.deps.manager.backgroundTasksOf(row.sessionId);
return {
sessionId: row.sessionId,
projectId: row.projectId,
@@ -107,6 +108,7 @@ export class SessionService {
hasTrace,
archived: (row.archivedAt ?? null) !== null,
...(messagingChannel !== null ? { messagingChannel } : {}),
+ ...(backgroundTasks !== undefined ? { backgroundTasks } : {}),
};
}
diff --git a/packages/server/test/session-background-tasks.test.ts b/packages/server/test/session-background-tasks.test.ts
new file mode 100644
index 00000000..b00f5608
--- /dev/null
+++ b/packages/server/test/session-background-tasks.test.ts
@@ -0,0 +1,229 @@
+/**
+ * `SessionInfo.backgroundTasks` and its user-channel event `session_background`.
+ *
+ * The counts are read live from a LOADED runtime's registries — command sessions still
+ * running past their yield window, subagent sessions promoted to a `subagent_id` and
+ * mid-round — and the field is present only while something is running: an unloaded Session
+ * (a resumed entry starts with empty registries) and a Session with nothing running both
+ * omit it, so a list can treat the field's presence as "this row has background work".
+ *
+ * The event is the core background-state ping re-counted: it is published only when the
+ * counts moved, carries the counts as they now stand (zeros included, so a list can clear its
+ * mark without refetching), and reaches the same audience `session_state` does.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { BackgroundCommandInfo, BackgroundSubagentInfo } from "@prismshadow/penguin-core";
+import type { ServerEvent, SessionResponse, SessionsResponse } from "../src/api/types.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import { userChannelKey } from "../src/http/routes/events.js";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SID = "session-2026-09-02-10-00-00-bbcc0001";
+const SID_UNLOADED = "session-2026-09-02-10-00-00-bbcc0002";
+const PROJECT = "owner-default_project";
+const STARTED_AT = Date.UTC(2026, 8, 2, 10, 4, 0);
+
+const proc = (processId: string, running: boolean): BackgroundCommandInfo => ({
+ processId,
+ pid: 4242,
+ cmd: "pnpm dev",
+ cwd: "/tmp/w",
+ startedAt: STARTED_AT,
+ running,
+});
+
+const sub = (
+ sessionId: string,
+ subagentId: string | null,
+ running: boolean,
+): BackgroundSubagentInfo => ({
+ sessionId,
+ subagentId,
+ running,
+});
+
+/** The core-side listener seam: the manager subscribes once, the test fires it as core would. */
+interface Hook {
+ ping: () => void;
+}
+
+/** Fake runtime whose registries are two mutable arrays the test edits between pings. */
+function backgroundFakeSession(
+ sessionId: string,
+ procs: BackgroundCommandInfo[],
+ subs: BackgroundSubagentInfo[],
+ hook: Hook,
+): RuntimeSession {
+ return {
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run() {},
+ async *compact() {},
+ listBackgroundCommands: () => [...procs],
+ listBackgroundSubagents: () => [...subs],
+ onBackgroundState: (listener) => {
+ hook.ping = listener;
+ },
+ };
+}
+
+function sessionRow(sessionId: string): SessionRow {
+ return {
+ sessionId,
+ projectId: PROJECT,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: "2026-09-02T09:00:00.000Z",
+ lastActiveAt: "2026-09-02T09:00:00.000Z",
+ };
+}
+
+/** Everything one user's channel received, as a connected client would see it. */
+function inbox(t: TestApp, userId: string) {
+ const events: ServerEvent[] = [];
+ t.deps.channels.get(userChannelKey(userId)).subscribe((evt) => {
+ if (evt.event === "server_event") events.push(JSON.parse(evt.data) as ServerEvent);
+ });
+ return {
+ events,
+ background: () => events.flatMap((e) => (e.type === "session_background" ? [e] : [])),
+ };
+}
+
+describe("SessionInfo.backgroundTasks", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let procs: BackgroundCommandInfo[];
+ let subs: BackgroundSubagentInfo[];
+ const hook: Hook = { ping: () => undefined };
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "owner");
+ api = apiClient(t.app, cookie);
+ procs = [proc("proc-11111111", true), proc("proc-22222222", false)];
+ subs = [
+ sub("session-child-0000000000000001", "subagent-00000001", true),
+ // Inside a foreground collect window: no id yet, the running Task's own work.
+ sub("session-child-0000000000000002", null, true),
+ sub("session-child-0000000000000003", "subagent-00000003", false),
+ ];
+ t.deps.sessionsRepo.insert(sessionRow(SID));
+ t.deps.manager.adopt(sessionRow(SID), backgroundFakeSession(SID, procs, subs, hook));
+ t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED));
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("counts running processes and promoted, mid-round subagents on the single GET and on list rows", async () => {
+ const single = await api.get(`/api/sessions/${SID}`);
+ expect(single.status).toBe(200);
+ expect(((await single.json()) as SessionResponse).session.backgroundTasks).toEqual({
+ processes: 1,
+ subagents: 1,
+ });
+
+ const list = await api.get(`/api/projects/${PROJECT}/agents/default_agent/sessions`);
+ expect(list.status).toBe(200);
+ const rows = ((await list.json()) as SessionsResponse).sessions;
+ expect(rows.find((s) => s.sessionId === SID)?.backgroundTasks).toEqual({
+ processes: 1,
+ subagents: 1,
+ });
+ // Not loaded: a resumed entry would start with empty registries, so nothing is reported.
+ const unloaded = rows.find((s) => s.sessionId === SID_UNLOADED)!;
+ expect("backgroundTasks" in unloaded).toBe(false);
+ });
+
+ it("omits the field once nothing is running any more", async () => {
+ procs[0] = proc("proc-11111111", false);
+ subs[0] = sub("session-child-0000000000000001", "subagent-00000001", false);
+ const single = (await (await api.get(`/api/sessions/${SID}`)).json()) as SessionResponse;
+ expect("backgroundTasks" in single.session).toBe(false);
+ });
+});
+
+describe("session_background on the user channel", () => {
+ let t: TestApp;
+ let procs: BackgroundCommandInfo[];
+ let subs: BackgroundSubagentInfo[];
+ const hook: Hook = { ping: () => undefined };
+ let owner: ReturnType<typeof inbox>;
+ let stranger: ReturnType<typeof inbox>;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ await provisionUser(t.app, "owner");
+ // A logged-in user with a live channel of their own and no access to the Project.
+ await provisionUser(t.app, "stranger");
+ procs = [];
+ subs = [];
+ t.deps.sessionsRepo.insert(sessionRow(SID));
+ t.deps.manager.adopt(sessionRow(SID), backgroundFakeSession(SID, procs, subs, hook));
+ owner = inbox(t, "owner");
+ stranger = inbox(t, "stranger");
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("publishes the counts as they stand after each change, and nothing when they did not move", () => {
+ // The counts at load time are the baseline: a ping that changes nothing is not news.
+ hook.ping();
+ expect(owner.background()).toEqual([]);
+
+ procs.push(proc("proc-11111111", true));
+ hook.ping();
+ expect(owner.background()).toEqual([
+ { type: "session_background", sessionId: SID, processes: 1, subagents: 0 },
+ ]);
+ hook.ping();
+ expect(owner.background()).toHaveLength(1);
+
+ // A promoted child mid-round counts; one still inside its foreground window does not.
+ subs.push(sub("session-child-0000000000000001", "subagent-00000001", true));
+ hook.ping();
+ expect(owner.background().at(-1)).toEqual({
+ type: "session_background",
+ sessionId: SID,
+ processes: 1,
+ subagents: 1,
+ });
+ subs.push(sub("session-child-0000000000000002", null, true));
+ hook.ping();
+ expect(owner.background()).toHaveLength(2);
+
+ // Zeros are published too: the list clears its mark from the event alone.
+ procs[0] = proc("proc-11111111", false);
+ subs[0] = sub("session-child-0000000000000001", "subagent-00000001", false);
+ hook.ping();
+ expect(owner.background().at(-1)).toEqual({
+ type: "session_background",
+ sessionId: SID,
+ processes: 0,
+ subagents: 0,
+ });
+ // The same audience rule as session_state: a stranger's live channel hears nothing.
+ expect(stranger.events).toEqual([]);
+ });
+
+ it("reads the same counts the manager's query surface reports", () => {
+ procs.push(proc("proc-11111111", true), proc("proc-22222222", true));
+ hook.ping();
+ const last = owner.background().at(-1)!;
+ expect(last).toMatchObject({ processes: 2, subagents: 0 });
+ expect(t.deps.manager.backgroundTasksOf(SID)).toEqual({ processes: 2, subagents: 0 });
+ expect(t.deps.manager.backgroundTasksOf(SID_UNLOADED)).toBeUndefined();
+ });
+});
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index c3bc2e20..96054e50 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -39,6 +39,7 @@ import type {
OmniMessage,
TextPayload,
} from "@prismshadow/penguin-core";
+import type { ServerEvent } from "../src/api/types.js";
import { openDatabase } from "../src/db/database.js";
import { HttpError } from "../src/http/errors.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
@@ -1154,6 +1155,48 @@ describe("session-manager", () => {
expect(loads).toBe(1);
});
+ it("invalidateAgentRuntimes: the discarded runtime's background-task count is published as cleared", async () => {
+ // The discard path drops the entry WITHOUT disposing it, so the replacement resumes with
+ // empty registries. The counts move without any core ping to carry them: without the
+ // publish below, a Session list that had drawn the background-task mark would sit on a
+ // count nothing can move again, while a plain list fetch already reports none.
+ const withProcess: RuntimeSession = {
+ ...approvalFakeSession("session-1"),
+ listBackgroundCommands: () => [
+ {
+ processId: "proc-11111111",
+ pid: 4242,
+ cmd: "pnpm dev",
+ cwd: "/tmp/w",
+ startedAt: Date.UTC(2026, 8, 2, 10, 0, 0),
+ running: true,
+ },
+ ],
+ };
+ const published: ServerEvent[] = [];
+ const manager = new SessionManager({
+ sessions,
+ channels,
+ sources,
+ loader: loaderOf(approvalFakeSession("session-1")),
+ recorder: { record: async () => undefined },
+ notifyProjectUsers: (_projectId, event) => published.push(event),
+ log: () => {},
+ });
+ sessions.updateApprovalMode("session-1", "allow-all");
+ manager.adopt(ROW, withProcess);
+ expect(manager.backgroundTasksOf("session-1")).toEqual({ processes: 1, subagents: 0 });
+
+ manager.invalidateAgentRuntimes("p1", "a1");
+ await manager.startTask("session-1", [userText("a")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+
+ expect(published.filter((e) => e.type === "session_background")).toEqual([
+ { type: "session_background", sessionId: "session-1", processes: 0, subagents: 0 },
+ ]);
+ expect(manager.backgroundTasksOf("session-1")).toBeUndefined();
+ });
+
it("invalidateAgentRuntimes mid-run: the in-flight Task keeps its runtime; the first Task after it finishes re-resumes", async () => {
let loads = 0;
const loader: SessionLoader = {
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 115fa237..a3c3564d 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -38,7 +38,7 @@ import type {
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { formatRelativeShort } from "../../lib/format";
-import { sessionRowActivity } from "../../lib/session-activity";
+import { sessionBackgroundTasks, sessionRowActivity } from "../../lib/session-activity";
import type { SessionActivity } from "../../lib/session-activity";
import { forgetSession, noteSessionSeen, useSessionSeen } from "../../lib/session-seen";
import { apiErrorText } from "../../lib/api-error";
@@ -140,7 +140,7 @@ import { toastError, toastInfo, toastSuccess } from "../ui/toast";
import { writeClipboard } from "../ui/copy-button";
import { Truncated } from "../ui/truncated";
import { Badge } from "../ui/badge";
-import { SessionActivityIcon } from "../ui/session-activity-icon";
+import { BackgroundTasksMark, SessionActivityIcon } from "../ui/session-activity-icon";
import { Modal } from "../ui/modal";
import { ConfirmModal } from "../ui/confirm-modal";
import { Button } from "../ui/button";
@@ -1183,6 +1183,7 @@ export function Sidebar({
// Busy / settled / read / never-ran, decided in one place (session-activity.ts) so
// the whole transition sequence is testable without a DOM.
activity={sessionRowActivity(s, sessionSeen, activeSessionId)}
+ background={sessionBackgroundTasks(s)}
pinned={pinnedSessions.has(s.sessionId)}
// Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /
// archived) are ordered chronologically inside their folder and never pass
@@ -2477,6 +2478,7 @@ function SessionRow({
s,
active,
activity,
+ background,
pinned,
canPin = false,
lastActive,
@@ -2499,6 +2501,8 @@ function SessionRow({
active: boolean;
/** Busy / settled-read / settled-unread / never-ran, already resolved by sessionRowActivity. */
activity: SessionActivity;
+ /** Background tasks the Session still owns (sessionBackgroundTasks); 0 draws no mark. */
+ background: number;
/** Row is pinned (bubbled to its group's top; small pin glyph on the title). */
pinned: boolean;
/** Whether pinning can actually reorder this row — active-list rows only; folder rows hide the action (see renderRows). */
@@ -2629,7 +2633,7 @@ function SessionRow({
title={S.chat.pinnedSession}
className="shrink-0 text-gray-400 dark:text-gray-500"
>
- <Icon d={PIN_ICON} size={12} />
+ <Icon d={PIN_ICON} size={ICON_SIZE.rowMark} />
<span className="sr-only">{S.chat.pinnedSession}</span>
</span>
)}
@@ -2641,12 +2645,20 @@ function SessionRow({
title={S.messaging.enabledIndicator[s.messagingChannel]}
className="shrink-0 text-gray-400 dark:text-gray-500"
>
- <Icon d={MESSAGING_RELAY_ICON} size={12} />
+ <Icon d={MESSAGING_RELAY_ICON} size={ICON_SIZE.rowMark} />
<span className="sr-only">{S.messaging.enabledIndicator[s.messagingChannel]}</span>
</span>
)}
{/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}
<StatusGlyph activity={activity} />
+ {/* Beside the glyph, not instead of it: an idle row can still own background work,
+ and the mark leaves with the last task (live via session_background). */}
+ {background > 0 && (
+ <BackgroundTasksMark
+ label={S.chat.backgroundTasks(background)}
+ size={ICON_SIZE.rowMark}
+ />
+ )}
{s.pendingApprovalCount > 0 && (
<span title={S.chat.pendingApprovals(s.pendingApprovalCount)}>
<Badge tone="amber">{s.pendingApprovalCount}</Badge>
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 906145b9..2e92d1bc 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -164,6 +164,20 @@ export function CloseButton({
/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */
export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";
+/**
+ * Activity trace (a flat line with one tall beat in it): work still going on behind the
+ * conversation — the background-task mark on a session row, the matching count in the chat
+ * header, and the marker on a tool row whose call was made with `run_in_background`.
+ *
+ * A trace rather than the layered stack it replaces, which read as "layers" (a thing) instead
+ * of "still running" (an event), and whose two parallelograms sit ~2.5px apart at the row's
+ * 12px and merge into a smudge. One continuous stroke with a single tall beat keeps its shape
+ * at that size, and it is nobody else's shape in these rows: not the hourglass or the compress
+ * chevrons (`attention`, session activity), not the spinner ring or the circled check / cross
+ * (a tool row's own status), not the unread dot.
+ */
+export const BACKGROUND_TASKS_ICON = "M2 12h4l3 9 6-18 3 9h4";
+
/** Chat bubble: the messaging binding's channel-neutral mark (dock panel tab). */
export const MESSAGING_ICON = "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z";
diff --git a/packages/web/src/components/ui/session-activity-icon.tsx b/packages/web/src/components/ui/session-activity-icon.tsx
index b160b5b2..8c8e6529 100644
--- a/packages/web/src/components/ui/session-activity-icon.tsx
+++ b/packages/web/src/components/ui/session-activity-icon.tsx
@@ -1,6 +1,9 @@
import { S } from "../../lib/strings";
+import { ICON_SIZE } from "../../lib/icon-scale";
import { toneDot, toneInk } from "../../lib/tone";
import type { SessionActivity } from "../../lib/session-activity";
+import { GlyphIcon } from "./glyph-icon";
+import { BACKGROUND_TASKS_ICON } from "./icons";
type Activity = Exclude<SessionActivity, null>;
@@ -25,6 +28,10 @@ type Activity = Exclude<SessionActivity, null>;
* legible only to a sighted user with full colour vision. The read state announces nothing
* because it renders nothing, which is correct — there is no state to report.
*
+ * Background work is a separate mark, not a fourth state (BackgroundTasksMark below): an
+ * activity trace in the `busy` tone, drawn beside whichever glyph the row wears — an idle, read
+ * Session can still own a dev server or a background subagent, and the row says both.
+ *
* Ink comes from the shared tone tokens (lib/tone.ts), which carry the measured contrast ratios
* against the two surfaces these glyphs sit on: the sidebar (gray-50 / gray-900) and the chat
* header (white / gray-950).
@@ -55,13 +62,34 @@ export function sessionActivityLabel(activity: Activity): string {
return S.chat.statusCompletedUnread;
}
-export function SessionActivityIcon({
- activity,
- size = 12,
-}: {
- activity: Activity;
- size?: number;
-}) {
+/**
+ * The background-task mark: "work is going on behind this" wherever the app says so — a
+ * session row and the chat header, where it stands for the conversation's whole set of
+ * background command processes and subagents, and a tool row, where it marks the one call
+ * that was made with `run_in_background`. `busy` ink, because that is what it means.
+ *
+ * Both props are the caller's to decide, because the two placements genuinely differ: the
+ * label names a count in one place and a single call in the other, and the size is the rung
+ * the surrounding row already uses (a session row's trailing marks, a tool row's inline
+ * glyphs). The label is the only carrier of the state — colour and shape never are — so it
+ * is required rather than defaulted. Rendered only when there is background work to report:
+ * the caller decides, so no row reserves a box for it.
+ */
+export function BackgroundTasksMark({ label, size }: { label: string; size: number }) {
+ return (
+ <span
+ role="img"
+ aria-label={label}
+ title={label}
+ className={`flex shrink-0 items-center ${toneInk.busy}`}
+ >
+ <GlyphIcon d={BACKGROUND_TASKS_ICON} size={size} />
+ </span>
+ );
+}
+
+export function SessionActivityIcon({ activity }: { activity: Activity }) {
+ const size = ICON_SIZE.rowMark;
const label = sessionActivityLabel(activity);
if (activity === "completedUnread") {
// The dot itself is exactly the Session status dot's geometry — `h-1.5 w-1.5`, 6px, the same
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index b0cffd19..7f5a747f 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -41,7 +41,7 @@ import {
humanizeTokens,
} from "../../lib/format";
import { latestConversation } from "../../lib/session-grouping";
-import { sessionActivity } from "../../lib/session-activity";
+import { sessionActivity, sessionBackgroundTasks } from "../../lib/session-activity";
import { noteSessionSeen } from "../../lib/session-seen";
import {
approvalKey,
@@ -128,7 +128,7 @@ import { PanelsToolbar } from "./panels-toolbar";
import { toneDot, toneInk } from "../../lib/tone";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { STAT_ICONS } from "../../lib/stat-icons";
-import { INFO_ICON } from "../../components/ui/icons";
+import { BACKGROUND_TASKS_ICON, INFO_ICON } from "../../components/ui/icons";
import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
/** How often the background-process list refreshes while it can still change (a run may promote a command at any time; a running process can exit on its own). */
@@ -286,9 +286,8 @@ export function ChatPage() {
const [infoOpen, setInfoOpen] = useState(false);
const [modeSaving, setModeSaving] = useState(false);
const [models, setModels] = useState<ModelsResponse | null>(null);
- // Background processes the conversation started (details popover list + the header's
- // running-services count), refreshed by the polling effect below; procBusy marks the
- // row whose stop request is in flight.
+ // Background processes the conversation started (the details popover list), refreshed by
+ // the polling effect below; procBusy marks the row whose stop request is in flight.
const [processes, setProcesses] = useState<SessionProcessInfo[]>([]);
const [procBusy, setProcBusy] = useState<string | null>(null);
// Session Token buckets from the last usage fetch (the popover's tokens-line breakdown):
@@ -826,6 +825,10 @@ export function ChatPage() {
const runningProcessCount = processes.filter((p) => p.running).length;
const processesCanChange =
stream.taskState !== "idle" || runningProcessCount > 0 || (infoOpen && processes.length > 0);
+ // The row's own count moves the moment the server sees a process promoted or gone (the
+ // user channel's session_background), so a change there re-reads the list at once instead
+ // of a poll interval later — the popover stays in step with the header's count.
+ const backgroundProcessCount = selected?.backgroundTasks?.processes ?? 0;
useEffect(() => {
if (!selectedSessionId) return;
let cancelled = false;
@@ -848,7 +851,7 @@ export function ChatPage() {
cancelled = true;
window.clearInterval(timer);
};
- }, [selectedSessionId, stream.taskState, processesCanChange]);
+ }, [selectedSessionId, stream.taskState, processesCanChange, backgroundProcessCount]);
/**
* Shared body of the per-row process actions (Stop / Remove): one request at a time
@@ -1659,6 +1662,8 @@ export function ChatPage() {
*/
const headerActivity =
selected === null ? null : sessionActivity(stream.taskState, selected.hasTrace, false);
+ /** Background tasks the conversation still owns — the same live count the sidebar row's mark carries. */
+ const backgroundCount = selected === null ? 0 : sessionBackgroundTasks(selected);
return (
// data-dock-host: the docks' edge bands, drop preview and the bottom dock's height
@@ -1748,15 +1753,19 @@ export function ChatPage() {
value={hs.elapsedNode}
label={S.chat.statElapsed}
/>
- {/* Right of the time, only while the conversation has live background
- processes: their count, in the live-status green. */}
- {runningProcessCount > 0 && (
+ {/* Right of the time, only while the conversation still owns background
+ work — command processes past their yield window, background subagents
+ mid-round: their count, in the live-status green, the same figure and
+ glyph as the session row's mark and read live off the row. Bare ink like
+ the chips beside it, not a tinted pill: this is one more reading in the
+ stat row, not a badge that should out-weigh them. */}
+ {backgroundCount > 0 && (
<span
- title={S.chat.runningServices(runningProcessCount)}
+ title={S.chat.backgroundTasks(backgroundCount)}
className={`flex shrink-0 items-center ${ICON_GAP.tight} font-mono text-xs ${toneInk.busy}`}
>
- <GlyphIcon d={STAT_ICONS.services} />
- {runningProcessCount}
+ <GlyphIcon d={BACKGROUND_TASKS_ICON} />
+ {backgroundCount}
</span>
)}
</span>
diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsx
index 42cf8179..189ef0e0 100644
--- a/packages/web/src/features/chat/tool-call-card.tsx
+++ b/packages/web/src/features/chat/tool-call-card.tsx
@@ -27,6 +27,8 @@ import {
DISCLOSURE_ROW_STICKY_CLASS,
} from "./disclosure-row";
import { ZoomableImage } from "../../components/ui/image-zoom";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { BackgroundTasksMark } from "../../components/ui/session-activity-icon";
import { StatusIcon } from "../../components/ui/status-icon";
import type { RunState } from "../../components/ui/status-icon";
import { ApprovalButtons } from "./approval-buttons";
@@ -117,6 +119,29 @@ export function headerSubtitle(name: string, argsJson: string, settled = true):
return null;
}
+/**
+ * Whether this call was launched with `run_in_background: true` — the argument `exec_command`
+ * and `run_subagent` share, and the one that leaves work running after the tool has returned.
+ * The row marks those calls the way the session list marks their conversation.
+ *
+ * Read from the parsed arguments rather than the streamed prefix: the flag is last in both
+ * schemas, so it only exists once the call has closed, and an incomplete or malformed argument
+ * string simply reads as "not background" — the mark appears with the closing brace.
+ */
+export function isBackgroundCall(argsJson: string): boolean {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(argsJson);
+ } catch {
+ return false;
+ }
+ return (
+ parsed !== null &&
+ typeof parsed === "object" &&
+ (parsed as Record<string, unknown>)["run_in_background"] === true
+ );
+}
+
/**
* Decoded file-tool payload for the pending-approval block: the user is approving a
* concrete rewrite (old_string/new_string/content), so the bare path is not enough — the
@@ -326,6 +351,14 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen
)
) : null}
</span>
+ {/* Right of the duration, on a call made with run_in_background: the same mark the
+ session list draws on the conversation, so a backgrounded call and the row that
+ counts it read as one thing. It sits after the duration rather than beside the
+ name so it never competes with the truncating subtitle, and the row's own status
+ icon keeps saying what the CALL did — this says where its work went. */}
+ {isBackgroundCall(item.argumentsText) && (
+ <BackgroundTasksMark label={S.chat.backgroundCall} size={ICON_SIZE.inlineGlyph} />
+ )}
<span className="min-w-0 flex-1" />
{/* Expand indicator on the right */}
<Chevron open={open} className="text-gray-400" />
diff --git a/packages/web/src/lib/icon-scale.ts b/packages/web/src/lib/icon-scale.ts
index 76b9a68d..8a34f7bc 100644
--- a/packages/web/src/lib/icon-scale.ts
+++ b/packages/web/src/lib/icon-scale.ts
@@ -13,6 +13,12 @@
*/
export const ICON_SIZE = {
+ /**
+ * A trailing status mark on a list row — a session row's activity glyph, background-task
+ * mark, pin and relay arrow. One rung below `inlineGlyph`: several of these may share the
+ * tail of one row behind a title they must not compete with.
+ */
+ rowMark: 12,
/** A glyph sitting inline with body or secondary text: stat chips, banner leads, buttons with a label, menu rows. The GlyphIcon default. */
inlineGlyph: 13,
/** The leading mark of a list row — a session row's agent avatar, a trace row's. */
diff --git a/packages/web/src/lib/session-activity.ts b/packages/web/src/lib/session-activity.ts
index f27ede0f..ce4ffedc 100644
--- a/packages/web/src/lib/session-activity.ts
+++ b/packages/web/src/lib/session-activity.ts
@@ -5,6 +5,10 @@ import type { SessionSeenState } from "./session-seen";
/**
* Visual state carried by a Session row / chat header. Three states, and `null` for "say
* nothing at all" — which is the resting state of every row the user has nothing to act on.
+ *
+ * Background work is a separate facet (see sessionBackgroundTasks), not a fourth state: a
+ * Session can be idle, read, and still own a dev server or a background subagent, and a row
+ * has to say both at once.
*/
export type SessionActivity = "running" | "compacting" | "completedUnread" | null;
@@ -36,6 +40,19 @@ export function sessionActivity(
return unread ? "completedUnread" : null;
}
+/**
+ * How many background tasks the Session still owns — command processes running past their
+ * yield window plus background subagents mid-round — or 0 when none. The server omits the
+ * field entirely at zero and pushes every change on the user channel, so this is live data
+ * on the row, not a snapshot from the last list fetch. It is independent of the activity
+ * state above: the mark it drives sits beside the glyph, on an idle row as readily as on a
+ * running one, and goes away the moment the last task ends.
+ */
+export function sessionBackgroundTasks(session: Pick<SessionInfo, "backgroundTasks">): number {
+ const tasks = session.backgroundTasks;
+ return tasks === undefined ? 0 : tasks.processes + tasks.subagents;
+}
+
/** The subset of a row this function needs (a whole SessionInfo satisfies it). */
export type SessionActivityRow = Pick<
SessionInfo,
diff --git a/packages/web/src/lib/stat-icons.ts b/packages/web/src/lib/stat-icons.ts
index 9d1ebc7c..caeaf9d8 100644
--- a/packages/web/src/lib/stat-icons.ts
+++ b/packages/web/src/lib/stat-icons.ts
@@ -25,9 +25,6 @@ export const STAT_ICONS = {
tps: "M5 18a8 8 0 1 1 14 0M12 12l4-3",
/** Elapsed time (clock) */
elapsed: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-14v5l3 2",
- /** Running background services (server rack: two stacked units, each with an indicator dot) */
- services:
- "M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5zm0 11a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3zM7 6.5h.01M7 17.5h.01",
/** Cost (dollar sign in a circle) */
cost: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-15v12m2.6-9.3c-.5-.8-1.5-1.2-2.6-1.2-1.5 0-2.7.8-2.7 2 0 2.7 5.4 1.3 5.4 4 0 1.2-1.2 2-2.7 2-1.2 0-2.2-.5-2.7-1.4",
/** Copy */
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 7261882f..16fd18ed 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1573,6 +1573,10 @@ Scenarios:
statusCompacting: "Compacting",
/** Settled Session that finished since the user last opened it (the unread dot; a Session already read shows no glyph, so it needs no label). */
statusCompletedUnread: "Done, unread",
+ /** The background-task mark on a session row and the chat header's count: background processes plus background subagents still running. */
+ backgroundTasks: (n: number) => (n === 1 ? "1 background task" : `${n} background tasks`),
+ /** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */
+ backgroundCall: "Runs in the background",
pendingApprovals: (n: number) => `${n} pending approval${n > 1 ? "s" : ""}`,
jumpToLatest: "Jump to latest",
/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */
@@ -1711,8 +1715,6 @@ Scenarios:
processRemove: "Remove",
/** Remove button tooltip: removal also drops the output captured from that process. */
processRemoveHint: "Remove this entry — the output captured from it is discarded too",
- /** Header chip title: count of the conversation's still-running background processes. */
- runningServices: (n: number) => (n === 1 ? "1 running service" : `${n} running services`),
statTokens: "Total Tokens",
/** Info-dropdown stats list: the tokens bullet's label and its cache-hit-rate parenthetical (rate = cacheRead ÷ all input, e.g. "68%"). */
statTotalTokens: "Total Tokens",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 5b16e93b..81203805 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1542,6 +1542,10 @@ Benchmark:
statusCompacting: "压缩中",
/** Settled Session that finished since the user last opened it (the unread dot; a Session already read shows no glyph, so it needs no label). */
statusCompletedUnread: "运行完毕,未读",
+ /** The background-task mark on a session row and the chat header's count: background processes plus background subagents still running. */
+ backgroundTasks: (n: number) => `${n} 个后台任务`,
+ /** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */
+ backgroundCall: "在后台运行",
pendingApprovals: (n: number) => `${n} 个待审批`,
jumpToLatest: "回到最新消息",
/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */
@@ -1676,8 +1680,6 @@ Benchmark:
processRemove: "移除",
/** Remove button tooltip: removal also drops the output captured from that process. */
processRemoveHint: "移除该条目——该进程已捕获的输出也会一并丢弃",
- /** Header chip title: count of the conversation's still-running background processes. */
- runningServices: (n: number) => `${n} 个运行中的服务`,
statTokens: "Token 累计",
/** Info-dropdown stats list: the tokens bullet's label and its cache-hit-rate parenthetical (rate = cacheRead ÷ all input, e.g. "68%"). */
statTotalTokens: "总 Token",
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 047bc47b..976250e1 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -27,6 +27,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState }
import type { ReactNode } from "react";
import type {
ServerEvent,
+ SessionBackgroundTasks,
SessionCategory,
SessionCategoryCounts,
SessionInfo,
@@ -184,6 +185,12 @@ interface SessionsStoreState {
replace: (session: SessionInfo) => void;
setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;
setTitle: (sessionId: string, title: string) => void;
+ /**
+ * Live background-task counts of one row, from the user channel's `session_background`;
+ * undefined clears the field the way the server omits it at zero. The row's mark and the
+ * chat header's count both read the field, so this is the one write that moves them.
+ */
+ setBackgroundTasks: (sessionId: string, tasks: SessionBackgroundTasks | undefined) => void;
}
/**
@@ -533,6 +540,31 @@ export function createSessionsStore() {
sessions: prev.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)),
});
},
+
+ /**
+ * Same drop rule as `setStatus` and `setTitle`: an unlisted id is ignored, and equal
+ * counts leave the array untouched (a ping that changed nothing must not re-render every
+ * row). Zero is stored as absence — the same shape a list fetch returns — so the
+ * "has background work" test stays one `backgroundTasks !== undefined` check everywhere.
+ */
+ setBackgroundTasks: (sessionId, tasks) => {
+ const prev = get().sessions;
+ const target = prev.find((s) => s.sessionId === sessionId);
+ if (!target) return;
+ const cur = target.backgroundTasks;
+ const same =
+ cur === undefined || tasks === undefined
+ ? cur === tasks
+ : cur.processes === tasks.processes && cur.subagents === tasks.subagents;
+ if (same) return;
+ set({
+ sessions: prev.map((s) => {
+ if (s.sessionId !== sessionId) return s;
+ const { backgroundTasks: _dropped, ...rest } = s;
+ return tasks === undefined ? rest : { ...rest, backgroundTasks: tasks };
+ }),
+ });
+ },
};
});
}
@@ -581,6 +613,20 @@ export function applyUserEvent(
store.getState().setTitle(ev.sessionId, ev.title);
return;
}
+ // A Session's background work changed — a command promoted past its yield window, a
+ // process that exited or was stopped, a background subagent starting or finishing a round.
+ // The event carries the counts as they now stand, zeros included, so the row's mark can
+ // appear and disappear without a list fetch; the pair collapses to "none" at zero.
+ if (ev.type === "session_background") {
+ const { processes, subagents } = ev;
+ store
+ .getState()
+ .setBackgroundTasks(
+ ev.sessionId,
+ processes > 0 || subagents > 0 ? { processes, subagents } : undefined,
+ );
+ return;
+ }
// The reconnect landed outside the channel's replay buffer, so an unknown number of the flips
// above were lost — away long enough and a row sits on an hourglass that will never stop.
// Refetch once, on the event that says so, rather than polling for it.
diff --git a/packages/web/test/icon-scale.test.ts b/packages/web/test/icon-scale.test.ts
index e778945a..3e743c00 100644
--- a/packages/web/test/icon-scale.test.ts
+++ b/packages/web/test/icon-scale.test.ts
@@ -59,6 +59,12 @@ describe("one glyph, one home", () => {
it("draws the collapse chevron in exactly one place", () => {
expect(occurrences("M9 5l7 7-7 7")).toEqual(["components/ui/chevron.tsx"]);
});
+
+ it("draws the background-task trace in exactly one place", () => {
+ // Three surfaces draw it now — a session row, the chat header pill and a backgrounded
+ // tool row — which is how the paths above ended up hand-typed five times each.
+ expect(occurrences("M2 12h4l3 9 6-18 3 9h4")).toEqual(["components/ui/icons.tsx"]);
+ });
});
describe("stroke weights", () => {
diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.ts
index f0fdb920..df0e56f5 100644
--- a/packages/web/test/session-activity.test.ts
+++ b/packages/web/test/session-activity.test.ts
@@ -1,13 +1,16 @@
import { describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
-import { sessionActivity } from "../src/lib/session-activity";
+import { sessionActivity, sessionBackgroundTasks } from "../src/lib/session-activity";
import type { SessionActivity } from "../src/lib/session-activity";
import {
ACTIVITY_GLYPH,
+ BackgroundTasksMark,
SessionActivityIcon,
sessionActivityLabel,
} from "../src/components/ui/session-activity-icon";
+import { BACKGROUND_TASKS_ICON } from "../src/components/ui/icons";
+import { ICON_SIZE } from "../src/lib/icon-scale";
import { S } from "../src/lib/strings";
import { toneInk } from "../src/lib/tone";
import { readFileSync } from "node:fs";
@@ -44,6 +47,63 @@ describe("sessionActivity", () => {
});
});
+describe("sessionBackgroundTasks", () => {
+ it("is zero without the field and the sum of both counts with it", () => {
+ // The server omits the field at zero, so absence is the common case, not an error.
+ expect(sessionBackgroundTasks({})).toBe(0);
+ expect(sessionBackgroundTasks({ backgroundTasks: { processes: 2, subagents: 0 } })).toBe(2);
+ expect(sessionBackgroundTasks({ backgroundTasks: { processes: 1, subagents: 3 } })).toBe(4);
+ });
+
+ it("is a facet beside the activity state, not a fourth state", () => {
+ // An idle, read Session can still own a dev server: the glyph says nothing and the
+ // background count says 1, and the row draws both.
+ expect(sessionActivity("idle", true, false)).toBeNull();
+ expect(sessionBackgroundTasks({ backgroundTasks: { processes: 1, subagents: 0 } })).toBe(1);
+ });
+});
+
+/**
+ * The background-task mark: one glyph in the `busy` tone for both of its placements — a
+ * session row / the chat header, where it stands for a count, and a tool row, where it marks
+ * the single call made with `run_in_background`. Rendered only when there is background work
+ * to report (the caller's decision), and always naming what it means in the accessible name
+ * and tooltip, so the glyph is never the only carrier.
+ */
+describe("BackgroundTasksMark", () => {
+ const render = (label: string, size: number) =>
+ renderToStaticMarkup(createElement(BackgroundTasksMark, { label, size }));
+
+ it("names the count where it stands for a count", () => {
+ const markup = render(S.chat.backgroundTasks(3), ICON_SIZE.rowMark);
+ expect(markup).toContain(`aria-label="${S.chat.backgroundTasks(3)}"`);
+ expect(markup).toContain(`title="${S.chat.backgroundTasks(3)}"`);
+ expect(markup).toContain('role="img"');
+ expect(S.chat.backgroundTasks(3)).toContain("3");
+ });
+
+ it("names one call where it marks one call, rather than a count of one", () => {
+ // The tool row marks a single run_in_background call: "1 background task" would be a
+ // count the row is not making, and would read as the conversation's total.
+ const markup = render(S.chat.backgroundCall, ICON_SIZE.inlineGlyph);
+ expect(markup).toContain(`aria-label="${S.chat.backgroundCall}"`);
+ expect(S.chat.backgroundCall).not.toBe(S.chat.backgroundTasks(1));
+ expect(S.chat.backgroundCall).not.toMatch(/\d/);
+ });
+
+ it("draws the activity trace in the busy tone, at the rung its caller passes", () => {
+ expect(render(S.chat.backgroundCall, ICON_SIZE.rowMark)).toMatch(/width="12"/);
+ expect(render(S.chat.backgroundCall, ICON_SIZE.inlineGlyph)).toMatch(/width="13"/);
+ const markup = render(S.chat.backgroundTasks(1), ICON_SIZE.rowMark);
+ expect(markup).toContain(`d="${BACKGROUND_TASKS_ICON}"`);
+ expect(markup).toContain(toneInk.busy);
+ // Not one of the activity glyphs, and no motion: it is a fact about the Session, not a
+ // live-progress indicator.
+ expect(markup).not.toContain(ACTIVITY_GLYPH.running);
+ expect(markup).not.toContain("hourglass-turn");
+ });
+});
+
/**
* Icon rendering contract, via react-dom/server static markup (node env, no DOM).
*
diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.ts
index 7d99125d..7a1c5de9 100644
--- a/packages/web/test/session-status-events.test.ts
+++ b/packages/web/test/session-status-events.test.ts
@@ -16,7 +16,7 @@ import type { ServerEvent, SessionInfo, SessionStatus } from "@prismshadow/pengu
import { applyUserEvent, createSessionsStore } from "../src/state/sessions";
import { isSessionUnread, markSessionSeen } from "../src/lib/session-seen";
import type { SessionSeenState } from "../src/lib/session-seen";
-import { sessionRowActivity } from "../src/lib/session-activity";
+import { sessionBackgroundTasks, sessionRowActivity } from "../src/lib/session-activity";
const CREATED = "2026-08-19T09:00:00.000Z";
/** When the user last had the Session open — every fixture's starting `lastActiveAt`. */
@@ -133,6 +133,62 @@ describe("session_state on the user channel", () => {
});
});
+describe("session_background on the user channel", () => {
+ const backgroundEvent = (
+ sessionId: string,
+ processes: number,
+ subagents: number,
+ ): ServerEvent => ({ type: "session_background", sessionId, processes, subagents });
+
+ it("sets the named row's counts and leaves every other row alone", () => {
+ const store = storeWith(session("a"), session("b"));
+ applyUserEvent(store, backgroundEvent("b", 1, 2), neverReload);
+ expect(rowOf(store, "b").backgroundTasks).toEqual({ processes: 1, subagents: 2 });
+ expect(sessionBackgroundTasks(rowOf(store, "b"))).toBe(3);
+ expect("backgroundTasks" in rowOf(store, "a")).toBe(false);
+ });
+
+ it("clears the field at zero, the shape a list fetch returns", () => {
+ const store = storeWith(session("a", { backgroundTasks: { processes: 1, subagents: 0 } }));
+ applyUserEvent(store, backgroundEvent("a", 0, 0), neverReload);
+ // Absent, not present-and-empty: every "has background work" check is one key test.
+ expect("backgroundTasks" in rowOf(store, "a")).toBe(false);
+ expect(sessionBackgroundTasks(rowOf(store, "a"))).toBe(0);
+ });
+
+ it("ignores a Session no loaded page holds instead of inventing a row", () => {
+ const store = storeWith(session("a"));
+ const before = store.getState().sessions;
+ applyUserEvent(store, backgroundEvent("not-loaded", 1, 0), neverReload);
+ expect(store.getState().sessions).toBe(before);
+ });
+
+ it("is a no-op when the counts already match", () => {
+ const store = storeWith(session("a", { backgroundTasks: { processes: 2, subagents: 1 } }));
+ const before = store.getState().sessions;
+ applyUserEvent(store, backgroundEvent("a", 2, 1), neverReload);
+ expect(store.getState().sessions).toBe(before);
+ // Zero onto an already-clear row is the same non-event.
+ const clear = storeWith(session("b"));
+ const beforeClear = clear.getState().sessions;
+ applyUserEvent(clear, backgroundEvent("b", 0, 0), neverReload);
+ expect(clear.getState().sessions).toBe(beforeClear);
+ });
+
+ it("moves neither the glyph nor the status: an idle, read row keeps its blank glyph and gains the mark", () => {
+ const store = storeWith(session("a"));
+ const seen = seenAt("a", LOOKED);
+ applyUserEvent(store, backgroundEvent("a", 1, 0), neverReload);
+ expect(glyph(store, "a", seen)).toBeNull();
+ expect(rowOf(store, "a").status).toBe("idle");
+ expect(sessionBackgroundTasks(rowOf(store, "a"))).toBe(1);
+ // A run ending does not touch the count either: the mark outlives the hourglass.
+ applyUserEvent(store, stateEvent("a", "running", STARTED), neverReload);
+ applyUserEvent(store, stateEvent("a", "idle", FINISHED), neverReload);
+ expect(sessionBackgroundTasks(rowOf(store, "a"))).toBe(1);
+ });
+});
+
describe("session_title on the user channel", () => {
const titleEvent = (sessionId: string, title: string): ServerEvent => ({
type: "session_title",
diff --git a/packages/web/test/tool-call-preview.test.ts b/packages/web/test/tool-call-preview.test.ts
index f931daf0..16cdeee7 100644
--- a/packages/web/test/tool-call-preview.test.ts
+++ b/packages/web/test/tool-call-preview.test.ts
@@ -9,6 +9,7 @@
import { describe, expect, it } from "vitest";
import {
headerSubtitle,
+ isBackgroundCall,
pendingFilePayload,
previewArguments,
shortenPath,
@@ -147,3 +148,25 @@ describe("pendingFilePayload", () => {
expect(pendingFilePayload("edit_file", '{"file_path":"a.txt","old_str')).toBeNull();
});
});
+
+describe("isBackgroundCall", () => {
+ it("marks exec_command and run_subagent launched with the flag", () => {
+ expect(isBackgroundCall('{"cmd":"pnpm dev","run_in_background":true}')).toBe(true);
+ expect(isBackgroundCall('{"prompt":"go","run_in_background":true}')).toBe(true);
+ });
+
+ it("leaves an ordinary call unmarked, flag absent or false", () => {
+ expect(isBackgroundCall('{"cmd":"ls"}')).toBe(false);
+ expect(isBackgroundCall('{"cmd":"ls","run_in_background":false}')).toBe(false);
+ // Only the real boolean counts: a string "true" is not the argument the tool acts on.
+ expect(isBackgroundCall('{"cmd":"ls","run_in_background":"true"}')).toBe(false);
+ });
+
+ it("reads nothing from a mid-stream or malformed argument string", () => {
+ // The flag is last in both schemas, so a still-growing call has not shown it yet — and a
+ // command that merely mentions it is not one that was launched with it.
+ expect(isBackgroundCall('{"cmd":"pnpm dev","run_in_background":tr')).toBe(false);
+ expect(isBackgroundCall('{"cmd":"grep run_in_background\\": true src"}')).toBe(false);
+ expect(isBackgroundCall("")).toBe(false);
+ });
+});