Skip to content

Commit 2099719

Browse files
authored
fix(ui): Desktop does not follow the chat session machine (#132255)
* fix(ui): keep session desktops connected to their execution machine * refactor(ui): remove obsolete desktop focus wrapper * test(ui): cover session desktop authentication in side rails * fix(ui): preserve the global desktop picker on chat routes * fix(ui): follow session placement changes in desktop popouts * test(ui): wait for desktop menu transitions to finish
1 parent 4008690 commit 2099719

16 files changed

Lines changed: 624 additions & 141 deletions

‎docs/gateway/cloud-sessions.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ Configure a profile under `cloudWorkers.profiles` and the bundled Crabbox plugin
4141

4242
See [Cloud Workers](/gateway/cloud-workers) for profiles, requirements, dispatching, moving sessions between destinations, and the security model.
4343

44+
## Viewing the session desktop
45+
46+
Open **Desktop** from a session to view its execution machine. Cloud sessions select their worker desktop; sessions on paired devices select that device. The pop-out window keeps the session in its link. Both viewers follow placement changes and disconnect from the previous machine when the session moves or stops. A stopped cloud session does not switch either viewer to the Gateway desktop.
47+
48+
The machine must already support desktop viewing. For cloud workers, enable the [Cloud Worker Desktop lab and desktop profile setting](/gateway/cloud-workers#desktop-interactive). Opening Desktop starts in view-only mode and does not change the machine's permissions or the agent's tool policy. The global Desktop command in the command palette still opens the machine picker, including on chat pages.
49+
4450
## Automatic load balancing across devices
4551

4652
You do not have to pick a device. Choosing **Auto** (least-busy device) in the Place picker — or dispatching with `autoDevice: true` — selects a paired session host automatically and retries up to three ranked hosts if provisioning fails before a machine is allocated. OpenClaw `worker-turn` placements rank hosts by most free worker slots, breaking ties by device ID; Codex `remote-exec` placements do not consume worker slots, so eligible hosts are ranked by device ID alone. When no host qualifies, the error says exactly why: no session hosts paired, all disconnected, or all at capacity.

‎ui/src/app/app-root.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -509,8 +509,8 @@ export class OpenClawApp extends OpenClawLightDomElement {
509509
.client=${gatewayConnected ? gatewaySnapshot.client : null}
510510
.available=${desktopAvailable}
511511
.documentMode=${true}
512-
.documentSource=${source}
513-
.documentSession=${session}
512+
.requestedSource=${source}
513+
.sessionKey=${session}
514514
.documentControl=${focusTarget.control}
515515
.onDocumentClose=${() => this.closeDocument(context.basePath)}
516516
></openclaw-desktop-panel>

‎ui/src/components/desktop/desktop-document-inventory.ts‎

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,21 @@
11
import type { EnvironmentSummary } from "@openclaw/gateway-protocol";
22
import type { GatewayBrowserClient } from "../../api/gateway.ts";
3-
import type { GatewaySessionRow } from "../../api/types.ts";
4-
import { resolveDesktopDocumentTarget } from "./desktop-source.ts";
3+
import { resolveDesktopDocumentSessionTarget } from "./desktop-session-controller.ts";
54

65
export async function resolveDesktopDocumentInventoryTarget(options: {
76
client: Pick<GatewayBrowserClient, "request"> | null;
87
source: string | null;
98
sessionKey: string | null;
109
environments: readonly Pick<EnvironmentSummary, "id">[];
10+
resolvedSessionTarget?: string | null;
1111
}): Promise<string | null> {
12-
let session: GatewaySessionRow | undefined;
13-
if (options.source === null && options.sessionKey !== null) {
14-
// `sessions.describe` is the exact-key lookup; a paged list cannot rule out a later match.
15-
try {
16-
session =
17-
(
18-
await options.client?.request<{ session?: GatewaySessionRow | null }>(
19-
"sessions.describe",
20-
{ key: options.sessionKey },
21-
)
22-
)?.session ?? undefined;
23-
} catch {}
24-
}
25-
const requestedSource = resolveDesktopDocumentTarget(
26-
{ source: options.source, session: options.sessionKey },
27-
session,
28-
);
12+
const requestedSource =
13+
options.source ??
14+
(options.resolvedSessionTarget !== undefined
15+
? options.resolvedSessionTarget
16+
: options.sessionKey !== null
17+
? await resolveDesktopDocumentSessionTarget(options.client, options.sessionKey)
18+
: null);
2919
return requestedSource !== null &&
3020
options.environments.some((environment) => environment.id === requestedSource)
3121
? requestedSource
Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
11
import { buildControlUiFocusPath } from "@openclaw/session-url-contract";
22
import { openExternalUrlSafe } from "../../lib/open-external-url.ts";
33

4-
export function desktopFocusPath(
5-
basePath: string,
6-
source?: string | null,
7-
control = false,
8-
): string {
9-
return buildControlUiFocusPath({ kind: "desktop", source, control }, basePath);
10-
}
11-
124
export function openDesktopFocus(basePath: string, source?: string | null, control = false): void {
13-
openExternalUrlSafe(desktopFocusPath(basePath, source, control));
5+
openExternalUrlSafe(buildControlUiFocusPath({ kind: "desktop", source, control }, basePath));
146
}

‎ui/src/components/desktop/desktop-panel.test.ts‎

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
/* @vitest-environment jsdom */
22

33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4-
import type { GatewayBrowserClient } from "../../api/gateway.ts";
4+
import { createDeferred } from "../../../../test/helpers/promise.js";
5+
import type { GatewayBrowserClient, GatewayEventListener } from "../../api/gateway.ts";
56
import { createStorageMock } from "../../test-helpers/storage.ts";
67
import { waitForFast } from "../../test-helpers/wait-for.ts";
78
import "./desktop-panel.ts";
89

910
type DesktopPanelElement = HTMLElement & {
1011
available: boolean;
12+
documentMode: boolean;
1113
client: GatewayBrowserClient | null;
1214
desktopClientFactory: () => {
1315
connect(options: { onConnect: () => void }): Promise<{ disconnect(): void }>;
1416
};
1517
embedded: boolean;
1618
handleToggleRequest(event: Event): void;
1719
presented: boolean;
20+
requestedSource: string | null;
21+
sessionKey: string | null;
1822
renderRoot: DocumentFragment;
1923
updateComplete: Promise<unknown>;
2024
};
@@ -63,6 +67,161 @@ describe("embedded desktop panel presentation", () => {
6367
vi.unstubAllGlobals();
6468
});
6569

70+
it("follows the session desktop and retires its connection before resolving a new placement", async () => {
71+
const replacement = { ...desktopEnvironment, id: "worker-desktop-2" };
72+
let refresh: Promise<void> | undefined;
73+
const request = vi.fn(async (method: string) => {
74+
if (method === "environments.list") {
75+
await refresh;
76+
return { environments: [desktopEnvironment, replacement] };
77+
}
78+
return {
79+
transport: "rfb",
80+
wsPath: "/desktop/observe?token=session",
81+
expiresAtMs: 60_000,
82+
control: false,
83+
};
84+
});
85+
const disconnect = vi.fn();
86+
const connect = vi.fn(async (options: { onConnect: () => void }) => {
87+
options.onConnect();
88+
return { disconnect };
89+
});
90+
const panel = createPanel();
91+
panel.client = { gatewayUrl: "ws://gateway.test", request } as unknown as GatewayBrowserClient;
92+
panel.available = true;
93+
panel.embedded = true;
94+
panel.presented = true;
95+
panel.sessionKey = "agent:main:cloud";
96+
panel.requestedSource = desktopEnvironment.id;
97+
panel.desktopClientFactory = () => ({ connect });
98+
document.body.append(panel);
99+
100+
await waitForFast(() => expect(connect).toHaveBeenCalledOnce());
101+
expect(request).toHaveBeenCalledWith("desktop.observe", {
102+
source: { kind: "environment", environmentId: desktopEnvironment.id },
103+
control: false,
104+
});
105+
106+
const nextInventory = createDeferred();
107+
refresh = nextInventory.promise;
108+
panel.requestedSource = replacement.id;
109+
await panel.updateComplete;
110+
expect(disconnect).toHaveBeenCalledOnce();
111+
expect(connect).toHaveBeenCalledOnce();
112+
nextInventory.resolve();
113+
refresh = undefined;
114+
await waitForFast(() => expect(connect).toHaveBeenCalledTimes(2));
115+
expect(request).toHaveBeenLastCalledWith("desktop.observe", {
116+
source: { kind: "environment", environmentId: replacement.id },
117+
control: false,
118+
});
119+
120+
panel.requestedSource = null;
121+
await panel.updateComplete;
122+
await settleTasks();
123+
expect(disconnect).toHaveBeenCalledTimes(2);
124+
expect(connect).toHaveBeenCalledTimes(2);
125+
expect(request.mock.calls.some(([method]) => method === "sessions.describe")).toBe(false);
126+
});
127+
128+
it("keeps focused session updates current across control changes and overlapping lookups", async () => {
129+
const sessionKey = "agent:main:focused";
130+
const active = {
131+
key: sessionKey,
132+
kind: "direct",
133+
placement: { state: "active", environmentId: desktopEnvironment.id },
134+
};
135+
const reclaimed = { ...active, placement: { state: "reclaimed" } };
136+
let sessionRead: Promise<unknown> | undefined;
137+
let listener: GatewayEventListener = () => {
138+
throw new Error("expected a focused session listener");
139+
};
140+
const unsubscribe = vi.fn();
141+
const request = vi.fn(async (method: string, params?: { control?: boolean }) => {
142+
if (method === "environments.list") {
143+
return { environments: [desktopEnvironment] };
144+
}
145+
if (method === "sessions.describe") {
146+
return sessionRead ?? { session: active };
147+
}
148+
return {
149+
transport: "rfb",
150+
wsPath: "/desktop/observe?token=focused",
151+
expiresAtMs: 60_000,
152+
control: params?.control ?? false,
153+
};
154+
});
155+
const disconnect = vi.fn();
156+
const connect = vi.fn(async (options: { onConnect: () => void }) => {
157+
options.onConnect();
158+
return { disconnect };
159+
});
160+
const panel = createPanel();
161+
panel.client = {
162+
gatewayUrl: "ws://gateway.test",
163+
request,
164+
addEventListener: (next: GatewayEventListener) => {
165+
listener = next;
166+
return unsubscribe;
167+
},
168+
} as unknown as GatewayBrowserClient;
169+
panel.available = true;
170+
panel.documentMode = true;
171+
panel.sessionKey = sessionKey;
172+
panel.desktopClientFactory = () => ({ connect });
173+
document.body.append(panel);
174+
await waitForFast(() => expect(connect).toHaveBeenCalledOnce());
175+
const descriptions = () =>
176+
request.mock.calls.filter(([method]) => method === "sessions.describe");
177+
const changed = (key = sessionKey) =>
178+
listener({ type: "event", event: "sessions.changed", payload: { sessionKey: key } });
179+
180+
changed("agent:main:unrelated");
181+
await settleTasks();
182+
expect(descriptions()).toHaveLength(1);
183+
changed();
184+
await waitForFast(() => expect(descriptions()).toHaveLength(2));
185+
await settleTasks();
186+
expect(disconnect).not.toHaveBeenCalled();
187+
188+
const pending = createDeferred<unknown>();
189+
sessionRead = pending.promise;
190+
changed();
191+
await waitForFast(() => expect(descriptions()).toHaveLength(3));
192+
const control = panel.renderRoot.querySelector<HTMLButtonElement>(
193+
'button[aria-label="Take control"]',
194+
);
195+
if (!control) {
196+
throw new Error("expected focused Desktop control button");
197+
}
198+
control.click();
199+
await waitForFast(() => expect(connect).toHaveBeenCalledTimes(2));
200+
pending.resolve({ session: reclaimed });
201+
await waitForFast(() =>
202+
expect(panel.renderRoot.querySelector(".desktop-picker")).not.toBeNull(),
203+
);
204+
expect(disconnect).toHaveBeenCalledTimes(2);
205+
206+
sessionRead = undefined;
207+
changed();
208+
await waitForFast(() => expect(connect).toHaveBeenCalledTimes(3));
209+
const stale = createDeferred<unknown>();
210+
sessionRead = stale.promise;
211+
changed();
212+
await waitForFast(() => expect(descriptions()).toHaveLength(5));
213+
sessionRead = Promise.resolve({ session: reclaimed });
214+
changed();
215+
await waitForFast(() =>
216+
expect(panel.renderRoot.querySelector(".desktop-picker")).not.toBeNull(),
217+
);
218+
stale.resolve({ session: active });
219+
await settleTasks();
220+
expect(connect).toHaveBeenCalledTimes(3);
221+
panel.remove();
222+
expect(unsubscribe).toHaveBeenCalledOnce();
223+
});
224+
66225
it("keeps a hidden embedded mount dormant even when the standalone dock was open", async () => {
67226
localStorage.setItem(
68227
"openclaw.desktopPanel",

0 commit comments

Comments
 (0)