11// OpenClaw gateway tests cover activation serialization and chat sessions.
22
3+ import fs from "node:fs" ;
4+ import path from "node:path" ;
35import { expectDefined } from "@openclaw/normalization-core" ;
46import { afterEach , beforeEach , describe , expect , it , vi } from "vitest" ;
7+ import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js" ;
58import type { OpenClawConfig } from "../../config/types.openclaw.js" ;
9+ import { createSafeGatewayRestartPreflight } from "../../infra/restart-coordinator.js" ;
610import type { SystemAgentApprovalRequestPayload } from "../../infra/system-agent-approvals.js" ;
11+ import { resetPluginStateStoreForTests } from "../../plugin-state/plugin-state-store.js" ;
712import { getCommandLaneSnapshot } from "../../process/command-queue.js" ;
813import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js" ;
14+ import { getActiveGatewayRootWorkCount } from "../../process/gateway-work-admission.js" ;
915import { CommandLane } from "../../process/lanes.js" ;
1016import { defaultRuntime } from "../../runtime.js" ;
1117import { SystemAgentChatEngine } from "../../system-agent/chat-engine.js" ;
1218import { SystemAgentInferenceUnavailableError } from "../../system-agent/inference-error.js" ;
13- import { createSystemAgentVerifiedInferenceTestFixture } from "../../system-agent/system-agent.test-helpers.js" ;
19+ import {
20+ createSystemAgentVerifiedInferenceTestFixture ,
21+ readLastSystemAgentAuditEntry ,
22+ } from "../../system-agent/system-agent.test-helpers.js" ;
1423import type {
1524 SystemAgentVerifiedInferenceBinding ,
1625 SystemAgentVerifiedInferenceDeps ,
1726} from "../../system-agent/verified-inference.js" ;
1827import { createDeferred } from "../../test-utils/deferred.js" ;
1928import type { WizardPrompter } from "../../wizard/prompts.js" ;
2029import { ExecApprovalManager } from "../exec-approval-manager.js" ;
30+ import { handleGatewayRequest } from "../server-methods.js" ;
2131import {
2232 systemAgentHandlers ,
2333 runExclusiveSystemAgentSetupActivation ,
@@ -28,6 +38,7 @@ import type { GatewayClient, GatewayRequestContext } from "./types.js";
2838const setupInferenceMocks = vi . hoisted ( ( ) => ( {
2939 activateSetupInference : vi . fn ( ) ,
3040 detectSetupInference : vi . fn ( ) ,
41+ resolvePersistentApplyInference : vi . fn ( ) ,
3142 verifySetupInference : vi . fn ( ) ,
3243} ) ) ;
3344const setupInferenceDetectionMocks = vi . hoisted ( ( ) => ( {
@@ -59,6 +70,7 @@ const onboardingWelcomeMocks = vi.hoisted(() => ({
5970vi . mock ( "../../system-agent/setup-inference.js" , ( ) => ( {
6071 activateSetupInference : setupInferenceMocks . activateSetupInference ,
6172 detectSetupInference : setupInferenceMocks . detectSetupInference ,
73+ resolvePersistentApplyInference : setupInferenceMocks . resolvePersistentApplyInference ,
6274 verifySetupInference : setupInferenceMocks . verifySetupInference ,
6375} ) ) ;
6476vi . mock ( "../../system-agent/setup-inference-detection.js" , ( ) => ( {
@@ -122,6 +134,7 @@ const verifiedConfig: OpenClawConfig = {
122134} ;
123135let verifiedInference : SystemAgentVerifiedInferenceBinding | undefined ;
124136let verifiedInferenceDeps : SystemAgentVerifiedInferenceDeps | undefined ;
137+ const systemAgentTempDirs = useAutoCleanupTempDirTracker ( afterEach ) ;
125138
126139function requireVerifiedInferenceFixture ( ) : SystemAgentVerifiedInferenceBinding {
127140 if ( ! verifiedInference ) {
@@ -197,6 +210,9 @@ beforeEach(async () => {
197210 latencyMs : 10 ,
198211 binding : verifiedInference ,
199212 } ) ;
213+ setupInferenceMocks . resolvePersistentApplyInference . mockResolvedValue (
214+ requireVerifiedInferenceFixture ( ) . configuredRoute ,
215+ ) ;
200216 setupSharedMocks . readSetupConfigFileSnapshot . mockResolvedValue ( {
201217 exists : true ,
202218 valid : true ,
@@ -230,6 +246,7 @@ afterEach(() => {
230246 vi . restoreAllMocks ( ) ;
231247 setupInferenceMocks . activateSetupInference . mockReset ( ) ;
232248 setupInferenceMocks . detectSetupInference . mockReset ( ) ;
249+ setupInferenceMocks . resolvePersistentApplyInference . mockReset ( ) ;
233250 setupInferenceDetectionMocks . detectSetupInferenceIsolated . mockReset ( ) ;
234251 setupInferenceMocks . verifySetupInference . mockReset ( ) ;
235252 providerAuthChoiceMocks . applyAuthChoiceLoadedPluginProvider . mockReset ( ) ;
@@ -241,7 +258,9 @@ afterEach(() => {
241258 onboardingWelcomeMocks . buildOnboardingWelcome . mockReset ( ) ;
242259 verifiedInference = undefined ;
243260 verifiedInferenceDeps = undefined ;
261+ resetPluginStateStoreForTests ( ) ;
244262 resetCommandQueueStateForTest ( ) ;
263+ vi . unstubAllEnvs ( ) ;
245264} ) ;
246265
247266async function callChat (
@@ -815,20 +834,34 @@ describe("openclaw.chat", () => {
815834 expect ( ( await invoke ( { limit : 501 } ) ) ?. ok ) . toBe ( false ) ;
816835 } ) ;
817836
818- it ( "surfaces delegated proposals without letting the agent arm them" , async ( ) => {
819- const operation = { kind : "config-set" as const , path : "gateway.port" , value : "19001" } ;
820- const proposalHash = "a" . repeat ( 64 ) ;
821- const engine = makeVerifiedEngine ( ) ;
837+ it ( "tracks approved delegated Gateway restarts until their completion drains" , async ( ) => {
838+ const operation = { kind : "gateway-restart" as const } ;
839+ const approvalStarted = createDeferred ( ) ;
840+ const releaseApproval = createDeferred ( ) ;
841+ const stateDir = systemAgentTempDirs . make ( "openclaw-approved-gateway-restart-" ) ;
842+ vi . stubEnv ( "OPENCLAW_STATE_DIR" , stateDir ) ;
843+ vi . stubEnv ( "OPENCLAW_CONFIG_PATH" , path . join ( stateDir , "openclaw.json" ) ) ;
844+ fs . writeFileSync ( path . join ( stateDir , "openclaw.json" ) , JSON . stringify ( verifiedConfig ) ) ;
845+ const runGatewayRestart = vi . fn ( async ( ) => {
846+ approvalStarted . resolve ( ) ;
847+ await releaseApproval . promise ;
848+ return true ;
849+ } ) ;
850+ const engine = new SystemAgentChatEngine ( {
851+ operatorApprovalOnly : true ,
852+ surface : "gateway" ,
853+ verifiedInference : requireVerifiedInferenceFixture ( ) ,
854+ deps : { ...requireVerifiedInferenceDeps ( ) , runGatewayRestart } ,
855+ } ) ;
856+ engine . propose ( operation ) ;
857+ const proposalHash = expectDefined (
858+ engine . getPendingOperatorProposal ( ) ,
859+ "approved Gateway restart proposal invariant" ,
860+ ) . hash ;
822861 const handle = vi
823862 . spyOn ( engine , "handle" )
824863 . mockResolvedValue ( { text : "Approval pending." , action : "none" } ) ;
825- vi . spyOn ( engine , "getPendingOperatorProposal" ) . mockReturnValue ( {
826- operation,
827- hash : proposalHash ,
828- } ) ;
829- const resolveOperatorApproval = vi
830- . spyOn ( engine , "resolveOperatorApproval" )
831- . mockResolvedValue ( null ) ;
864+ const resolveOperatorApproval = vi . spyOn ( engine , "resolveOperatorApproval" ) ;
832865 const sessions = new Map < string , SystemAgentChatSession > ( [
833866 [
834867 "delegate-1" ,
@@ -851,12 +884,30 @@ describe("openclaw.chat", () => {
851884 hasExecApprovalClients : ( ) => true ,
852885 } as unknown as GatewayRequestContext ;
853886
854- const first = await callChat ( context , {
855- sessionId : "delegate-1" ,
856- message : "Change port." ,
857- context : { page : "channels" } ,
858- delegation : { agentId : "main" , sessionKey : "agent:main:main" } ,
887+ const requestResponses = makeRespond ( ) ;
888+ await handleGatewayRequest ( {
889+ req : {
890+ type : "req" ,
891+ id : "delegated-gateway-restart" ,
892+ method : "openclaw.chat" ,
893+ params : {
894+ sessionId : "delegate-1" ,
895+ message : "Restart Gateway." ,
896+ context : { page : "channels" } ,
897+ delegation : { agentId : "main" , sessionKey : "agent:main:main" } ,
898+ } ,
899+ } ,
900+ respond : requestResponses . respond ,
901+ client : {
902+ ...defaultClient ,
903+ connect : { ...defaultClient . connect , role : "operator" , scopes : [ "operator.admin" ] } ,
904+ } as GatewayClient ,
905+ isWebchatConnect : ( ) => false ,
906+ context,
907+ extraHandlers : { "openclaw.chat" : systemAgentHandlers [ "openclaw.chat" ] ! } ,
859908 } ) ;
909+ const first = expectDefined ( requestResponses . calls [ 0 ] , "delegated Gateway response invariant" ) ;
910+ expect ( getActiveGatewayRootWorkCount ( ) ) . toBe ( 0 ) ;
860911 const proposalId = ( first . payload as { proposalId ?: string } ) . proposalId ;
861912
862913 expect ( first . payload ) . toMatchObject ( {
@@ -875,7 +926,7 @@ describe("openclaw.chat", () => {
875926 { dropIfSlow : true } ,
876927 ) ;
877928 expect ( resolveOperatorApproval ) . not . toHaveBeenCalled ( ) ;
878- expect ( handle ) . toHaveBeenNthCalledWith ( 1 , "Change port ." ) ;
929+ expect ( handle ) . toHaveBeenNthCalledWith ( 1 , "Restart Gateway ." ) ;
879930
880931 await callChat ( context , {
881932 sessionId : "delegate-1" ,
@@ -885,9 +936,35 @@ describe("openclaw.chat", () => {
885936 expect ( resolveOperatorApproval ) . not . toHaveBeenCalled ( ) ;
886937
887938 manager . resolve ( proposalId ! , "allow-once" , "operator-ui" ) ;
939+ await approvalStarted . promise ;
940+ try {
941+ expect ( getCommandLaneSnapshot ( CommandLane . SystemAgent ) ) . toMatchObject ( {
942+ activeCount : 1 ,
943+ queuedCount : 0 ,
944+ } ) ;
945+ const restartPreflight = createSafeGatewayRestartPreflight ( ) ;
946+ expect ( restartPreflight . safe ) . toBe ( false ) ;
947+ expect ( restartPreflight . counts . queueSize ) . toBe ( 1 ) ;
948+ expect ( restartPreflight . blockers ) . toContainEqual (
949+ expect . objectContaining ( { kind : "queue" , count : 1 } ) ,
950+ ) ;
951+ } finally {
952+ releaseApproval . resolve ( ) ;
953+ }
888954 await vi . waitFor ( ( ) => {
889955 expect ( resolveOperatorApproval ) . toHaveBeenCalledWith ( "allow-once" , proposalHash ) ;
956+ expect ( runGatewayRestart ) . toHaveBeenCalledOnce ( ) ;
957+ expect ( getCommandLaneSnapshot ( CommandLane . SystemAgent ) . activeCount ) . toBe ( 0 ) ;
958+ } ) ;
959+ await expect ( resolveOperatorApproval . mock . results [ 0 ] ?. value ) . resolves . toMatchObject ( {
960+ text : expect . stringContaining ( "[openclaw] done: gateway.restart" ) ,
961+ } ) ;
962+ expect ( readLastSystemAgentAuditEntry ( ) ) . toMatchObject ( {
963+ operation : "gateway.restart" ,
964+ summary : "Scheduled Gateway restart" ,
890965 } ) ;
966+ expect ( getActiveGatewayRootWorkCount ( ) ) . toBe ( 0 ) ;
967+ expect ( createSafeGatewayRestartPreflight ( ) . counts . queueSize ) . toBe ( 0 ) ;
891968 } ) ;
892969
893970 it ( "drops a failed session and requires fresh inference on retry" , async ( ) => {
0 commit comments