Skip to content

Commit 57e8629

Browse files
authored
feat(gateway): carry machine class through session moves (#125292)
* feat(gateway): carry machine class through session moves Profile move targets accept an optional machineClass with new-session parity: validated in the protocol, persisted on the durable move intent (bare nullable column, lazy same-version ALTER), replayed exactly by restart recovery, and selectable from the Control UI move dialog. Moving to the current profile with a different class resizes the session's worker. * fix(gateway): project placement facts on chat startup chat.startup and chat.history built sessionInfo without the placement projection sessions.list applies, so clients merging that row erased a live worker placement and its move intent — the Runs on Cloud chip disappeared after any turn until a full reload. Reuse the canonical ensureColumn helper for the move table's additive column instead of a hand-rolled PRAGMA read.
1 parent 8a7b6aa commit 57e8629

19 files changed

Lines changed: 446 additions & 46 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7877,25 +7877,29 @@ public struct SessionMoveGatewayTarget: Codable, Sendable {
78777877
public struct SessionMoveProfileTarget: Codable, Sendable {
78787878
public let kind: String
78797879
public let profileid: String
7880+
public let machineclass: String?
78807881

78817882
public init(
7882-
profileid: String
7883+
profileid: String,
7884+
machineclass: String? = nil
78837885
)
78847886
{
78857887
self.kind = "profile"
78867888
self.profileid = profileid
7889+
self.machineclass = machineclass
78877890
}
78887891

78897892
private enum CodingKeys: String, CodingKey {
78907893
case kind
78917894
case profileid = "profileId"
7895+
case machineclass = "machineClass"
78927896
}
78937897

78947898
public init(from decoder: Decoder) throws {
78957899
let rawContainer = try decoder.container(keyedBy: GatewayAnyCodingKey.self)
78967900
let unexpectedKeys = rawContainer.allKeys
78977901
.map(\.stringValue)
7898-
.filter { !Set(["kind", "profileId"]).contains($0) }
7902+
.filter { !Set(["kind", "profileId", "machineClass"]).contains($0) }
78997903
if !unexpectedKeys.isEmpty {
79007904
throw DecodingError.dataCorrupted(
79017905
.init(
@@ -7915,12 +7919,14 @@ public struct SessionMoveProfileTarget: Codable, Sendable {
79157919
}
79167920
self.kind = "profile"
79177921
self.profileid = try container.decode(String.self, forKey: .profileid)
7922+
self.machineclass = try container.decodeIfPresent(String.self, forKey: .machineclass)
79187923
}
79197924

79207925
public func encode(to encoder: Encoder) throws {
79217926
var container = encoder.container(keyedBy: CodingKeys.self)
79227927
try container.encode("profile", forKey: .kind)
79237928
try container.encode(profileid, forKey: .profileid)
7929+
try container.encodeIfPresent(machineclass, forKey: .machineclass)
79247930
}
79257931
}
79267932

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ Apply uses the dispatch-time manifest as the merge base. Cloud-only changes are
195195

196196
While a fenced result is still reconciling, a new turn waits up to 15 seconds for the prior claim to release. If it is still busy, the turn fails with an actionable “previous cloud turn's workspace result is still reconciling” message and can be retried shortly. On restart, recovery discovers pending and staged results before stale-claim cleanup, completes or retries their local apply, and reclaims dead environments only after preserving the result. The bounded SQLite rollback journal makes an interrupted filesystem apply recoverable without replaying already accepted mutations.
197197

198-
To continue the same session somewhere else, open the **Runs on Cloud** chip and choose **Move session…**. Select the Gateway, a paired device, or another configured cloud profile. The Gateway closes new admission, interrupts any active turn, reconciles the source workspace, destroys the old environment, and then activates the destination. An interrupted turn is never replayed: partial output may disappear, and you send the next turn again after the move. Move intent and bounded errors are durable, so the Control UI shows **Moving to…** or the recovery error after a reconnect, and Gateway restart recovery resumes the same operation before generic placement cleanup.
198+
To continue the same session somewhere else, open the **Runs on Cloud** chip and choose **Move session…**. Select the Gateway, a paired device, or a configured cloud profile and, when available, its machine class. Moving to the current profile with a different class resizes the session by replacing its worker. The Gateway closes new admission, interrupts any active turn, reconciles the source workspace, destroys the old environment, and then activates the destination. An interrupted turn is never replayed: partial output may disappear, and you send the next turn again after the move. The exact target, including a machine override, and bounded errors are durable, so the Control UI shows **Moving to…** or the recovery error after a reconnect, and Gateway restart recovery resumes the same operation before generic placement cleanup.
199199

200200
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.
201201

@@ -221,7 +221,7 @@ openclaw gateway call sessions.move \
221221
--params '{"key":"agent:main:big-refactor","expected":{"generation":5,"environmentId":"worker:source","ownerEpoch":2},"target":{"kind":"gateway"}}'
222222
```
223223

224-
Worker targets use `{"kind":"profile","profileId":"aws"}` or `{"kind":"device","deviceId":"paired-device-id"}`. A stale source is rejected rather than moving a newer placement. Successful results end in `local` for the Gateway target or `active` for a worker target.
224+
Worker targets use `{"kind":"profile","profileId":"aws","machineClass":"fast"}` or `{"kind":"device","deviceId":"paired-device-id"}`. Omit `machineClass` to use the profile default. Moving to the same profile with a different class is the resize workflow. A stale source is rejected rather than moving a newer placement. Successful results end in `local` for the Gateway target or `active` for a worker target.
225225

226226
Placement moves through a durable state machine (`local → requested → provisioning → syncing → starting → active`), so a Gateway restart mid-dispatch reconciles instead of leaking machines. A failed model turn keeps the active placement available for a retry. Workspace path conflicts keep the local version, apply the rest of the cloud result, and preserve the staged cloud ref for inspection; other reconciliation or lifecycle failures retain their durable recovery fence and diagnostic tail until recovery can safely retry or reclaim the environment.
227227

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ The sidebar organizes everything around the agent. The identity row at the top i
228228

229229
### Session placement
230230

231-
A selected session running on a worker shows a quiet **Runs on Cloud** chip in the chat header. Open it and choose **Move session…** to continue on the Gateway, an eligible paired device, or another configured cloud profile. The confirmation explains that an active turn is interrupted and never replayed; OpenClaw reconciles the workspace before activating the destination. While the durable operation is in progress, the chip shows **Moving to…**. If recovery is blocked, the chip exposes the bounded error after reconnect so the action never fails silently. **Stop cloud worker…** remains the destructive action for returning the session to a reclaimed state without immediately selecting another runner.
231+
A selected session running on a worker shows a quiet **Runs on Cloud** chip in the chat header. Open it and choose **Move session…** to continue on the Gateway, an eligible paired device, or a configured cloud profile. Profiles with multiple machine classes show a machine picker; choosing the default omits an override, while choosing a different class on the current profile resizes the session. The confirmation explains that an active turn is interrupted and never replayed; OpenClaw reconciles the workspace before activating the destination. While the durable operation is in progress, the chip shows **Moving to…**. If recovery is blocked, the chip exposes the bounded error after reconnect so the action never fails silently. **Stop cloud worker…** remains the destructive action for returning the session to a reclaimed state without immediately selecting another runner.
232232

233233
### Session icons
234234

‎packages/gateway-protocol/src/schema/session-placement.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ describe("session dispatch protocol schemas", () => {
364364

365365
it.each([
366366
{ kind: "gateway" },
367-
{ kind: "profile", profileId: "development" },
367+
{ kind: "profile", profileId: "development", machineClass: "beast" },
368368
{ kind: "device", deviceId: "device-1" },
369369
] as const)("accepts the closed $kind move target", (target) => {
370370
expect(
@@ -384,9 +384,18 @@ describe("session dispatch protocol schemas", () => {
384384
validateSessionsMoveParams({
385385
key: "agent:main:dispatch",
386386
expected: { generation: 4, environmentId: accepted, ownerEpoch: 7 },
387-
target: { kind: "profile", profileId: accepted },
387+
target: { kind: "profile", profileId: accepted, machineClass: "x".repeat(128) },
388388
}),
389389
).toBe(true);
390+
for (const machineClass of ["", "x".repeat(129)]) {
391+
expect(
392+
validateSessionsMoveParams({
393+
key: "agent:main:dispatch",
394+
expected: { generation: 4, environmentId: "environment-1", ownerEpoch: 7 },
395+
target: { kind: "profile", profileId: "development", machineClass },
396+
}),
397+
).toBe(false);
398+
}
390399
for (const value of [rejected, " leading", "trailing "]) {
391400
expect(
392401
validateSessionsMoveParams({
@@ -407,9 +416,11 @@ describe("session dispatch protocol schemas", () => {
407416

408417
it.each([
409418
{ kind: "gateway", profileId: "development" },
419+
{ kind: "gateway", machineClass: "beast" },
410420
{ kind: "profile" },
411421
{ kind: "profile", profileId: "development", deviceId: "device-1" },
412422
{ kind: "device" },
423+
{ kind: "device", deviceId: "device-1", machineClass: "beast" },
413424
{ kind: "other" },
414425
])("rejects an invalid or mixed move target %#", (target) => {
415426
expect(

‎packages/gateway-protocol/src/schema/session-placement.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ export const SessionMoveGatewayTargetSchema = closedObject({
253253
export const SessionMoveProfileTargetSchema = closedObject({
254254
kind: Type.Literal("profile"),
255255
profileId: WorkerIdentifierSchema,
256+
machineClass: Type.Optional(WorkerMachineClassSchema),
256257
});
257258

258259
/** Moves the session to one paired device worker. */

‎src/gateway/server-methods/chat-history-handler.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
startOptionalServerMethodModelCatalogSnapshotLoad,
6262
} from "./optional-model-catalog.js";
6363
import { resolveVisibleActiveSessionRunState } from "./session-active-runs.js";
64+
import { readSessionPlacementFields } from "./session-placement-read-projection.js";
6465
import type { GatewayRequestHandlerOptions, GatewayRequestHandlers } from "./types.js";
6566
import { assertValidParams } from "./validation.js";
6667

@@ -479,6 +480,10 @@ async function handleChatHistoryRequest({
479480
});
480481
sessionInfo.hasActiveRun = activeRunState.active;
481482
sessionInfo.activeRunIds = activeRunState.runIds;
483+
// Clients merge this row into the same store sessions.list fills, so it must
484+
// carry the placement facts that projection adds; without them the merge
485+
// erases a live worker placement and its move intent.
486+
Object.assign(sessionInfo, readSessionPlacementFields(context, entry?.sessionId));
482487
if (Object.hasOwn(historyPage, "activeLeafEntryId")) {
483488
sessionInfo.activeLeafEntryId = historyPage.activeLeafEntryId ?? null;
484489
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ export async function invokeSessionMove(
145145
expected: { generation: number; environmentId: string; ownerEpoch: number };
146146
target:
147147
| { kind: "gateway" }
148-
| { kind: "profile"; profileId: string }
148+
| { kind: "profile"; profileId: string; machineClass?: string }
149149
| { kind: "device"; deviceId: string };
150150
},
151151
) {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,13 +411,13 @@ describe("sessions.dispatch", () => {
411411
}),
412412
{
413413
expected: { generation: 4, environmentId: "environment-previous", ownerEpoch: 1 },
414-
target: { kind: "profile", profileId: "test" },
414+
target: { kind: "profile", profileId: "test", machineClass: "beast" },
415415
},
416416
);
417417

418418
expect(move).toHaveBeenCalledWith(
419419
expect.objectContaining({
420-
target: { kind: "profile", profileId: "test" },
420+
target: { kind: "profile", profileId: "test", machineClass: "beast" },
421421
}),
422422
expect.any(Function),
423423
);

‎src/gateway/server-worker-placement-startup.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
367367
const destination = resolveWorkerPlacementDestination({
368368
cfg: config,
369369
...(moveTarget.kind === "profile"
370-
? { profileId: moveTarget.profileId }
370+
? { profileId: moveTarget.profileId, machineClass: moveTarget.machineClass }
371371
: { deviceId: moveTarget.deviceId }),
372372
});
373373
if (!destination.ok || !destination.value) {

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,60 @@ async function prepareMainHistoryHarness(params: {
684684
}
685685

686686
describe("gateway server chat", () => {
687+
test.each(["chat.history", "chat.startup"] as const)(
688+
"%s projects the session's durable worker placement",
689+
async (method) => {
690+
openDirectChatSession();
691+
try {
692+
await writeMainSessionStore();
693+
const placement = {
694+
sessionId: "sess-main",
695+
agentId: "main",
696+
sessionKey: "agent:main:main",
697+
executionMode: "worker-turn",
698+
state: "active",
699+
environmentId: "env-placement",
700+
generation: 7,
701+
activeOwnerEpoch: 12,
702+
workspaceBaseManifestRef: "manifest-base",
703+
remoteWorkspaceDir: "/workspace/main",
704+
workerBundleHash: "ab".repeat(32),
705+
recoveryError: null,
706+
terminalReason: null,
707+
terminalAtMs: null,
708+
turnClaim: null,
709+
createdAtMs: 100,
710+
updatedAtMs: 300,
711+
stateChangedAtMs: 200,
712+
};
713+
const context = createDirectChatContext({
714+
workerSessionPlacementService: {
715+
getMany: () => new Map([[placement.sessionId, placement]]),
716+
getPlacementMoves: () => new Map(),
717+
},
718+
} as unknown as Partial<GatewayRequestContext>);
719+
const responses: Array<{ ok: boolean; payload?: unknown }> = [];
720+
await callDirectChat(method, {
721+
id: method,
722+
params: makeMainSessionParams(),
723+
respond: captureChatResult(responses),
724+
context,
725+
});
726+
727+
expect(responses[0]?.ok).toBe(true);
728+
// Clients merge this row into the same store sessions.list fills, so a
729+
// missing placement here silently erases a live worker placement.
730+
expect(
731+
(responses[0]?.payload as { sessionInfo?: { placement?: { state?: string } } })
732+
?.sessionInfo?.placement,
733+
).toMatchObject({ state: "active", environmentId: "env-placement" });
734+
} finally {
735+
testState.sessionStorePath = undefined;
736+
clearConfigCache();
737+
}
738+
},
739+
);
740+
687741
test.each(["chat.history", "chat.startup"] as const)(
688742
"%s replays the active plan snapshot in inFlightRun",
689743
async (method) => {

0 commit comments

Comments
 (0)