From 08dcd5a4610ff69b7607dfe9e429b44adc5bbc4c Mon Sep 17 00:00:00 2001 From: bigbang20061 <446282471@qq.com> Date: Wed, 11 Nov 2026 09:34:13 +0000 Subject: [PATCH 1/2] perf(subagents): slim and rate-limit subagent frames sent to the browser omp mirrors every child event as subagent_event (7-26 KB each) and sends a full subagent_progress snapshot every ~150 ms per child. With ten children one open session received ~430 KiB/s. Cut each child event to the fields the browser reads, let streaming child events tick at most once a second per child, and send newest-only subagent_progress once a second per child (terminal at once, always before agent_end or the child's lifecycle change). --- AGENTS.md | 9 ++ CHANGELOG.md | 1 + lib/rpc-manager.ts | 11 +- lib/subagent-stream.test.mjs | 168 +++++++++++++++++++++++++ lib/subagent-stream.ts | 233 +++++++++++++++++++++++++++++++++++ 5 files changed, 421 insertions(+), 1 deletion(-) create mode 100644 lib/subagent-stream.test.mjs create mode 100644 lib/subagent-stream.ts diff --git a/AGENTS.md b/AGENTS.md index 03cd434c4..23e632c61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1388,6 +1388,15 @@ during the wait. count (`inflightTaskDetails`/`extractedToolData.task` progress), and the `⤴` async marker (live `detached` flag or history `details.async` presence). Shared formatters live in `lib/subagent-format.ts`. +- **Wire diet** (`lib/subagent-stream.ts`, `SubagentStreamLimiter` in `AgentSessionWrapper.handleFrame`): + omp mirrors every child event and snapshots progress every ~150 ms per child, ~430 KiB/s per open + session with ten children. Before `emit`, `subagent_event` is cut to what `parseSubagentActivityEvent` + reads (child id, tool name/intent/arg keys, a 140-char label); streaming child events + (`message_update`, `tool_stream_update`, `tool_execution_update`) pass at most once a second per child; + `subagent_progress` is newest-wins once a second per child (terminal at once). `subagent_lifecycle` + and `agent_end` flush the held progress first, so a snapshot never lands after the change that + supersedes it; `dispose` drops it. A new consumer of a child event's fields must extend + `slimInnerEvent`, or it reads nothing. Transcripts come from disk, never from these frames. ### Worktrees and project grouping - `lib/worktree.ts` resolves linked worktree top-levels back to the main repo `projectRoot`; `listAllSessions()` attaches that to each `SessionInfo` so all worktrees for one repo are grouped together in the sidebar. diff --git a/CHANGELOG.md b/CHANGELOG.md index 43f39a088..37d36f4d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **Sessions with many subagents no longer saturate the server's bandwidth.** omp mirrors every child event as a `subagent_event` (message updates carry the whole message twice, 7-26 KB each) and sends a full `subagent_progress` snapshot every ~150 ms per child; with ten running children one open session received ~430 KiB/s. The wrapper (`lib/subagent-stream.ts`) now cuts each child event to the fields the browser reads (the child id and the one-line activity label), lets streaming child events tick a child's transcript revision at most once a second, and sends at most one `subagent_progress` per child per second (the newest; a terminal one at once, and always before the run's end or the child's lifecycle change). The subagent dialog still reads transcripts from disk, so its content is unchanged. - **Listing files in a folder that is not a Git repository no longer leaves a `git` process running in it.** The @-mention and file-search index asks Git first; when the folder is not a repository it now waits for both Git queries to exit before falling back to reading the folder. A leftover `git` process could briefly keep Windows from deleting or renaming that folder. - **Dollar amounts no longer render as math.** In text such as “$5 and $10”, the span between the two dollar signs turned into glued italic formula text. Single-dollar math now follows Pandoc's rule: the opening `$` must be followed by a non-space, and the closing `$` must be preceded by a non-space and not followed by a digit. `$x^2$` still renders as math. - **Dollar amounts no longer render as math.** In text such as “$5 and $10” or “R$5 or US$10”, the span between the two dollar signs turned into glued italic formula text. Single-dollar math now follows Pandoc's rule: the opening `$` must be followed by a non-space, and the closing `$` must be preceded by a non-space and not followed by a digit. A letter directly before `$` and a digit after it (R$5, US$10) marks a price. `$x^2$` still renders as math; single-dollar math that spans lines now renders as text. diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 098447502..ce3743806 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -6,6 +6,7 @@ import { invalidateModelsCache } from "./models-cache"; import { RpcCommandError, RpcCommandTimeoutError, RpcProcess, type RpcFrame } from "./omp/rpc-process"; import type { RpcTransport } from "./omp/rpc-transport"; import { editSessionHistory, isSessionEditReply, SESSION_EDIT_COMMAND, SessionEditAgentInvocationError, type SessionEditResult } from "./omp/session-edit"; +import { SubagentStreamLimiter } from "./subagent-stream"; import { cacheSessionPath } from "./session-reader"; import { allowFileRoot } from "./file-access"; import { loadWebServerSettings } from "./web-settings"; @@ -472,6 +473,10 @@ export class AgentSessionWrapper { * the same conversation moving to a sibling file, not a session switch. */ private sessionMovePending = false; private unsubscribeFrames: (() => void) | null = null; + /** Slims and rate-limits subagent frames before they reach any tab (lib/subagent-stream.ts). */ + private readonly subagentStream = new SubagentStreamLimiter((frame) => { + if (this._alive) this.emit(frame); + }); private readonly detectNotification = createNotificationDetector(); /** Agent activity since the last `session_settled`: background work may still run after the turn ended. */ private unsettled = false; @@ -1245,6 +1250,8 @@ export class AgentSessionWrapper { if (event.isTerminal !== false) { // A server dialog belongs to a tool call of this run; nobody can answer it after the run. this.dropServerUiRequests(); + // Held-back progress must land before the run's end, never after it. + this.subagentStream.flushAll(); this.streaming = false; this.promptRunning = false; this.awaitingAgentStart = false; @@ -1450,7 +1457,8 @@ export class AgentSessionWrapper { } this.publishNotifications(event); - this.emit(event); + // Subagent frames are slimmed or held back (newest progress per child per second) before any tab sees them. + if (!this.subagentStream.push(event)) this.emit(event); notifyRunningChange({ refreshSessionList }); } @@ -3037,6 +3045,7 @@ export class AgentSessionWrapper { this.sessionFileSignalTimer = null; } this.unsubscribeFrames?.(); + this.subagentStream.dispose(); this.unsubscribeHostStatus?.(); this.unsubscribeHostStatus = null; this.clearPendingUiRequests(); diff --git a/lib/subagent-stream.test.mjs b/lib/subagent-stream.test.mjs new file mode 100644 index 000000000..b032db8af --- /dev/null +++ b/lib/subagent-stream.test.mjs @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { SubagentStreamLimiter, slimSubagentEvent, SUBAGENT_PROGRESS_INTERVAL_MS, SUBAGENT_NOISY_EVENT_INTERVAL_MS } = await import("./subagent-stream.ts"); +const { parseSubagentActivityEvent } = await import("./subagent-types.ts"); + +const assistant = (text, extra = {}) => ({ role: "assistant", content: [{ type: "thinking", thinking: "x".repeat(5000) }, { type: "text", text }], usage: { input: 1 }, ...extra }); + +/** What the browser derives from a frame, minus the timestamp. */ +const activity = (frame) => { + const parsed = parseSubagentActivityEvent(frame.payload); + return parsed && { kind: parsed.kind, label: parsed.label }; +}; + +const eventFrame = (id, event) => ({ type: "subagent_event", payload: { id, event }, web: { sequence: 1 } }); +const progressFrame = (id, status = "running", tokens = 0) => ({ type: "subagent_progress", payload: { index: 0, progress: { id, status, tokens } } }); +const lifecycleFrame = (id, status) => ({ type: "subagent_lifecycle", payload: { id, status, agent: "worker", index: 0 } }); + +/** A limiter on a manual clock; timers fire when `advance` passes them. */ +function harness() { + let clock = 0; + let nextHandle = 1; + const timers = new Map(); + const out = []; + const limiter = new SubagentStreamLimiter((frame) => out.push(frame), { + now: () => clock, + setTimer: (run, ms) => { + const handle = nextHandle++; + timers.set(handle, { at: clock + ms, run }); + return handle; + }, + clearTimer: (handle) => timers.delete(handle), + }); + const advance = (ms) => { + clock += ms; + for (const [handle, timer] of [...timers]) { + if (timer.at <= clock && timers.delete(handle)) timer.run(); + } + }; + return { limiter, out, advance, timers }; +} + +test("a slimmed child event yields the same activity label as the full one", () => { + const events = [ + { type: "tool_execution_start", toolName: "write", intent: "Writing the report", args: { path: "/a", content: "y".repeat(9000) } }, + { type: "tool_execution_start", toolName: "grep", args: { pattern: "x", path: ".", glob: "*.ts", extra: 1 } }, + { type: "tool_execution_start", toolName: "bash" }, + { type: "message_end", message: assistant(" The answer is 42. ") }, + { type: "message_end", message: assistant("z".repeat(500)) }, + { type: "message_end", message: { role: "toolResult", content: [{ type: "text", text: "ignored" }] } }, + { type: "message_end", message: { role: "assistant", content: "plain string content" } }, + { type: "notice", message: "n".repeat(300), level: "warning" }, + { type: "message_update", message: assistant("partial"), assistantMessageEvent: { type: "text_delta", partial: assistant("partial") } }, + { type: "turn_end", message: assistant("done"), toolResults: [{ role: "toolResult", content: [] }] }, + ]; + for (const event of events) { + const full = eventFrame("Child", event); + const slim = slimSubagentEvent(full); + assert.deepEqual(activity(slim), activity(full), `activity of ${event.type}`); + assert.equal(slim.payload.id, "Child"); + assert.equal(slim.payload.event.type, event.type); + assert.deepEqual(slim.web, full.web, "the wrapper's sequence stamp survives"); + } +}); + +test("a slimmed message_update carries no message body", () => { + const full = eventFrame("Child", { type: "message_update", message: assistant("x"), assistantMessageEvent: { type: "text_delta", delta: "x", partial: assistant("x") } }); + const slim = slimSubagentEvent(full); + assert.deepEqual(slim.payload.event, { type: "message_update" }); + assert.ok(JSON.stringify(slim).length < JSON.stringify(full).length / 10); +}); + +test("a malformed child event passes through untouched", () => { + const noEvent = { type: "subagent_event", payload: { id: "Child" } }; + assert.equal(slimSubagentEvent(noEvent), noEvent); + const noPayload = { type: "subagent_event" }; + assert.equal(slimSubagentEvent(noPayload), noPayload); +}); + +test("progress is sent at once for a quiet child, then newest-only once per interval", () => { + const { limiter, out, advance } = harness(); + limiter.push(progressFrame("A", "running", 1)); + assert.equal(out.length, 1); + limiter.push(progressFrame("A", "running", 2)); + limiter.push(progressFrame("A", "running", 3)); + limiter.push(progressFrame("A", "running", 4)); + assert.equal(out.length, 1, "held back inside the interval"); + advance(SUBAGENT_PROGRESS_INTERVAL_MS - 1); + assert.equal(out.length, 1); + advance(1); + assert.equal(out.length, 2); + assert.equal(out[1].payload.progress.tokens, 4, "the newest snapshot wins"); +}); + +test("children are throttled independently", () => { + const { limiter, out } = harness(); + limiter.push(progressFrame("A")); + limiter.push(progressFrame("B")); + assert.deepEqual(out.map((frame) => frame.payload.progress.id), ["A", "B"]); +}); + +test("a terminal progress goes out at once and cancels the held one", () => { + const { limiter, out, advance, timers } = harness(); + limiter.push(progressFrame("A", "running", 1)); + limiter.push(progressFrame("A", "running", 2)); + limiter.push(progressFrame("A", "completed", 3)); + assert.deepEqual(out.map((frame) => frame.payload.progress.tokens), [1, 3]); + assert.equal(timers.size, 0); + advance(5000); + assert.equal(out.length, 2, "the cancelled snapshot never lands after the terminal one"); +}); + +test("a lifecycle frame lands after the progress it supersedes, never before", () => { + const { limiter, out } = harness(); + limiter.push(progressFrame("A", "running", 1)); + limiter.push(progressFrame("A", "running", 2)); + limiter.push(lifecycleFrame("A", "completed")); + assert.deepEqual(out.map((frame) => frame.type), ["subagent_progress", "subagent_progress", "subagent_lifecycle"]); + assert.equal(out[1].payload.progress.tokens, 2); +}); + +test("a progress frame that names no child is passed through unchanged", () => { + const { limiter, out } = harness(); + const frame = { type: "subagent_progress", payload: { index: 2, task: "t" } }; + limiter.push(frame); + limiter.push(frame); + assert.deepEqual(out, [frame, frame]); +}); + +test("streaming child events tick a revision at most once per interval; labelled ones always pass", () => { + const { limiter, out, advance } = harness(); + const update = () => eventFrame("A", { type: "message_update", message: assistant("x") }); + for (let i = 0; i < 50; i += 1) limiter.push(update()); + assert.equal(out.length, 1); + limiter.push(eventFrame("A", { type: "tool_execution_start", toolName: "bash" })); + limiter.push(eventFrame("A", { type: "message_end", message: assistant("done") })); + assert.equal(out.length, 3, "events the activity line is built from are never dropped"); + limiter.push(eventFrame("B", { type: "message_update", message: assistant("x") })); + assert.equal(out.length, 4, "another child has its own budget"); + advance(SUBAGENT_NOISY_EVENT_INTERVAL_MS); + limiter.push(update()); + assert.equal(out.length, 5); +}); + +test("flushAll emits what is held back; dispose drops it", () => { + const first = harness(); + first.limiter.push(progressFrame("A", "running", 1)); + first.limiter.push(progressFrame("A", "running", 2)); + first.limiter.flushAll(); + assert.equal(first.out.length, 2); + first.advance(5000); + assert.equal(first.out.length, 2, "nothing is sent twice"); + + const second = harness(); + second.limiter.push(progressFrame("A", "running", 1)); + second.limiter.push(progressFrame("A", "running", 2)); + second.limiter.dispose(); + second.advance(5000); + assert.equal(second.out.length, 1); + assert.equal(second.timers.size, 0); +}); + +test("other frame types are not claimed", () => { + const { limiter, out } = harness(); + assert.equal(limiter.push({ type: "message_update" }), false); + assert.equal(limiter.push({ type: "agent_end" }), false); + assert.equal(out.length, 0); +}); diff --git a/lib/subagent-stream.ts b/lib/subagent-stream.ts new file mode 100644 index 000000000..e4ec33b00 --- /dev/null +++ b/lib/subagent-stream.ts @@ -0,0 +1,233 @@ +// Bandwidth limits for the subagent frames omp sends over the event stream. +// +// With `set_subagent_subscription level: "events"` omp mirrors every event of +// every child session as a `subagent_event` (message updates carry the whole +// message twice, 7-26 KB per frame) and sends a full `subagent_progress` +// snapshot every ~150 ms per child. With ten children that was ~430 KiB/s per +// open session. The browser reads very little of it: +// - `subagent_event`: the child's id (a transcript revision tick) and the +// one-line activity label `parseSubagentActivityEvent` derives from +// tool_execution_start / assistant message_end / notice (lib/subagent-types.ts). +// The transcript itself is paged from disk, never from these frames. +// - `subagent_progress`: the latest snapshot; the hook keeps only the newest. +// So the wrapper shrinks `subagent_event` to those fields and sends at most one +// `subagent_progress` per child per interval (the newest one, trailing; a +// terminal one at once). Anything that changes what the transcript view shows +// must be added to `slimInnerEvent`. + +import { isRecord } from "./type-guards"; + +export type SubagentFrame = { type: string; [key: string]: unknown }; + +/** Newest `subagent_progress` per child goes out at most this often. */ +export const SUBAGENT_PROGRESS_INTERVAL_MS = 1000; +/** Streaming-only child events (no activity label) tick a child's revision at most this often. */ +export const SUBAGENT_NOISY_EVENT_INTERVAL_MS = 1000; +/** Same cut `parseSubagentActivityEvent` applies to a label. */ +const LABEL_MAX = 140; +const ARG_KEYS_MAX = 3; + +/** Child events that stream continuously and carry no activity label. */ +const NOISY_EVENTS: Record = { message_update: true, tool_stream_update: true, tool_execution_update: true }; +const TERMINAL_STATUSES: Record = { completed: true, failed: true, aborted: true }; +const isTerminalStatus = (status: unknown): boolean => typeof status === "string" && TERMINAL_STATUSES[status] === true; + +const asString = (value: unknown): string | undefined => (typeof value === "string" ? value : undefined); + +/** The child event reduced to what `parseSubagentActivityEvent` reads. */ +export function slimInnerEvent(event: Record): Record { + const type = asString(event.type) ?? "unknown"; + switch (type) { + case "tool_execution_start": { + const slim: Record = { type }; + const toolName = asString(event.toolName); + if (toolName !== undefined) slim.toolName = toolName; + const intent = asString(event.intent); + if (intent !== undefined) slim.intent = intent; + if (isRecord(event.args)) { + const args: Record = {}; + for (const key of Object.keys(event.args).slice(0, ARG_KEYS_MAX)) args[key] = null; + slim.args = args; + } + return slim; + } + case "message_end": { + const message = isRecord(event.message) ? event.message : null; + if (!message || message.role !== "assistant") return { type }; + const content = message.content; + const text = typeof content === "string" + ? content + : Array.isArray(content) + ? content + .filter((block): block is { type: "text"; text?: unknown } => isRecord(block) && block.type === "text") + .map((block) => (typeof block.text === "string" ? block.text : "")) + .join("\n") + : ""; + const label = text.trim().slice(0, LABEL_MAX); + return label ? { type, message: { role: "assistant", content: [{ type: "text", text: label }] } } : { type }; + } + case "notice": { + const message = asString(event.message); + return message ? { type, message: message.slice(0, LABEL_MAX) } : { type }; + } + default: + return { type }; + } +} + +/** A `subagent_event` frame with its child event slimmed; other fields (`payload.id`, `web`) are kept. */ +export function slimSubagentEvent(frame: F): F { + const payload = frame.payload; + if (!isRecord(payload) || !isRecord(payload.event)) return frame; + return { ...frame, payload: { ...payload, event: slimInnerEvent(payload.event) } }; +} + +export interface SubagentStreamLimiterOptions { + now?: () => number; + setTimer?: (run: () => void, ms: number) => unknown; + clearTimer?: (handle: unknown) => void; +} + +interface PendingProgress { + frame: SubagentFrame; + handle: unknown; +} + +/** + * Sits between omp's frames and the wrapper's `emit`: slims `subagent_event`, + * rate-limits `subagent_progress` and keeps `subagent_lifecycle` ordered + * after the progress it supersedes. + */ +export class SubagentStreamLimiter { + private readonly now: () => number; + private readonly setTimer: (run: () => void, ms: number) => unknown; + private readonly clearTimer: (handle: unknown) => void; + private readonly progressSentAt = new Map(); + private readonly pendingProgress = new Map(); + private readonly noisySentAt = new Map(); + + constructor(private readonly emit: (frame: SubagentFrame) => void, options: SubagentStreamLimiterOptions = {}) { + this.now = options.now ?? Date.now; + this.setTimer = options.setTimer ?? ((run, ms) => { + const handle: unknown = setTimeout(run, ms); + // Bun/Node timers have unref; a held-back frame must not keep the process alive. + if (isRecord(handle) && typeof handle.unref === "function") handle.unref(); + return handle; + }); + this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as number)); + } + + /** Handles a subagent frame (emitting now or later) and returns true; false for any other frame. */ + push(frame: SubagentFrame): boolean { + switch (frame.type) { + case "subagent_event": + this.pushEvent(frame); + return true; + case "subagent_progress": + this.pushProgress(frame); + return true; + case "subagent_lifecycle": + this.pushLifecycle(frame); + return true; + default: + return false; + } + } + + /** Emits what is held back (the run ended: nothing may stay behind). */ + flushAll(): void { + for (const id of [...this.pendingProgress.keys()]) this.flushProgress(id); + } + + /** Drops everything held back without emitting (the wrapper is gone). */ + dispose(): void { + for (const pending of this.pendingProgress.values()) this.clearTimer(pending.handle); + this.pendingProgress.clear(); + this.progressSentAt.clear(); + this.noisySentAt.clear(); + } + + private pushEvent(frame: SubagentFrame): void { + const payload = frame.payload; + const id = isRecord(payload) ? asString(payload.id) : undefined; + const innerType = isRecord(payload) && isRecord(payload.event) ? asString(payload.event.type) : undefined; + if (id !== undefined && innerType !== undefined && NOISY_EVENTS[innerType] === true) { + const now = this.now(); + const last = this.noisySentAt.get(id); + if (last !== undefined && now - last < SUBAGENT_NOISY_EVENT_INTERVAL_MS) return; + this.noisySentAt.set(id, now); + } + this.emit(slimSubagentEvent(frame)); + } + + private pushProgress(frame: SubagentFrame): void { + const id = progressId(frame); + // A frame that names no child cannot be keyed: pass it as omp sent it. + if (id === undefined) { + this.emit(frame); + return; + } + if (isTerminalProgress(frame)) { + this.cancelPending(id); + this.progressSentAt.set(id, this.now()); + this.emit(frame); + return; + } + const existing = this.pendingProgress.get(id); + if (existing) { + existing.frame = frame; + return; + } + const last = this.progressSentAt.get(id); + const wait = last === undefined ? 0 : SUBAGENT_PROGRESS_INTERVAL_MS - (this.now() - last); + if (wait <= 0) { + this.progressSentAt.set(id, this.now()); + this.emit(frame); + return; + } + this.pendingProgress.set(id, { frame, handle: this.setTimer(() => this.flushProgress(id), wait) }); + } + + private pushLifecycle(frame: SubagentFrame): void { + const payload = frame.payload; + const id = isRecord(payload) ? asString(payload.id) : undefined; + if (id !== undefined) { + // The newest snapshot must not land after the status change that supersedes it. + this.flushProgress(id); + if (isRecord(payload) && isTerminalStatus(payload.status)) { + this.progressSentAt.delete(id); + this.noisySentAt.delete(id); + } + } + this.emit(frame); + } + + private flushProgress(id: string): void { + const pending = this.pendingProgress.get(id); + if (!pending) return; + this.clearTimer(pending.handle); + this.pendingProgress.delete(id); + this.progressSentAt.set(id, this.now()); + this.emit(pending.frame); + } + + private cancelPending(id: string): void { + const pending = this.pendingProgress.get(id); + if (!pending) return; + this.clearTimer(pending.handle); + this.pendingProgress.delete(id); + } +} + +/** The child a `subagent_progress` frame is about: `payload.progress.id` as the hook keys it. */ +function progressId(frame: SubagentFrame): string | undefined { + const payload = frame.payload; + if (!isRecord(payload) || !isRecord(payload.progress)) return undefined; + return asString(payload.progress.id); +} + +function isTerminalProgress(frame: SubagentFrame): boolean { + const payload = frame.payload; + if (!isRecord(payload) || !isRecord(payload.progress)) return false; + return isTerminalStatus(payload.progress.status); +} From 3aa94a08fb60e72a876a0adec45f343661a28f5e Mon Sep 17 00:00:00 2001 From: bigbang20061 <446282471@qq.com> Date: Tue, 17 Nov 2026 03:02:00 +0000 Subject: [PATCH 2/2] fix(subagents): recover live roster without reactivating chat Refresh authoritative subagent snapshots on every recoverable reconnect and unknown running progress. Coalesce concurrent recovery reads and fence stale roster pruning across run boundaries. Verified 511 related tests, types, touched lint, browser-visible recovery, and explicit-host compiled runtime smoke. --- AGENTS.md | 10 ++-- CHANGELOG.md | 1 + hooks/useAgentSession.rpc.test.mjs | 78 ++++++++++++++++++++++++++++++ hooks/useAgentSession.ts | 25 +++++++++- 4 files changed, 109 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6393bc917..c7def580c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1558,9 +1558,13 @@ during the wait. frames also feed a bounded per-subagent activity buffer shown in the transcript dialog. - **Roster hydration**: `get_subagents` snapshots (which carry progress) - rehydrate the roster after SSE reconnect (`refreshSubagentRoster`, wired - into mount, send, and the reconcile poll). Terminal subagents vanish from - the live registry — history fills that gap. + rehydrate the roster after every event-stream reconnect (`refreshSubagentRoster`, + wired into mount, send, and the reconcile poll), even when the same stream has + carried later prompt runs. Running/pending progress for an unknown child also + requests the registry; never fabricate a roster entry from a possibly late + progress frame. Concurrent reads share one in-flight request per session/run/ + roster generation, and both merging and pruning reject a stale generation. + Terminal subagents vanish from the live registry — history fills that gap. - **On-disk history** (`lib/subagent-history.ts`, `/api/sessions/[id]/subagents*`): omp persists each subagent's transcript to the parent session's sibling artifacts dir (`/.jsonl`) and the parent file's diff --git a/CHANGELOG.md b/CHANGELOG.md index 03e0c08bc..c174a14d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixed +- **Running subagents recover without reactivating the chat.** Every event-stream reconnect refreshes the live roster, including reconnects after a new prompt on the same connection. Progress for an unknown running child requests an authoritative roster snapshot instead of silently disappearing; concurrent recovery reads are shared, and responses from a finished run cannot resurrect its children. - **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery. ## [v0.7.2] - 2026-11-14 diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index efce900b5..665e69284 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -3318,6 +3318,84 @@ test("subagent roster is restored from the get_subagents snapshot after reconnec ); }); +test("unknown running progress restores a missed subagent without activating the chat", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + const { w, es } = await startStreamingRun("s1"); + const child = { id: "missed-child", agent: "explore", status: "running", index: 0, task: "keep searching", progress: { id: "missed-child", status: "running", tokens: 42 } }; + world.subagentSnapshots.set("s1", [child]); + let release; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "get_subagents", + produce: () => new Promise((resolve) => { release = () => resolve({ value: { success: true, data: { subagents: [child] } } }); }), + }); + const before = world.calls.filter((c) => c.body?.type === "get_subagents").length; + await act(async () => { + for (let i = 0; i < 5; i++) es.emit({ type: "subagent_progress", payload: { progress: child.progress } }); + }); + await until(() => !!release, "unknown progress must trigger registry recovery"); + assert.equal(world.calls.filter((c) => c.body?.type === "get_subagents").length - before, 1, "concurrent recovery triggers share one read"); + await act(async () => { release(); }); + await until(() => w.latest.subagents.some((s) => s.id === child.id), "the missing chip appears without focus or another prompt"); + assert.equal(w.latest.subagents.find((s) => s.id === child.id)?.progress.tokens, 42); + assert.equal(w.latest.agentRunning, true); +}); + +test("late unknown progress cannot fabricate a child absent from omp's registry", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + const { w, es } = await startStreamingRun("s1"); + await act(async () => { + es.emit({ type: "subagent_progress", payload: { progress: { id: "old-child", status: "running", tokens: 42 } } }); + }); + await settle(); + assert.deepEqual(w.latest.subagents, [], "a late frame is only a recovery hint, never proof of a running child"); +}); + +test("roster recovery started by progress cannot repopulate a finished run", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + const { w, es } = await startStreamingRun("s1"); + let release; + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "get_subagents", + produce: () => new Promise((resolve) => { + release = () => resolve({ value: { success: true, data: { subagents: [{ id: "old-child", agent: "explore", status: "running" }] } } }); + }), + }); + await act(async () => { + es.emit({ type: "subagent_progress", payload: { progress: { id: "old-child", status: "running" } } }); + }); + await until(() => !!release, "recovery read starts"); + await act(async () => { es.emit({ type: "agent_end", isTerminal: true }); }); + await until(() => !w.latest.agentRunning, "the main run finishes"); + await act(async () => { release(); }); + await settle(); + assert.deepEqual(w.latest.subagents, [], "the old generation cannot restore a ghost chip"); +}); + +test("every recoverable stream reconnect restores quiet subagents across prompt runs", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + const { w, es } = await startStreamingRun("s1"); + world.agents.set("s1", { running: true, state: { isStreaming: true } }); + for (const id of ["first-reconnect", "next-run-reconnect"]) { + world.subagentSnapshots.set("s1", [{ id, agent: "explore", status: "running", index: 0, task: "quiet child" }]); + await act(async () => { + es.dropRecoverably(); + es.open(); + }); + await until(() => w.latest.subagents.some((s) => s.id === id), "reopening the same stream must restore its roster"); + if (id === "first-reconnect") { + await act(async () => { es.emit({ type: "agent_end", isTerminal: true }); }); + await until(() => !w.latest.agentRunning, "the first prompt finishes"); + await act(async () => { es.emit({ type: "agent_start" }); }); + await settle(); + } + } + assert.equal(w.latest.agentRunning, true); +}); + /** Poll inside act until `check` holds (btw frames flush on a display-rate timer). */ async function until(check, message, timeoutMs = 2000) { const deadline = Date.now() + timeoutMs; diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0d3a9ed84..c7a02dd84 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -579,6 +579,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { updateQueuedMessages(readQueueSnapshot(value) ?? EMPTY_QUEUE); }, [updateQueuedMessages]); const [subagents, setSubagents] = useState([]); + const subagentsRef = useRef(subagents); + subagentsRef.current = subagents; const [subagentEvents, setSubagentEvents] = useState>({}); const [subagentTranscriptVersions, setSubagentTranscriptVersions] = useState>({}); const [todoPhases, setTodoPhases] = useState([]); @@ -688,6 +690,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const wasRunningForGaugeRef = useRef(false); // so a stale get_subagents cannot target a session that was switched away. const rosterRefreshTimerRef = useRef | null>(null); + const rosterRefreshInFlightRef = useRef<{ sid: string; runId: number; generation: number } | null>(null); const promptRunIdRef = useRef(0); // An idle snapshot during local startup is not evidence the new prompt finished. const promptDispatchPendingRef = useRef(false); @@ -1006,6 +1009,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const requestedAt = Date.now(); const runId = promptRunIdRef.current; const generation = subagentRosterGenerationRef.current; + const pending = rosterRefreshInFlightRef.current; + if (pending?.sid === sid && pending.runId === runId && pending.generation === generation) return; + const request = { sid, runId, generation }; + rosterRefreshInFlightRef.current = request; try { const result = await sendAgentCommand<{ subagents?: SubagentSnapshotLike[] }>(sid, { type: "get_subagents" }); // Fence: the request may resolve after the user switched sessions, the @@ -1027,6 +1034,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // state we got and must survive the prune. const liveIds = new Set(snapshots.map((s) => s.id)); setSubagents((prev) => { + if (!hookAliveRef.current || sessionIdRef.current !== sid || promptRunIdRef.current !== runId || subagentRosterGenerationRef.current !== generation) return prev; const next = prev.filter((s) => s.source !== "live" || liveIds.has(s.id) || (s.lastUpdate ?? 0) >= requestedAt); return next.length === prev.length ? prev : next; }); @@ -1036,6 +1044,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void refreshSubagentHistory(sid); } catch { // Best effort: subagent_lifecycle/progress frames are the primary source. + } finally { + if (rosterRefreshInFlightRef.current === request) rosterRefreshInFlightRef.current = null; } }, [mergeSubagents, refreshSubagentHistory]); @@ -1599,14 +1609,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { catchUp.disconnect(); const es = openEventStream({ kind: "session", sessionId: sid }); eventSourceRef.current = es; - const runId = promptRunIdRef.current; return new Promise((resolve) => { let settled = false; let restored = false; const restore = () => { if (!restoreWrapper || restored || !hookAliveRef.current || sessionIdRef.current !== sid - || promptRunIdRef.current !== runId || eventSourceRef.current !== es) return; + || eventSourceRef.current !== es) return; restored = true; reconnectActionsRef.current?.(sid); }; @@ -1694,6 +1703,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }; es.onerror = () => { + restored = false; + // Even a stream opened for this tab's own send must rehydrate after + // reconnect. Wait for connected so a wrapper-less held stream stays passive. + restoreWrapper = "connected"; // The server rejected this chat's pending host tools when its subscription left (rejectPendingHostTools), and // the cancel it emitted had no listener: withdraw them here so nothing answers or opens a settled call. if (eventSourceRef.current === es) { @@ -3073,6 +3086,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const task = typeof payload?.task === "string" && payload.task.trim() ? payload.task : (progress?.task ?? null); const assignment = typeof payload?.assignment === "string" ? payload.assignment : progress?.assignment; if (!progressId && !task && !parentToolCallId && index < 0) break; + // Progress keeps arriving if the start frame was missed or the roster + // was cleared while detached children kept running. Recover from omp's + // registry, not from this possibly late frame (which may be stale). + if (progressId && (progress?.status === "running" || progress?.status === "pending") + && !subagentsRef.current.some((subagent) => subagent.id === progressId)) { + const sid = sessionIdRef.current; + if (sid) void refreshSubagentRoster(sid); + } // Fence progress frames against roster clear / new run (same as mergeSubagents). const progressGeneration = subagentRosterGenerationRef.current; const progressRunId = promptRunIdRef.current;