Skip to content

Commit 24898ba

Browse files
authored
fix(workers): repair cloud session lifecycle and recovery (#121564)
* fix(workers): repair cloud session lifecycle and recovery * test(workers): preserve dual-mode provider dispatch coverage * refactor(workers): centralize inherited profile authorization
1 parent 55cd6fe commit 24898ba

20 files changed

Lines changed: 631 additions & 110 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ Use `cloudWorkers.projectProfiles` to select a default profile from a managed se
128128
}
129129
```
130130

131-
An explicit `profileId` or `deviceId` in `sessions.dispatch` always wins. A target-less project-profile lookup requires `operator.admin`. If a configured mapping names a profile that is not present in `cloudWorkers.profiles`, dispatch fails closed and names both the repository key and missing profile. A worktree with no `origin` or no matching mapping returns a typed `INVALID_REQUEST` without provisioning or falling back to another target.
131+
An explicit `profileId` or `deviceId` in `sessions.dispatch` always wins. A target-less project-profile lookup requires `operator.admin`. Deleting a profile from the Cloud workers settings also removes project defaults that reference it. If a manually configured mapping names a profile that is not present in `cloudWorkers.profiles`, dispatch fails closed and names both the repository key and missing profile. A worktree with no `origin` or no matching mapping returns a typed `INVALID_REQUEST` without provisioning or falling back to another target.
132132

133133
The enrolled node stores its identity, durable device token, endpoint, worker bundles, and workspaces under an isolated per-lease state directory on the disposable box. Provision replay first adopts the fixed Crabbox lease, then either resumes that node state or reuses the still-pending setup credential. It never mints a second environment identity for the same operation.
134134

@@ -286,7 +286,7 @@ local Codex turn claim without waiting for an acknowledgment from the offline
286286
node. If the device is already available, use the
287287
ordinary reconcile-first move instead.
288288

289-
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 deleting the session.
289+
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.
290290

291291
Archiving a non-main cloud-worker session with an active placement also performs this safe stop and reclaim before the Gateway records it as archived. If the placement is still transitioning or failed without proof that its environment is gone, the session remains unarchived; wait for the placement to settle, then retry. Restoring the session retains the reclaimed placement metadata so the next turn can dispatch a fresh worker with the same workspace profile.
292292

‎src/gateway/server-methods/sessions.dispatch.device.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,15 @@ function useDeviceSession(agentRuntimeOverride?: string): void {
4949
dispatchTestMocks.resolveTarget.mockReturnValue(
5050
makeSessionTarget({
5151
sessionId: dispatchTestSessionId,
52-
...(agentRuntimeOverride ? { agentRuntimeOverride } : {}),
52+
...(agentRuntimeOverride
53+
? {
54+
agentHarnessId: agentRuntimeOverride,
55+
agentRuntimeOverride,
56+
modelSelectionLocked: true,
57+
modelOverride: "gpt-test",
58+
providerOverride: "openai",
59+
}
60+
: {}),
5361
worktree: { id: "worktree-1", branch: "openclaw/device-test", repoRoot: "/repo" },
5462
}),
5563
);

‎src/gateway/server-methods/sessions.dispatch.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,8 @@ describe("sessions.dispatch", () => {
406406
targetWithEntry({
407407
sessionId,
408408
agentRuntimeOverride: "codex",
409+
providerOverride: "openai",
410+
modelOverride: "gpt-test",
409411
worktree: { id: "worktree-1", branch: "openclaw/cloud-test", repoRoot: "/repo" },
410412
}),
411413
);
@@ -455,6 +457,8 @@ describe("sessions.dispatch", () => {
455457
targetWithEntry({
456458
sessionId,
457459
agentRuntimeOverride: "codex",
460+
providerOverride: "openai",
461+
modelOverride: "gpt-test",
458462
worktree: { id: "worktree-1", branch: "openclaw/cloud-test", repoRoot: "/repo" },
459463
}),
460464
);

‎src/gateway/server.sessions.worker-placement-lifecycle.test.ts‎

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import type {
2222
WorkerSessionPlacementRetirementService,
2323
WorkerSessionPlacementStore,
2424
} from "./worker-environments/placement-store.js";
25+
import { resolveSessionWorkerPlacementMutationError } from "./worker-environments/session-placement-lifecycle.js";
2526

2627
const { createSessionStoreDir, seedActiveMainSession } = setupGatewaySessionsHandlerTestHarness();
2728

@@ -148,6 +149,35 @@ function sequencedPlacementService(
148149
};
149150
}
150151

152+
test.each([
153+
{ action: "fork" as const, allowed: true },
154+
{ action: "restore" as const, allowed: false },
155+
{ action: "rewind" as const, allowed: false },
156+
{ action: "switch" as const, allowed: false },
157+
])("stopped cloud placement only permits identity-preserving $action", ({ action, allowed }) => {
158+
for (const state of ["reclaimed", "failed"] as const) {
159+
const sessionId = `stopped-${state}-${action}`;
160+
const placement = terminalPlacementRecord(sessionId, state);
161+
const placementService = sequencedPlacementService([placement]);
162+
const error = resolveSessionWorkerPlacementMutationError({
163+
action,
164+
context: {
165+
workerEnvironmentService: { get: () => ({ state: "destroyed" }) } as never,
166+
workerSessionPlacementService: placementService,
167+
},
168+
key: placement.sessionKey,
169+
sessionId,
170+
});
171+
172+
if (allowed) {
173+
expect(error).toBeUndefined();
174+
} else {
175+
expect(error?.message).toContain(`cannot ${action} while cloud worker placement is ${state}`);
176+
}
177+
expect(placementService.retireSessionPlacement).not.toHaveBeenCalled();
178+
}
179+
});
180+
151181
async function beginClaimedLocalTurn(params: {
152182
events: string[];
153183
onInterrupt?: () => void;
@@ -576,13 +606,35 @@ test.each([
576606
name: "ordinary reset",
577607
sessionKey: "discord:group:local-reset",
578608
incognito: false,
609+
state: "local" as const,
579610
},
580611
{
581612
name: "incognito reset",
582613
sessionKey: "agent:main:dashboard:incognito-local-reset",
583614
incognito: true,
615+
state: "local" as const,
616+
},
617+
{
618+
name: "reclaimed cloud reset",
619+
sessionKey: "discord:group:reclaimed-reset",
620+
incognito: false,
621+
state: "reclaimed" as const,
622+
},
623+
{
624+
name: "failed cloud reset after worker destruction",
625+
sessionKey: "discord:group:destroyed-worker-reset",
626+
incognito: false,
627+
state: "failed" as const,
628+
environment: { state: "destroyed" },
584629
},
585-
])("sessions.reset retires the old local placement before $name", async (testCase) => {
630+
{
631+
name: "failed cloud reset after proven bootstrap teardown",
632+
sessionKey: "discord:group:failed-worker-reset",
633+
incognito: false,
634+
state: "failed" as const,
635+
environment: { state: "failed", leaseId: null },
636+
},
637+
])("sessions.reset retires the old placement before $name", async (testCase) => {
586638
await createSessionStoreDir();
587639
const sessionId = testCase.incognito
588640
? await (async () => {
@@ -602,14 +654,25 @@ test.each([
602654
entries: { [testCase.sessionKey]: sessionStoreEntry(sessionId) },
603655
});
604656
}
605-
const placementService = sequencedPlacementService([placementRecord(sessionId, "local")], () => {
657+
const placement =
658+
testCase.state === "local"
659+
? placementRecord(sessionId, "local")
660+
: terminalPlacementRecord(sessionId, testCase.state);
661+
const placementService = sequencedPlacementService([placement], () => {
606662
expect(loadSessionEntry(testCase.sessionKey).entry?.sessionId).toBe(sessionId);
607663
});
608664

609665
const reset = await directSessionReq(
610666
"sessions.reset",
611667
{ key: testCase.sessionKey },
612-
{ context: { workerSessionPlacementService: placementService } },
668+
{
669+
context: {
670+
...(testCase.state === "failed"
671+
? { workerEnvironmentService: { get: () => testCase.environment } as never }
672+
: {}),
673+
workerSessionPlacementService: placementService,
674+
},
675+
},
613676
);
614677

615678
if (!reset.ok) {
@@ -618,8 +681,8 @@ test.each([
618681
expect(placementService.retireSessionPlacement).toHaveBeenCalledWith({
619682
status: "retirement-required",
620683
sessionId,
621-
expectedState: "local",
622-
expectedGeneration: 0,
684+
expectedState: testCase.state,
685+
expectedGeneration: placement.generation,
623686
});
624687
expect(loadSessionEntry(testCase.sessionKey).entry === undefined).toBe(testCase.incognito);
625688
});

‎src/gateway/worker-environments/live-events.test.ts‎

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
claimAgentRunContext,
2525
clearAgentRunContext,
2626
getAgentRunContext,
27+
hasProjectedAgentRunForSession,
2728
releaseAgentRunContext,
2829
sweepStaleRunContexts,
2930
} from "../../infra/agent-run-registry.js";
@@ -651,28 +652,77 @@ describe("worker live events", () => {
651652
expect(deltas()).toEqual(["worker"]);
652653
});
653654

654-
it("adopts a visible dispatch-owned run context so worker live events stay visible", () => {
655+
it.each(["terminal process turnover", "detach"])(
656+
"clears an ownerless Gateway run context on %s",
657+
(settledBy) => {
658+
claimAgentRunContext(RUN, {
659+
...LOCAL,
660+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
661+
});
662+
663+
ack(msg(1, "worker"));
664+
if (settledBy === "terminal process turnover") {
665+
ack(live(2, lifecycle({ phase: "end", startedAt: 100, endedAt: 200 })));
666+
expect(
667+
rx.rotateCredential({
668+
credentialHash: "next-process-credential-hash",
669+
environmentId: ID.environmentId,
670+
newProcessTurn: true,
671+
previousCredentialHash: ID.credentialHash,
672+
runEpoch: EPOCH,
673+
sessionId: SID,
674+
}),
675+
).toBe(true);
676+
} else {
677+
rx.clearEnvironment(ID.environmentId);
678+
}
679+
680+
expect(getAgentRunContext(RUN)).toBeUndefined();
681+
expect(hasProjectedAgentRunForSession({ sessionKeys: [KEY], sessionId: SID })).toBe(false);
682+
},
683+
);
684+
685+
it("joins a visible dispatch-owned run context without blocking its terminal", () => {
655686
const lifecycleGeneration = getAgentEventLifecycleGeneration();
656687
// A worker-routed turn keeps its dispatch-owned Control UI visibility. The
657688
// gateway claims the run context (isControlUiVisible: true for a visible
658-
// turn) before handing the turn to the remote worker; adopting live events
659-
// must inherit that visibility instead of forcing the run hidden.
689+
// turn) before handing the turn to the remote worker; joining live events
690+
// must inherit that visibility without excluding the outer terminal.
660691
claimAgentRunContext(RUN, {
661692
...LOCAL,
662693
isControlUiVisible: true,
663694
lifecycleGeneration,
664695
});
665696

666-
ack(msg(1, "worker"));
697+
ack(live(1, lifecycle({ phase: "start", startedAt: 100 })));
698+
ack(msg(2, "worker", 1));
699+
ack(live(3, lifecycle({ phase: "finishing", startedAt: 100, endedAt: 200 })));
667700

668701
expect(getAgentRunContext(RUN)).toMatchObject({
669702
...LOCAL,
670703
isControlUiVisible: true,
671704
lifecycleGeneration,
672705
projectSessionActive: true,
673706
});
674-
expect(deltas()).toEqual(["worker"]);
675-
expect(events[0]?.controlUiVisible).toBe(true);
707+
expect(hasProjectedAgentRunForSession({ sessionKeys: [KEY], sessionId: SID })).toBe(true);
708+
expect(events.map((event) => [event.stream, event.data.phase ?? event.data.delta])).toEqual([
709+
["lifecycle", "start"],
710+
["assistant", "worker"],
711+
["lifecycle", "finishing"],
712+
]);
713+
expect(events.map((event) => event.controlUiVisible)).toEqual([true, true, true]);
714+
715+
emitAgentEvent({
716+
runId: RUN,
717+
stream: "lifecycle",
718+
data: { phase: "end", startedAt: 100, endedAt: 200 },
719+
});
720+
721+
const end = events.at(-1);
722+
expect(end?.data.phase).toBe("end");
723+
clearAgentRunContext(RUN, end?.lifecycleGeneration, end?.contextClaimId);
724+
expect(getAgentRunContext(RUN)).toBeUndefined();
725+
expect(hasProjectedAgentRunForSession({ sessionKeys: [KEY], sessionId: SID })).toBe(false);
676726
});
677727

678728
it("shares a compatible non-exclusive Gateway run owner", () => {

‎src/gateway/worker-environments/live-events.ts‎

Lines changed: 9 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import {
1515
claimAgentRunContext,
1616
getAgentRunContext,
17+
getAgentRunContextOwnership,
1718
getAgentRunContextOwnerStatus,
1819
registerAgentRunContext,
1920
releaseAgentRunContext,
@@ -491,13 +492,9 @@ export function createWorkerLiveEventReceiver(options: WorkerLiveEventReceiverOp
491492
}
492493
const lifecycleGeneration = getAgentEventLifecycleGeneration();
493494
const existingContext = getAgentRunContext(runId);
494-
// A dispatch-owned turn context (e.g. a worker-routed turn) owns the run's
495-
// Control UI visibility; adopt it so worker live events keep reaching the
496-
// visible clients that started the turn. Identity still has to match, so a
497-
// foreign run is rejected; only the visibility preference is inherited. With
498-
// no pre-existing turn context we scope live events to this session.
495+
// Existing dispatch contexts must admit their outer terminal. Ownerless contexts still need
496+
// worker-owned cleanup so a definitive worker terminal cannot leave the session active.
499497
const controlUiVisible = existingContext?.isControlUiVisible ?? false;
500-
const adoptExistingUnowned = existingContext !== undefined;
501498
if (
502499
existingContext &&
503500
(existingContext.sessionId !== window.sessionId ||
@@ -508,8 +505,10 @@ export function createWorkerLiveEventReceiver(options: WorkerLiveEventReceiverOp
508505
) {
509506
return invalidEvent();
510507
}
511-
let emissionMode: OwnedLiveRun["emissionMode"] = "exclusive";
512-
let claimId = claimAgentRunContext(
508+
const hasExistingTrackedOwner =
509+
getAgentRunContextOwnership(runId)?.lifecycleGeneration === lifecycleGeneration;
510+
const emissionMode: OwnedLiveRun["emissionMode"] = existingContext ? "shared" : "exclusive";
511+
const claimId = claimAgentRunContext(
513512
runId,
514513
{
515514
...(window.target.agentId ? { agentId: window.target.agentId } : {}),
@@ -520,44 +519,16 @@ export function createWorkerLiveEventReceiver(options: WorkerLiveEventReceiverOp
520519
sessionKey: window.target.sessionKey,
521520
},
522521
{
523-
adoptExistingUnowned,
524-
exclusive: true,
522+
exclusive: existingContext === undefined,
525523
onClearRequested: (clearedClaimId) => {
526524
if (window.activeRuns.get(runId)?.claimId === clearedClaimId) {
527525
fenceReleasedRun(window, runId);
528526
}
529527
},
530-
ownsContext: true,
528+
ownsContext: !hasExistingTrackedOwner,
531529
trackOwner: true,
532530
},
533531
);
534-
if (!claimId && existingContext) {
535-
// Cron and other Gateway-owned handoffs retain a non-exclusive claim while the
536-
// assigned worker runs. Share only that corroborated identity; exclusive owners
537-
// still reject this claim and prevent a foreign execution from joining the run.
538-
claimId = claimAgentRunContext(
539-
runId,
540-
{
541-
...(window.target.agentId ? { agentId: window.target.agentId } : {}),
542-
isControlUiVisible: controlUiVisible,
543-
lifecycleGeneration,
544-
projectSessionActive: true,
545-
sessionId: window.sessionId,
546-
sessionKey: window.target.sessionKey,
547-
},
548-
{
549-
exclusive: false,
550-
onClearRequested: (clearedClaimId) => {
551-
if (window.activeRuns.get(runId)?.claimId === clearedClaimId) {
552-
fenceReleasedRun(window, runId);
553-
}
554-
},
555-
ownsContext: false,
556-
trackOwner: true,
557-
},
558-
);
559-
emissionMode = "shared";
560-
}
561532
if (!claimId) {
562533
return invalidEvent();
563534
}

0 commit comments

Comments
 (0)