Skip to content

Commit 4f0e131

Browse files
authored
feat(ui): run sessions on cloud workers (#107670)
* feat(ui): add cloud session targets * test(ui): cover cloud session attachments * test(ui): use recovery token fixture * test(ui): record cloud locale fallbacks * fix(ui): harden cloud session recovery * fix(ui): track cloud handoff phase * fix(ui): close cloud recovery escape paths * fix(ui): finish cloud recovery hardening * fix(ui): recover ambiguous cloud session creation * fix(ui): isolate stale cloud creation recovery * test(ui): preserve cloud recovery literals * fix(ui): complete cloud session release artifacts * chore: move cloud release note to PR body * docs(ui): name cloud session menu exactly
1 parent 8d739df commit 4f0e131

95 files changed

Lines changed: 4766 additions & 657 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -957,15 +957,19 @@ public struct EnvironmentsListParams: Codable, Sendable {}
957957

958958
public struct EnvironmentsListResult: Codable, Sendable {
959959
public let environments: [EnvironmentSummary]
960+
public let profiles: [[String: AnyCodable]]?
960961

961962
public init(
962-
environments: [EnvironmentSummary])
963+
environments: [EnvironmentSummary],
964+
profiles: [[String: AnyCodable]]? = nil)
963965
{
964966
self.environments = environments
967+
self.profiles = profiles
965968
}
966969

967970
private enum CodingKeys: String, CodingKey {
968971
case environments
972+
case profiles
969973
}
970974
}
971975

‎docs/gateway/cloud-workers.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ Profile fields:
7777

7878
## Dispatching a session
7979

80+
In the Control UI, open **New Session**, choose an agent whose configured runtime is OpenClaw, select a configured **Cloud · profile** target from the **Where** menu, and start the task. Cloud selection enables the required managed worktree automatically; the Gateway creates the session, finishes dispatch, and only then sends the first turn. The server badge in the session sidebar shows the durable placement state. Cloud targets are not offered for external CLI session catalogs.
81+
82+
The equivalent RPC flow is:
83+
8084
Create a session with a managed worktree, then dispatch it (the RPC requires `operator.admin` and only exists when profiles are configured):
8185

8286
Cloud workers run the OpenClaw agent runtime. Choose an `openai/*` or other model that resolves to that runtime; sessions configured for an external CLI runtime such as `claude-cli` cannot dispatch.

