Skip to content

Commit c17e476

Browse files
committed
fix: stop queued cloud work and persist canceled turns
Keep pending session admission owned across cloud worker Stop and route active cancellation through canonical terminal persistence before teardown. Preserve fresh post-Stop input and the existing two-step UI flow.
1 parent 46c1eef commit c17e476

22 files changed

Lines changed: 1816 additions & 610 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ local Codex turn claim without waiting for an acknowledgment from the offline
370370
node. If the device is already available, use the
371371
ordinary reconcile-first move instead.
372372

373-
When the work is complete and no turn is running, choose **Stop cloud worker…** from the same chip. The Gateway performs one final workspace reconciliation before it destroys the environment. A placement already in `draining` or `reconciling` is finishing teardown; wait for its badge to become `reclaimed` before resetting or deleting the session. Starting another turn after reclaim provisions a replacement worker only while its original cloud profile remains configured for the same provider; deleting that profile prevents new cloud allocation.
373+
To stop a running turn in the Control UI, use chat **Stop** or `/stop` first. Once no turn is running, choose **Stop cloud worker…** from the placement chip. The Gateway performs one final workspace reconciliation before it destroys the environment. A placement already in `draining` or `reconciling` is finishing teardown; wait for its badge to become `reclaimed` before resetting or deleting the session. Starting another turn after reclaim provisions a replacement worker only while its original cloud profile remains configured for the same provider; deleting that profile prevents new cloud allocation.
374374

375375
Archiving or deleting a non-main cloud-worker session with an active placement first interrupts and drains its current work, then safely reclaims the worker. The Gateway records the archive or deletion only after final reconciliation and safe teardown succeed. If reclaim is unavailable, fails, or the placement is transitioning or failed without proof that its environment is gone, the operation reports an error and retains the session and recovery state; it never force-discards unsynced work. Restoring an archived session retains reclaimed placement metadata so the next turn can dispatch a fresh worker with the same workspace profile.
376376

