33 * Covers target resolution, cursor mode tracking, exit outcome classification,
44 * system events, and process lifecycle behavior.
55 */
6- import { beforeAll , beforeEach , describe , expect , it , vi } from "vitest" ;
6+ import { afterEach , beforeAll , beforeEach , describe , expect , it , vi } from "vitest" ;
7+ import type { RunExit } from "../process/supervisor/types.js" ;
78import { MAX_SAFE_TIMEOUT_DELAY_MS } from "../utils/timer-delay.js" ;
9+ import type { BashSandboxConfig } from "./bash-tools.shared.js" ;
810
911const requestHeartbeatMock = vi . hoisted ( ( ) => vi . fn ( ) ) ;
1012const enqueueSystemEventMock = vi . hoisted ( ( ) => vi . fn ( ) ) ;
@@ -27,15 +29,21 @@ vi.mock("../process/supervisor/index.js", () => ({
2729} ) ) ;
2830
2931let markBackgrounded : typeof import ( "./bash-process-registry.js" ) . markBackgrounded ;
32+ let getActiveBackgroundExecSessionCount : typeof import ( "./bash-process-registry.js" ) . getActiveBackgroundExecSessionCount ;
33+ let resetProcessRegistryForTests : typeof import ( "./bash-process-registry.js" ) . resetProcessRegistryForTests ;
3034let buildExecExitOutcome : typeof import ( "./bash-tools.exec-runtime.js" ) . buildExecExitOutcome ;
3135let detectCursorKeyMode : typeof import ( "./bash-tools.exec-runtime.js" ) . detectCursorKeyMode ;
3236let formatExecFailureReason : typeof import ( "./bash-tools.exec-runtime.js" ) . formatExecFailureReason ;
3337let renderExecUpdateText : typeof import ( "./bash-tools.exec-runtime.js" ) . renderExecUpdateText ;
3438let resolveExecTarget : typeof import ( "./bash-tools.exec-runtime.js" ) . resolveExecTarget ;
3539let runExecProcess : typeof import ( "./bash-tools.exec-runtime.js" ) . runExecProcess ;
40+ let prepareGatewaySuspend : typeof import ( "../infra/gateway-suspend-coordinator.js" ) . prepareGatewaySuspend ;
41+ let resetGatewaySuspendCoordinatorForTest : typeof import ( "../infra/gateway-suspend-coordinator.js" ) . resetGatewaySuspendCoordinatorForTest ;
42+ let resumeGatewaySuspend : typeof import ( "../infra/gateway-suspend-coordinator.js" ) . resumeGatewaySuspend ;
3643
3744beforeAll ( async ( ) => {
38- ( { markBackgrounded } = await import ( "./bash-process-registry.js" ) ) ;
45+ ( { getActiveBackgroundExecSessionCount, markBackgrounded, resetProcessRegistryForTests } =
46+ await import ( "./bash-process-registry.js" ) ) ;
3947 ( {
4048 buildExecExitOutcome,
4149 detectCursorKeyMode,
@@ -44,14 +52,41 @@ beforeAll(async () => {
4452 resolveExecTarget,
4553 runExecProcess,
4654 } = await import ( "./bash-tools.exec-runtime.js" ) ) ;
55+ ( { prepareGatewaySuspend, resetGatewaySuspendCoordinatorForTest, resumeGatewaySuspend } =
56+ await import ( "../infra/gateway-suspend-coordinator.js" ) ) ;
4757} ) ;
4858
4959beforeEach ( ( ) => {
60+ resetGatewaySuspendCoordinatorForTest ( ) ;
61+ resetProcessRegistryForTests ( ) ;
5062 requestHeartbeatMock . mockClear ( ) ;
5163 enqueueSystemEventMock . mockClear ( ) ;
5264 supervisorMock . spawn . mockReset ( ) ;
5365} ) ;
5466
67+ afterEach ( ( ) => {
68+ resetGatewaySuspendCoordinatorForTest ( ) ;
69+ resetProcessRegistryForTests ( ) ;
70+ } ) ;
71+
72+ function createDeferred < T > ( ) {
73+ let resolve ! : ( value : T | PromiseLike < T > ) => void ;
74+ let reject ! : ( reason ?: unknown ) => void ;
75+ const promise = new Promise < T > ( ( resolvePromise , rejectPromise ) => {
76+ resolve = resolvePromise ;
77+ reject = rejectPromise ;
78+ } ) ;
79+ return { promise, reject, resolve } ;
80+ }
81+
82+ function prepareSuspension ( requestId : string ) {
83+ return prepareGatewaySuspend ( {
84+ requestId,
85+ pauseScheduling : vi . fn ( ) ,
86+ resumeScheduling : vi . fn ( ) ,
87+ } ) ;
88+ }
89+
5590function expectExecTarget (
5691 actual : ReturnType < typeof resolveExecTarget > ,
5792 expected : {
@@ -503,6 +538,130 @@ describe("exec notifyOnExit suppression", () => {
503538 } ) ;
504539} ) ;
505540
541+ describe ( "sandbox exec finalization suspension" , ( ) => {
542+ it . each ( [
543+ {
544+ scenario : "successful cleanup" ,
545+ finalizeRejects : false ,
546+ processTimesOut : false ,
547+ expectedStatus : "completed" as const ,
548+ expectedFailureKind : undefined ,
549+ } ,
550+ {
551+ scenario : "failed cleanup" ,
552+ finalizeRejects : true ,
553+ processTimesOut : false ,
554+ expectedStatus : "failed" as const ,
555+ expectedFailureKind : "runtime-error" as const ,
556+ } ,
557+ {
558+ scenario : "failed cleanup after a process timeout" ,
559+ finalizeRejects : true ,
560+ processTimesOut : true ,
561+ expectedStatus : "failed" as const ,
562+ expectedFailureKind : "overall-timeout" as const ,
563+ } ,
564+ ] ) (
565+ "keeps suspension busy until asynchronous finalization settles after $scenario" ,
566+ async ( { finalizeRejects, processTimesOut, expectedFailureKind, expectedStatus } ) => {
567+ const exit = createDeferred < RunExit > ( ) ;
568+ const finalization = createDeferred < void > ( ) ;
569+ const finalizeExec = vi . fn < NonNullable < BashSandboxConfig [ "finalizeExec" ] > > (
570+ async ( ) => await finalization . promise ,
571+ ) ;
572+ supervisorMock . spawn . mockImplementationOnce (
573+ async ( input : { onStdout ?: ( chunk : string ) => void } ) => {
574+ input . onStdout ?.( "sandbox output\n" ) ;
575+ return {
576+ runId : "sandbox-run" ,
577+ startedAtMs : Date . now ( ) ,
578+ pid : 123 ,
579+ wait : async ( ) => await exit . promise ,
580+ cancel : vi . fn ( ) ,
581+ } ;
582+ } ,
583+ ) ;
584+
585+ const run = await runExecProcess ( {
586+ command : "sandbox-command" ,
587+ workdir : "/tmp" ,
588+ env : { } ,
589+ sandbox : {
590+ containerName : "sandbox" ,
591+ workspaceDir : "/workspace" ,
592+ containerWorkdir : "/workspace" ,
593+ buildExecSpec : async ( ) => ( {
594+ argv : [ "sandbox-command" ] ,
595+ env : { } ,
596+ stdinMode : "pipe-closed" ,
597+ finalizeToken : "sandbox-token" ,
598+ } ) ,
599+ finalizeExec,
600+ } ,
601+ usePty : false ,
602+ warnings : [ ] ,
603+ maxOutput : 1000 ,
604+ pendingMaxOutput : 1000 ,
605+ notifyOnExit : true ,
606+ sessionKey : "agent:main:main" ,
607+ timeoutSec : null ,
608+ } ) ;
609+ markBackgrounded ( run . session ) ;
610+ expect ( getActiveBackgroundExecSessionCount ( ) ) . toBe ( 1 ) ;
611+
612+ exit . resolve ( {
613+ reason : processTimesOut ? "overall-timeout" : "exit" ,
614+ exitCode : processTimesOut ? null : 0 ,
615+ exitSignal : processTimesOut ? "SIGKILL" : null ,
616+ durationMs : 1 ,
617+ stdout : "" ,
618+ stderr : "" ,
619+ timedOut : processTimesOut ,
620+ noOutputTimedOut : false ,
621+ } ) ;
622+ await vi . waitFor ( ( ) => expect ( finalizeExec ) . toHaveBeenCalledOnce ( ) ) ;
623+ expect ( run . session . finalizing ) . toBe ( true ) ;
624+
625+ const busy = prepareSuspension ( `before-finalize-${ expectedFailureKind ?? "success" } ` ) ;
626+ expect ( busy . status ) . toBe ( "busy" ) ;
627+ if ( busy . status === "busy" ) {
628+ expect ( busy . blockers ) . toContainEqual (
629+ expect . objectContaining ( { kind : "background-exec" , count : 1 } ) ,
630+ ) ;
631+ }
632+ expect ( getActiveBackgroundExecSessionCount ( ) ) . toBe ( 1 ) ;
633+
634+ if ( finalizeRejects ) {
635+ finalization . reject ( new Error ( "sandbox finalize failed" ) ) ;
636+ } else {
637+ finalization . resolve ( ) ;
638+ }
639+ const outcome = await run . promise ;
640+
641+ expect ( outcome . status ) . toBe ( expectedStatus ) ;
642+ if ( outcome . status === "failed" ) {
643+ expect ( outcome . failureKind ) . toBe ( expectedFailureKind ) ;
644+ expect ( outcome . reason ) . toContain (
645+ expectedFailureKind === "runtime-error" ? "sandbox finalize failed" : "timed out" ,
646+ ) ;
647+ }
648+ expect ( finalizeExec ) . toHaveBeenCalledOnce ( ) ;
649+ expect ( getActiveBackgroundExecSessionCount ( ) ) . toBe ( 0 ) ;
650+ expect ( run . session . finalizing ) . toBe ( false ) ;
651+ expect ( enqueueSystemEventMock ) . toHaveBeenCalledTimes ( 1 ) ;
652+ expect ( requireSystemEventCall ( ) [ 0 ] ) . toContain (
653+ expectedStatus === "failed" ? "Exec failed" : "Exec completed" ,
654+ ) ;
655+
656+ const ready = prepareSuspension ( `after-finalize-${ expectedFailureKind ?? "success" } ` ) ;
657+ expect ( ready . status ) . toBe ( "ready" ) ;
658+ if ( ready . status === "ready" ) {
659+ expect ( resumeGatewaySuspend ( ready . suspensionId ) ) . toMatchObject ( { ok : true } ) ;
660+ }
661+ } ,
662+ ) ;
663+ } ) ;
664+
506665describe ( "formatExecFailureReason" , ( ) => {
507666 it ( "formats timeout guidance with the configured timeout" , ( ) => {
508667 expect (
0 commit comments