From 2ad6f63b9f3898bab14de6804d572e78be309c01 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 01:17:32 +0000 Subject: [PATCH 1/2] Unify subagent progression helpers and harden Proactive Aiden race tests --- .../services/chat-run-input-admission.test.ts | 115 +++++++++++++ main/services/goal/goal-loop.test.ts | 136 +++++++++++++++- main/services/goal/goal-loop.ts | 11 +- .../keep-awake/keep-awake-core.test.ts | 145 +++++++++++++++++ main/services/scheduled-task-triggers.test.ts | 99 ++++++++++++ .../subagents/subagent-control-v2.test.ts | 49 ++++++ .../services/subagents/subagent-control-v2.ts | 86 +++------- .../subagents/subagent-run-store-core.ts | 53 +----- .../subagents/subagent-run-store-v2-core.ts | 70 +------- renderer/shared/subagent-runs-v2.test.ts | 153 ++++++++++++++++++ renderer/shared/subagent-runs.ts | 100 ++++++++---- 11 files changed, 798 insertions(+), 219 deletions(-) diff --git a/main/services/chat-run-input-admission.test.ts b/main/services/chat-run-input-admission.test.ts index 7c2e226817..2ee84e0692 100644 --- a/main/services/chat-run-input-admission.test.ts +++ b/main/services/chat-run-input-admission.test.ts @@ -647,6 +647,121 @@ test("a lead chat's message to a chat it started reaches its run before the queu assert.equal((app.appended[1]!.message as { fromLeadChat?: true }).fromLeadChat, undefined); }); +test("stop, chat deletion, or run end while awaiting leadChatInput prevents queueing and gates owed turns", async () => { + // 1. Cancelled while awaiting leadChatInput: committed, cancelled, never queued or owed. + for (const kind of ["stop", "delete"] as const) { + const app = fixture(); + const owed = owedTurnStub("accept"); + app.generation.owedTurn = owed.owedTurn; + let release!: () => void; + app.generation.leadChatInput = () => new Promise((resolve) => { release = resolve; }); + const pending = app.admission.admit({ + streamId: "stream-1", + mode: "steer", + text: "From the lead", + fromLeadChat: true, + }); + await new Promise((resolve) => setImmediate(resolve)); + if (kind === "stop") app.generation.cancelRequested = true; + else app.deleting.add("chat-1"); + release(); + assert.deepEqual( + await pending, + { admitted: false, reason: "cancelled", committed: true, messageId: "message_admitted_1" }, + kind, + ); + assert.equal(app.appended.length, 1, kind); + assert.equal(app.steered.length, 0, kind); + assert.deepEqual(owed.registered, [], kind); + assert.equal(owed.holdsReleased(), 1, kind); + } + + // 2. Run naturally ends (leaves active map) while awaiting leadChatInput: registered as owed turn. + { + const app = fixture(); + const owed = owedTurnStub("accept"); + app.generation.owedTurn = owed.owedTurn; + app.generation.leadChatInput = async () => { + app.active.delete("stream-1"); + }; + const result = await app.admission.admit({ + streamId: "stream-1", + mode: "steer", + text: "From the lead", + fromLeadChat: true, + }); + assert.deepEqual(result, { + admitted: true, + queue: "follow-up", + committed: true, + messageId: "message_admitted_1", + }); + assert.equal(app.steered.length, 0); + assert.deepEqual(owed.registered, [{ messageId: "message_admitted_1" }]); + assert.equal(owed.holdsReleased(), 1); + } + + // 3. Run leaves active AND is cancelled/deleting while awaiting leadChatInput: not owed. + for (const kind of ["stop", "delete"] as const) { + const app = fixture(); + const owed = owedTurnStub("accept"); + app.generation.owedTurn = owed.owedTurn; + app.generation.leadChatInput = async () => { + if (kind === "stop") app.generation.cancelRequested = true; + else app.deleting.add("chat-1"); + app.active.delete("stream-1"); + }; + const result = await app.admission.admit({ + streamId: "stream-1", + mode: "queue", + text: "From the lead", + fromLeadChat: true, + }); + assert.deepEqual( + result, + { admitted: false, reason: "run_not_active", committed: true, messageId: "message_admitted_1" }, + kind, + ); + assert.equal(app.followedUp.length, 0, kind); + assert.deepEqual(owed.registered, [], kind); + assert.equal(owed.holdsReleased(), 1, kind); + } + + // 4. A rejecting leadChatInput still queues while active, but still respects a concurrent stop. + { + const app = fixture(); + app.generation.leadChatInput = async () => { + throw new Error("link unreadable"); + }; + const admitted = await app.admission.admit({ + streamId: "stream-1", + mode: "steer", + text: "Still queued", + fromLeadChat: true, + }); + assert.equal(admitted.admitted, true); + assert.equal(app.steered.length, 1); + + app.generation.leadChatInput = async () => { + app.generation.cancelRequested = true; + throw new Error("link unreadable"); + }; + const cancelled = await app.admission.admit({ + streamId: "stream-1", + mode: "steer", + text: "Stopped during rejection", + fromLeadChat: true, + }); + assert.deepEqual(cancelled, { + admitted: false, + reason: "cancelled", + committed: true, + messageId: "message_admitted_1", + }); + assert.equal(app.steered.length, 1); + } +}); + test("a started chat's ending that quotes outside text reaches the run's taint before the queue does; a clean ending, the person's words and plain notices don't", async () => { const app = fixture(); const order: string[] = []; diff --git a/main/services/goal/goal-loop.test.ts b/main/services/goal/goal-loop.test.ts index 8a77e9c972..3dc8f0d737 100644 --- a/main/services/goal/goal-loop.test.ts +++ b/main/services/goal/goal-loop.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { GOAL_MAX_ROUNDS, type GoalRecordV1, type GoalView } from "../../../renderer/shared/goal.js"; +import { GOAL_MAX_ROUNDS, GOAL_WAIT_LIMIT_MS, type GoalRecordV1, type GoalView } from "../../../renderer/shared/goal.js"; import { agentNotice, type AgentNoticeV1 } from "../../../renderer/shared/agent-notices.js"; import { createGoal, type GoalRoundActivity } from "./goal-core.js"; import { GoalLoop, type GoalAnalyticsEvent, type GoalRoundStart } from "./goal-loop.js"; @@ -45,15 +45,20 @@ function harness(options: { throws: { activity: false, context: false, start: false, noticeContext: false }, /** Holds startRound open, as a window's 5-second claim does. */ holdStart: undefined as Promise | undefined, + /** Holds startNoticeRound open to test races while a notice round starts. */ + holdNoticeStart: undefined as Promise | undefined, review: (async (goal) => continueWith(`Next step ${goal.rounds}`)) as Review, }; const rounds: Array<{ text: string; notice: AgentNoticeV1 }> = []; const roundCurrent: Array<() => boolean> = []; + const noticeCurrent: Array<() => boolean> = []; const noticeRounds: string[] = []; const events: GoalAnalyticsEvent[] = []; const changes: Array = []; const saved: GoalRecordV1[][] = []; const settled: GoalRecordV1[] = []; + const timers = new Map void }>(); + let nextTimerId = 1; /** Looks waiting for the chat to be idle; `becomeIdle` releases them. */ let idleWaiters: Array<() => void> = []; let lookingChanges = 0; @@ -63,7 +68,13 @@ function harness(options: { now: () => clock, newId: () => `goal-${++ids}`, delay: (_ms, signal) => (signal.aborted ? Promise.reject(signal.reason) : Promise.resolve()), - setTimer: () => () => {}, + setTimer: (run, ms) => { + const id = nextTimerId++; + timers.set(id, { at: clock + ms, run }); + return () => { + timers.delete(id); + }; + }, persist: (goals) => saved.push([...goals]), onChange: (_chatId, goal) => changes.push(goal), eligibility: async () => options.refusal, @@ -99,7 +110,10 @@ function harness(options: { rounds.push(round); return state.roundStart; }, - startNoticeRound: async (chatId, _context, notice) => { + startNoticeRound: async (chatId, _context, notice, isCurrent) => { + noticeCurrent.push(isCurrent); + await state.holdNoticeStart; + if (!isCurrent()) return { kind: "unavailable", reason: "Goal changed" }; noticeRounds.push(notice?.text ?? "(saved)"); if (state.noticeStart !== "started") return state.noticeStart === "busy" ? { kind: "busy" } : { kind: "unavailable", reason: "No model" }; return { kind: "started", streamId: `notice-${chatId}-${noticeRounds.length}` }; @@ -127,6 +141,7 @@ function harness(options: { state, rounds, roundCurrent, + noticeCurrent, noticeRounds, events, changes, @@ -136,6 +151,24 @@ function harness(options: { settle, flush, reviews: () => reviewCount, + activeTimers: () => timers.size, + fireDueTimers: async () => { + for (const [id, timer] of [...timers.entries()]) { + if (timer.at <= clock) { + timers.delete(id); + timer.run(); + } + } + await flush(); + }, + idleWaitersCount: () => idleWaiters.length, + /** Resolves current idle waiters without clearing busy, for spurious/re-check wakeups. */ + pulseIdleWaiters: async () => { + const waiters = idleWaiters; + idleWaiters = []; + for (const resolve of waiters) resolve(); + await flush(); + }, /** Whatever held the chat lets go without a run settling. */ becomeIdle: async () => { state.busy = false; @@ -849,3 +882,100 @@ test("news that drops a review but whose round doesn't start leaves the goal loo assert.equal(h.reviews(), 1); assert.equal(h.rounds.length, 1); }); + +test("a 30-minute watchdog pauses a waiting goal, and starting a round or changing the goal cancels it", async () => { + // 1. A `wait` verdict arms the 30-minute watchdog and pauses once the limit passes. + const waiting = harness(); + await waiting.loop.set(CHAT, { objective: "Wait for CI", source: "slash" }); + waiting.state.jobs = true; + waiting.state.review = async () => ({ kind: "verdict", verdict: { verdict: "wait", reason: "Waiting on tests" }, via: "continuation" }); + await waiting.runSettles(); + assert.equal(waiting.activeTimers(), 1, "wait verdict arms one watchdog timer"); + waiting.tick(GOAL_WAIT_LIMIT_MS - 1); + await waiting.fireDueTimers(); + assert.equal(waiting.goal()?.status, "active", "not expired before 30 minutes"); + waiting.tick(1); + await waiting.fireDueTimers(); + assert.equal(waiting.goal()?.status, "paused"); + assert.equal(waiting.goal()?.cause, "wait-limit"); + assert.equal(waiting.settled.length, 1); + assert.equal(waiting.activeTimers(), 0); + + // 2. A running helper also arms the watchdog, and a subsequent round cancels it. + const helper = harness(); + await helper.loop.set(CHAT, { objective: "Wait for helper", source: "slash" }); + helper.state.helper = true; + await helper.runSettles(); + assert.equal(helper.activeTimers(), 1); + helper.state.helper = false; + await helper.runSettles(); + assert.equal(helper.activeTimers(), 0, "the next round cancels the wait watchdog"); + + // 3. Replacing, pausing, clearing, deleting, or shutting down cancels an armed watchdog. + for (const action of ["replace", "pause", "clear", "delete", "shutdown"] as const) { + const h = harness(); + await h.loop.set(CHAT, { objective: "Wait for helper", source: "slash" }); + h.state.helper = true; + await h.runSettles(); + assert.equal(h.activeTimers(), 1, `${action}: watchdog armed`); + if (action === "replace") await h.loop.set(CHAT, { objective: "Different goal", source: "slash" }); + else if (action === "pause") h.loop.pause(CHAT); + else if (action === "clear") h.loop.clear(CHAT); + else if (action === "delete") h.loop.deleteChat(CHAT); + else h.loop.shutdown(); + assert.equal(h.activeTimers(), 0, `${action}: watchdog cancelled immediately`); + } +}); + +test("replacing, pausing, or clearing a goal while noticeRound starts never clobbers or relooks the replacement", async () => { + const news = { text: "job ended", notice: agentNotice({ source: "background_job", tone: "success", title: "Done", summary: "x" }) }; + for (const action of ["pause", "clear", "replace"] as const) { + const h = harness(); + await h.loop.set(CHAT, { objective: "Old goal", source: "slash" }); + let release!: () => void; + h.state.holdNoticeStart = new Promise((resolve) => { release = resolve; }); + const pending = h.loop.noticeRound(CHAT, news); + await h.flush(); + assert.equal(h.noticeCurrent.length, 1, action); + assert.equal(h.noticeCurrent[0]!(), true, action); + + if (action === "pause") h.loop.pause(CHAT); + else if (action === "clear") h.loop.clear(CHAT); + else await h.loop.set(CHAT, { objective: "Fresh goal", source: "slash" }); + + assert.equal(h.noticeCurrent[0]!(), false, `${action}: notice round becomes stale`); + release(); + const result = await pending; + assert.equal(result?.kind, "unavailable", action); + assert.equal(h.idleWaitersCount(), 0, `${action}: no spurious relook armed`); + await h.becomeIdle(); + assert.equal(h.reviews(), 0, `${action}: no review triggered for stale notice round`); + if (action === "replace") { + assert.equal(h.goal()?.objective, "Fresh goal"); + assert.equal(h.goal()?.rounds, 1); + } + } +}); + +test("a relook that wakes while the chat is still busy waits again, and shutdown drops pending relooks", async () => { + const h = harness(); + await h.loop.set(CHAT, { objective: "Ship it", source: "slash" }); + h.state.busy = true; + await h.runSettles(); + assert.equal(h.idleWaitersCount(), 1); + // Spurious wakeup while still busy re-arms waitForIdle without starting a review. + await h.pulseIdleWaiters(); + assert.equal(h.reviews(), 0); + assert.equal(h.idleWaitersCount(), 1); + await h.becomeIdle(); + assert.equal(h.reviews(), 1); + assert.equal(h.rounds.length, 1); + + const stopping = harness(); + await stopping.loop.set(CHAT, { objective: "Ship it", source: "slash" }); + stopping.state.busy = true; + await stopping.runSettles(); + stopping.loop.shutdown(); + await stopping.becomeIdle(); + assert.equal(stopping.reviews(), 0); +}); diff --git a/main/services/goal/goal-loop.ts b/main/services/goal/goal-loop.ts index a3f8345c85..00d309c0af 100644 --- a/main/services/goal/goal-loop.ts +++ b/main/services/goal/goal-loop.ts @@ -183,6 +183,7 @@ export class GoalLoop { if (!created.ok) throw new GoalLoopError(created.message); const previous = this.goals.get(chatId); this.stopReview(chatId); + this.cancelWatchdog(chatId); if (previous?.status === "active") this.reportSettled(previous, "cleared"); // A command goal sends no objective message: its first check runs now if // the chat is idle, or when the current answer ends, and the round after @@ -294,7 +295,8 @@ export class GoalLoop { * its settling runs the loop as any round's does. Undefined with no active goal. */ async noticeRound(chatId: string, notice?: { text: string; notice: AgentNoticeV1 }): Promise { - if (this.stopped || this.goals.get(chatId)?.status !== "active") return undefined; + const before = this.goals.get(chatId); + if (this.stopped || before?.status !== "active") return undefined; // The news is newer than what a look under way read: its review is // dropped (its verdict would be stale) and this round's settling is looked at. this.dropLook(chatId); @@ -304,12 +306,13 @@ export class GoalLoop { } catch (error) { // The notice is still saved, as one no round could answer. this.deps.log("A keep-going notice round could not read the chat.", error); - if (this.goals.get(chatId)?.status !== "active") return undefined; + const current = this.goals.get(chatId); + if (current?.id !== before.id || current.status !== "active") return undefined; this.relookAfterNotice(chatId); return { kind: "unavailable", reason: "The round could not start." }; } const latest = this.goals.get(chatId); - if (latest?.status !== "active") return undefined; + if (latest?.id !== before.id || latest.status !== "active") return undefined; if (!context) { this.relookAfterNotice(chatId); return { kind: "unavailable", reason: "The chat has no model yet." }; @@ -337,7 +340,7 @@ export class GoalLoop { if (result.kind !== "started") { const restored = compareAndSetGoal(this.goals.get(chatId), counted, (current) => goalRoundNotStarted(current, latest.rounds, this.deps.now())); if (restored.ok && restored.goal !== this.goals.get(chatId)) this.write(restored.goal); - this.relookAfterNotice(chatId); + if (restored.ok) this.relookAfterNotice(chatId); } return result; } diff --git a/main/services/keep-awake/keep-awake-core.test.ts b/main/services/keep-awake/keep-awake-core.test.ts index b58809b51d..37a46093e2 100644 --- a/main/services/keep-awake/keep-awake-core.test.ts +++ b/main/services/keep-awake/keep-awake-core.test.ts @@ -223,3 +223,148 @@ test("a recheck time far ahead (or behind a clock jump) waits at most an hour, n assert.equal(reads, afterAdd + 1, "one hourly re-read"); controller.dispose(); }); + +test("removing an input starts the grace period, releases after grace, and is idempotent", () => { + const clock = fakeClock(); + const active = new Set(); + let nextHandle = 1; + const controller = new KeepAwakeController({ + blocker: { + start: () => { + const id = nextHandle++; + active.add(id); + return id; + }, + stop: (id) => { active.delete(id); }, + }, + clock, + idleSeconds: () => 0, + }); + const remove = controller.addInput({ read: () => ({ reasons: [chat("a")] }) }); + assert.equal(active.size, 1); + remove(); + assert.equal(active.size, 1, "removing the last active input still honors grace"); + clock.advance(KEEP_AWAKE_GRACE_MS - 1); + assert.equal(active.size, 1); + // A second removal is a safe no-op and does not reset grace. + remove(); + clock.advance(1); + assert.equal(active.size, 0); + assert.equal(clock.pending(), 0); +}); + +test("a past recheckAt waits at least a second rather than spinning, and grace is not reset by idle rechecks", () => { + const clock = fakeClock(); + let reads = 0; + let reasons: KeepAwakeReason[] = [chat("a")]; + let recheckAt: number | undefined; + const active = new Set(); + const controller = new KeepAwakeController({ + blocker: { + start: () => { active.add(1); return 1; }, + stop: (id) => { active.delete(id); }, + }, + clock, + idleSeconds: () => 0, + }); + controller.addInput({ + read: () => { + reads += 1; + return { reasons, ...(recheckAt === undefined ? {} : { recheckAt }) }; + }, + }); + // Enter grace with a past recheckAt (already due). + reasons = []; + recheckAt = clock.now() - 5_000; + controller.update(); + const afterUpdate = reads; + clock.advance(999); + assert.equal(reads, afterUpdate, "past recheckAt is floored to 1,000 ms"); + clock.advance(1); + assert.equal(reads, afterUpdate + 1, "fires once after the 1,000 ms floor"); + recheckAt = undefined; + // Grace still ends at KEEP_AWAKE_GRACE_MS from when work ended, not from the recheck. + clock.advance(KEEP_AWAKE_GRACE_MS - 1_001); + assert.equal(active.size, 1); + clock.advance(1); + assert.equal(active.size, 0); + assert.equal(clock.pending(), 0); +}); + +test("pausedWhileIdle clears cleanly without grace when work ends, and mid-grace idle-capped work releases at once", () => { + const h = harness(); + h.setIdle(KEEP_AWAKE_IDLE_CAP_SECONDS); + h.set([chat("a")]); + assert.equal(h.blocker.active.size, 0); + assert.equal(h.controller.status().pausedWhileIdle, true); + + // All work ends while pausedWhileIdle: no grace timer or idle timer remains. + h.set([]); + assert.equal(h.controller.status().pausedWhileIdle, false); + assert.equal(h.clock.pending(), 0); + + // Hold while active, enter grace, then idle past the cap before non-exempt work arrives. + h.setIdle(0); + h.set([chat("b")]); + assert.equal(h.blocker.active.size, 1); + h.set([]); + assert.equal(h.blocker.active.size, 1, "in grace"); + h.setIdle(KEEP_AWAKE_IDLE_CAP_SECONDS); + h.set([chat("c")]); + assert.equal(h.blocker.active.size, 0, "idle-capped work cancels grace and releases immediately"); + assert.equal(h.controller.status().pausedWhileIdle, true); +}); + +test("blocker, idleSeconds, and onStatus errors are isolated via onError without leaking state", () => { + const clock = fakeClock(); + const errors: unknown[] = []; + let failStart = true; + let failStop = false; + let idleMode: "throw" | "nan" | "normal" = "throw"; + let failStatus = true; + const active = new Set(); + const controller = new KeepAwakeController({ + blocker: { + start: () => { + if (failStart) throw new Error("start failed"); + active.add(1); + return 1; + }, + stop: (id) => { + active.delete(id); + if (failStop) throw new Error("stop failed"); + }, + }, + clock, + idleSeconds: () => { + if (idleMode === "throw") throw new Error("idle failed"); + if (idleMode === "nan") return Number.NaN; + return 0; + }, + onStatus: () => { + if (failStatus) throw new Error("status failed"); + }, + onError: (error) => errors.push(error), + }); + let reasons: KeepAwakeReason[] = [chat("a")]; + controller.addInput({ read: () => ({ reasons }) }); + assert.equal(controller.status().holding, false, "failed start leaves holding false"); + assert.ok(errors.length >= 2, "idleSeconds, start, and onStatus errors reported"); + + // Non-finite idleSeconds falls back to 0 rather than triggering the idle cap. + failStart = false; + failStatus = false; + idleMode = "nan"; + controller.update(); + assert.equal(controller.status().holding, true); + assert.equal(active.size, 1); + + // Failed stop still clears the handle so status reflects release. + failStop = true; + idleMode = "normal"; + reasons = []; + controller.setEnabled(false); + assert.equal(controller.status().holding, false); + assert.equal(active.size, 0); + controller.dispose(); +}); diff --git a/main/services/scheduled-task-triggers.test.ts b/main/services/scheduled-task-triggers.test.ts index 95e4cad197..e33b94c9ff 100644 --- a/main/services/scheduled-task-triggers.test.ts +++ b/main/services/scheduled-task-triggers.test.ts @@ -1246,3 +1246,102 @@ test("changing a link task to a schedule or removing it releases its secret, and assert.deepEqual(link.released, ["task-1"], "a URL watch leaves nothing behind"); link.triggers.stop(); }); + +test("link webhook 415, 413, 400, and 401 refusals release only their own slot, while disabled 404 retains and 429 stays pre-slot", async () => { + // 1. 415 on admit releases its slot, short-circuits past 30 refusals without calling open, and leaves all 60 valid slots free. + { + const link = linkHarness(); + await link.setUp(); + for (let n = 0; n < REFUSED_LINK_CALLS_PER_MINUTE + 40; n += 1) { + assert.deepEqual( + await link.triggers.webhook.admit({ token: link.token, contentType: "application/xml" }), + { status: 415 }, + ); + } + for (let n = 0; n < 60; n += 1) assert.equal(await link.call({ n }), 202); + assert.equal(await link.call({ over: 1 }), 429, "all 60 slots were still available after 70 415s"); + link.triggers.stop(); + } + + // 2. 413 via tooLarge and deliver, plus 415 via deliver, release only their own slot; foreign admission ids never free another call's slot. + { + const link = linkHarness(); + await link.setUp(); + // 70 oversized calls via tooLarge + 5 via deliver + 5 wrong-type deliver calls. + for (let n = 0; n < 70; n += 1) { + const admitted = await link.triggers.webhook.admit({ token: link.token, contentType: "application/json" }); + assert.ok("accept" in admitted); + assert.deepEqual( + await link.triggers.webhook.tooLarge({ token: link.token, admission: admitted.admission }), + { status: 413 }, + ); + } + const oversized = new Uint8Array(256 * 1024 + 1); + for (let n = 0; n < 5; n += 1) { + const admitted = await link.triggers.webhook.admit({ token: link.token, contentType: "application/json" }); + assert.ok("accept" in admitted); + assert.deepEqual( + await link.triggers.webhook.deliver({ token: link.token, admission: admitted.admission, contentType: "application/json", body: oversized }), + { status: 413 }, + ); + } + for (let n = 0; n < 5; n += 1) { + const admitted = await link.triggers.webhook.admit({ token: link.token, contentType: "application/json" }); + assert.ok("accept" in admitted); + assert.deepEqual( + await link.triggers.webhook.deliver({ token: link.token, admission: admitted.admission, contentType: "application/xml", body: new TextEncoder().encode("") }), + { status: 415 }, + ); + } + // Use all 60 valid slots, and verify a bogus/reused admission id on tooLarge cannot free one. + for (let n = 0; n < 60; n += 1) assert.equal(await link.call({ n }), 202); + assert.deepEqual( + await link.triggers.webhook.tooLarge({ token: link.token, admission: "bogus-slot" }), + { status: 413 }, + ); + assert.equal(await link.call({ over: 1 }), 429, "60 slots remain full after unrelated tooLarge"); + link.triggers.stop(); + } + + // 3. >60 invalid-JSON (400) calls release all slots, leaving all 60 valid calls available. + { + const link = linkHarness(); + await link.setUp(); + for (let n = 0; n < 70; n += 1) assert.equal(await link.call("{not json"), 400); + for (let n = 0; n < 60; n += 1) assert.equal(await link.call({ n }), 202); + assert.equal(await link.call({ over: 1 }), 429); + link.triggers.stop(); + } + + // 4. 429 refusals are pre-slot: mid-minute 429s never occupy slots after the original 60 age out. + { + const link = linkHarness(); + await link.setUp(); + for (let n = 0; n < 60; n += 1) assert.equal(await link.call({ n }), 202); + link.advance(30_000); + for (let n = 0; n < 20; n += 1) assert.equal(await link.call({ mid: n }), 429); + // Advance just past 60s from the original 60 calls (still only 30s after the 429s). + link.advance(30_001); + for (let n = 0; n < 60; n += 1) assert.equal(await link.call({ fresh: n }), 202); + assert.equal(await link.call({ over: 1 }), 429); + link.triggers.stop(); + } + + // 5. A disabled task's known token retains its slot and returns 404 (then 429) even with an unsupported content type. + { + const link = linkHarness(); + await link.setUp(); + link.tasks[0] = { ...link.tasks[0]!, enabled: false }; + for (let n = 0; n < 60; n += 1) { + assert.deepEqual( + await link.triggers.webhook.admit({ token: link.token, contentType: "application/xml" }), + { status: 404 }, + ); + } + assert.deepEqual( + await link.triggers.webhook.admit({ token: link.token, contentType: "application/xml" }), + { status: 429 }, + ); + link.triggers.stop(); + } +}); diff --git a/main/services/subagents/subagent-control-v2.test.ts b/main/services/subagents/subagent-control-v2.test.ts index a0be4ad374..5f05ff797e 100644 --- a/main/services/subagents/subagent-control-v2.test.ts +++ b/main/services/subagents/subagent-control-v2.test.ts @@ -466,3 +466,52 @@ test("only a pristine queued preparation can be unregistered before launch", () /unlaunched queued/u, ); }); + +test("update rejects direct stopped transitions and treats unknown as terminal", async () => { + let revocations = 0; + let stops = 0; + const registry = new SubagentControlRegistryV2(); + registry.register( + registration(snapshot({ state: "queued", activity: "Waiting for an execution slot" }), { + revokeApprovals: () => { + revocations += 1; + }, + stop: () => { + stops += 1; + }, + }), + ); + + // Stops must go through registry.stop() so approvals are fenced and cancelled synchronously. + assert.throws( + () => registry.update(owner, terminal("stopped")), + /lifecycle cannot move backward/u, + ); + assert.equal(registry.status(owner, "run-one").state, "queued"); + assert.equal(revocations, 0); + + // Transitioning to unknown closes the control record as terminal. + const unknownSnapshot = snapshot({ + revision: 2, + state: "unknown", + activity: undefined, + updatedAt: 200, + finishedAt: 200, + terminalMarkdown: "Outcome unknown.", + }); + registry.update(owner, unknownSnapshot); + assert.equal(revocations, 1); + assert.equal(registry.stop(owner, "run-one").changed, false); + assert.equal(stops, 0); + await assert.rejects(registry.steer(owner, "run-one", "late"), /terminal/u); + assert.throws( + () => + registry.update(owner, { + ...terminal("completed"), + revision: 3, + updatedAt: 300, + finishedAt: 300, + }), + /lifecycle cannot move backward/u, + ); +}); diff --git a/main/services/subagents/subagent-control-v2.ts b/main/services/subagents/subagent-control-v2.ts index 7e473b2de2..aa89d6a572 100644 --- a/main/services/subagents/subagent-control-v2.ts +++ b/main/services/subagents/subagent-control-v2.ts @@ -1,10 +1,11 @@ import { randomUUID } from "node:crypto"; import { isSafeSubagentIdentifier, + isSubagentRunStateTerminal, parseSubagentRunSnapshotV2, - subagentProjectionNoticesAreMonotonic, + sameSubagentRunSnapshotIdentity, + subagentRunSnapshotProgresses, type SubagentRunSnapshotV2, - type SubagentRunStateV2, } from "../../../renderer/shared/subagent-runs.js"; import { parseSubagentManagementRequestV2, @@ -17,14 +18,6 @@ export const MAX_SUBAGENT_CONTROL_STEERING_PER_RUN = 8; export const MAX_SUBAGENT_CONTROL_STEERING_CHARS_PER_RUN = 32_000; const MAX_IDENTIFIER_ALLOCATION_ATTEMPTS = 128; -const TERMINAL_STATES = new Set([ - "completed", - "failed", - "timed_out", - "interrupted", - "stopped", -]); - export interface SubagentControlOwnerV2 { chatId: string; workspaceId: string; @@ -147,58 +140,15 @@ function sameOptional(left: string | undefined, right: string | undefined): bool return left === right; } -function sameRunIdentity(left: SubagentRunSnapshotV2, right: SubagentRunSnapshotV2): boolean { - return ( - left.runId === right.runId && - left.groupId === right.groupId && - left.generationId === right.generationId && - left.childId === right.childId && - left.chatId === right.chatId && - left.workspaceId === right.workspaceId && - left.role === right.role && - left.label === right.label && - left.taskPreview === right.taskPreview && - left.startedAt === right.startedAt && - left.modelId === right.modelId && - left.providerId === right.providerId && - left.thinkingLevel === right.thinkingLevel && - left.modelSelection === right.modelSelection && - sameOptional(left.parentRunId, right.parentRunId) && - sameOptional(left.retryOfRunId, right.retryOfRunId) && - left.depth === right.depth && - left.execution === right.execution && - left.context === right.context && - left.authorityRevision === right.authorityRevision - ); -} - -function validStateProgression(current: SubagentRunStateV2, next: SubagentRunStateV2): boolean { - if (TERMINAL_STATES.has(current) || next === "stopped") return false; - if (current === "queued") return true; - if (current === "starting") return next !== "queued"; - return next !== "queued" && next !== "starting"; -} - function assertMonotonicProgress( current: SubagentRunSnapshotV2, next: SubagentRunSnapshotV2, ): void { - const currentMilestones = current.milestones ?? []; - const nextMilestones = next.milestones ?? []; if ( next.revision <= current.revision || - next.updatedAt < current.updatedAt || - next.turns < current.turns || - next.tools < current.tools || - next.tokens < current.tokens || - nextMilestones.length < currentMilestones.length || - currentMilestones.some((milestone, index) => nextMilestones[index] !== milestone) || - !subagentProjectionNoticesAreMonotonic( - current.projectionNotices, - next.projectionNotices, - TERMINAL_STATES.has(next.state), - ) || - !validStateProgression(current.state, next.state) + // Stops must go through `SubagentControlRegistryV2.stop` (`stoppedSnapshot`) + // so the control plane synchronously revokes approvals and cancels active work. + !subagentRunSnapshotProgresses(current, next, { allowStopped: false }) ) { throw new Error("Subagent control lifecycle cannot move backward."); } @@ -284,7 +234,7 @@ export class SubagentControlRegistryV2 { steeringActive: false, retryInFlight: false, }; - if (TERMINAL_STATES.has(snapshot.state)) { + if (isSubagentRunStateTerminal(snapshot.state)) { // Complete the mandatory approval fence before capacity eviction so a // rejected terminal admission cannot discard already accepted history. record.revokeApprovals(); @@ -294,7 +244,7 @@ export class SubagentControlRegistryV2 { throw new Error("The subagent control registry is full."); } this.records.set(snapshot.runId, record); - if (TERMINAL_STATES.has(snapshot.state)) { + if (isSubagentRunStateTerminal(snapshot.state)) { this.closeTerminalRecord(record); } return cloneSnapshot(snapshot); @@ -330,7 +280,7 @@ export class SubagentControlRegistryV2 { ): SubagentRunSnapshotV2 { const record = this.ownedRecord(owner, candidate.runId); const next = parseSubagentRunSnapshotV2(candidate); - if (!next || !sameRunIdentity(record.snapshot, next)) { + if (!next || !sameSubagentRunSnapshotIdentity(record.snapshot, next)) { throw new Error("Subagent control update changed immutable run authority."); } assertMonotonicProgress(record.snapshot, next); @@ -351,7 +301,7 @@ export class SubagentControlRegistryV2 { }); if (parsed.action !== "wait") throw new Error("Invalid subagent wait request."); const record = this.ownedRecord(owner, parsed.runId); - if (TERMINAL_STATES.has(record.snapshot.state)) { + if (isSubagentRunStateTerminal(record.snapshot.state)) { return { snapshot: cloneSnapshot(record.snapshot), timedOut: false }; } if (parsed.timeoutMs === 0) { @@ -377,7 +327,7 @@ export class SubagentControlRegistryV2 { runId: string, ): { snapshot: SubagentRunSnapshotV2; changed: boolean } { const record = this.ownedRecord(owner, runId); - if (TERMINAL_STATES.has(record.snapshot.state)) { + if (isSubagentRunStateTerminal(record.snapshot.state)) { return { snapshot: cloneSnapshot(record.snapshot), changed: false }; } const reason = new Error("Subagent run stopped by its owner."); @@ -404,7 +354,7 @@ export class SubagentControlRegistryV2 { }); if (parsed.action !== "steer") throw new Error("Invalid subagent steer request."); const record = this.ownedRecord(owner, parsed.runId); - if (TERMINAL_STATES.has(record.snapshot.state)) { + if (isSubagentRunStateTerminal(record.snapshot.state)) { throw new Error("A terminal subagent cannot be steered."); } if (!record.steer) throw new Error("Subagent steering is unavailable for this run."); @@ -428,7 +378,7 @@ export class SubagentControlRegistryV2 { runId: string, ): Promise<{ sourceSnapshot: SubagentRunSnapshotV2; snapshot: SubagentRunSnapshotV2 }> { const sourceRecord = this.ownedRecord(owner, runId); - if (!TERMINAL_STATES.has(sourceRecord.snapshot.state)) { + if (!isSubagentRunStateTerminal(sourceRecord.snapshot.state)) { throw new Error("Only a terminal subagent run can be retried."); } if (!this.options.prepareRetry) throw new Error("Subagent retry is unavailable."); @@ -516,12 +466,12 @@ export class SubagentControlRegistryV2 { } private publish(record: ControlRecord, snapshot: SubagentRunSnapshotV2): void { - if (TERMINAL_STATES.has(snapshot.state)) record.revokeApprovals(); + if (isSubagentRunStateTerminal(snapshot.state)) record.revokeApprovals(); record.snapshot = snapshot; if (record.onSnapshot) { ignoreControlHookFailure(() => record.onSnapshot?.(cloneSnapshot(snapshot))); } - if (TERMINAL_STATES.has(snapshot.state)) this.closeTerminalRecord(record); + if (isSubagentRunStateTerminal(snapshot.state)) this.closeTerminalRecord(record); } private closeTerminalRecord(record: ControlRecord): void { @@ -542,7 +492,7 @@ export class SubagentControlRegistryV2 { private evictOldestTerminalRecord(): void { const candidate = [...this.records.entries()] - .filter(([, record]) => TERMINAL_STATES.has(record.snapshot.state)) + .filter(([, record]) => isSubagentRunStateTerminal(record.snapshot.state)) .sort( ([leftId, left], [rightId, right]) => left.snapshot.updatedAt - right.snapshot.updatedAt || @@ -552,7 +502,7 @@ export class SubagentControlRegistryV2 { } private pumpSteering(record: ControlRecord): void { - if (record.steeringActive || TERMINAL_STATES.has(record.snapshot.state)) return; + if (record.steeringActive || isSubagentRunStateTerminal(record.snapshot.state)) return; const work = record.steering.shift(); if (!work || !record.steer) return; record.steeringActive = true; @@ -576,7 +526,7 @@ export class SubagentControlRegistryV2 { aborted, ]) .then(() => { - if (TERMINAL_STATES.has(record.snapshot.state) || signal.aborted) { + if (isSubagentRunStateTerminal(record.snapshot.state) || signal.aborted) { throw new Error("The subagent ended before steering was accepted."); } work.resolve(cloneSnapshot(record.snapshot)); diff --git a/main/services/subagents/subagent-run-store-core.ts b/main/services/subagents/subagent-run-store-core.ts index 14e5352273..a7aa2049a8 100644 --- a/main/services/subagents/subagent-run-store-core.ts +++ b/main/services/subagents/subagent-run-store-core.ts @@ -4,9 +4,9 @@ import { isDeepStrictEqual, TextDecoder } from "node:util"; import { isSafeSubagentIdentifier, parseSubagentRunSnapshotV1, + sameSubagentRunSnapshotIdentity, SUBAGENT_ACTIVE_STATES, - SUBAGENT_TERMINAL_STATES, - subagentProjectionNoticesAreMonotonic, + subagentRunSnapshotProgresses, type SubagentRunSnapshotV1, } from "../../../renderer/shared/subagent-runs.js"; import { sanitizeSubagentSnapshotText } from "../../../renderer/shared/subagent-safe-text.js"; @@ -423,7 +423,7 @@ function parseDatabase(value: unknown, maxRuns: number): SubagentRunDatabaseV1 { if (pendingChatDeletionSet.has(run.chatId)) continue; if (conflictedRunIds.has(run.runId)) continue; const existing = byRunId.get(run.runId); - if (existing && !hasStableIdentity(existing, run)) { + if (existing && !sameSubagentRunSnapshotIdentity(existing, run)) { // A duplicate durable ID with a different immutable owner is // ambiguous untrusted state. Preserve neither claimant. byRunId.delete(run.runId); @@ -529,49 +529,6 @@ function interruptedSnapshot( } } -function hasStableIdentity(existing: SubagentRunSnapshotV1, next: SubagentRunSnapshotV1): boolean { - return ( - existing.runId === next.runId && - existing.groupId === next.groupId && - existing.generationId === next.generationId && - existing.childId === next.childId && - existing.chatId === next.chatId && - existing.workspaceId === next.workspaceId && - existing.role === next.role && - existing.label === next.label && - existing.taskPreview === next.taskPreview && - existing.startedAt === next.startedAt && - existing.modelId === next.modelId && - existing.providerId === next.providerId && - existing.thinkingLevel === next.thinkingLevel && - existing.modelSelection === next.modelSelection - ); -} - -function isValidProgression(existing: SubagentRunSnapshotV1, next: SubagentRunSnapshotV1): boolean { - const existingMilestones = existing.milestones ?? []; - const nextMilestones = next.milestones ?? []; - if ( - SUBAGENT_ACTIVE_STATES.has(existing.state) === false || - next.updatedAt < existing.updatedAt || - next.turns < existing.turns || - next.tools < existing.tools || - next.tokens < existing.tokens || - nextMilestones.length < existingMilestones.length || - existingMilestones.some((milestone, index) => nextMilestones[index] !== milestone) || - !subagentProjectionNoticesAreMonotonic( - existing.projectionNotices, - next.projectionNotices, - SUBAGENT_TERMINAL_STATES.has(next.state), - ) - ) { - return false; - } - if (existing.state === "queued") return true; - if (existing.state === "starting") return next.state !== "queued"; - return next.state !== "queued" && next.state !== "starting"; -} - /** * Private, renderer-safe child-run persistence. The resolver is injectable so * tests never import Electron and production can resolve `userData` lazily. @@ -820,7 +777,7 @@ export function createSubagentRunStore( throw new Error("Subagent history is no longer available for this chat."); } const existing = database.runs.find((run) => run.runId === snapshot.runId); - if (existing && !hasStableIdentity(existing, snapshot)) { + if (existing && !sameSubagentRunSnapshotIdentity(existing, snapshot)) { throw new Error("Subagent run identity cannot change."); } if (existing && snapshot.revision <= existing.revision) { @@ -828,7 +785,7 @@ export function createSubagentRunStore( return structuredClone(existing); throw new Error("Subagent run revisions must increase monotonically."); } - if (existing && !isValidProgression(existing, snapshot)) { + if (existing && !subagentRunSnapshotProgresses(existing, snapshot)) { throw new Error("Subagent run lifecycle cannot move backward."); } const next = retainedRuns( diff --git a/main/services/subagents/subagent-run-store-v2-core.ts b/main/services/subagents/subagent-run-store-v2-core.ts index 39f6e10d52..adcae30274 100644 --- a/main/services/subagents/subagent-run-store-v2-core.ts +++ b/main/services/subagents/subagent-run-store-v2-core.ts @@ -3,9 +3,10 @@ import { isDeepStrictEqual, TextDecoder } from "node:util"; import { isSafeSubagentIdentifier, parseSubagentRunSnapshotV2, - subagentProjectionNoticesAreMonotonic, + sameSubagentRunSnapshotIdentity, + SUBAGENT_V2_ACTIVE_STATES, + subagentRunSnapshotProgresses, type SubagentRunSnapshotV2, - type SubagentRunStateV2, } from "../../../renderer/shared/subagent-runs.js"; import { createSubagentAuthorityV2, @@ -57,12 +58,6 @@ const STORE_VERSION = 2 as const; const MIGRATION_ADAPTER_VERSION = 1 as const; const MAX_NATIVE_GENERATION_CONFLICT_RETRIES = 1; const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]); -const ACTIVE_STATES = new Set([ - "queued", - "starting", - "running", - "needs_attention", -]); const STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); export interface NativeSubagentPrivateRunManifestV2 { @@ -472,61 +467,12 @@ function parseDurableContents(contents: Buffer): MutableSubagentRunDatabaseV2 { return database; } -function stableIdentity(left: SubagentRunSnapshotV2, right: SubagentRunSnapshotV2): boolean { - return ( - left.runId === right.runId && - left.groupId === right.groupId && - left.generationId === right.generationId && - left.childId === right.childId && - left.chatId === right.chatId && - left.workspaceId === right.workspaceId && - left.role === right.role && - left.label === right.label && - left.taskPreview === right.taskPreview && - left.startedAt === right.startedAt && - left.modelId === right.modelId && - left.providerId === right.providerId && - left.thinkingLevel === right.thinkingLevel && - left.modelSelection === right.modelSelection && - left.parentRunId === right.parentRunId && - left.retryOfRunId === right.retryOfRunId && - left.depth === right.depth && - left.execution === right.execution && - left.context === right.context && - left.authorityRevision === right.authorityRevision - ); -} - -function validProgression(existing: SubagentRunSnapshotV2, next: SubagentRunSnapshotV2): boolean { - const existingMilestones = existing.milestones ?? []; - const nextMilestones = next.milestones ?? []; - if ( - !ACTIVE_STATES.has(existing.state) || - next.updatedAt < existing.updatedAt || - next.turns < existing.turns || - next.tools < existing.tools || - next.tokens < existing.tokens || - nextMilestones.length < existingMilestones.length || - existingMilestones.some((milestone, index) => nextMilestones[index] !== milestone) || - !subagentProjectionNoticesAreMonotonic( - existing.projectionNotices, - next.projectionNotices, - !ACTIVE_STATES.has(next.state), - ) - ) { - return false; - } - if (existing.state === "queued") return true; - if (existing.state === "starting") return next.state !== "queued"; - return next.state !== "queued" && next.state !== "starting"; -} - function newestFirst(values: readonly SubagentRunSnapshotV2[]): SubagentRunSnapshotV2[] { return [...values].sort((left, right) => right.updatedAt - left.updatedAt || right.revision - left.revision || left.runId.localeCompare(right.runId)); } function interrupt(snapshot: SubagentRunSnapshotV2, now: number): SubagentRunSnapshotV2 { - if (!ACTIVE_STATES.has(snapshot.state)) return snapshot; + if (!SUBAGENT_V2_ACTIVE_STATES.has(snapshot.state)) return snapshot; if (snapshot.revision >= Number.MAX_SAFE_INTEGER) { throw new Error("Active subagent V2 evidence cannot be reconciled losslessly."); } @@ -827,9 +773,9 @@ export function createSubagentRunStoreV2( if ( !existingSnapshot || !existingManifest || - !stableIdentity(existingSnapshot, run.snapshot) || + !sameSubagentRunSnapshotIdentity(existingSnapshot, run.snapshot) || !isDeepStrictEqual(existingManifest, manifest) || - !validProgression(existingSnapshot, run.snapshot) + !subagentRunSnapshotProgresses(existingSnapshot, run.snapshot) ) { throw new Error("Background lifecycle identity or progression changed."); } @@ -952,14 +898,14 @@ export function createSubagentRunStoreV2( if (existingIndex >= 0) { const existing = database.snapshots[existingIndex]!; const existingManifest = database.manifests.find(({ runId }) => runId === snapshot.runId)!; - if (!stableIdentity(existing, snapshot) || !isDeepStrictEqual(existingManifest, manifest)) { + if (!sameSubagentRunSnapshotIdentity(existing, snapshot) || !isDeepStrictEqual(existingManifest, manifest)) { throw new Error("Subagent V2 run identity or authority cannot change."); } if (snapshot.revision <= existing.revision) { if (isDeepStrictEqual(snapshot, existing)) return undefined; throw new Error("Subagent V2 run revisions must increase monotonically."); } - if (!validProgression(existing, snapshot)) throw new Error("Subagent V2 lifecycle cannot move backward."); + if (!subagentRunSnapshotProgresses(existing, snapshot)) throw new Error("Subagent V2 lifecycle cannot move backward."); } else if ( database.snapshots.length + runReservations.size - diff --git a/renderer/shared/subagent-runs-v2.test.ts b/renderer/shared/subagent-runs-v2.test.ts index 95ffe61fbb..e92e97c0b2 100644 --- a/renderer/shared/subagent-runs-v2.test.ts +++ b/renderer/shared/subagent-runs-v2.test.ts @@ -3,16 +3,20 @@ import test from "node:test"; import { adaptSubagentRunSnapshotV1ToV2, adaptSubagentRunSnapshotV2ToV1, + isSubagentRunStateTerminal, MAX_SUBAGENT_ACTIVITY_CHARS, SUBAGENT_NEEDS_ATTENTION_FALLBACK_ACTIVITY, subagentPendingQuestion, subagentPendingQuestionActivity, + subagentRunSnapshotUpdateIsMonotonic, + subagentRunStateProgresses, parseSubagentHistoryDetailV1, parseSubagentRunSnapshot, parseSubagentRunSnapshotV1, parseSubagentRunSnapshotV2, type SubagentRunSnapshotV1, type SubagentRunSnapshotV2, + type SubagentRunStateV2, } from "./subagent-runs.js"; function v1(state: SubagentRunSnapshotV1["state"] = "completed"): SubagentRunSnapshotV1 { @@ -286,3 +290,152 @@ test("pending questions redact control-split credentials before flattening", () assert.ok(parseSubagentRunSnapshotV2({ ...v2("needs_attention"), activity })); } }); + +test("subagentRunStateProgresses enforces the exhaustive transition matrix for allowStopped true and false", () => { + const allStates: readonly SubagentRunStateV2[] = [ + "queued", + "starting", + "running", + "needs_attention", + "completed", + "failed", + "timed_out", + "interrupted", + "stopped", + "unknown", + ]; + + // Explicit oracle table of allowed target states per source state (with allowStopped: true). + const expectedAllowStoppedTrue: Record> = { + queued: new Set([ + "queued", + "starting", + "running", + "needs_attention", + "completed", + "failed", + "timed_out", + "interrupted", + "stopped", + "unknown", + ]), + starting: new Set([ + "starting", + "running", + "needs_attention", + "completed", + "failed", + "timed_out", + "interrupted", + "stopped", + "unknown", + ]), + running: new Set([ + "running", + "needs_attention", + "completed", + "failed", + "timed_out", + "interrupted", + "stopped", + "unknown", + ]), + needs_attention: new Set([ + "running", + "needs_attention", + "completed", + "failed", + "timed_out", + "interrupted", + "stopped", + "unknown", + ]), + completed: new Set(), + failed: new Set(), + timed_out: new Set(), + interrupted: new Set(), + stopped: new Set(), + unknown: new Set(), + }; + + for (const current of allStates) { + assert.equal( + isSubagentRunStateTerminal(current), + expectedAllowStoppedTrue[current].size === 0, + `terminal classification for ${current}`, + ); + for (const next of allStates) { + const allowedWithStopped = expectedAllowStoppedTrue[current].has(next); + assert.equal( + subagentRunStateProgresses(current, next), + allowedWithStopped, + `default progression ${current} -> ${next}`, + ); + assert.equal( + subagentRunStateProgresses(current, next, { allowStopped: true }), + allowedWithStopped, + `allowStopped:true progression ${current} -> ${next}`, + ); + assert.equal( + subagentRunStateProgresses(current, next, { allowStopped: false }), + allowedWithStopped && next !== "stopped", + `allowStopped:false progression ${current} -> ${next}`, + ); + } + } + + // Unrecognized states at runtime are rejected rather than falling through. + assert.equal( + subagentRunStateProgresses("bogus" as SubagentRunStateV2, "running"), + false, + ); + assert.equal( + subagentRunStateProgresses("queued", "bogus" as SubagentRunStateV2), + false, + ); +}); + +test("subagentRunSnapshotUpdateIsMonotonic enforces state, identity, and exact-replay rules", () => { + const queued = v2("queued"); + const running: SubagentRunSnapshotV2 = { + ...v2("running"), + revision: 2, + updatedAt: 2_500, + turns: 3, + tools: 4, + tokens: 150, + milestones: ["reading"], + }; + const attention: SubagentRunSnapshotV2 = { + ...v2("needs_attention"), + revision: 3, + updatedAt: 2_600, + turns: 3, + tools: 4, + tokens: 150, + milestones: ["reading"], + }; + const stopped: SubagentRunSnapshotV2 = { + ...v2("stopped"), + revision: 4, + updatedAt: 2_700, + finishedAt: 2_700, + turns: 3, + tools: 4, + tokens: 150, + milestones: ["reading"], + }; + + assert.equal(subagentRunSnapshotUpdateIsMonotonic(queued, running), true); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(running, attention), true); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(attention, { ...running, revision: 4, updatedAt: 2_650 }), true); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(attention, stopped), true); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(stopped, { ...running, revision: 5, updatedAt: 2_800 }), false); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(running, { ...queued, revision: 3, updatedAt: 2_600 }), false); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(running, running), false); + assert.equal(subagentRunSnapshotUpdateIsMonotonic(running, running, { allowExactReplay: true }), true); + assert.equal( + subagentRunSnapshotUpdateIsMonotonic(queued, { ...running, label: "Renamed" }), + false, + ); +}); diff --git a/renderer/shared/subagent-runs.ts b/renderer/shared/subagent-runs.ts index b9b540d124..41db8b6256 100644 --- a/renderer/shared/subagent-runs.ts +++ b/renderer/shared/subagent-runs.ts @@ -635,12 +635,19 @@ const V2_OPTIONAL_SNAPSHOT_KEYS = new Set([ "parentRunId", "retryOfRunId", ]); -const V2_STATES = new Set([ - ...RUN_STATES, +export const SUBAGENT_V2_ACTIVE_STATES: ReadonlySet = new Set([ + ...SUBAGENT_ACTIVE_STATES, "needs_attention", +]); +export const SUBAGENT_V2_TERMINAL_STATES: ReadonlySet = new Set([ + ...SUBAGENT_TERMINAL_STATES, "stopped", "unknown", ]); +const V2_STATES = new Set([ + ...SUBAGENT_V2_ACTIVE_STATES, + ...SUBAGENT_V2_TERMINAL_STATES, +]); const V2_EXECUTION_MODES = new Set(["foreground", "background"]); const V2_CONTEXT_MODES = new Set(["fresh", "fork"]); @@ -761,22 +768,17 @@ export function parseSubagentRunSnapshot(value: unknown): SubagentRunSnapshot | : undefined; } -function subagentRunSnapshotIsTerminal(snapshot: SubagentRunSnapshot): boolean { - return snapshot.version === 2 - ? snapshot.state === "completed" || - snapshot.state === "failed" || - snapshot.state === "timed_out" || - snapshot.state === "interrupted" || - snapshot.state === "stopped" || - snapshot.state === "unknown" - : SUBAGENT_TERMINAL_STATES.has(snapshot.state); +export function isSubagentRunStateTerminal( + state: SubagentRunState | SubagentRunStateV2, +): boolean { + return SUBAGENT_V2_TERMINAL_STATES.has(state); } function sameOptionalIdentifier(left: string | undefined, right: string | undefined): boolean { return left === right; } -function sameSubagentRunSnapshotIdentity( +export function sameSubagentRunSnapshotIdentity( current: SubagentRunSnapshot, next: SubagentRunSnapshot, ): boolean { @@ -807,14 +809,60 @@ function sameSubagentRunSnapshotIdentity( ); } -function subagentRunStateProgresses( +export interface SubagentRunStateProgressionOptions { + /** + * Whether transitioning into `"stopped"` is accepted on this path. + * Defaults to `true`. `SubagentControlRegistryV2.update` passes `false` + * because stops must go through `SubagentControlRegistryV2.stop` so the + * control plane synchronously revokes approvals and emits its own stopped snapshot. + */ + allowStopped?: boolean; +} + +/** + * Shared pure lifecycle progression fence for V1 and V2 subagent run states. + * Terminal runs never transition again; active runs progress monotonically + * (`queued` -> `starting` -> `running` / `needs_attention` -> terminal). + */ +export function subagentRunStateProgresses( + current: SubagentRunState | SubagentRunStateV2, + next: SubagentRunState | SubagentRunStateV2, + options: SubagentRunStateProgressionOptions = {}, +): boolean { + if (!SUBAGENT_V2_ACTIVE_STATES.has(current) || !V2_STATES.has(next)) return false; + if (options.allowStopped === false && next === "stopped") return false; + if (current === "queued") return true; + if (current === "starting") return next !== "queued"; + return next !== "queued" && next !== "starting"; +} + +/** + * Shared monotonic field and state progression check for parsed snapshots of + * the same version. Callers that distinguish revision regressions from + * lifecycle regressions check `next.revision > current.revision` separately. + */ +export function subagentRunSnapshotProgresses( current: SubagentRunSnapshot, next: SubagentRunSnapshot, + options: SubagentRunStateProgressionOptions = {}, ): boolean { - if (subagentRunSnapshotIsTerminal(current)) return false; - if (current.state === "queued") return true; - if (current.state === "starting") return next.state !== "queued"; - return next.state !== "queued" && next.state !== "starting"; + if (current.version !== next.version) return false; + const currentMilestones = current.milestones ?? []; + const nextMilestones = next.milestones ?? []; + return ( + next.updatedAt >= current.updatedAt && + next.turns >= current.turns && + next.tools >= current.tools && + next.tokens >= current.tokens && + nextMilestones.length >= currentMilestones.length && + currentMilestones.every((milestone, index) => nextMilestones[index] === milestone) && + subagentProjectionNoticesAreMonotonic( + current.projectionNotices, + next.projectionNotices, + isSubagentRunStateTerminal(next.state), + ) && + subagentRunStateProgresses(current.state, next.state, options) + ); } /** @@ -834,23 +882,7 @@ export function subagentRunSnapshotUpdateIsMonotonic( if (next.revision === current.revision) { return options.allowExactReplay === true && JSON.stringify(next) === JSON.stringify(current); } - const currentMilestones = current.milestones ?? []; - const nextMilestones = next.milestones ?? []; - return ( - next.revision > current.revision && - next.updatedAt >= current.updatedAt && - next.turns >= current.turns && - next.tools >= current.tools && - next.tokens >= current.tokens && - nextMilestones.length >= currentMilestones.length && - currentMilestones.every((milestone, index) => nextMilestones[index] === milestone) && - subagentProjectionNoticesAreMonotonic( - current.projectionNotices, - next.projectionNotices, - subagentRunSnapshotIsTerminal(next), - ) && - subagentRunStateProgresses(current, next) - ); + return next.revision > current.revision && subagentRunSnapshotProgresses(current, next); } export const MAX_SUBAGENT_EFFECT_ACTIVITY = 512; From e1295c7f60511493bbbce7be85feb1d3ab47f0ea Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 05:53:45 +0000 Subject: [PATCH 2/2] Fence noticeRound on exact goal revision and tighten keep-awake error assertions --- main/services/goal/goal-loop.test.ts | 70 +++++++++++++++++++ main/services/goal/goal-loop.ts | 21 ++++-- .../keep-awake/keep-awake-core.test.ts | 11 ++- 3 files changed, 97 insertions(+), 5 deletions(-) diff --git a/main/services/goal/goal-loop.test.ts b/main/services/goal/goal-loop.test.ts index 3dc8f0d737..07588ce243 100644 --- a/main/services/goal/goal-loop.test.ts +++ b/main/services/goal/goal-loop.test.ts @@ -47,6 +47,8 @@ function harness(options: { holdStart: undefined as Promise | undefined, /** Holds startNoticeRound open to test races while a notice round starts. */ holdNoticeStart: undefined as Promise | undefined, + /** Overrides fallbackContext for tests that hold or vary context lookup. */ + fallbackContext: undefined as (() => Promise) | undefined, review: (async (goal) => continueWith(`Next step ${goal.rounds}`)) as Review, }; const rounds: Array<{ text: string; notice: AgentNoticeV1 }> = []; @@ -86,6 +88,7 @@ function harness(options: { return state.activity; }, fallbackContext: async () => { + if (state.fallbackContext) return state.fallbackContext(); if (state.throws.context || state.throws.noticeContext) throw new Error("The chat file could not be read."); return CONTEXT; }, @@ -979,3 +982,70 @@ test("a relook that wakes while the chat is still busy waits again, and shutdown await stopping.becomeIdle(); assert.equal(stopping.reviews(), 0); }); + +test("pausing and resuming the same goal while noticeRound awaits fallbackContext fences the stale notice", async () => { + const news = { text: "job ended", notice: agentNotice({ source: "background_job", tone: "success", title: "Done", summary: "x" }) }; + for (const outcome of ["context", "empty", "reject"] as const) { + const h = harness(); + const initial = await h.loop.set(CHAT, { objective: "Ship it", source: "slash" }); + let resolveContext!: (value: typeof CONTEXT | undefined) => void; + let rejectContext!: (reason: Error) => void; + h.state.fallbackContext = () => + new Promise((resolve, reject) => { + resolveContext = resolve; + rejectContext = reject; + }); + + const pending = h.loop.noticeRound(CHAT, news); + await h.flush(); + + // Same-goal pause + resume retains the goal ID and restores active, + // while advancing the revision. + h.loop.pause(CHAT); + h.state.busy = true; + const resumed = await h.loop.resume(CHAT); + assert.equal(resumed?.id, initial.id, outcome); + assert.equal(resumed?.status, "active", outcome); + assert.ok((resumed?.revision ?? 0) > initial.revision, `${outcome}: revision advanced`); + const resumedRevision = resumed!.revision; + + if (outcome === "context") resolveContext(CONTEXT); + else if (outcome === "empty") resolveContext(undefined); + else rejectContext(new Error("The chat file could not be read.")); + + const result = await pending; + assert.equal(result, undefined, `${outcome}: stale notice returns undefined`); + assert.deepEqual(h.noticeRounds, [], `${outcome}: stale notice starts no round`); + assert.equal(h.goal()?.id, initial.id, outcome); + assert.equal(h.goal()?.revision, resumedRevision, `${outcome}: resumed revision untouched`); + assert.equal(h.goal()?.rounds, 1, `${outcome}: stale notice does not count a round`); + assert.equal(h.idleWaitersCount(), 0, `${outcome}: no relook armed on resumed revision`); + await h.becomeIdle(); + assert.equal(h.reviews(), 0, `${outcome}: no review triggered on resumed revision`); + } + + // Capturing the revision fence after dropLook() still lets a current notice + // proceed when dropLook() synchronously restores an uncounted round. + const h = harness(); + await h.loop.set(CHAT, { objective: "Ship it", source: "slash" }); + let releaseStart!: () => void; + h.state.holdStart = new Promise((resolve) => { releaseStart = resolve; }); + h.loop.runSettled({ chatId: CHAT, streamId: "s", stopped: false, failed: false }); + await h.flush(); + assert.equal(h.roundCurrent.length, 1, "the look's round is waiting to start"); + assert.equal(h.goal()?.rounds, 2, "the waiting look counted round 2"); + + let resolveContext!: (value: typeof CONTEXT | undefined) => void; + h.state.fallbackContext = () => new Promise((resolve) => { resolveContext = resolve; }); + const pending = h.loop.noticeRound(CHAT, news); + await h.flush(); + assert.equal(h.goal()?.rounds, 1, "dropLook restored the uncounted round before fallbackContext"); + resolveContext(CONTEXT); + const started = await pending; + releaseStart(); + await h.flush(); + assert.equal(started?.kind, "started", "the current notice still starts after dropLook uncounted"); + assert.deepEqual(h.noticeRounds, ["job ended"]); + assert.equal(h.rounds.length, 0, "the dropped look's round never started"); + assert.equal(h.goal()?.rounds, 2); +}); diff --git a/main/services/goal/goal-loop.ts b/main/services/goal/goal-loop.ts index 00d309c0af..4e94898e64 100644 --- a/main/services/goal/goal-loop.ts +++ b/main/services/goal/goal-loop.ts @@ -300,19 +300,32 @@ export class GoalLoop { // The news is newer than what a look under way read: its review is // dropped (its verdict would be stale) and this round's settling is looked at. this.dropLook(chatId); + // Capture the exact revision after dropLook(), which may synchronously + // restore an uncounted round, so a same-goal pause/resume across the await + // cannot look active under a stale notice. + const fenced = this.goals.get(chatId); + if (this.stopped || fenced?.id !== before.id || fenced.status !== "active") return undefined; + const expected: GoalRef = { id: fenced.id, revision: fenced.revision }; + const currentIfFenced = (): GoalRecordV1 | undefined => { + if (this.stopped) return undefined; + const current = this.goals.get(chatId); + if (current?.id !== expected.id || current.revision !== expected.revision || current.status !== "active") { + return undefined; + } + return current; + }; let context: OwedTurnContext | undefined; try { context = this.contexts.get(chatId) ?? (await this.deps.fallbackContext(chatId)); } catch (error) { // The notice is still saved, as one no round could answer. this.deps.log("A keep-going notice round could not read the chat.", error); - const current = this.goals.get(chatId); - if (current?.id !== before.id || current.status !== "active") return undefined; + if (!currentIfFenced()) return undefined; this.relookAfterNotice(chatId); return { kind: "unavailable", reason: "The round could not start." }; } - const latest = this.goals.get(chatId); - if (latest?.id !== before.id || latest.status !== "active") return undefined; + const latest = currentIfFenced(); + if (!latest) return undefined; if (!context) { this.relookAfterNotice(chatId); return { kind: "unavailable", reason: "The chat has no model yet." }; diff --git a/main/services/keep-awake/keep-awake-core.test.ts b/main/services/keep-awake/keep-awake-core.test.ts index 37a46093e2..490f29c154 100644 --- a/main/services/keep-awake/keep-awake-core.test.ts +++ b/main/services/keep-awake/keep-awake-core.test.ts @@ -349,7 +349,11 @@ test("blocker, idleSeconds, and onStatus errors are isolated via onError without let reasons: KeepAwakeReason[] = [chat("a")]; controller.addInput({ read: () => ({ reasons }) }); assert.equal(controller.status().holding, false, "failed start leaves holding false"); - assert.ok(errors.length >= 2, "idleSeconds, start, and onStatus errors reported"); + assert.deepEqual( + errors.map((error) => (error instanceof Error ? error.message : String(error))), + ["idle failed", "start failed", "status failed"], + "idleSeconds, start, and onStatus errors are each reported", + ); // Non-finite idleSeconds falls back to 0 rather than triggering the idle cap. failStart = false; @@ -366,5 +370,10 @@ test("blocker, idleSeconds, and onStatus errors are isolated via onError without controller.setEnabled(false); assert.equal(controller.status().holding, false); assert.equal(active.size, 0); + assert.deepEqual( + errors.map((error) => (error instanceof Error ? error.message : String(error))), + ["idle failed", "start failed", "status failed", "stop failed"], + "stop error is also reported", + ); controller.dispose(); });