Skip to content

Commit 7bd16a3

Browse files
author
Peter Steinberger
committed
fix(gateway): safely defer agent-approved Gateway restarts
1 parent 17625e5 commit 7bd16a3

9 files changed

Lines changed: 173 additions & 36 deletions

‎src/agents/system-prompt.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -853,9 +853,11 @@ describe("buildAgentSystemPrompt", () => {
853853
});
854854

855855
expect(prompt).toContain(
856-
"Config, channels, plugins, new agents, model/provider, updates: ask `openclaw`.",
856+
"Gateway restart, config, channels, plugins, agents, models/providers, updates: ask `openclaw`.",
857+
);
858+
expect(prompt).toContain(
859+
"Never restart the Gateway through shell commands or write your own config.",
857860
);
858-
expect(prompt).toContain("Never write own config; OpenClaw is system expert.");
859861
expect(prompt).toContain("`visible:true` only web/app user or asked.");
860862
});
861863

@@ -866,6 +868,7 @@ describe("buildAgentSystemPrompt", () => {
866868
});
867869

868870
expect(prompt).not.toContain("ask `openclaw`");
871+
expect(prompt).not.toContain("Gateway restart, config");
869872
});
870873

871874
it("includes skills guidance when skills prompt is present", () => {

‎src/agents/system-prompt.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -874,7 +874,7 @@ export function buildAgentSystemPrompt(params: {
874874
conversations_list: "List exact external conversation addresses",
875875
conversations_send: "Send directly to an external conversation",
876876
conversations_turn: "Send and wait for one correlated external reply",
877-
openclaw: "System setup/config expert; writes need human approval",
877+
openclaw: "Gateway restart/system setup/config; changes need human approval",
878878
gateway: "Read gateway config/schema",
879879
agents_list: acpSpawnRuntimeEnabled
880880
? "List allowed OpenClaw subagent ids; not ACP ids"
@@ -1275,7 +1275,7 @@ export function buildAgentSystemPrompt(params: {
12751275
"Do not invent commands.",
12761276
...(hasOpenClaw
12771277
? [
1278-
"Config, channels, plugins, new agents, model/provider, updates: ask `openclaw`. Never write own config; OpenClaw is system expert.",
1278+
"Gateway restart, config, channels, plugins, agents, models/providers, updates: ask `openclaw`. Never restart the Gateway through shell commands or write your own config.",
12791279
]
12801280
: [
12811281
"Config read: `gateway` (`config.get|config.schema.lookup`). Write/restart unavailable; ask human.",

‎src/agents/tools/openclaw-delegate-tool.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ describe("openclaw delegation tool", () => {
3232
if (!tool) {
3333
throw new Error("expected OpenClaw delegation tool");
3434
}
35+
expect(tool.description).toContain("Gateway restart");
36+
expect(tool.description).toContain("human approval");
3537

3638
const result = await tool.execute("call-1", { message: "Add channel." });
3739

‎src/agents/tools/openclaw-delegate-tool.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ function createOpenClawDelegateTool(options?: {
4848
name: "openclaw",
4949
label: "OpenClaw",
5050
description:
51-
"Ask system expert. Config, channels, plugins, agents, models/providers, updates. Writes need human approval.",
51+
"Ask system expert. Gateway restart, config, channels, plugins, agents, models/providers, updates. Changes need human approval.",
5252
parameters: OpenClawDelegateSchema,
5353
outputSchema: OpenClawDelegateOutputSchema,
5454
execute: async (_toolCallId, args) => {

‎src/gateway/server-methods/system-agent.test.ts‎

Lines changed: 95 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,33 @@
11
// OpenClaw gateway tests cover activation serialization and chat sessions.
22

3+
import fs from "node:fs";
4+
import path from "node:path";
35
import { expectDefined } from "@openclaw/normalization-core";
46
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
58
import type { OpenClawConfig } from "../../config/types.openclaw.js";
9+
import { createSafeGatewayRestartPreflight } from "../../infra/restart-coordinator.js";
610
import type { SystemAgentApprovalRequestPayload } from "../../infra/system-agent-approvals.js";
11+
import { resetPluginStateStoreForTests } from "../../plugin-state/plugin-state-store.js";
712
import { getCommandLaneSnapshot } from "../../process/command-queue.js";
813
import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js";
14+
import { getActiveGatewayRootWorkCount } from "../../process/gateway-work-admission.js";
915
import { CommandLane } from "../../process/lanes.js";
1016
import { defaultRuntime } from "../../runtime.js";
1117
import { SystemAgentChatEngine } from "../../system-agent/chat-engine.js";
1218
import { 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";
1423
import type {
1524
SystemAgentVerifiedInferenceBinding,
1625
SystemAgentVerifiedInferenceDeps,
1726
} from "../../system-agent/verified-inference.js";
1827
import { createDeferred } from "../../test-utils/deferred.js";
1928
import type { WizardPrompter } from "../../wizard/prompts.js";
2029
import { ExecApprovalManager } from "../exec-approval-manager.js";
30+
import { handleGatewayRequest } from "../server-methods.js";
2131
import {
2232
systemAgentHandlers,
2333
runExclusiveSystemAgentSetupActivation,
@@ -28,6 +38,7 @@ import type { GatewayClient, GatewayRequestContext } from "./types.js";
2838
const setupInferenceMocks = vi.hoisted(() => ({
2939
activateSetupInference: vi.fn(),
3040
detectSetupInference: vi.fn(),
41+
resolvePersistentApplyInference: vi.fn(),
3142
verifySetupInference: vi.fn(),
3243
}));
3344
const setupInferenceDetectionMocks = vi.hoisted(() => ({
@@ -59,6 +70,7 @@ const onboardingWelcomeMocks = vi.hoisted(() => ({
5970
vi.mock("../../system-agent/setup-inference.js", () => ({
6071
activateSetupInference: setupInferenceMocks.activateSetupInference,
6172
detectSetupInference: setupInferenceMocks.detectSetupInference,
73+
resolvePersistentApplyInference: setupInferenceMocks.resolvePersistentApplyInference,
6274
verifySetupInference: setupInferenceMocks.verifySetupInference,
6375
}));
6476
vi.mock("../../system-agent/setup-inference-detection.js", () => ({
@@ -122,6 +134,7 @@ const verifiedConfig: OpenClawConfig = {
122134
};
123135
let verifiedInference: SystemAgentVerifiedInferenceBinding | undefined;
124136
let verifiedInferenceDeps: SystemAgentVerifiedInferenceDeps | undefined;
137+
const systemAgentTempDirs = useAutoCleanupTempDirTracker(afterEach);
125138

126139
function 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

247266
async 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 () => {

‎src/gateway/server-methods/system-agent.ts‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
} from "../../infra/system-agent-approvals.js";
2121
import { KeyedAsyncQueue } from "../../plugin-sdk/keyed-async-queue.js";
2222
import { enqueueCommandInLane, setCommandLaneConcurrency } from "../../process/command-queue.js";
23+
import { runWithGatewayIndependentRootWorkContinuation } from "../../process/gateway-work-admission.js";
2324
import { CommandLane } from "../../process/lanes.js";
2425
import { defaultRuntime } from "../../runtime.js";
2526
import { SystemAgentChatEngine } from "../../system-agent/chat-engine.js";
@@ -237,15 +238,19 @@ function queueDelegatedApproval(params: {
237238
deliverRequest: () => false,
238239
keepPendingWithoutRoute: true,
239240
requireDeliveryRoute: false,
240-
afterDecision: async (decision) => {
241-
if (params.sessions.get(params.sessionId) !== params.session) {
242-
return;
243-
}
244-
if (params.session.pendingApproval?.id === record.id) {
245-
params.session.pendingApproval = undefined;
246-
}
247-
await params.session.engine.resolveOperatorApproval(decision, params.proposal.hash);
248-
},
241+
afterDecision: async (decision) =>
242+
await runWithGatewayIndependentRootWorkContinuation(() =>
243+
runSystemAgentGatewayTask(async () => {
244+
// The original request has returned; keep approval, audit, and restart drain-visible.
245+
if (params.sessions.get(params.sessionId) !== params.session) {
246+
return;
247+
}
248+
if (params.session.pendingApproval?.id === record.id) {
249+
params.session.pendingApproval = undefined;
250+
}
251+
await params.session.engine.resolveOperatorApproval(decision, params.proposal.hash);
252+
}),
253+
),
249254
afterDecisionErrorLabel: "OpenClaw approval apply failed",
250255
});
251256
return record.id;

‎src/system-agent/operations-execute.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -485,13 +485,19 @@ export async function executeSystemAgentOperation(
485485
runtime,
486486
opts,
487487
run: async (ctx) => {
488+
const gatewayHosted = ctx.deps?.setupSurface === "gateway";
488489
const runGatewayRestart =
489-
ctx.deps?.runGatewayRestart ?? (() => runGatewayLifecycle("restart"));
490+
ctx.deps?.runGatewayRestart ??
491+
(() => runGatewayLifecycle("restart", gatewayHosted ? "gateway" : undefined));
490492
const restarted = await ctx.commit(runGatewayRestart);
491493
if (restarted === false) {
492494
throw new Error("Gateway restart did not complete");
493495
}
494-
return { summary: "Restarted Gateway" };
496+
const summary = gatewayHosted ? "Scheduled Gateway restart" : "Restarted Gateway";
497+
if (gatewayHosted) {
498+
ctx.runtime.log(summary);
499+
}
500+
return { summary };
495501
},
496502
});
497503
case "open-tui": {

‎src/system-agent/operations-execution-helpers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ export function formatGatewayStatusLine(overview: SystemAgentOverview): string {
9494

9595
export async function runGatewayLifecycle(
9696
operation: "start" | "stop" | "restart",
97+
surface?: "cli" | "gateway",
9798
): Promise<void | boolean> {
9899
const lifecycle = await import("../cli/daemon-cli/lifecycle.js");
99100
if (operation === "start") {
@@ -106,7 +107,8 @@ export async function runGatewayLifecycle(
106107
await lifecycle.runDaemonStop({ force: true });
107108
return;
108109
}
109-
return await lifecycle.runDaemonRestart();
110+
// Gateway-hosted operations must finish and drain before restarting their owner.
111+
return await lifecycle.runDaemonRestart(surface === "gateway" ? { safe: true } : undefined);
110112
}
111113

112114
export async function readConfigFileSnapshotLazy(): Promise<ConfigFileSnapshot> {

0 commit comments

Comments
 (0)