Skip to content

Commit 0978d55

Browse files
authored
feat(nodes): automatic device placement for sessions.dispatch (#128421)
* feat(nodes): automatic device placement for sessions.dispatch sessions.dispatch gains autoDevice: true — the gateway selects the eligible session-host node with the most available worker slots (deterministic tie-break), retries up to three candidates when a node churns at the pre-provisioning eligibility fence, and reports the chosen device in the placement runner projection. Control UI offers Any available node with actionable disabled reasons. No-eligible-host failures state why. * fix(ui): break draft-place-state/draft-session-placement import cycle resolveDraftSessionPlacement only needs four scalar fields; a structural param type replaces the Pick<DraftPlaceState,...> import that created the madge cycle. * fix(ui): keep the devices section hidden when no devices are paired The Any available node row lives inside the Your devices section; rendering it with zero paired devices resurrected the section on gateway-only setups. Gate it on device presence — Connect a machine remains the discoverability path — and cover both the empty and non-hostable cases. * fix(gateway): project dispatch runner state through the canonical reader The dispatch reply no longer synthesizes an available device runner; it uses the fenced workerPlacementRunnerAvailabilityReader (and disk-space reader) exactly like session reads, so a node lost after durable provisioning projects offline consistently. Documents placement.runner.deviceId in the protocol reference.
1 parent 6621eac commit 0978d55

32 files changed

Lines changed: 1220 additions & 130 deletions

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7175,13 +7175,22 @@ public struct SessionPlacementDiskSpace: Codable, Sendable {
71757175
public struct SessionPlacementRunner: Codable, Sendable {
71767176
public let kind: String
71777177
public let status: AnyCodable
7178+
public let deviceid: String?
71787179

71797180
public init(
71807181
kind: String,
7181-
status: AnyCodable)
7182+
status: AnyCodable,
7183+
deviceid: String? = nil)
71827184
{
71837185
self.kind = kind
71847186
self.status = status
7187+
self.deviceid = deviceid
7188+
}
7189+
7190+
private enum CodingKeys: String, CodingKey {
7191+
case kind
7192+
case status
7193+
case deviceid = "deviceId"
71857194
}
71867195
}
71877196

@@ -7714,19 +7723,22 @@ public struct SessionsDispatchParams: Codable, Sendable {
77147723
public let agentid: String?
77157724
public let profileid: String?
77167725
public let deviceid: String?
7726+
public let autodevice: Bool?
77177727
public let machineclass: String?
77187728

77197729
public init(
77207730
key: String,
77217731
agentid: String? = nil,
77227732
profileid: String? = nil,
77237733
deviceid: String? = nil,
7734+
autodevice: Bool? = nil,
77247735
machineclass: String? = nil)
77257736
{
77267737
self.key = key
77277738
self.agentid = agentid
77287739
self.profileid = profileid
77297740
self.deviceid = deviceid
7741+
self.autodevice = autodevice
77307742
self.machineclass = machineclass
77317743
}
77327744

@@ -7735,6 +7747,7 @@ public struct SessionsDispatchParams: Codable, Sendable {
77357747
case agentid = "agentId"
77367748
case profileid = "profileId"
77377749
case deviceid = "deviceId"
7750+
case autodevice = "autoDevice"
77387751
case machineclass = "machineClass"
77397752
}
77407753
}

‎docs/gateway/protocol.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -650,14 +650,14 @@ methods. Treat this as feature discovery, not a full enumeration of
650650
</Accordion>
651651

652652
<Accordion title="Session control">
653-
- `sessions.list` returns the current session index, including per-row `agentRuntime` metadata when an agent runtime backend is configured. `hasActiveRun` is the authoritative aggregate direct-session activity fact. When projected, `activeRunIds` is the complete exact active set; an empty array proves the session is idle. If aggregate activity is true while the field is omitted, another runtime owner is active but its exact identities are unavailable. Snapshot omission means identities unavailable. On incremental events, omission means no change, `null` is the event-only tombstone that clears cached exact IDs to unavailable, and an array replaces the cache. Clients correlate only exact IDs they own locally or received from requests, history, or events and never select the first list entry as an owner. When cloud-worker placement is enabled or durable recovery state exists, session rows also include a closed `placement` state (`local`, `requested`, `provisioning`, `syncing`, `starting`, `active`, `draining`, `reconciling`, `reclaimed`, or `failed`) plus state-specific environment, owner-epoch, workspace, bundle, ACK-cursor, or recovery fields. Active placements may include an advisory `diskSpace` sample with `status` (`ok`, `warning`, or `critical`), `availableBytes`, `totalBytes`, and `observedAtMs`. An active paired-device placement also includes `runner: { kind: "device", status: "available" | "offline" }`; non-device placements omit it. This availability is process-current, derived from the exact active environment binding and reconnect-scoped node-runner proof, and starts offline after Gateway restart until that runner reconnects. Inventory changes emit `sessions.changed` so clients refresh the canonical row. Rows carry ownership projections — write-once `createdActor`, the mutable `owner` (actor plus `assignedBy`/`assignedAt`), a bounded `participants` list (owner excluded, up to 4 actors), and the full `participantCount`; actor display labels and avatars are resolved from current profiles and agent identities at read time. Pass `creatorId` to filter by immutable `createdActor.id`; pass `ownerId` to filter by the current assignable owner, falling back to `createdActor` when no owner is assigned. The complete `owners` facet is independent of pagination and remains unfiltered by either query, so clients can render the full owner picker. Authenticated callers can pass `involvingMe: true` to keep only sessions the caller owns or has prompted, evaluated against the full participant history (profile-backed human participants only).
653+
- `sessions.list` returns the current session index, including per-row `agentRuntime` metadata when an agent runtime backend is configured. `hasActiveRun` is the authoritative aggregate direct-session activity fact. When projected, `activeRunIds` is the complete exact active set; an empty array proves the session is idle. If aggregate activity is true while the field is omitted, another runtime owner is active but its exact identities are unavailable. Snapshot omission means identities unavailable. On incremental events, omission means no change, `null` is the event-only tombstone that clears cached exact IDs to unavailable, and an array replaces the cache. Clients correlate only exact IDs they own locally or received from requests, history, or events and never select the first list entry as an owner. When cloud-worker placement is enabled or durable recovery state exists, session rows also include a closed `placement` state (`local`, `requested`, `provisioning`, `syncing`, `starting`, `active`, `draining`, `reconciling`, `reclaimed`, or `failed`) plus state-specific environment, owner-epoch, workspace, bundle, ACK-cursor, or recovery fields. Active placements may include an advisory `diskSpace` sample with `status` (`ok`, `warning`, or `critical`), `availableBytes`, `totalBytes`, and `observedAtMs`. An active paired-device placement also includes `runner: { kind: "device", status: "available" | "offline", deviceId? }`; `deviceId` names the paired device hosting the placement (the selected host for `autoDevice` dispatch), and non-device placements omit the field. This availability is process-current, derived from the exact active environment binding and reconnect-scoped node-runner proof, and starts offline after Gateway restart until that runner reconnects. Inventory changes emit `sessions.changed` so clients refresh the canonical row. Rows carry ownership projections — write-once `createdActor`, the mutable `owner` (actor plus `assignedBy`/`assignedAt`), a bounded `participants` list (owner excluded, up to 4 actors), and the full `participantCount`; actor display labels and avatars are resolved from current profiles and agent identities at read time. Pass `creatorId` to filter by immutable `createdActor.id`; pass `ownerId` to filter by the current assignable owner, falling back to `createdActor` when no owner is assigned. The complete `owners` facet is independent of pagination and remains unfiltered by either query, so clients can render the full owner picker. Authenticated callers can pass `involvingMe: true` to keep only sessions the caller owns or has prompted, evaluated against the full participant history (profile-backed human participants only).
654654
- `sessions.subscribe` enables session change events for the current WebSocket client. The subscription ends when that client disconnects.
655655
- `sessions.messages.subscribe` and `sessions.messages.unsubscribe` toggle transcript/message event subscriptions for one session. Pass `includeApprovals: true` to also receive sanitized `session.approval` lifecycle events for approvals whose persisted audience includes that exact session and whose reviewer binding authorizes the subscribing client. The subscribe response then includes a bounded pending `approvalReplay`; it is authoritative when `truncated` is false. The opt-in is per subscribe call, not sticky: re-subscribing to the same session without `includeApprovals: true` removes an existing approval subscription. In addition to normal session-read authority, this opt-in requires `operator.admin`, or `operator.approvals` on a paired device.
656656
- `sessions.preview` returns bounded transcript previews for specific session keys.
657657
- `sessions.describe` returns one gateway session row for an exact session key.
658658
- `sessions.resolve` resolves or canonicalizes a session target by key, raw session ID, label, or Control UI short ID. Ambiguous short IDs return a bounded candidate list as a successful RPC result.
659659
- `sessions.create` creates a new session entry. Optional `model`, `contextWindow`, and `thinkingLevel` values persist the initial model, advertised context-window choice, and reasoning overrides atomically; optional `category` assigns the session to a custom group and registers that group when first used. `worktree: true` provisions a managed worktree; optional `worktreeBaseRef`/`worktreeName` select the base ref and branch name, and `execNode` (`operator.admin`) binds session exec to a node host. Without `worktreeName`, OpenClaw derives a readable name from the session label or generated first-message title, then falls back to a crustacean-themed name; names already occupied by another owner, local branch, or unmanaged path receive a numeric suffix. The created worktree is echoed in the result and persisted on the session row (`worktree: { id, branch, repoRoot }`). When the entry is created but its nested initial `chat.send` is rejected, the successful result includes `runStarted: false` and `runError`; clients can preserve the prompt and retry against the returned session key. A caller that passes `parentSessionKey` with `emitCommandHooks: true` should also declare the lifecycle disposition of a distinct child: `succeedsParent: true` ends the parent with `session_end`, while `false` keeps the parent active and emits only the child's `session_start`. Omitting `succeedsParent` preserves the legacy parent-rollover behavior for existing clients. The disposition requires both parent linkage and command hooks; a fork cannot succeed its parent. Main-session reset-in-place behavior is unchanged because no distinct child is created. New rows are stamped with write-once creation provenance (`createdVia`, `createdActor`, `createdAt`) from the trusted creation seam; adopting an existing key never restamps it. For human profile actors, `createdActor.label` is resolved from the current user profile when the row is projected and is never stored on the session entry, so profile renames do not drift. Session rows also carry `parentSessionKey` (navigation parent, persisted), `controlOwnerSessionKey` (runtime controller when live), `forkSource` (exact source key + transcript generation for forks), and `previousSessionId` (prior transcript generation under the same key).
660-
- `sessions.dispatch` moves an authorized local OpenClaw session with a live, registry-owned session managed worktree to a paired device or configured cloud profile. Pass `{ key, deviceId, agentId? }` for an explicit device, `{ key, profileId, machineClass?, agentId? }` for an explicit profile, or `{ key, agentId? }` to look up the managed worktree's normalized origin in `cloudWorkers.projectProfiles`. Explicit targets take precedence over project-profile lookup. Device dispatch requires `operator.write`; explicit-profile and project-profile dispatch require `operator.admin`. A missing origin, unmatched mapping, or mapping to an unconfigured profile returns a typed `INVALID_REQUEST` without provisioning or falling back to another target. Malformed params use the write scope before schema validation. A missing cloud profile hides only cloud targets; eligible paired-device dispatch remains available. Dispatch closes local turn admission before draining active work and returns only after placement reaches `active` worker ownership. Arbitrary plain directories are not dispatchable; after admission, the workspace transport may use manifest mirroring if the managed worktree's Git metadata later becomes unavailable. SSH fallback candidates rotate only for idempotent probes, content-addressed transfers, receipt/lock-guarded artifact installation, convergent managed-worktree mirroring, and tunnel reconnects. Ambiguous unguarded stateful commands fail closed and are not replayed. Dispatch is one-way; worker-to-local pull-back is not part of this RPC.
660+
- `sessions.dispatch` moves an authorized local OpenClaw session with a live, registry-owned session managed worktree to a paired device or configured cloud profile. Pass `{ key, deviceId, agentId? }` for an explicit device, `{ key, autoDevice: true, agentId? }` for automatic paired-device selection, `{ key, profileId, machineClass?, agentId? }` for an explicit profile, or `{ key, agentId? }` to look up the managed worktree's normalized origin in `cloudWorkers.projectProfiles`. These target modes are mutually exclusive and explicit targets take precedence over project-profile lookup. Automatic selection ranks worker-slot runtimes by available slots and then device ID; runtimes without worker slots use device ID order. If a candidate becomes ineligible during dispatch, up to three ranked candidates are attempted; other errors are not retried. Explicit and automatic device dispatch require `operator.write`; explicit-profile and project-profile dispatch require `operator.admin`. A missing origin, unmatched mapping, or mapping to an unconfigured profile returns a typed `INVALID_REQUEST` without provisioning or falling back to another target. Malformed params use the write scope before schema validation. A missing cloud profile hides only cloud targets; eligible paired-device dispatch remains available. Dispatch closes local turn admission before draining active work and returns only after placement reaches `active` worker ownership. Arbitrary plain directories are not dispatchable; after admission, the workspace transport may use manifest mirroring if the managed worktree's Git metadata later becomes unavailable. SSH fallback candidates rotate only for idempotent probes, content-addressed transfers, receipt/lock-guarded artifact installation, convergent managed-worktree mirroring, and tunnel reconnects. Ambiguous unguarded stateful commands fail closed and are not replayed. Dispatch is one-way; worker-to-local pull-back is not part of this RPC.
661661
- `sessions.reclaim` (`operator.write`) safely stops a session placement by key. It waits for an in-flight dispatch, drains admitted work, reconciles active workspace changes, and retries pending failed-environment teardown through the placement owner. Callers never need raw environment-destroy authority.
662662
- `sessions.move` moves an authorized active session to the Gateway, a paired device, or a configured profile. Gateway and device targets require `operator.write`; profile targets require `operator.admin`; malformed targets use the write scope before schema validation. The caller supplies the exact observed generation, environment, and owner epoch; session authorization and those source facts are revalidated before the move commits. Ordinary moves always reconcile the source. Only a Gateway target may add `abandonSource: true`, and only when the exact source is a currently offline paired-device placement. That durable decision force-fences and destroys the remote owner, skips remote workspace reconciliation, and continues from the last Gateway-synced state without replay; unsynced files and in-flight work may be lost. Available, unknown, profile, and other-worker sources reject explicit abandonment.
663663
- `sessions.groups.list`, `sessions.groups.put`, `sessions.groups.rename`, and `sessions.groups.delete` manage the gateway-owned custom session group catalog (names + display order). The read-scoped list result is intentionally path-free. `sessions.groups.defaults` and `sessions.groups.update` require `operator.write` and read or replace one custom group's optional working-directory and worktree defaults. Non-admin callers can save only directories inside a configured agent workspace; other absolute Gateway paths require `operator.admin`. Membership stays on each session's `category` field; rename and delete update member sessions server-side.

‎docs/nodes/index.md‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -471,9 +471,10 @@ while its receipt still matches the Gateway's current build.
471471

472472
You can also enroll and enable a service host in one step with
473473
`openclaw connect --service --session-host`. In Control UI New Session, a
474-
write-scoped operator selects a Gateway project or folder and then the paired
475-
device. OpenClaw creates a session-owned managed worktree on the Gateway,
476-
dispatches it with the exact `deviceId`, and sends the first turn only after the
474+
write-scoped operator selects a Gateway project or folder and then either a
475+
specific paired device or **Any available node**. OpenClaw creates a
476+
session-owned managed worktree on the Gateway, dispatches it with the exact
477+
`deviceId` or `autoDevice: true`, and sends the first turn only after the chosen
477478
device placement becomes active. New Session does not bind `execNode` or browse
478479
the device filesystem.
479480

@@ -511,6 +512,17 @@ visible but disabled with an actionable reason. Enable hosting with
511512
setting, then restart the node host. Update-required hosts must be upgraded and
512513
restarted before selection.
513514

515+
Choose **Any available node** to let the Gateway select an eligible paired,
516+
connected session host. For OpenClaw worker turns, it selects the host with the
517+
most available worker slots and breaks ties by device ID. Runtimes that do not
518+
consume worker slots choose the eligible host with the lowest device ID instead.
519+
If a selected host disconnects, reaches capacity, or otherwise becomes
520+
ineligible before dispatch finishes, the Gateway tries the next ranked host, up
521+
to three hosts total. Other dispatch failures are returned immediately. If no
522+
host is eligible, the error explains whether no session hosts are paired, hosts
523+
are disconnected or at capacity, a host needs an update, or the selected runtime
524+
is unsupported. The dispatch response identifies the device that was selected.
525+
514526
When a known session host disconnects, its paired-device record preserves only
515527
the last accepted current-v6 hosting consent. The offline row remains visible
516528
and disabled with status unavailable. A current disabled or empty v6

0 commit comments

Comments
 (0)