11import path from "node:path" ;
22import { afterEach , describe , expect , it , vi } from "vitest" ;
3+ import { createDeferred } from "../../../test/helpers/promise.js" ;
34import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js" ;
5+ import { transitionMainSessionRecovery } from "../../agents/main-session-recovery/main-session-recovery-state.js" ;
46import {
57 claimMainSessionRecoveryOwner ,
68 releaseMainSessionRecoveryOwner ,
79} from "../../agents/main-session-recovery/main-session-recovery-store.js" ;
810import {
911 loadSessionEntry ,
12+ markSessionAbortTarget ,
1013 replaceSessionEntry ,
1114 updateSessionEntry ,
1215} from "../../config/sessions/session-accessor.js" ;
1316import type { InternalSessionEntry , SessionEntry } from "../../config/sessions/types.js" ;
14- import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js" ;
17+ import {
18+ getAgentEventLifecycleGeneration ,
19+ rotateAgentEventLifecycleGeneration ,
20+ } from "../../infra/agent-events.js" ;
21+ import { isAgentRunStaleLifecycleError } from "../../infra/agent-lifecycle-error.js" ;
1522import { createUserTurnTranscriptRecorder } from "../../sessions/user-turn-transcript.js" ;
1623import type {
1724 UserTurnTranscriptRecorder ,
@@ -64,6 +71,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
6471 } ;
6572 await replaceSessionEntry ( { storePath, sessionKey } , entry ) ;
6673 const controller = createReplyRestartRecoveryClaimController ( {
74+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
6775 admissionRunId : "recovery-run" ,
6876 getEntry : ( ) => entry ,
6977 getSessionId : ( ) => sessionId ,
@@ -110,6 +118,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
110118 } ;
111119 await replaceSessionEntry ( { storePath, sessionKey } , entry ) ;
112120 const controller = createReplyRestartRecoveryClaimController ( {
121+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
113122 admissionRunId : "recovery-run" ,
114123 getEntry : ( ) => entry ,
115124 getSessionId : ( ) => sessionId ,
@@ -133,6 +142,173 @@ describe("createReplyRestartRecoveryClaimController", () => {
133142 } ) ;
134143 } ) ;
135144
145+ it . each ( [
146+ "restart-handoff" ,
147+ "restart-abort" ,
148+ "successor-generation" ,
149+ "missing-generation" ,
150+ "commit-rotation" ,
151+ "commit-abort" ,
152+ ] as const ) (
153+ "preserves the delivery claim when queued cleanup loses ownership through %s" ,
154+ async ( interruption ) => {
155+ const root = tempDirs . make ( "openclaw-reply-claim-queued-cleanup-" ) ;
156+ const scope = { storePath : path . join ( root , "sessions.json" ) , sessionKey : "agent:main:main" } ;
157+ const lifecycleGeneration = getAgentEventLifecycleGeneration ( ) ;
158+ const deliveryContext = { channel : "telegram" , to : "chat" , accountId : "default" } ;
159+ let restartAborted = false ;
160+ let interruptBeforeCommit = false ;
161+ let entry : InternalSessionEntry = {
162+ sessionId : "session" ,
163+ updatedAt : 1 ,
164+ status : "running" ,
165+ abortedLastRun : false ,
166+ restartRecoveryDeliveryRunId : "recovery-run" ,
167+ restartRecoveryDeliverySourceRunId : "source-turn" ,
168+ restartRecoveryDeliveryContext : deliveryContext ,
169+ restartRecoverySourceIngress : "channel" ,
170+ } ;
171+ await replaceSessionEntry ( scope , entry ) ;
172+ const controller = createReplyRestartRecoveryClaimController ( {
173+ lifecycleGeneration :
174+ interruption === "missing-generation" ? undefined : lifecycleGeneration ,
175+ admissionRunId : "recovery-run" ,
176+ getEntry : ( ) => entry ,
177+ getSessionId : ( ) => {
178+ if ( interruptBeforeCommit ) {
179+ interruptBeforeCommit = false ;
180+ // The store awaits the prepared patch before entering its write transaction.
181+ queueMicrotask ( ( ) => {
182+ if ( interruption === "commit-rotation" ) {
183+ rotateAgentEventLifecycleGeneration ( ) ;
184+ } else {
185+ restartAborted = true ;
186+ }
187+ } ) ;
188+ }
189+ return "session" ;
190+ } ,
191+ isRestartAbort : ( ) => restartAborted ,
192+ resolveDeliveryContext : ( ) => deliveryContext ,
193+ setEntry : ( next ) => {
194+ entry = next ;
195+ } ,
196+ ...scope ,
197+ } ) ;
198+ await expect ( controller . admitUserTurn ( ) ) . resolves . toBe ( "admitted" ) ;
199+
200+ const writerEntered = createDeferred ( ) ;
201+ const releaseWriter = createDeferred ( ) ;
202+ let successorGeneration : string | undefined ;
203+ const handoff = updateSessionEntry ( scope , async ( current ) => {
204+ writerEntered . resolve ( ) ;
205+ await releaseWriter . promise ;
206+ if ( interruption === "restart-handoff" || interruption === "successor-generation" ) {
207+ transitionMainSessionRecovery ( current , {
208+ kind : "mark_interrupted" ,
209+ cycleId : "restart-cycle" ,
210+ now : 2 ,
211+ runs : [ { runId : "original-run" , lifecycleGeneration } ] ,
212+ } ) ;
213+ if ( successorGeneration ) {
214+ const recovery = current . mainRestartRecovery ! ;
215+ transitionMainSessionRecovery ( current , {
216+ kind : "prepare_attempt" ,
217+ attempt : 1 ,
218+ lifecycleGeneration : successorGeneration ,
219+ now : 3 ,
220+ observation : {
221+ sessionId : current . sessionId ,
222+ cycleId : recovery . cycleId ,
223+ revision : recovery . revision ,
224+ } ,
225+ runId : "recovery-run" ,
226+ executionIdentity : { state : "disabled" } ,
227+ } ) ;
228+ transitionMainSessionRecovery ( current , {
229+ kind : "admit_recovery" ,
230+ lifecycleGeneration : successorGeneration ,
231+ now : 4 ,
232+ runId : "recovery-run" ,
233+ sessionId : current . sessionId ,
234+ } ) ;
235+ }
236+ }
237+ return current ;
238+ } ) ;
239+ await writerEntered . promise ;
240+ interruptBeforeCommit = interruption === "commit-rotation" || interruption === "commit-abort" ;
241+ // The old cleanup enters before shutdown; its actual write waits behind the handoff.
242+ const clearing = controller . clear ( ) . catch ( ( error : unknown ) => {
243+ expect ( isAgentRunStaleLifecycleError ( error ) ) . toBe ( true ) ;
244+ } ) ;
245+ try {
246+ if ( interruption === "restart-abort" ) {
247+ restartAborted = true ;
248+ } else if ( interruption === "successor-generation" ) {
249+ successorGeneration = rotateAgentEventLifecycleGeneration ( ) ;
250+ }
251+ } finally {
252+ releaseWriter . resolve ( ) ;
253+ }
254+ await Promise . all ( [ handoff , clearing ] ) ;
255+
256+ const persisted = loadSessionEntry ( scope ) ;
257+ expect ( persisted ) . toMatchObject ( {
258+ status : "running" ,
259+ abortedLastRun : interruption === "restart-handoff" ,
260+ restartRecoveryDeliveryRunId : "recovery-run" ,
261+ restartRecoveryDeliverySourceRunId : "source-turn" ,
262+ restartRecoveryDeliveryContext : deliveryContext ,
263+ restartRecoverySourceIngress : "channel" ,
264+ } ) ;
265+ expect ( persisted ?. restartRecoveryTerminalRunIds ) . toBeUndefined ( ) ;
266+ if ( successorGeneration ) {
267+ expect ( persisted ?. restartRecoveryRuns ) . toContainEqual ( {
268+ runId : "recovery-run" ,
269+ lifecycleGeneration : successorGeneration ,
270+ } ) ;
271+ }
272+ } ,
273+ ) ;
274+
275+ it ( "retires the source claim after an ordinary user abort" , async ( ) => {
276+ const root = tempDirs . make ( "openclaw-reply-claim-user-abort-" ) ;
277+ const scope = { storePath : path . join ( root , "sessions.json" ) , sessionKey : "agent:main:main" } ;
278+ let entry : InternalSessionEntry = {
279+ sessionId : "session" ,
280+ updatedAt : 1 ,
281+ status : "running" ,
282+ restartRecoveryDeliveryRunId : "recovery-run" ,
283+ restartRecoveryDeliverySourceRunId : "source-turn" ,
284+ restartRecoveryDeliveryContext : { channel : "telegram" , to : "chat" } ,
285+ restartRecoverySourceIngress : "channel" ,
286+ } ;
287+ await replaceSessionEntry ( scope , entry ) ;
288+ const controller = createReplyRestartRecoveryClaimController ( {
289+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
290+ admissionRunId : "recovery-run" ,
291+ getEntry : ( ) => entry ,
292+ getSessionId : ( ) => "session" ,
293+ isRestartAbort : ( ) => false ,
294+ resolveDeliveryContext : ( ) => undefined ,
295+ setEntry : ( next ) => {
296+ entry = next ;
297+ } ,
298+ ...scope ,
299+ } ) ;
300+ await expect ( controller . admitUserTurn ( ) ) . resolves . toBe ( "admitted" ) ;
301+ await markSessionAbortTarget ( { scope } ) ;
302+ await controller . clear ( ) ;
303+
304+ const persisted = loadSessionEntry ( scope ) ;
305+ expect ( persisted ?. abortedLastRun ) . toBe ( true ) ;
306+ expect ( persisted ?. restartRecoveryDeliveryRunId ) . toBeUndefined ( ) ;
307+ expect ( persisted ?. restartRecoveryDeliveryContext ) . toBeUndefined ( ) ;
308+ expect ( persisted ?. restartRecoveryDeliverySourceRunId ) . toBeUndefined ( ) ;
309+ expect ( persisted ?. restartRecoveryTerminalRunIds ) . toContain ( "source-turn" ) ;
310+ } ) ;
311+
136312 it ( "adopts an exact channel recovery claim before execution starts" , async ( ) => {
137313 const root = tempDirs . make ( "openclaw-reply-channel-claim-adoption-" ) ;
138314 const storePath = path . join ( root , "sessions.json" ) ;
@@ -160,6 +336,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
160336 } ;
161337 await replaceSessionEntry ( { storePath, sessionKey } , entry ) ;
162338 const controller = createReplyRestartRecoveryClaimController ( {
339+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
163340 admissionRunId : "recovery-run" ,
164341 getEntry : ( ) => entry ,
165342 getSessionId : ( ) => sessionId ,
@@ -228,6 +405,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
228405 persistFallback : async ( ) => undefined ,
229406 } satisfies UserTurnTranscriptRecorder ;
230407 const controller = createReplyRestartRecoveryClaimController ( {
408+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
231409 getEntry : ( ) => entry ,
232410 getSessionId : ( ) => sessionId ,
233411 isRestartAbort : ( ) => false ,
@@ -311,6 +489,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
311489 persistFallback : async ( ) => undefined ,
312490 } satisfies UserTurnTranscriptRecorder ;
313491 const controller = createReplyRestartRecoveryClaimController ( {
492+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
314493 getEntry : ( ) => entry ,
315494 getSessionId : ( ) => sessionId ,
316495 isRestartAbort : ( ) => false ,
@@ -405,6 +584,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
405584 persistFallback : async ( ) => undefined ,
406585 } satisfies UserTurnTranscriptRecorder ;
407586 const controller = createReplyRestartRecoveryClaimController ( {
587+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
408588 getEntry : ( ) => entry ,
409589 getSessionId : ( ) => sessionId ,
410590 isRestartAbort : ( ) => false ,
@@ -505,6 +685,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
505685 } ,
506686 } satisfies UserTurnTranscriptRecorder ;
507687 const controller = createReplyRestartRecoveryClaimController ( {
688+ lifecycleGeneration : getAgentEventLifecycleGeneration ( ) ,
508689 getEntry : ( ) => entry ,
509690 getSessionId : ( ) => sessionId ,
510691 isRestartAbort : ( ) => false ,
0 commit comments