@@ -384,6 +384,8 @@ openclaw gateway call sessions.reclaim \
384384
--params '{"key":"agent:main:big-refactor"}'
385385
```
386386

387+
Calling `sessions.reclaim` while a turn is active cancels running and pending work and records the active turn’s stopped outcome before workspace reconciliation and teardown. Inputs already waiting, or submitted while reclaim is in progress, do not restart the worker when reclaim completes. Send a new message after reclaim finishes to start new work.
388+
387389
The result placement is `reclaimed` after an active worker is safely stopped. Reclaim also waits for an in-flight dispatch and retries pending teardown for a failed placement before returning `local`. No other placement states are successful reclaim results.
388390

389391
If provider teardown fails or times out during stop or move, the request reports that failure even if recovery subsequently finishes cleanup. Check the current placement before retrying. A dedicated cloud worker can remain recorded as attached while destruction is uncertain, but its closed authority cannot resume remote workspace processes.

‎src/gateway/server-methods/agent-expected-session.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export function assertExpectedExistingSession(params: {
6969
export function consumeExpectedSessionWorkAdmission(params: {
7070
constraint?: ExpectedExistingSessionConstraint;
7171
identities: Iterable<string | undefined>;
72-
onInterrupt: () => void;
72+
onInterrupt: (reason?: Error) => void;
7373
scope: string;
7474
}): SessionWorkAdmissionLease | undefined {
7575
const handoffId = params.constraint?.handoffId;

‎src/gateway/server-methods/chat-send-admission.ts‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import { randomUUID } from "node:crypto";
22
import { isFutureDateTimestampMs } from "@openclaw/normalization-core/number-coercion";
33
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
4-
import { createAgentRunRestartAbortError } from "../../agents/run-termination.js";
4+
import {
5+
createAgentRunRestartAbortError,
6+
isAgentRunDirectAbortReason,
7+
} from "../../agents/run-termination.js";
58
import { hasPendingFollowupQueueWork } from "../../auto-reply/reply/queue/state.js";
69
import {
710
interruptReplyRunTarget,
@@ -407,15 +410,35 @@ export async function admitChatSend(params: {
407410
identities: [sessionKey, backingSessionId],
408411
assertAllowed: () => assertChatWorkAdmissionAllowed(false),
409412
revalidateAllowed: () => assertChatWorkAdmissionAllowed(true),
410-
onInterrupt: () => {
411-
if (admittedRunAbort?.entry) {
412-
admittedRunAbort.entry.abortStopReason = "restart";
413+
onInterrupt: (reason) => {
414+
const stopReason = isAgentRunDirectAbortReason(reason) ? "rpc" : "restart";
415+
if (!admittedRunAbort) {
416+
if (!context.chatRunState.hasAbortMarker(clientRunId)) {
417+
writePreRegisteredChatAbort({
418+
context,
419+
runId: clientRunId,
420+
stopReason,
421+
attemptId: pendingAttemptId,
422+
});
423+
}
424+
} else if (!admittedRunAbort.controller.signal.aborted) {
425+
if (admittedRunAbort.entry) {
426+
admittedRunAbort.entry.abortStopReason = stopReason;
427+
}
428+
admittedRunAbort.controller.abort(
429+
stopReason === "rpc" ? reason : createAgentRunRestartAbortError(),
430+
);
413431
}
414-
admittedRunAbort?.controller.abort(createAgentRunRestartAbortError());
415432
},
416433
});
417434
} catch (err) {
418435
clearPendingChatSendReservation();
436+
const aborted =
437+
context.chatRunState.hasAbortMarker(clientRunId) && context.dedupe.get(`chat:${clientRunId}`);
438+
if (aborted) {
439+
respond(aborted.ok, aborted.payload, aborted.error, { cached: true, runId: clientRunId });
440+
return { ok: false as const };
441+
}
419442
if (err instanceof Error && err.message === "goal-session-busy") {
420443
respond(
421444
false,

‎src/gateway/server-runtime-state-prepare.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,15 @@ export async function prepareGatewayKernelState(params: {
223223
snapshots: [{ sessionId, agentId, runId, text, abortOrigin: "placement-abandon" }],
224224
});
225225
},
226+
cancelSessionWork: async (request) => {
227+
const context = pluginGatewayContext.current;
228+
if (!context) {
229+
throw new Error("Worker session cancellation is not ready");
230+
}
231+
const { cancelGatewayWorkerSessionWork } =
232+
await import("./server-worker-placement-cancel.js");
233+
await cancelGatewayWorkerSessionWork(context, request);
234+
},
226235
revokeSessionAuthority: (request) => workerDispatchAuthority.revoke(request),
227236
info: (message) => log.info(message),
228237
warn: (message) => log.warn(message),
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { expect, it, vi } from "vitest";
5+
import { createDeferred } from "../../test/helpers/promise.js";
6+
import {
7+
loadSessionEntry,
8+
replaceSessionEntry,
9+
patchSessionEntryCore,
10+
} from "../config/sessions/session-accessor.js";
11+
import { onAgentEvent } from "../infra/agent-events.js";
12+
import { clearAgentRunContext } from "../infra/agent-run-registry.js";
13+
import type { SubsystemLogger } from "../logging/subsystem.js";
14+
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
15+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
16+
import {
17+
createChatRunState,
18+
createSessionEventSubscriberRegistry,
19+
createSessionMessageSubscriberRegistry,
20+
} from "./server-chat-state.js";
21+
import { admitChatSend } from "./server-methods/chat-send-admission.js";
22+
import { startGatewayEventSubscriptions } from "./server-runtime-subscriptions.js";
23+
import { cancelGatewayWorkerSessionWork } from "./server-worker-placement-cancel.js";
24+
import { createGatewayWorkerPlacementReclaimBarriers } from "./server-worker-placement-reclaim.js";
25+
import { admitWorkerStopChat } from "./server-worker-placement.test-harness.js";
26+
const routing = vi.hoisted(() => ({ load: vi.fn() }));
27+
vi.mock("./session-utils.js", async (importOriginal) => ({
28+
...(await importOriginal<typeof import("./session-utils.js")>()),
29+
loadSessionEntry: routing.load,
30+
}));
31+
32+
it("Stop waits for canonical cancelled terminal persistence and rejects input arriving during that write", async () => {
33+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "worker-stop-terminal-"));
34+
const target = {
35+
storePath: path.join(root, "sessions.json"),
36+
sessionKey: "agent:main:terminal-stop",
37+
};
38+
const sessionId = "terminal-stop-session";
39+
const runId = "terminal-stop-run";
40+
const entry = {
41+
sessionId,
42+
worktree: { id: "terminal-worktree", branch: "test", repoRoot: root },
43+
updatedAt: Date.now(),
44+
};
45+
const events: Array<{ phase: unknown; status: unknown; aborted: unknown; stopReason: unknown }> =
46+
[];
47+
const chatRunState = createChatRunState();
48+
const log: SubsystemLogger = {
49+
subsystem: "test-terminal",
50+
child: () => log,
51+
isEnabled: () => false,
52+
trace: vi.fn(),
53+
debug: vi.fn(),
54+
info: vi.fn(),
55+
warn: vi.fn(),
56+
error: vi.fn(),
57+
fatal: vi.fn(),
58+
raw: vi.fn(),
59+
};
60+
const context = {
61+
dedupe: new Map(),
62+
chatRunState,
63+
chatAbortControllers: new Map(),
64+
chatQueuedTurns: new Map(),
65+
agentRunSeq: new Map(),
66+
getRuntimeConfig: () => ({}),
67+
removeChatRun: vi.fn(),
68+
broadcast: vi.fn(),
69+
nodeSendToSession: vi.fn(),
70+
cancelRunBoundApprovals: vi.fn(),
71+
logGateway: log,
72+
} as unknown as import("./server-methods/types.js").GatewayRequestContext;
73+
routing.load.mockImplementation(() => ({
74+
...target,
75+
canonicalKey: target.sessionKey,
76+
cfg: {},
77+
entry: loadSessionEntry(target),
78+
}));
79+
let subscriptions: ReturnType<typeof startGatewayEventSubscriptions> | undefined;
80+
let heldWriter: Promise<unknown> | undefined;
81+
let reclaim: Promise<unknown> | undefined;
82+
const writerEntered = createDeferred();
83+
const releaseWriter = createDeferred();
84+
const abortObserved = createDeferred();
85+
let placement = {
86+
sessionId,
87+
sessionKey: target.sessionKey,
88+
agentId: "main",
89+
state: "active" as "active" | "reclaimed",
90+
turnClaim: null,
91+
};
92+
let reclaimEffectStarted = false;
93+
let active: Awaited<ReturnType<typeof admitChatSend>> | undefined;
94+
const unsubscribe = onAgentEvent((event) => {
95+
if (event.runId === runId && event.stream === "lifecycle") {
96+
events.push({
97+
phase: event.data.phase,
98+
status: event.data.status,
99+
aborted: event.data.aborted,
100+
stopReason: event.data.stopReason,
101+
});
102+
}
103+
});
104+
const admit = (id: string) =>
105+
admitWorkerStopChat({
106+
context,
107+
storePath: target.storePath,
108+
sessionKey: target.sessionKey,
109+
sessionId,
110+
agentId: "main",
111+
entry,
112+
runId: id,
113+
}).promise;
114+
try {
115+
await replaceSessionEntry(target, entry);
116+
subscriptions = startGatewayEventSubscriptions({
117+
log,
118+
broadcast: context.broadcast,
119+
broadcastToConnIds: vi.fn(),
120+
nodeSendToSession: context.nodeSendToSession,
121+
agentRunSeq: context.agentRunSeq,
122+
chatRunState,
123+
toolEventRecipients: chatRunState.toolEventRecipients,
124+
sessionEventSubscribers: createSessionEventSubscriberRegistry(),
125+
sessionMessageSubscribers: createSessionMessageSubscriberRegistry(),
126+
chatAbortControllers: context.chatAbortControllers,
127+
restartRecoveryCandidates: new Map(),
128+
terminalSessions: { closeTaskSessions: vi.fn() },
129+
});
130+
active = await admit(runId);
131+
expect(active.ok).toBe(true);
132+
if (!active.ok) {
133+
throw new Error("active admission missing");
134+
}
135+
const owned = active.value;
136+
await replaceSessionEntry(target, {
137+
...entry,
138+
status: "running",
139+
lifecycleRunId: runId,
140+
startedAt: Date.now(),
141+
});
142+
owned.activeRunAbort.controller.signal.addEventListener(
143+
"abort",
144+
() => {
145+
owned.cleanupAdmittedRun();
146+
abortObserved.resolve();
147+
},
148+
{ once: true },
149+
);
150+
heldWriter = patchSessionEntryCore(target, async () => {
151+
writerEntered.resolve();
152+
await releaseWriter.promise;
153+
return null;
154+
});
155+
await writerEntered.promise;
156+
const sessionTarget = {
157+
storePath: target.storePath,
158+
canonicalKey: target.sessionKey,
159+
storeKeys: [target.sessionKey],
160+
agentId: "main",
161+
store: { [target.sessionKey]: entry },
162+
};
163+
const barriers = createGatewayWorkerPlacementReclaimBarriers({
164+
placements: { get: () => placement as never, waitForTurnClaimRelease: async () => {} },
165+
loadSessionRuntime: async () =>
166+
({
167+
managedWorktrees: {
168+
findLiveByOwner: () => ({
169+
id: "terminal-worktree",
170+
ownerId: target.sessionKey,
171+
path: root,
172+
}),
173+
},
174+
resolveGatewaySessionStoreTargetWithStore: () => sessionTarget,
175+
resolveCanonicalSessionEntryFromStoreKeys: () => entry,
176+
}) as never,
177+
cancelSessionWork: (request) => cancelGatewayWorkerSessionWork(context, request),
178+
revokeSessionAuthority: vi.fn(),
179+
});
180+
reclaim = barriers.runReclaimBarrier({
181+
sessionId,
182+
sessionKey: target.sessionKey,
183+
agentId: "main",
184+
begin: () => ({ ...placement, state: "draining" }) as never,
185+
reclaim: async () => {
186+
reclaimEffectStarted = true;
187+
expect(loadSessionEntry(target)).toMatchObject({
188+
status: "killed",
189+
lastRunId: runId,
190+
abortedLastRun: true,
191+
});
192+
placement = { ...placement, state: "reclaimed" };
193+
return placement as never;
194+
},
195+
});
196+
await abortObserved.promise;
197+
expect(context.chatAbortControllers.has(runId)).toBe(true);
198+
expect(owned.activeRunAbort.entry?.projectSessionTerminalPersistence).toBeInstanceOf(Promise);
199+
expect(reclaimEffectStarted).toBe(false);
200+
expect(loadSessionEntry(target)?.status).toBe("running");
201+
const late = await admit("during-terminal-write");
202+
expect(late.ok).toBe(false);
203+
expect(
204+
(
205+
context.dedupe.get("chat:during-terminal-write")?.payload as
206+
| { summary?: string }
207+
| undefined
208+
)?.summary,
209+
).toBe("aborted");
210+
releaseWriter.resolve();
211+
await heldWriter;
212+
await reclaim;
213+
expect(events.filter((event) => event.phase === "end")).toEqual([
214+
{ phase: "end", status: "cancelled", aborted: true, stopReason: "rpc" },
215+
]);
216+
expect(context.chatAbortControllers.has(runId)).toBe(false);
217+
closeOpenClawAgentDatabasesForTest();
218+
const persisted = loadSessionEntry({ ...target, readConsistency: "latest" });
219+
expect(persisted).toMatchObject({ status: "killed", lastRunId: runId, abortedLastRun: true });
220+
expect(persisted?.endedAt).toBeTypeOf("number");
221+
const fresh = await admit("explicit-after-terminal-stop");
222+
expect(fresh.ok).toBe(true);
223+
if (fresh.ok) {
224+
fresh.value.cleanupAdmittedRun({ force: true });
225+
clearAgentRunContext("explicit-after-terminal-stop", fresh.value.lifecycleGeneration);
226+
}
227+
} finally {
228+
releaseWriter.resolve();
229+
await heldWriter;
230+
await reclaim?.catch(() => {});
231+
if (active?.ok) {
232+
active.value.cleanupAdmittedRun({ force: true });
233+
clearAgentRunContext(runId, active.value.lifecycleGeneration);
234+
}
235+
unsubscribe();
236+
await subscriptions?.agentUnsub();
237+
subscriptions?.heartbeatUnsub();
238+
subscriptions?.transcriptUnsub();
239+
subscriptions?.lifecycleUnsub();
240+
await subscriptions?.taskUnsub();
241+
closeOpenClawAgentDatabasesForTest();
242+
closeOpenClawStateDatabaseForTest();
243+
routing.load.mockReset();
244+
await fs.rm(root, { recursive: true, force: true });
245+
}
246+
});
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { SESSION_WORK_ADMISSION_DRAIN_TIMEOUT_MS } from "../sessions/session-lifecycle-admission.js";
2+
import { waitForChatAbortControllerRemoval } from "./chat-abort-lifecycle-internal.js";
3+
import {
4+
abortChatRunsForSessionKeyWithPartials,
5+
createChatAbortOps,
6+
} from "./server-methods/chat-abort-runtime.js";
7+
import type { GatewayRequestContext } from "./server-methods/types.js";
8+
9+
export type WorkerPlacementSessionWorkCancellation = (request: {
10+
sessionId: string;
11+
sessionKeys: readonly string[];
12+
agentId: string;
13+
assertCurrent: () => void;
14+
}) => Promise<void>;
15+
16+
export async function cancelGatewayWorkerSessionWork(
17+
context: GatewayRequestContext,
18+
request: Parameters<WorkerPlacementSessionWorkCancellation>[0],
19+
): Promise<void> {
20+
request.assertCurrent();
21+
let controllerDrain = Promise.resolve(true);
22+
const aborted = await abortChatRunsForSessionKeyWithPartials({
23+
context,
24+
ops: createChatAbortOps(context),
25+
sessionId: request.sessionId,
26+
sessionKey: request.sessionKeys[0]!,
27+
sessionKeyAliases: request.sessionKeys.slice(1),
28+
agentId: request.agentId,
29+
// The revalidated session lifecycle owns every run on this resource, just as
30+
// archive/delete do; these internal flags do not elevate the RPC caller.
31+
requester: { isAdmin: true },
32+
includeProtectedRuns: true,
33+
abortOrigin: "rpc",
34+
stopReason: "rpc",
35+
onControllerTargets: (targets) => {
36+
controllerDrain = waitForChatAbortControllerRemoval({
37+
entries: context.chatAbortControllers,
38+
targets,
39+
timeoutMs: SESSION_WORK_ADMISSION_DRAIN_TIMEOUT_MS,
40+
});
41+
},
42+
});
43+
if (aborted.unauthorized || !(await controllerDrain)) {
44+
throw new Error("Session cancellation did not persist before cloud worker stop");
45+
}
46+
}

0 commit comments

Comments
 (0)