@@ -58,6 +58,7 @@ type GatewayRequest = {
5858
5959let lifecycleHandler : ( ( evt : LifecycleEvent ) => void ) | undefined ;
6060let agentCallPlan : Array < "ok" | "throw" > = [ ] ;
61+ let agentCallGates = new Map < string , Promise < void > > ( ) ;
6162let chatHistoryBySessionKey = new Map < string , Array < Record < string , unknown > > > ( ) ;
6263let sessionStore : Record < string , SessionStoreEntry > = { } ;
6364
@@ -75,6 +76,11 @@ const callGatewayMock = vi.fn(async (request: GatewayRequest) => {
7576 } ;
7677 }
7778 if ( method === "agent" ) {
79+ const sourceSessionKey = request . params ?. inputProvenance ?. sourceSessionKey ;
80+ const gate = sourceSessionKey ? agentCallGates . get ( sourceSessionKey ) : undefined ;
81+ if ( gate ) {
82+ await gate ;
83+ }
7884 const next = agentCallPlan . shift ( ) ?? "ok" ;
7985 if ( next === "throw" ) {
8086 throw new Error ( "announce delivery failed" ) ;
@@ -118,6 +124,20 @@ vi.mock("./subagent-depth.js", () => ({
118124 getSubagentDepthFromSessionStore : ( ) => 0 ,
119125} ) ) ;
120126
127+ const loadSubagentRegistryRuntimeForTest = async ( ) =>
128+ ( {
129+ countActiveDescendantRuns : mod . countActiveDescendantRuns ,
130+ countPendingDescendantRuns : mod . countPendingDescendantRuns ,
131+ countPendingDescendantRunsExcludingRun : mod . countPendingDescendantRunsExcludingRun ,
132+ hasDescendantRunAwaitingSettle : announceRead . hasDescendantRunAwaitingSettle ,
133+ getLatestSubagentRunByChildSessionKey : mod . getLatestSubagentRunByChildSessionKey ,
134+ isSubagentSessionRunActive : mod . isSubagentSessionRunActive ,
135+ listSubagentRunsForRequester : mod . listSubagentRunsForRequester ,
136+ replaceSubagentRunAfterSteer : mod . replaceSubagentRunAfterSteer ,
137+ resolveRequesterForChildSession : mod . resolveRequesterForChildSession ,
138+ shouldIgnorePostCompletionAnnounceForSession : mod . shouldIgnorePostCompletionAnnounceForSession ,
139+ } ) as unknown as typeof import ( "./subagent-registry-runtime.js" ) ;
140+
121141describe ( "subagent registry lifecycle error grace" , ( ) => {
122142 let previousFastTestEnv : string | undefined ;
123143
@@ -132,6 +152,7 @@ describe("subagent registry lifecycle error grace", () => {
132152 session : { mainKey : "main" , scope : "per-sender" } ,
133153 } ) ;
134154 agentCallPlan = [ ] ;
155+ agentCallGates = new Map ( ) ;
135156 chatHistoryBySessionKey = new Map ( ) ;
136157 sessionStore = new Proxy < Record < string , SessionStoreEntry > > (
137158 {
@@ -163,20 +184,6 @@ describe("subagent registry lifecycle error grace", () => {
163184 onAgentEvent :
164185 onAgentEventMock as unknown as typeof import ( "../infra/agent-events.js" ) . onAgentEvent ,
165186 } ) ;
166- const loadSubagentRegistryRuntimeForTest = async ( ) =>
167- ( {
168- countActiveDescendantRuns : mod . countActiveDescendantRuns ,
169- countPendingDescendantRuns : mod . countPendingDescendantRuns ,
170- countPendingDescendantRunsExcludingRun : mod . countPendingDescendantRunsExcludingRun ,
171- hasDescendantRunAwaitingSettle : announceRead . hasDescendantRunAwaitingSettle ,
172- getLatestSubagentRunByChildSessionKey : mod . getLatestSubagentRunByChildSessionKey ,
173- isSubagentSessionRunActive : mod . isSubagentSessionRunActive ,
174- listSubagentRunsForRequester : mod . listSubagentRunsForRequester ,
175- replaceSubagentRunAfterSteer : mod . replaceSubagentRunAfterSteer ,
176- resolveRequesterForChildSession : mod . resolveRequesterForChildSession ,
177- shouldIgnorePostCompletionAnnounceForSession :
178- mod . shouldIgnorePostCompletionAnnounceForSession ,
179- } ) as unknown as typeof import ( "./subagent-registry-runtime.js" ) ;
180187 subagentAnnounceTesting . setDepsForTest ( {
181188 callGateway : callGatewayMock as typeof import ( "../gateway/call.js" ) . callGateway ,
182189 getRuntimeConfig : loadConfigMock as typeof import ( "../config/config.js" ) . getRuntimeConfig ,
@@ -294,9 +301,15 @@ describe("subagent registry lifecycle error grace", () => {
294301 throw new Error ( `run ${ runId } frozen result did not refresh` ) ;
295302 } ;
296303
297- function registerCompletionRun ( runId : string , childSuffix : string , task : string ) {
304+ function registerCompletionRun (
305+ runId : string ,
306+ childSuffix : string ,
307+ task : string ,
308+ requesterTurnRunId ?: string ,
309+ ) {
298310 mod . registerSubagentRun ( {
299311 runId,
312+ requesterTurnRunId,
300313 childSessionKey : `agent:main:subagent:${ childSuffix } ` ,
301314 requesterSessionKey : MAIN_REQUESTER_SESSION_KEY ,
302315 requesterDisplayKey : MAIN_REQUESTER_DISPLAY_KEY ,
@@ -370,6 +383,131 @@ describe("subagent registry lifecycle error grace", () => {
370383 } ) ;
371384 }
372385
386+ it ( "lets the delivered cleanup own a yielded batch after a stale wake loses generation" , async ( ) => {
387+ const requesterTurnRunId = "run-requester-yield-race" ;
388+ const alphaSessionKey = "agent:main:subagent:yield-alpha" ;
389+ const betaSessionKey = "agent:main:subagent:yield-beta" ;
390+ registerCompletionRun ( "run-yield-alpha" , "yield-alpha" , "yield alpha" , requesterTurnRunId ) ;
391+ registerCompletionRun ( "run-yield-beta" , "yield-beta" , "yield beta" , requesterTurnRunId ) ;
392+ setAssistantOutput ( alphaSessionKey , "alpha complete" ) ;
393+ setAssistantOutput ( betaSessionKey , "beta complete" ) ;
394+
395+ let releaseAlphaWakeRuntime : ( ( ) => void ) | undefined ;
396+ const alphaWakeRuntimeGate = new Promise < void > ( ( resolve ) => {
397+ releaseAlphaWakeRuntime = resolve ;
398+ } ) ;
399+ let settleWakeRuntimeLoads = 0 ;
400+ settleWakeTesting . setDepsForTest ( {
401+ loadSubagentRegistryRuntime : async ( ) => {
402+ settleWakeRuntimeLoads += 1 ;
403+ if ( settleWakeRuntimeLoads === 1 ) {
404+ await alphaWakeRuntimeGate ;
405+ }
406+ return await loadSubagentRegistryRuntimeForTest ( ) ;
407+ } ,
408+ } ) ;
409+
410+ let releaseBetaDelivery : ( ( ) => void ) | undefined ;
411+ agentCallGates . set (
412+ betaSessionKey ,
413+ new Promise < void > ( ( resolve ) => {
414+ releaseBetaDelivery = resolve ;
415+ } ) ,
416+ ) ;
417+
418+ emitLifecycleEvent ( "run-yield-alpha" , { phase : "end" , endedAt : Date . now ( ) } ) ;
419+ await waitForAgentCallCount ( 1 ) ;
420+ await vi . waitFor ( ( ) => expect ( settleWakeRuntimeLoads ) . toBe ( 1 ) ) ;
421+
422+ emitLifecycleEvent ( "run-yield-beta" , { phase : "end" , endedAt : Date . now ( ) + 1 } ) ;
423+ await waitForAgentCallCount ( 2 ) ;
424+ const betaBeforeYield = mod
425+ . listSubagentRunsForRequester ( MAIN_REQUESTER_SESSION_KEY )
426+ . find ( ( run ) => run . runId === "run-yield-beta" ) ;
427+ if ( ! betaBeforeYield ) {
428+ throw new Error ( "expected beta run before requester yield" ) ;
429+ }
430+ betaBeforeYield . delivery = { ...betaBeforeYield . delivery , status : "in_progress" } ;
431+
432+ expect (
433+ mod . markRequesterTurnYielded ( {
434+ requesterSessionKey : MAIN_REQUESTER_SESSION_KEY ,
435+ requesterTurnRunId,
436+ } ) ,
437+ ) . toBe ( 2 ) ;
438+ expect (
439+ mod . settleRequesterAfterSessionSpawns ( {
440+ requesterSessionKey : MAIN_REQUESTER_SESSION_KEY ,
441+ requesterTurnRunId,
442+ requesterYielded : true ,
443+ acceptedSessionSpawns : [
444+ { runId : "run-yield-alpha" , childSessionKey : alphaSessionKey } ,
445+ { runId : "run-yield-beta" , childSessionKey : betaSessionKey } ,
446+ ] ,
447+ } ) ,
448+ ) . toBe ( true ) ;
449+
450+ releaseAlphaWakeRuntime ?.( ) ;
451+ await vi . advanceTimersByTimeAsync ( 0 ) ;
452+ await flushAsync ( ) ;
453+
454+ const yieldedBatch = mod . listSubagentRunsForRequester ( MAIN_REQUESTER_SESSION_KEY ) ;
455+ expect (
456+ yieldedBatch . map ( ( run ) => ( {
457+ runId : run . runId ,
458+ delivery : run . delivery ?. status ,
459+ nextAttemptAt : run . requesterSettleWake ?. nextAttemptAt ,
460+ rearmGeneration : run . requesterSettleWake ?. rearmGeneration ,
461+ } ) ) ,
462+ ) . toEqual ( [
463+ {
464+ runId : "run-yield-alpha" ,
465+ delivery : "delivered" ,
466+ nextAttemptAt : undefined ,
467+ rearmGeneration : 1 ,
468+ } ,
469+ {
470+ runId : "run-yield-beta" ,
471+ delivery : "in_progress" ,
472+ nextAttemptAt : undefined ,
473+ rearmGeneration : 1 ,
474+ } ,
475+ ] ) ;
476+ const requesterWakeCalls = ( ) =>
477+ getAgentCalls ( ) . filter ( ( request ) => {
478+ const idempotencyKey = ( request . params as Record < string , unknown > | undefined )
479+ ?. idempotencyKey ;
480+ return (
481+ typeof idempotencyKey === "string" &&
482+ idempotencyKey . startsWith ( "announce:requester-settle:" )
483+ ) ;
484+ } ) ;
485+ expect ( requesterWakeCalls ( ) ) . toHaveLength ( 0 ) ;
486+
487+ agentCallGates . delete ( betaSessionKey ) ;
488+ releaseBetaDelivery ?.( ) ;
489+ await waitForAgentCallCount ( 3 ) ;
490+ await waitForDeliveredCleanup ( "run-yield-alpha" ) ;
491+ await waitForDeliveredCleanup ( "run-yield-beta" ) ;
492+
493+ expect ( requesterWakeCalls ( ) ) . toHaveLength ( 1 ) ;
494+ const requesterWakeParams = requesterWakeCalls ( ) [ 0 ] ?. params as
495+ | Record < string , unknown >
496+ | undefined ;
497+ expect ( requesterWakeParams ?. idempotencyKey ) . toContain ( ":yield-1" ) ;
498+ expect ( requesterWakeParams ?. message ) . toContain ( "visible final answer" ) ;
499+ expect (
500+ mod
501+ . listSubagentRunsForRequester ( MAIN_REQUESTER_SESSION_KEY )
502+ . filter ( ( run ) => run . runId === "run-yield-alpha" || run . runId === "run-yield-beta" )
503+ . every ( ( run ) => run . requesterSettleWake === undefined ) ,
504+ ) . toBe ( true ) ;
505+
506+ await vi . advanceTimersByTimeAsync ( 30_000 ) ;
507+ await flushAsync ( ) ;
508+ expect ( requesterWakeCalls ( ) ) . toHaveLength ( 1 ) ;
509+ } ) ;
510+
373511 it ( "ignores transient lifecycle errors when run retries and then ends successfully" , async ( ) => {
374512 registerCompletionRun ( "run-transient-error" , "transient-error" , "transient error test" ) ;
375513 setAssistantOutput ( "agent:main:subagent:transient-error" , "Final answer transient" ) ;
0 commit comments