Skip to content

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

feat(server,web): a Session waiting for approval is marked live

lmliheng8b528f05f07f
diff --git a/changelog/unreleased/2026-10-10-session-approvals-event.md b/changelog/unreleased/2026-10-10-session-approvals-event.md
new file mode 100644
index 00000000..5fcc7b8e
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-approvals-event.md
@@ -0,0 +1,29 @@
+# A Session waiting for approval is marked live in every list
+
+- **Date:** 2026-10-10
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+
+[中文版](2026-10-10-session-approvals-event.zh.md)
+
+This is ported from upstream PenguinHarness (#1002, commit `60f34c47`).
+
+A sidebar row's approvals mark came only from the last list fetch, so a Session that started
+waiting for a tool approval while another conversation was open showed nothing until the list was
+loaded again. The user channel gained a `session_approvals` event with the Session's count of
+waiting calls, and the Web App applied it to the row as it arrived. Any client watching a
+Project's Sessions over `GET /api/events` can tell which one waits for a person without
+subscribing to every Session's stream.
+
+## Details
+
+- `session_approvals` carries `sessionId` and `count`, the row's `pendingApprovalCount` as it
+ stands after the change, zeros included. It is published when a call is escalated to a person,
+ when a call is answered, and when an interrupt or a Task boundary denies the waiting calls;
+ an interrupt that denies several calls publishes one event. Its audience is the same as for
+ `session_state`.
+- A call the approval mode answers by itself (`allow-all`, `deny-all`, read-only tools under
+ `read-only`) and a call an unattended Session denies on the spot publish nothing.
+- The calls themselves stay on the Session's own stream as `approval_request`, replayed on
+ subscribe.
+- The Server API page lists the event and when it fires, in both languages.
diff --git a/changelog/unreleased/2026-10-10-session-approvals-event.zh.md b/changelog/unreleased/2026-10-10-session-approvals-event.zh.md
new file mode 100644
index 00000000..b3ba4e13
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-approvals-event.zh.md
@@ -0,0 +1,18 @@
+# 等待审批的 Session 在所有列表中实时标记
+
+- **Date:** 2026-10-10
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+
+[English](2026-10-10-session-approvals-event.md)
+
+移植自上游 PenguinHarness(#1002,提交 `60f34c47`)。
+
+侧栏行上的审批标记只来自最近一次列表拉取,所以当用户打开着另一个对话时,开始等待工具审批的 Session 不会显示任何标记,直到列表重新加载。用户通道新增 `session_approvals` 事件,携带该 Session 等待审批的调用数,Web App 收到后立即更新对应的行。任何通过 `GET /api/events` 关注某个 Project 下各 Session 的客户端,都能知道哪个 Session 在等人处理,而无需订阅每个 Session 的流。
+
+## 细节
+
+- `session_approvals` 携带 `sessionId` 和 `count`,即变化后该行的 `pendingApprovalCount`,归零时同样发送。以下情况会发布该事件:调用升级给人审批;某个调用得到回答;中断或 Task 边界拒绝了等待中的调用。一次中断拒绝多个调用时只发布一个事件。受众与 `session_state` 相同。
+- 由审批模式自行回答的调用(`allow-all`、`deny-all`、`read-only` 下的只读工具),以及无人值守 Session 当场拒绝的调用,都不发布事件。
+- 调用本身仍以 `approval_request` 出现在该 Session 自己的流上,订阅时会重放。
+- Server API 页面中英两版都列出了这个事件及其触发时机。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 3b5d02ba..dfad405b 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -1109,7 +1109,7 @@ Real-time delivery uses Server-Sent Events, not WebSocket, on two kinds of chann
| Channel | Path | Contents |
| --- | --- | --- |
| Per Session | `GET /api/sessions/:sessionId/stream` | The Session's message stream and run events, including `session_created` for its subagent Sessions and the goal-mode events |
-| Per user | `GET /api/events` | The `hello` handshake and notifications across Sessions: `session_created`, `session_state`, `session_background`, `session_title`, `schedule_fired`, `schedule_queued`, `web_updated` and company mode's `org_*` events |
+| Per user | `GET /api/events` | The `hello` handshake and notifications across Sessions: `session_created`, `session_state`, `session_background`, `session_approvals`, `session_title`, `schedule_fired`, `schedule_queued`, `web_updated` and company mode's `org_*` events |
### Wire Format
@@ -1130,6 +1130,7 @@ export type ServerEvent =
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; projectId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
| { type: "session_background"; sessionId: string; processes: number; subagents: number }
+ | { type: "session_approvals"; sessionId: string; count: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
@@ -1153,6 +1154,7 @@ export type ServerEvent =
| `session_title` | The model-generated title is saved after the first turn |
| `session_state` | A Session's run state changes; the user-channel counterpart of `task_state` |
| `session_background` | A Session's background-task counts change |
+| `session_approvals` | A Session's count of tool calls waiting for approval changes |
| `resync_required` | The `Last-Event-ID` was evicted from the buffer; the client must refetch history |
| `credentials_updated` | The Project's model credentials changed |
| `hello` | Handshake on the user channel |
@@ -1173,6 +1175,7 @@ export type ServerEvent =
- `session_title` is sent on the Session's channel and on the user channels of the Project's owner and members.
- `session_state` names the Session by `sessionId` and its Project by `projectId`, so every row of a Session list stays live, not only the conversation a client has open, and a list can tell a Session of its own Project that it holds no row for, which it can then fetch by id. It carries the row fields needed to redraw the row without refetching: `lastActiveAt` as just stamped, and `hasTrace`, which is true whenever the state is `running` or `compacting`, because a running Session has by definition started a Task. It is sent to the user channels of the Project's owner and members.
- `session_background` fires when a command moves to the background past its yield window or starts with `run_in_background`, when a process exits or is stopped, and when a background subagent starts, settles or is released. It carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = subagent Sessions moved to the background and mid-round), zeros included, so a list can clear its mark without refetching. The list rows and the single-Session GET omit the field when both counts are zero. Its audience is the same as for `session_state`.
+- `session_approvals` fires when a tool call is escalated to a person (every call under `always-ask`, read-write or unknown-permission calls under `read-only`), when one is answered, and when an interrupt denies the waiting ones (one event for all of them). `count` is the Session's `pendingApprovalCount` as it now stands, zeros included. The calls themselves arrive on the Session's own stream as `approval_request` and are replayed on subscribe. Its audience is the same as for `session_state`.
- `credentials_updated` follows `PUT /models` or a completed key-minting flow. Cached runtimes were invalidated, so the client clears any composer state disabled by an auth failure.
- `web_updated` carries the new web revision as `rev` and is sent to every user channel.
- `session_created` is sent for every creation to the user channels of the Project's owner and members, and for a subagent also on the parent Session's channel. `source` is what the new Session's `session_meta` records. A title set through `PATCH /api/sessions/:id` is announced as `session_title` the same way.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index e4c94222..e5d50a44 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -1109,7 +1109,7 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。
| 通道 | 路径 | 内容 |
| --- | --- | --- |
| 每个 Session | `GET /api/sessions/:sessionId/stream` | Session 的消息流和运行事件,包括子 Agent Session 的 `session_created` 以及目标模式事件 |
-| 每个用户 | `GET /api/events` | `hello` 握手和跨 Session 的通知:`session_created`、`session_state`、`session_background`、`session_title`、`schedule_fired`、`schedule_queued`、`web_updated` 以及公司模式的 `org_*` 事件 |
+| 每个用户 | `GET /api/events` | `hello` 握手和跨 Session 的通知:`session_created`、`session_state`、`session_background`、`session_approvals`、`session_title`、`schedule_fired`、`schedule_queued`、`web_updated` 以及公司模式的 `org_*` 事件 |
### 传输格式
@@ -1130,6 +1130,7 @@ export type ServerEvent =
| { type: "session_title"; sessionId: string; title: string }
| { type: "session_state"; sessionId: string; projectId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }
| { type: "session_background"; sessionId: string; processes: number; subagents: number }
+ | { type: "session_approvals"; sessionId: string; count: number }
| { type: "resync_required" }
| { type: "credentials_updated" }
| { type: "hello" }
@@ -1153,6 +1154,7 @@ export type ServerEvent =
| `session_title` | 第一轮对话后,模型生成的标题已保存 |
| `session_state` | Session 的运行状态变化;`task_state` 在用户通道上的对应事件 |
| `session_background` | Session 的后台任务计数变化 |
+| `session_approvals` | Session 中等待审批的工具调用数变化 |
| `resync_required` | `Last-Event-ID` 已被挤出缓冲区;客户端必须重新拉取历史 |
| `credentials_updated` | Project 的模型凭据发生变化 |
| `hello` | 用户通道上的握手 |
@@ -1173,6 +1175,7 @@ export type ServerEvent =
- `session_title` 发送到 Session 的通道,以及 Project 所有者和成员的用户通道。
- `session_state` 用 `sessionId` 指明是哪个 Session、用 `projectId` 指明所属 Project,因此 Session 列表的每一行都能保持实时,而不只是客户端当前打开的那个会话;列表还能据此认出本 Project 中自己尚未持有的 Session,再按 id 单独拉取。事件携带重绘这一行所需的字段,无需重新拉取:刚写入的 `lastActiveAt`,以及 `hasTrace`。状态为 `running` 或 `compacting` 时 `hasTrace` 必为 true,因为正在运行的 Session 必然已经启动过 Task。它发送到 Project 所有者和成员的用户通道。
- 以下情况会触发 `session_background`:命令超过让出窗口转入后台,或以 `run_in_background` 启动;进程退出或停止;后台子 Agent 开始一轮、结束一轮或释放。事件携带 `SessionInfo.backgroundTasks` 的当前值(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转入后台、正处于一轮中的子 Agent Session 数),归零时同样发送,列表无需重新拉取就能撤下标记。两个计数都为零时,列表行和单个 Session 的 GET 会省略这个字段。受众与 `session_state` 相同。
+- 以下情况会触发 `session_approvals`:工具调用升级给人审批(`always-ask` 下的每个调用,`read-only` 下读写或权限未知的调用);某个审批得到回答;中断拒绝了所有等待中的审批(只发一个事件)。`count` 是 Session 当前的 `pendingApprovalCount`,归零时同样发送。调用本身以 `approval_request` 出现在该 Session 自己的流上,订阅时会重放。受众与 `session_state` 相同。
- `credentials_updated` 在 `PUT /models` 或签发 API key 的流程完成之后发送。缓存的运行时已失效,客户端应清除因认证失败而禁用的输入框状态。
- `web_updated` 以 `rev` 携带新的 web 修订号,发送到每个用户通道。
- `session_created` 在每次创建时发送到 Project 所有者和成员的用户通道;子 Agent Session 还会同时发送到父 Session 的通道。`source` 是新 Session 的 `session_meta` 所记录的来源。通过 `PATCH /api/sessions/:id` 设置的标题以同样方式作为 `session_title` 宣告。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 0fd1e8e3..b625cc52 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3118,6 +3118,15 @@ export type ServerEvent =
* the user channels of the Project's owner and members, like `session_state`.
*/
| { type: "session_background"; sessionId: string; processes: number; subagents: number }
+ /**
+ * A Session's count of tool calls waiting for a person's approval changed: a call was
+ * escalated (every call under always-ask, rw/unknown calls under read-only), answered, or
+ * denied by an interrupt. The count is the row's `pendingApprovalCount` as it stands after
+ * the change, zeros included, so a list moves its mark without refetching; the calls
+ * themselves are on the Session's own stream (`approval_request`, replayed on subscribe).
+ * Published to the user channels of the Project's owner and members, like `session_state`.
+ */
+ | { type: "session_approvals"; sessionId: string; count: 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/approvals.ts b/packages/server/src/runtime/approvals.ts
index 542ca39f..92221ab9 100644
--- a/packages/server/src/runtime/approvals.ts
+++ b/packages/server/src/runtime/approvals.ts
@@ -37,6 +37,14 @@ interface PendingEntry extends PendingApproval {
/** Pending approval registry (key = tool_call_id), one per Session runtime. */
export class ApprovalRegistry {
private readonly pending = new Map<string, PendingEntry>();
+ /** Inside a multi-entry change (`wait` replacing an entry, `denyAll`, `denyMain`): reported once, at its end. */
+ private batching = false;
+
+ /**
+ * `onChange` hears every change of `size`, once per call that made it (a `denyAll` over
+ * three entries is one change) and never for a call that left the count where it was.
+ */
+ constructor(private readonly onChange?: () => void) {}
get size(): number {
return this.pending.size;
@@ -53,18 +61,23 @@ export class ApprovalRegistry {
/** Register and wait for a decision. Re-registering the same id (defensive) resolves the old entry as deny. */
wait(toolCall: OmniMessage<ToolCallPayload>): Promise<ApprovalDecision> {
const id = toolCall.payload.tool_call_id;
- this.pending.get(id)?.resolve("deny");
- return new Promise<ApprovalDecision>((resolve) => {
- const entry: PendingEntry = {
- toolCall,
- ...(toolCall.origin !== undefined ? { origin: toolCall.origin } : {}),
- resolve: (decision) => {
- this.pending.delete(id);
- resolve(decision);
- },
- };
- this.pending.set(id, entry);
- });
+ return this.batch(
+ () =>
+ new Promise<ApprovalDecision>((resolve) => {
+ this.pending.get(id)?.resolve("deny");
+ const entry: PendingEntry = {
+ toolCall,
+ ...(toolCall.origin !== undefined ? { origin: toolCall.origin } : {}),
+ resolve: (decision) => {
+ if (this.pending.get(id) !== entry) return;
+ this.pending.delete(id);
+ this.changed();
+ resolve(decision);
+ },
+ };
+ this.pending.set(id, entry);
+ }),
+ );
}
/** Submit a decision; returns false if not found (already decided/unknown). */
@@ -77,7 +90,9 @@ export class ApprovalRegistry {
/** Interruption convergence: resolve all pending approvals as deny. */
denyAll(): void {
- for (const entry of [...this.pending.values()]) entry.resolve("deny");
+ this.batch(() => {
+ for (const entry of [...this.pending.values()]) entry.resolve("deny");
+ });
}
/**
@@ -87,8 +102,27 @@ export class ApprovalRegistry {
* denied only with the child itself (kill/dispose paths use denyAll).
*/
denyMain(): void {
- for (const entry of [...this.pending.values()]) {
- if (entry.origin === undefined || entry.origin.length === 0) entry.resolve("deny");
+ this.batch(() => {
+ for (const entry of [...this.pending.values()]) {
+ if (entry.origin === undefined || entry.origin.length === 0) entry.resolve("deny");
+ }
+ });
+ }
+
+ private changed(): void {
+ if (!this.batching) this.onChange?.();
+ }
+
+ /** Runs `fn` as one change: `onChange` hears it once, and only when the count moved. */
+ private batch<T>(fn: () => T): T {
+ if (this.batching) return fn();
+ const before = this.pending.size;
+ this.batching = true;
+ try {
+ return fn();
+ } finally {
+ this.batching = false;
+ if (this.pending.size !== before) this.onChange?.();
}
}
}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index b71e40d5..0d5d4de8 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -891,7 +891,7 @@ export class SessionManager {
/** Add a newly created Session to the active table (status idle), avoiding a redundant load on the next Task. */
adopt(row: SessionRow, session: RuntimeSession): void {
- this.entries.set(row.sessionId, {
+ const entry: RuntimeEntry = {
sessionId: row.sessionId,
projectId: row.projectId,
agentId: row.agentId,
@@ -899,7 +899,7 @@ export class SessionManager {
modelId: row.modelId,
session,
status: "idle",
- approvals: new ApprovalRegistry(),
+ approvals: new ApprovalRegistry(() => this.publishApprovals(entry)),
abort: null,
running: null,
generation: this.generationOf(row.projectId, row.agentId),
@@ -910,7 +910,8 @@ export class SessionManager {
returnedSteering: [],
lastActivityMs: Date.now(),
backgroundTasks: backgroundTaskCounts(session),
- });
+ };
+ this.entries.set(row.sessionId, entry);
// 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
// freshly created sessions unable to deliver idle-arrival completion reports.
@@ -1989,7 +1990,7 @@ export class SessionManager {
modelId: row.modelId,
session,
status: "idle",
- approvals: new ApprovalRegistry(),
+ approvals: new ApprovalRegistry(() => this.publishApprovals(entry)),
abort: null,
running: null,
generation,
@@ -2464,6 +2465,29 @@ export class SessionManager {
});
}
+ /**
+ * Publishes `session_approvals` on the user channel: how many tool calls of this Session wait
+ * for a person now. The Session's own stream carries the calls; this is what lets a list, or
+ * a host watching every Session of a Project, see which one waits without subscribing to each.
+ * Sent for an entry that is being disposed too, so a mark it had is cleared.
+ */
+ private publishApprovals(entry: RuntimeEntry): void {
+ try {
+ this.deps.notifyProjectUsers?.(entry.projectId, {
+ type: "session_approvals",
+ sessionId: entry.sessionId,
+ count: entry.approvals.size,
+ });
+ } catch (err) {
+ // The notifier reads the Project's audience from the database, which shutdown can close
+ // while a run outlives its drain window (the failure publishState guards too). A list
+ // mark is never worth throwing out of an approval's wait, answer or interrupt.
+ this.log(
+ `[session] approvals notice failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ }
+
/** 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/test/session-approvals-events.test.ts b/packages/server/test/session-approvals-events.test.ts
new file mode 100644
index 00000000..9364d035
--- /dev/null
+++ b/packages/server/test/session-approvals-events.test.ts
@@ -0,0 +1,127 @@
+/**
+ * `session_approvals` on the user channel: how many tool calls of a Session wait for a
+ * person, published whenever that count changes, so a list (or any client watching every
+ * Session of a Project) sees which Session waits without subscribing to each one's stream.
+ *
+ * - Given an always-ask Session whose Task calls a tool, when the call is escalated, the
+ * owner's channel hears the count 1; when the person answers it, the count 0.
+ * - Given a Task waiting on two approvals, when it is interrupted, one event brings the count
+ * to 0 (the interrupt denies both).
+ * - Given an allow-all Session, a call that nobody is asked about publishes nothing.
+ * - A stranger with a live channel and no access to the Project hears nothing.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import {
+ approvalDecision,
+ assistantText,
+ toolCall,
+ userText,
+ type ApproveFn,
+ type OmniMessage,
+} from "@lmliheng/penguin-core";
+import type { ServerEvent } from "../src/api/types.js";
+import { userChannelKey } from "../src/http/routes/events.js";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const PROJECT = "owner-default_project";
+
+/** A runtime whose Task asks to approve one call per id, in parallel, then answers. */
+function approvingSession(sessionId: string, toolCallIds: string[]): RuntimeSession {
+ return fakeSession(sessionId, {
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const calls = toolCallIds.map((id) =>
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: id }),
+ );
+ for (const tc of calls) yield tc;
+ const decisions = await Promise.all(calls.map((tc) => opts.approve(tc)));
+ for (const [i, decision] of decisions.entries()) {
+ yield approvalDecision(decision, toolCallIds[i]!);
+ }
+ yield assistantText("done");
+ },
+ });
+}
+
+/** The `session_approvals` events one user's live channel received. */
+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,
+ approvals: () => events.flatMap((e) => (e.type === "session_approvals" ? [e] : [])),
+ };
+}
+
+let t: TestApp;
+let api: ReturnType<typeof apiClient>;
+
+beforeAll(async () => {
+ t = await createTestApp();
+ api = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);
+ await provisionUser(t.app, "stranger");
+});
+afterAll(async () => {
+ await t.cleanup();
+});
+
+describe("session_approvals on the user channel", () => {
+ let SID: string;
+ let owner: ReturnType<typeof inbox>;
+ let stranger: ReturnType<typeof inbox>;
+
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ owner = inbox(t, "owner");
+ stranger = inbox(t, "stranger");
+ });
+
+ it("an escalated call publishes the count 1, and the person's answer the count 0", async () => {
+ adoptSession(t.deps, approvingSession(SID, ["tc-1"]), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => owner.approvals().length === 1);
+ expect(owner.approvals()).toEqual([{ type: "session_approvals", sessionId: SID, count: 1 }]);
+
+ const res = await api.post(`/api/sessions/${SID}/approvals/tc-1`, { decision: "allow" });
+ expect(res.status).toBe(204);
+ expect(owner.approvals().at(-1)).toEqual({
+ type: "session_approvals",
+ sessionId: SID,
+ count: 0,
+ });
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ expect(owner.approvals()).toHaveLength(2);
+ expect(stranger.events).toEqual([]);
+ });
+
+ it("an interrupt that denies two waiting calls publishes one event, with the count 0", async () => {
+ adoptSession(t.deps, approvingSession(SID, ["tc-a", "tc-b"]), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 2);
+ expect(owner.approvals().map((e) => e.count)).toEqual([1, 2]);
+
+ t.deps.manager.abortTask(SID);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ expect(owner.approvals().map((e) => e.count)).toEqual([1, 2, 0]);
+ });
+
+ it("a call nobody is asked about (allow-all) publishes nothing", async () => {
+ adoptSession(t.deps, approvingSession(SID, ["tc-auto"]), {
+ projectId: PROJECT,
+ approvalMode: "allow-all",
+ });
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ expect(owner.approvals()).toEqual([]);
+ });
+});
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index d5d1b849..d1200cfb 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -29,7 +29,7 @@
* heals the index; a swept channel is re-read before every publish; a Project abort hands
* back its in-flight runs; a loader's HttpError passes through; shutdown disposes every
* environment and refuses new Tasks, and a run parked on an approval is denied, winds down,
- * and is disposed only after it has.
+ * and is disposed only after it has, even once the database has closed under it.
* - Idle entries are evicted (running ones, pending approvals and working subagents pin them);
* invalidating an Agent's or a Project's runtimes rebuilds them at next access, never
* mid-run, and publishes a discarded runtime's background count as cleared.
@@ -124,6 +124,29 @@ function approvalFakeSession(sessionId: string, toolName = "write_file"): Runtim
});
}
+/**
+ * A run that parks one call on a person, logging into `order` how the call was decided, whether
+ * the run was aborted by then, when it ended, and when its environment was disposed.
+ */
+function parkedRunSession(order: string[]): RuntimeSession {
+ const fake = fakeSession("session-1", {
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ try {
+ const tc = toolCall({ name: "write_file", arguments: "{}", toolCallId: "tc-1" });
+ yield tc;
+ order.push(`decided ${await opts.approve(tc)}`);
+ order.push(`aborted ${String(opts.signal.aborted)}`);
+ } finally {
+ order.push("run ended");
+ }
+ },
+ });
+ (fake as { dispose?: () => void }).dispose = () => {
+ order.push("disposed");
+ };
+ return fake;
+}
+
/**
* A repo whose last-active writes always throw — the realistic failure being a
* DatabaseSync handle closed by shutdown while a run outlived its drain window. Everything
@@ -196,7 +219,7 @@ describe("session-manager", () => {
});
afterEach(() => {
channels.dispose();
- db.close();
+ if (db.isOpen) db.close();
});
it("unknown Session → 404", async () => {
@@ -1196,21 +1219,7 @@ describe("session-manager", () => {
// What a hot swap or an exit meets mid-conversation: a run waiting on an approval nobody
// in this process will ever give.
const order: string[] = [];
- const fake = fakeSession("session-1", {
- async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
- try {
- const tc = toolCall({ name: "write_file", arguments: "{}", toolCallId: "tc-1" });
- yield tc;
- order.push(`decided ${await opts.approve(tc)}`);
- order.push(`aborted ${String(opts.signal.aborted)}`);
- } finally {
- order.push("run ended");
- }
- },
- });
- (fake as { dispose?: () => void }).dispose = () => {
- order.push("disposed");
- };
+ const fake = parkedRunSession(order);
const manager = makeManager(loaderOf(fake));
await manager.startTask("session-1", [userText("write it")]);
await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
@@ -1220,6 +1229,34 @@ describe("session-manager", () => {
expect(order).toEqual(["decided deny", "aborted true", "run ended", "disposed"]);
});
+ it("shutdown still denies, winds down and disposes once the database has closed", async () => {
+ // The approvals count reaches the Project's users through a notifier that reads the
+ // database first (who owns and shares the Project). A handle closed under a run that
+ // outlived its drain window must not stop the shutdown that denies the call.
+ const order: string[] = [];
+ const fake = parkedRunSession(order);
+ const counts: number[] = [];
+ const manager = new SessionManager({
+ sessions,
+ channels,
+ sources,
+ loader: loaderOf(fake),
+ recorder: { record: async () => undefined },
+ notifyProjectUsers: (_projectId, event) => {
+ sessions.findById(ROW.sessionId); // the audience lookup: a database read
+ if (event.type === "session_approvals") counts.push(event.count);
+ },
+ log: () => {},
+ });
+ await manager.startTask("session-1", [userText("write it")]);
+ await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
+ expect(counts).toEqual([1]);
+
+ db.close();
+ await manager.shutdown();
+ expect(order).toEqual(["decided deny", "aborted true", "run ended", "disposed"]);
+ });
+
it("rejects new Tasks once shutdown is set (503 shutting_down)", async () => {
const manager = makeManager(loaderOf(approvalFakeSession("session-1")));
await manager.shutdown();
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 05b19d03..6904bfbb 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -399,6 +399,12 @@ interface SessionsStoreState {
* chat header's count both read the field, so this is the one write that moves them.
*/
setBackgroundTasks: (sessionId: string, tasks: SessionBackgroundTasks | undefined) => void;
+ /**
+ * Live count of tool calls waiting for approval on one row, from the user channel's
+ * `session_approvals`. The row's approvals mark reads it, so a Session that starts waiting
+ * while another one is open is marked at once instead of at the next list fetch.
+ */
+ setPendingApprovals: (sessionId: string, count: number) => void;
}
/**
@@ -1144,6 +1150,18 @@ export function createSessionsStore() {
}),
});
},
+
+ /** Same drop rule as `setBackgroundTasks`: an unlisted id is ignored, an equal count is a no-op. */
+ setPendingApprovals: (sessionId, count) => {
+ const prev = get().sessions;
+ const target = prev.find((s) => s.sessionId === sessionId);
+ if (!target || target.pendingApprovalCount === count) return;
+ set({
+ sessions: prev.map((s) =>
+ s.sessionId === sessionId ? { ...s, pendingApprovalCount: count } : s,
+ ),
+ });
+ },
};
});
}
@@ -1234,6 +1252,12 @@ export function applyUserEvent(
);
return;
}
+ // A Session's count of tool calls waiting for approval changed. Like the background counts,
+ // the event carries the count as it now stands, so the row's mark follows without a fetch.
+ if (ev.type === "session_approvals") {
+ store.getState().setPendingApprovals(ev.sessionId, ev.count);
+ 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. The remembered
diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.ts
index 1b371be3..55c5f039 100644
--- a/packages/web/test/session-status-events.test.ts
+++ b/packages/web/test/session-status-events.test.ts
@@ -8,6 +8,7 @@
* leaves every other row alone; a stamp change alone still lands.
* - session_background sets or clears the named row's counts, and moves neither the glyph nor
* the status.
+ * - session_approvals sets the named row's pending-approval count, zero included.
* - session_title renames the named row in place.
* - An event for a Session no loaded page holds changes nothing (a status from another Project;
* one of this Project's is fetched — sessions-store.test.ts), and one that matches the row
@@ -168,6 +169,23 @@ describe("session_background on the user channel", () => {
});
});
+describe("session_approvals on the user channel", () => {
+ const approvalsEvent = (sessionId: string, count: number): ServerEvent => ({
+ type: "session_approvals",
+ sessionId,
+ count,
+ });
+
+ it("sets the named row's count and leaves every other row alone, then clears it at zero", () => {
+ const store = storeWith(session("a"), session("b"));
+ applyUserEvent(store, approvalsEvent("b", 2), neverReload);
+ expect(rowOf(store, "b").pendingApprovalCount).toBe(2);
+ expect(rowOf(store, "a").pendingApprovalCount).toBe(0);
+ applyUserEvent(store, approvalsEvent("b", 0), neverReload);
+ expect(rowOf(store, "b").pendingApprovalCount).toBe(0);
+ });
+});
+
describe("session_title on the user channel", () => {
const titleEvent = (sessionId: string, title: string): ServerEvent => ({
type: "session_title",
@@ -190,6 +208,7 @@ describe("events that need no change", () => {
stateEvent("not-loaded", "running", STARTED, true, "another-project"),
{ type: "session_background", sessionId: "not-loaded", processes: 1, subagents: 0 },
{ type: "session_title", sessionId: "not-loaded", title: "whatever" },
+ { type: "session_approvals", sessionId: "not-loaded", count: 1 },
];
it("an event for a Session no loaded page holds invents no row and re-renders nothing", () => {
@@ -223,6 +242,7 @@ describe("events that need no change", () => {
{ type: "session_title", sessionId: "a", title: "Login page bug" },
neverReload,
);
+ applyUserEvent(store, { type: "session_approvals", sessionId: "a", count: 0 }, neverReload);
// Zero onto an already-clear row is the same non-event.
applyUserEvent(
store,