‎packages/gateway-protocol/src/schema/environments.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
33
import {
44
EnvironmentsCreateResultSchema,
55
EnvironmentsDestroyResultSchema,
6+
EnvironmentsListResultSchema,
67
EnvironmentSummarySchema,
78
validateEnvironmentsCreateParams,
89
validateEnvironmentsDestroyParams,
@@ -95,6 +96,21 @@ describe("worker environment protocol schemas", () => {
9596
expect(Value.Check(EnvironmentsDestroyResultSchema, destroyed)).toBe(true);
9697
});
9798

99+
it("lists configured worker profiles without provider settings", () => {
100+
expect(
101+
Value.Check(EnvironmentsListResultSchema, {
102+
environments: [],
103+
profiles: [{ id: "aws", providerId: "crabbox" }],
104+
}),
105+
).toBe(true);
106+
expect(
107+
Value.Check(EnvironmentsListResultSchema, {
108+
environments: [],
109+
profiles: [{ id: "aws", providerId: "crabbox", settings: { token: "hidden" } }],
110+
}),
111+
).toBe(false);
112+
});
113+
98114
it("preserves summaries without worker metadata and rejects malformed worker metadata", () => {
99115
expect(
100116
Value.Check(EnvironmentSummarySchema, {

‎packages/gateway-protocol/src/schema/environments.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,16 @@ export const EnvironmentSummarySchema = createEnvironmentSummarySchema();
6565
/** Empty request payload for listing known environments. */
6666
export const EnvironmentsListParamsSchema = closedObject({});
6767

68+
/** Configured worker target exposed without provider settings or credentials. */
69+
export const WorkerEnvironmentProfileSummarySchema = closedObject({
70+
id: NonEmptyString,
71+
providerId: NonEmptyString,
72+
});
73+
6874
/** List response containing all gateway-visible environment summaries. */
6975
export const EnvironmentsListResultSchema = closedObject({
7076
environments: Type.Array(EnvironmentSummarySchema),
77+
profiles: Type.Optional(Type.Array(WorkerEnvironmentProfileSummarySchema)),
7178
});
7279

7380
/** Status lookup request for one environment id. */
@@ -95,6 +102,7 @@ export type EnvironmentStatus = Static<typeof EnvironmentStatusSchema>;
95102
export type WorkerEnvironmentState = Static<typeof WorkerEnvironmentStateSchema>;
96103
export type WorkerTunnelStatus = Static<typeof WorkerTunnelStatusSchema>;
97104
export type WorkerEnvironmentMetadata = Static<typeof WorkerEnvironmentMetadataSchema>;
105+
export type WorkerEnvironmentProfileSummary = Static<typeof WorkerEnvironmentProfileSummarySchema>;
98106
export type EnvironmentSummary = Static<typeof EnvironmentSummarySchema>;
99107
export type EnvironmentsCreateParams = Static<typeof EnvironmentsCreateParamsSchema>;
100108
export type EnvironmentsCreateResult = Static<typeof EnvironmentsCreateResultSchema>;

‎src/gateway/server-methods/environments.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,19 @@ function mockContext(workerEnvironmentService?: TestWorkerService) {
4444
],
4545
},
4646
workerEnvironmentService,
47+
...(workerEnvironmentService
48+
? {
49+
workerPlacementDispatchService: { dispatch: vi.fn() },
50+
getRuntimeConfig: () => ({
51+
cloudWorkers: {
52+
profiles: {
53+
zeta: { provider: "static-ssh", settings: {} },
54+
aws: { provider: "crabbox", settings: {} },
55+
},
56+
},
57+
}),
58+
}
59+
: {}),
4760
};
4861
}
4962

@@ -178,6 +191,10 @@ describe("environment gateway methods", () => {
178191

179192
expect(ok).toBe(true);
180193
expect(payload).toMatchObject({
194+
profiles: [
195+
{ id: "aws", providerId: "crabbox" },
196+
{ id: "zeta", providerId: "static-ssh" },
197+
],
181198
environments: [
182199
{ id: "gateway", type: "local" },
183200
{ id: "node:node-live", type: "node" },

‎src/gateway/server-methods/environments.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,18 @@ function listWorkerEnvironments(context: GatewayRequestContext): WorkerEnvironme
9898
return [];
9999
}
100100
}
101+
function listWorkerProfiles(context: GatewayRequestContext) {
102+
if (!context.workerEnvironmentService || !context.workerPlacementDispatchService) {
103+
return [];
104+
}
105+
const profiles = context.getRuntimeConfig().cloudWorkers?.profiles ?? {};
106+
return Object.entries(profiles)
107+
.flatMap(([id, profile]) => {
108+
const providerId = typeof profile.provider === "string" ? profile.provider.trim() : "";
109+
return id.trim() && providerId ? [{ id: id.trim(), providerId }] : [];
110+
})
111+
.toSorted((left, right) => left.id.localeCompare(right.id));
112+
}
101113
async function respondWorkerMutation(
102114
respond: RespondFn,
103115
run: () => Promise<WorkerEnvironmentServiceRecord>,
@@ -129,7 +141,8 @@ export const environmentsHandlers: GatewayRequestHandlers = {
129141
environments.push(
130142
...workers.map((record) => summarizeWorkerEnvironment(record, summarizedAtMs)),
131143
);
132-
respond(true, { environments }, undefined);
144+
const profiles = listWorkerProfiles(context);
145+
respond(true, { environments, ...(profiles.length > 0 ? { profiles } : {}) }, undefined);
133146
});
134147
},
135148
"environments.status": async ({ params, respond, context }) => {

‎ui/src/api/gateway-browser-auth.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import type { GatewayConnectAuthSelection } from "@openclaw/gateway-client/browser";
2+
import { loadDeviceAuthToken, peekStoredDeviceIdentityId } from "../lib/nodes/index.ts";
3+
4+
const CONTROL_UI_OPERATOR_ROLE = "operator";
5+
6+
export function storedDeviceTokenScopesAllowRead(role: string, scopes: readonly string[]): boolean {
7+
return (
8+
role !== CONTROL_UI_OPERATOR_ROLE ||
9+
scopes.includes("operator.read") ||
10+
scopes.includes("operator.write") ||
11+
scopes.includes("operator.admin")
12+
);
13+
}
14+
15+
/** True when the next browser connect would present a usable stored credential. */
16+
export function hasStoredGatewayAuth(params: {
17+
gatewayUrl: string;
18+
token?: string;
19+
password?: string;
20+
}): boolean {
21+
if (params.token?.trim() || params.password?.trim()) {
22+
return true;
23+
}
24+
// Insecure contexts skip device identity, so their stored token is unusable.
25+
if (typeof crypto === "undefined" || !crypto.subtle) {
26+
return false;
27+
}
28+
const deviceId = peekStoredDeviceIdentityId();
29+
if (!deviceId) {
30+
return false;
31+
}
32+
const storedEntry = loadDeviceAuthToken({
33+
deviceId,
34+
gatewayUrl: params.gatewayUrl,
35+
role: CONTROL_UI_OPERATOR_ROLE,
36+
});
37+
return Boolean(
38+
storedEntry && storedDeviceTokenScopesAllowRead(CONTROL_UI_OPERATOR_ROLE, storedEntry.scopes),
39+
);
40+
}
41+
42+
export function gatewayRecoveryScopeMaterial(
43+
selected: GatewayConnectAuthSelection,
44+
): string | undefined {
45+
return selected.authDeviceToken ?? selected.resolvedDeviceToken ?? selected.authToken;
46+
}
47+
48+
async function deriveRecoveryScope(scopeMaterial: string | undefined): Promise<string> {
49+
if (!scopeMaterial || typeof crypto === "undefined" || !crypto.subtle) {
50+
return "";
51+
}
52+
try {
53+
// Recovery records contain the unsent task. Bind them to the exact
54+
// credential without persisting that credential in browser storage.
55+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(scopeMaterial));
56+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(
57+
"",
58+
);
59+
} catch {
60+
return "";
61+
}
62+
}
63+
64+
export class GatewayRecoveryScopeTracker {
65+
scope = "";
66+
ready = false;
67+
private generation = 0;
68+
69+
begin(generation: number) {
70+
this.generation = generation;
71+
this.ready = false;
72+
}
73+
74+
async resolve(params: {
75+
generation: number;
76+
scopeMaterial?: string;
77+
isConnected: () => boolean;
78+
}): Promise<boolean> {
79+
const scope = await deriveRecoveryScope(params.scopeMaterial);
80+
if (params.generation !== this.generation || !params.isConnected()) {
81+
return false;
82+
}
83+
this.scope = scope;
84+
this.ready = true;
85+
return true;
86+
}
87+
}

‎ui/src/api/gateway.node.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/** @vitest-environment node */
2+
import { createHash } from "node:crypto";
23
import {
34
ConnectErrorDetailCodes,
45
GATEWAY_CLIENT_CAPS,
@@ -820,6 +821,39 @@ describe("GatewayBrowserClient", () => {
820821
}
821822
});
822823

824+
it("publishes a credential-scoped recovery identity after hello", async () => {
825+
const onRecoveryScopeChange = vi.fn();
826+
const client = new GatewayBrowserClient({
827+
url: DEFAULT_GATEWAY_URL,
828+
token: "test-auth-token",
829+
onRecoveryScopeChange,
830+
});
831+
832+
const { ws, connectFrame } = await startConnect(client);
833+
ws.emitMessage({
834+
type: "res",
835+
id: connectFrame.id,
836+
ok: true,
837+
payload: {
838+
type: "hello-ok",
839+
protocol: 4,
840+
auth: {
841+
role: "operator",
842+
scopes: [...CONTROL_UI_OPERATOR_SCOPES],
843+
deviceToken: "test-token-placeholder",
844+
},
845+
},
846+
});
847+
848+
await vi.waitFor(() => expect(onRecoveryScopeChange).toHaveBeenCalledOnce());
849+
expect(client.recoveryScopeReady).toBe(true);
850+
expect(client.recoveryScope).toBe(
851+
createHash("sha256").update("test-token-placeholder").digest("hex"),
852+
);
853+
expect(client.recoveryScope).not.toContain("test-token-placeholder");
854+
client.stop();
855+
});
856+
823857
it("keeps close callback errors from blocking reconnect scheduling", async () => {
824858
useNodeFakeTimers();
825859
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);

0 commit comments

Comments
 (0)