diff --git a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts index 433a219e62..56c5e4df87 100644 --- a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts +++ b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts @@ -702,6 +702,30 @@ describe("a child that ends its turn while it is still working", () => { expect(state.delivery.prompts[2]).toContain("Helper final"); }); + test("a followed helper settles when its last delegation ends without reporting to it", async () => { + const state = await scenario(); + await state.service.register({ callerAgentId: "parent", childAgentId: "helper" }); + await state.service.register({ + callerAgentId: "helper", + childAgentId: "sub", + requireParentOwnership: true, + }); + await until(() => state.observation.waits.length === 2); + const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!; + + wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper")); + await until(() => state.delivery.prompts.length === 1); + expect(state.delivery.prompts[0]).toContain("ended its turn but is still working"); + state.delivery.acknowledgments[0]!.resolve("steered"); + + // The sub was detached from the helper, so its result is not reported to the helper. + wait("sub").result.resolve(outcome("idle", "sub", "Sub result")); + await until(() => state.delivery.prompts.length === 2); + expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished."); + expect(state.delivery.prompts[1]).toContain("Waiting for my helper"); + expect(state.delivery.prompts[1]).not.toContain("Sub result"); + }); + test("agents that only wait on each other settle and both callers hear finished", async () => { const state = await scenario(); await state.service.register({ callerAgentId: "parent", childAgentId: "helper" }); diff --git a/packages/server/src/server/agent/finish-subscriptions/index.ts b/packages/server/src/server/agent/finish-subscriptions/index.ts index 697111b63c..35df189ecc 100644 --- a/packages/server/src/server/agent/finish-subscriptions/index.ts +++ b/packages/server/src/server/agent/finish-subscriptions/index.ts @@ -85,6 +85,8 @@ interface Watch { decide(accepted: boolean): void; pending: boolean; task?: Promise; + /** Decides a followed child's state again; see `createFollowing`. */ + recheck?(): void; } function key(record: FinishSubscription): string { return JSON.stringify([record.callerAgentId, record.childAgentId, record.serverId]); @@ -131,6 +133,18 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio if (!group.size && watches.get(key(watch.records[0]!)) === group) watches.delete(key(watch.records[0]!)); } + /** + * A watch that ends without telling its caller leaves that caller's own watchers with no event: + * the caller may have no work left now. + */ + function recheckCallerOf(watch: Watch): void { + const { callerAgentId } = watch.records[0]!; + for (const group of watches.values()) + for (const watcher of group) { + const record = watcher.records[0]!; + if (record.childAgentId === callerAgentId && !record.serverId) watcher.recheck?.(); + } + } async function remove(watch: Watch): Promise { // Only IDs captured by this observer are eligible; newer registrations survive. for (const record of watch.records) await deps.store.remove(record.id); @@ -287,6 +301,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio pendingWork: () => pendingWork(record), reasonFor, }); + watch.recheck = following.recheck; const permissions = new Set(); let observation: FinishObservationSession | undefined; /** One outcome and how far it got. Retries resume it: nothing is lost or sent twice. */ @@ -319,9 +334,10 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio }; } } - async function end(): Promise { + async function end(notified: boolean): Promise { await remove(watch); stop(watch, group); + if (!notified) recheckCallerOf(watch); return true; } async function decide(outcome: FollowOutcome): Promise { @@ -336,7 +352,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio } /** Handles one outcome. Returns true once the subscription has ended. */ async function step(): Promise { - if (await suppressed(record)) return end(); + if (await suppressed(record)) return end(false); if (!current) { const outcome = await observeNext(); if (!outcome) { @@ -348,7 +364,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio signal.throwIfAborted(); if (!current.decided) { const notice = await decide(current.outcome); - if (notice === "suppressed") return end(); + if (notice === "suppressed") return end(false); current = { ...current, decided: true, notice }; } const { notice } = current; @@ -358,7 +374,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio current.sent = true; } // A removal failure retries only the commit, never the already accepted callback. - if (notice && endsSubscription(notice.reason)) return end(); + if (notice && endsSubscription(notice.reason)) return end(true); current = undefined; retries = 0; warned = false; diff --git a/packages/server/src/server/agent/finish-subscriptions/internal/following.ts b/packages/server/src/server/agent/finish-subscriptions/internal/following.ts index eb5cc5ff74..ffa423bda5 100644 --- a/packages/server/src/server/agent/finish-subscriptions/internal/following.ts +++ b/packages/server/src/server/agent/finish-subscriptions/internal/following.ts @@ -36,6 +36,16 @@ export function createFollowing(options: Options) { .filter((value) => value !== undefined) .sort()[0]; let latest: FinishObservationResult | null = null; + /** Set when something outside the child's own events may have settled it. */ + let stale = false; + let wake: (() => void) | undefined; + + /** The child's last idle outcome, decided again. Nothing while it waits on a permission. */ + function recheckOutcome(): FinishObservationResult | undefined { + stale = false; + if (latest?.status !== "idle") return undefined; + return { ...latest, workChanged: true }; + } async function follow(): Promise { const followingSince = new Date().toISOString(); @@ -50,6 +60,8 @@ export function createFollowing(options: Options) { if (!since) return observed; // The losing side settles when the observation closes. observed.catch(() => undefined); + const rechecked = stale && recheckOutcome(); + if (rechecked) return rechecked; const timer = new AbortController(); const limit = pause( Math.max(0, Date.parse(since) + options.limitMs - Date.now()), @@ -57,12 +69,28 @@ export function createFollowing(options: Options) { { signal: AbortSignal.any([signal, timer.signal]) }, ); limit.catch(() => undefined); + const recheck = new Promise((resolve) => { + wake = () => { + const outcome = recheckOutcome(); + if (outcome) resolve(outcome); + }; + }); try { - return await Promise.race([observed, limit]); + return await Promise.race([observed, limit, recheck]); } finally { + wake = undefined; timer.abort(); } }, + /** + * Decides the child's state again without an event from it, as when a delegation of its + * own ended without reporting back. Only a followed child is decided again. + */ + recheck() { + if (!since) return; + stale = true; + wake?.(); + }, /** Returns nothing when the outcome is not worth telling the caller. */ async decide(outcome: FollowOutcome): Promise { if (outcome === FOLLOW_LIMIT)