Skip to content

Commit 346a870

Browse files
authored
fix(claws): harden add and remove lifecycle (#114670)
* fix(claws): wait for agent reload before cron add * test(claws): cover gateway config readiness * test(claws): cover gateway config readiness
1 parent fafe7d9 commit 346a870

9 files changed

Lines changed: 166 additions & 7 deletions

File tree

‎src/claws/add.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ type ClawAddApplyOptions = OpenClawStateDatabaseOptions & {
5454
installPackages?: typeof installClawPackages;
5555
installMcpServers?: typeof installClawMcpServers;
5656
installCronJobs?: typeof installClawCronJobs;
57-
cronGateway?: Pick<ClawCronGateway, "add" | "list">;
57+
cronGateway?: Pick<ClawCronGateway, "add" | "list" | "waitUntilAgentAvailable">;
5858
nowMs?: number;
5959
};
6060
export class ClawAddMutationError extends Error {

‎src/claws/cron.test.ts‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,23 @@ async function fixture() {
5151
describe("installClawCronJobs", () => {
5252
it("pins declarations and execution to the final agent id", async () => {
5353
const current = await fixture();
54-
const add = vi.fn().mockResolvedValue({ id: "scheduler-123" });
54+
const calls: string[] = [];
55+
const waitUntilAgentAvailable = vi.fn(async () => {
56+
calls.push("wait");
57+
});
58+
const add = vi.fn(async (_input: Record<string, unknown>) => {
59+
calls.push("add");
60+
return { id: "scheduler-123" };
61+
});
5562

5663
const refs = await installClawCronJobs(current.plan, {
5764
env: current.env,
58-
gateway: { add },
65+
gateway: { add, waitUntilAgentAvailable },
5966
nowMs: 42,
6067
});
6168

69+
expect(waitUntilAgentAvailable).toHaveBeenCalledWith("worker-two");
70+
expect(calls).toEqual(["wait", "add"]);
6271
expect(add).toHaveBeenCalledWith({
6372
name: "Daily report",
6473
declarationKey: "claw:worker-two:daily-report",
@@ -96,6 +105,25 @@ describe("installClawCronJobs", () => {
96105
expect(refs[0]).toMatchObject({ schedulerJobId: "existing-1", status: "complete" });
97106
});
98107

108+
it("does not require the gateway when every cron reference is already complete", async () => {
109+
const current = await fixture();
110+
await installClawCronJobs(current.plan, {
111+
env: current.env,
112+
gateway: { add: vi.fn().mockResolvedValue({ id: "scheduler-123" }) },
113+
});
114+
const waitUntilAgentAvailable = vi.fn().mockRejectedValue(new Error("gateway unavailable"));
115+
const add = vi.fn();
116+
117+
await expect(
118+
installClawCronJobs(current.plan, {
119+
env: current.env,
120+
gateway: { add, waitUntilAgentAvailable },
121+
}),
122+
).resolves.toMatchObject([{ schedulerJobId: "scheduler-123", status: "complete" }]);
123+
expect(waitUntilAgentAvailable).not.toHaveBeenCalled();
124+
expect(add).not.toHaveBeenCalled();
125+
});
126+
99127
it("preserves an ambiguous pending reference when cron.add fails", async () => {
100128
const current = await fixture();
101129

@@ -113,6 +141,28 @@ describe("installClawCronJobs", () => {
113141
]);
114142
});
115143

144+
it("preserves the pending reference when agent readiness fails", async () => {
145+
const current = await fixture();
146+
const add = vi.fn();
147+
148+
await expect(
149+
installClawCronJobs(current.plan, {
150+
env: current.env,
151+
gateway: {
152+
add,
153+
waitUntilAgentAvailable: vi.fn().mockRejectedValue(new Error("reload timed out")),
154+
},
155+
}),
156+
).rejects.toMatchObject({
157+
code: "cron_install_failed",
158+
cronJobs: [{ manifestId: "daily-report", status: "pending", error: "reload timed out" }],
159+
});
160+
expect(add).not.toHaveBeenCalled();
161+
expect(readClawCronRefs("worker-two", { env: current.env })).toMatchObject([
162+
{ manifestId: "daily-report", status: "pending", error: "reload timed out" },
163+
]);
164+
});
165+
116166
it("reconciles a response-lost retry by declaration key", async () => {
117167
const current = await fixture();
118168
const add = vi.fn().mockRejectedValue(new Error("response lost"));

‎src/claws/cron.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { resolveCronJobConfigRevision } from "../cron/config-revision.js";
22
import { normalizeCronJobCreate } from "../cron/normalize.js";
3+
import { createTrustedCronScheduledToolPolicy } from "../cron/scheduled-tool-policy.js";
34
import { applyDefaultCronToolsAllow } from "../cron/tools-allow.js";
45
import type { CronJob } from "../cron/types.js";
56
import {
@@ -42,6 +43,7 @@ export type ClawCronGateway = {
4243
get?: (schedulerJobId: string) => Promise<unknown>;
4344
list?: (agentId: string) => Promise<unknown>;
4445
remove: (schedulerJobId: string) => Promise<unknown>;
46+
waitUntilAgentAvailable?: (agentId: string) => Promise<void>;
4547
};
4648

4749
export class ClawCronInstallError extends Error {
@@ -256,10 +258,16 @@ export function clawCronGatewayJobMatchesRef(
256258
const comparableLive = { ...live, payload: { ...live.payload } } as CronJob;
257259
applyDefaultCronToolsAllow(expected);
258260
applyDefaultCronToolsAllow(comparableLive);
261+
const expectedWithPolicy = {
262+
...expected,
263+
...(comparableLive.scheduledToolPolicy
264+
? { scheduledToolPolicy: createTrustedCronScheduledToolPolicy() }
265+
: {}),
266+
};
259267
try {
260268
return (
261269
resolveCronJobConfigRevision({
262-
...expected,
270+
...expectedWithPolicy,
263271
id: live.id,
264272
createdAtMs: live.createdAtMs,
265273
updatedAtMs: live.updatedAtMs,
@@ -274,7 +282,7 @@ export function clawCronGatewayJobMatchesRef(
274282
export async function installClawCronJobs(
275283
plan: ClawAddPlan,
276284
options: OpenClawStateDatabaseOptions & {
277-
gateway?: Pick<ClawCronGateway, "add" | "list">;
285+
gateway?: Pick<ClawCronGateway, "add" | "list" | "waitUntilAgentAvailable">;
278286
nowMs?: number;
279287
} = {},
280288
): Promise<PersistedClawCronRef[]> {
@@ -290,6 +298,7 @@ export async function installClawCronJobs(
290298
);
291299
}
292300
const refs: PersistedClawCronRef[] = [];
301+
let agentAvailable = false;
293302
for (const action of actions) {
294303
const details = action.details as (ClawCronJob & { agentId?: string }) | undefined;
295304
if (!details?.id) {
@@ -314,6 +323,10 @@ export async function installClawCronJobs(
314323
}
315324
let result: { id: string } | undefined;
316325
try {
326+
if (!agentAvailable) {
327+
await options.gateway.waitUntilAgentAvailable?.(plan.agent.finalId);
328+
agentAvailable = true;
329+
}
317330
if (options.gateway.list) {
318331
result = schedulerJobByDeclarationKey(
319332
await options.gateway.list(plan.agent.finalId),

‎src/claws/lifecycle-config-removal.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ export async function claimClawAgentConfigRemoval(params: {
9595
try {
9696
const committed = await deleteAgentConfigEntry({
9797
agentId: params.agentId,
98+
allowConfigSizeDrop: true,
9899
allowMissing: params.expectedState === "missing",
99100
fallbackWorkspace: params.fallbackWorkspace,
100101
validateConfig: (config) => {

‎src/claws/lifecycle-state.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ describe("Claw status and remove", () => {
456456
});
457457
});
458458

459-
it("accepts the scheduler's default tool cap when removing a Claw cron job", async () => {
459+
it("accepts scheduler defaults when removing a Claw cron job", async () => {
460460
const current = await addFixture({ withCron: true });
461461
const plan = await buildClawRemovePlan("worker", {
462462
env: current.env,
@@ -475,6 +475,7 @@ describe("Claw status and remove", () => {
475475
get: async () => ({
476476
...live,
477477
payload: { ...live.payload, toolsAllow: ["*"] },
478+
scheduledToolPolicy: { version: 1, mode: "trusted" },
478479
}),
479480
remove,
480481
},
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { sleep } from "../utils/sleep.js";
2+
import { callGatewayFromCli } from "./gateway-rpc.js";
3+
4+
const CLAW_AGENT_RELOAD_TIMEOUT_MS = 15_000;
5+
const CLAW_AGENT_RELOAD_POLL_MS = 100;
6+
7+
export async function waitUntilGatewayConfigApplied(): Promise<void> {
8+
const deadline = Date.now() + CLAW_AGENT_RELOAD_TIMEOUT_MS;
9+
let lastError: unknown;
10+
while (Date.now() < deadline) {
11+
try {
12+
const response = (await callGatewayFromCli("config.get", { timeout: "5000" }, {})) as {
13+
configRevisionHash?: unknown;
14+
appliedConfigHash?: unknown;
15+
};
16+
if (
17+
typeof response.configRevisionHash === "string" &&
18+
response.configRevisionHash === response.appliedConfigHash
19+
) {
20+
return;
21+
}
22+
lastError = undefined;
23+
} catch (error) {
24+
lastError = error;
25+
}
26+
await sleep(CLAW_AGENT_RELOAD_POLL_MS);
27+
}
28+
const suffix = lastError instanceof Error ? `: ${lastError.message}` : "";
29+
throw new Error(`Gateway did not apply the Claw agent configuration in time${suffix}`);
30+
}

‎src/cli/claws-cli.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
} from "../cron/store.js";
4545
import { redactSensitiveText } from "../logging/redact.js";
4646
import { defaultRuntime, writeRuntimeJson, type RuntimeEnv } from "../runtime.js";
47+
import { waitUntilGatewayConfigApplied } from "./claws-cli.gateway-readiness.js";
4748
import type {
4849
ClawsAddOptions,
4950
ClawsExportOptions,
@@ -349,6 +350,7 @@ export async function runClawsAddCommand(
349350
add: async (input) => await callGatewayFromCli("cron.add", {}, input),
350351
list: async (agentId) =>
351352
await callGatewayFromCli("cron.list", {}, { agentId, includeDisabled: true }),
353+
waitUntilAgentAvailable: async () => await waitUntilGatewayConfigApplied(),
352354
},
353355
});
354356
} catch (error) {

‎src/cli/claws-cli.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ const mocks = vi.hoisted(() => {
3737
applyClawUpdatePlan: vi.fn(),
3838
buildClawUpdatePlan: vi.fn(),
3939
exportClawAgent: vi.fn(),
40+
callGatewayFromCli: vi.fn(),
41+
sleep: vi.fn(),
4042
};
4143
});
4244

@@ -58,6 +60,14 @@ vi.mock("../config/mcp-config.js", async () => ({
5860
listConfiguredMcpServers: mocks.listConfiguredMcpServers,
5961
}));
6062

63+
vi.mock("./gateway-rpc.js", () => ({
64+
callGatewayFromCli: mocks.callGatewayFromCli,
65+
}));
66+
67+
vi.mock("../utils/sleep.js", () => ({
68+
sleep: mocks.sleep,
69+
}));
70+
6171
vi.mock("../state/openclaw-state-db.js", async () => ({
6272
...(await vi.importActual<typeof import("../state/openclaw-state-db.js")>(
6373
"../state/openclaw-state-db.js",
@@ -95,6 +105,7 @@ vi.mock("../claws/update-apply.js", async () => ({
95105
}));
96106

97107
const { registerClawsCli } = await import("./claws-cli.js");
108+
const { waitUntilGatewayConfigApplied } = await import("./claws-cli.gateway-readiness.js");
98109
const { runClawsAddCommand } = await import("./claws-cli.runtime.js");
99110
const { ClawUpdateMutationError } = await import("../claws/update-apply.js");
100111
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
@@ -178,6 +189,9 @@ describe("claws cli", () => {
178189
config: {},
179190
mcpServers: {},
180191
});
192+
mocks.callGatewayFromCli.mockReset();
193+
mocks.sleep.mockReset();
194+
mocks.sleep.mockResolvedValue(undefined);
181195
mocks.closeReadOnlyDatabase.mockReset();
182196
mocks.stateTableGet.mockReset();
183197
mocks.stateTableGet.mockReturnValue({ 1: 1 });
@@ -312,6 +326,7 @@ describe("claws cli", () => {
312326
});
313327

314328
afterEach(() => {
329+
vi.restoreAllMocks();
315330
closeOpenClawStateDatabaseForTest();
316331
});
317332

@@ -339,6 +354,49 @@ describe("claws cli", () => {
339354
]);
340355
});
341356

357+
it("accepts an already-applied Gateway config revision", async () => {
358+
mocks.callGatewayFromCli.mockResolvedValue({
359+
configRevisionHash: "revision-new",
360+
appliedConfigHash: "revision-new",
361+
});
362+
363+
await expect(waitUntilGatewayConfigApplied()).resolves.toBeUndefined();
364+
365+
expect(mocks.callGatewayFromCli).toHaveBeenCalledOnce();
366+
expect(mocks.callGatewayFromCli).toHaveBeenCalledWith("config.get", { timeout: "5000" }, {});
367+
expect(mocks.sleep).not.toHaveBeenCalled();
368+
});
369+
370+
it("retries until the Gateway applies the persisted config revision", async () => {
371+
mocks.callGatewayFromCli
372+
.mockResolvedValueOnce({
373+
configRevisionHash: "revision-new",
374+
appliedConfigHash: "revision-old",
375+
})
376+
.mockResolvedValueOnce({
377+
configRevisionHash: "revision-new",
378+
appliedConfigHash: "revision-new",
379+
});
380+
381+
await expect(waitUntilGatewayConfigApplied()).resolves.toBeUndefined();
382+
383+
expect(mocks.callGatewayFromCli).toHaveBeenCalledTimes(2);
384+
expect(mocks.sleep).toHaveBeenCalledOnce();
385+
expect(mocks.sleep).toHaveBeenCalledWith(100);
386+
});
387+
388+
it("reports the last Gateway error after the reload deadline", async () => {
389+
vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(15_000);
390+
mocks.callGatewayFromCli.mockRejectedValue(new Error("gateway unavailable"));
391+
392+
await expect(waitUntilGatewayConfigApplied()).rejects.toThrow(
393+
"Gateway did not apply the Claw agent configuration in time: gateway unavailable",
394+
);
395+
396+
expect(mocks.callGatewayFromCli).toHaveBeenCalledOnce();
397+
expect(mocks.sleep).toHaveBeenCalledOnce();
398+
});
399+
342400
it("prints versioned experimental JSON for a development manifest", async () => {
343401
const manifestPath = await writeManifest();
344402

‎src/gateway/server-methods/agents-config-mutations.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,18 @@ export async function deleteAgentConfigEntry(params: {
6060
validate?: (agent: AgentConfig) => void;
6161
validateConfig?: (config: OpenClawConfig) => void;
6262
allowMissing?: boolean;
63+
allowConfigSizeDrop?: boolean;
6364
fallbackWorkspace?: string;
6465
}): Promise<{
6566
nextConfig: OpenClawConfig;
6667
result: AgentDeleteMutationResult | undefined;
6768
}> {
6869
const committed = await mutateConfigFileWithRetry<AgentDeleteMutationResult | undefined>({
6970
afterWrite: { mode: "auto" },
70-
writeOptions: { allowedAgentRosterRemovals: [params.agentId] },
71+
writeOptions: {
72+
allowedAgentRosterRemovals: [params.agentId],
73+
...(params.allowConfigSizeDrop ? { allowConfigSizeDrop: true } : {}),
74+
},
7175
mutate: (draft) => {
7276
params.validateConfig?.(draft);
7377
const configured = isConfiguredAgent(draft, params.agentId);

0 commit comments

Comments
 (0)