Skip to content

Commit 97fcfa9

Browse files
committed
fix(ui): follow session placement changes in desktop popouts
1 parent b799acd commit 97fcfa9

7 files changed

Lines changed: 245 additions & 37 deletions

File tree

‎docs/gateway/cloud-sessions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ See [Cloud Workers](/gateway/cloud-workers) for profiles, requirements, dispatch
4343

4444
## Viewing the session desktop
4545

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 and resolves the current machine when opened. When placement changes, the embedded viewer disconnects from the previous machine. A stopped cloud session does not switch the viewer to the Gateway desktop.
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.
4747

4848
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.
4949

‎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

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

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
44
import { createDeferred } from "../../../../test/helpers/promise.js";
5-
import type { GatewayBrowserClient } from "../../api/gateway.ts";
5+
import type { GatewayBrowserClient, GatewayEventListener } from "../../api/gateway.ts";
66
import { createStorageMock } from "../../test-helpers/storage.ts";
77
import { waitForFast } from "../../test-helpers/wait-for.ts";
88
import "./desktop-panel.ts";
99

1010
type DesktopPanelElement = HTMLElement & {
1111
available: boolean;
12+
documentMode: boolean;
1213
client: GatewayBrowserClient | null;
1314
desktopClientFactory: () => {
1415
connect(options: { onConnect: () => void }): Promise<{ disconnect(): void }>;
@@ -124,6 +125,103 @@ describe("embedded desktop panel presentation", () => {
124125
expect(request.mock.calls.some(([method]) => method === "sessions.describe")).toBe(false);
125126
});
126127

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+
127225
it("keeps a hidden embedded mount dormant even when the standalone dock was open", async () => {
128226
localStorage.setItem(
129227
"openclaw.desktopPanel",

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
renderDesktopPanelHeader,
4040
renderDesktopPicker,
4141
} from "./desktop-panel-view.ts";
42+
import { DesktopSessionController } from "./desktop-session-controller.ts";
4243
import { desktopSourceForEnvironment } from "./desktop-source.ts";
4344

4445
/** `<openclaw-desktop-panel>` — dockable RFB access to Gateway desktop sources. */
@@ -84,6 +85,15 @@ class OpenClawDesktopPanel extends OpenClawLitElement {
8485
private launchOperationId = 0;
8586
private controlTakeoverRecoveryUsed = false;
8687
private sourceSelection: "pending" | "resolved" | "picker" = "pending";
88+
private readonly sessionSource = new DesktopSessionController(
89+
this,
90+
() => this.environmentId,
91+
(target) => {
92+
this.returnToPicker();
93+
this.sourceSelection = "pending";
94+
void this.refreshEnvironments(undefined, target);
95+
},
96+
);
8797
private readonly mobileKeyboard = new DesktopMobileKeyboard({
8898
connection: () => this.connection,
8999
controlling: () => this.controlling,
@@ -222,6 +232,7 @@ class OpenClawDesktopPanel extends OpenClawLitElement {
222232
}
223233

224234
private returnToPicker(): void {
235+
this.sessionSource.invalidate();
225236
this.disconnectConnection();
226237
this.clearLaunchState();
227238
this.state = "picker";
@@ -249,7 +260,10 @@ class OpenClawDesktopPanel extends OpenClawLitElement {
249260
this.launchErrorText = null;
250261
}
251262

252-
private async refreshEnvironments(expectedOperationId?: number): Promise<boolean> {
263+
private async refreshEnvironments(
264+
expectedOperationId?: number,
265+
resolvedSessionTarget?: string | null,
266+
): Promise<boolean> {
253267
const client = this.client;
254268
if (!client || !this.available || (this.embedded && !this.presented)) {
255269
return false;
@@ -279,12 +293,15 @@ class OpenClawDesktopPanel extends OpenClawLitElement {
279293
}
280294
}
281295
if (refreshed) {
282-
await this.resolveRequestedSource(operationId);
296+
await this.resolveRequestedSource(operationId, resolvedSessionTarget);
283297
}
284298
return refreshed;
285299
}
286300

287-
private async resolveRequestedSource(operationId: number): Promise<void> {
301+
private async resolveRequestedSource(
302+
operationId: number,
303+
resolvedSessionTarget?: string | null,
304+
): Promise<void> {
288305
if (this.sourceSelection !== "pending" || operationId !== this.operationId) {
289306
return;
290307
}
@@ -295,6 +312,7 @@ class OpenClawDesktopPanel extends OpenClawLitElement {
295312
// Embedded presenters already receive the chat owner's current placement; do not rediscover it.
296313
sessionKey: this.documentMode ? this.sessionKey : null,
297314
environments: this.environments,
315+
resolvedSessionTarget,
298316
});
299317
if (operationId !== this.operationId) {
300318
return;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import type { ReactiveControllerHost } from "lit";
2+
import type { GatewayBrowserClient } from "../../api/gateway.ts";
3+
import type { GatewaySessionRow } from "../../api/types.ts";
4+
import { readSessionChangedEvent } from "../../lib/sessions/reconcile.ts";
5+
import { areUiSessionKeysEquivalent } from "../../lib/sessions/session-key.ts";
6+
import { SubscriptionsController } from "../../lit/subscriptions-controller.ts";
7+
import { resolveChatPaneDesktopTarget } from "../../pages/chat/chat-pane-placement.ts";
8+
9+
// Keep the chat placement dependency in this lazily loaded desktop owner, outside the boot chunk.
10+
export async function resolveDesktopDocumentSessionTarget(
11+
client: Pick<GatewayBrowserClient, "request"> | null,
12+
sessionKey: string,
13+
): Promise<string | null> {
14+
let session: GatewaySessionRow | undefined;
15+
// `sessions.describe` is the exact-key lookup; a paged list cannot rule out a later match.
16+
try {
17+
session =
18+
(
19+
await client?.request<{ session?: GatewaySessionRow | null }>("sessions.describe", {
20+
key: sessionKey,
21+
})
22+
)?.session ?? undefined;
23+
} catch {}
24+
return resolveChatPaneDesktopTarget(session);
25+
}
26+
27+
type DesktopSessionHost = ReactiveControllerHost & {
28+
isConnected: boolean;
29+
client: GatewayBrowserClient | null;
30+
available: boolean;
31+
documentMode: boolean;
32+
requestedSource: string | null;
33+
sessionKey: string | null;
34+
};
35+
36+
export class DesktopSessionController {
37+
private refreshId = 0;
38+
39+
constructor(
40+
private readonly host: DesktopSessionHost,
41+
private readonly currentTarget: () => string | null,
42+
private readonly onTargetChange: (target: string | null) => void,
43+
) {
44+
new SubscriptionsController(host).effect(
45+
() =>
46+
host.documentMode &&
47+
host.available &&
48+
host.sessionKey !== null &&
49+
host.requestedSource === null
50+
? host.client
51+
: null,
52+
(client) =>
53+
client.addEventListener((event) => {
54+
const changed =
55+
event.event === "sessions.changed" ? readSessionChangedEvent(event.payload) : null;
56+
if (changed && areUiSessionKeysEquivalent(changed.key, host.sessionKey)) {
57+
void this.refresh();
58+
}
59+
}),
60+
);
61+
}
62+
63+
invalidate(): void {
64+
this.refreshId += 1;
65+
}
66+
67+
private async refresh(): Promise<void> {
68+
const { client, sessionKey } = this.host;
69+
if (!client || !sessionKey) {
70+
return;
71+
}
72+
const refreshId = ++this.refreshId;
73+
const target = await resolveDesktopDocumentSessionTarget(client, sessionKey);
74+
if (
75+
refreshId !== this.refreshId ||
76+
!this.host.isConnected ||
77+
client !== this.host.client ||
78+
sessionKey !== this.host.sessionKey ||
79+
!this.host.documentMode ||
80+
!this.host.available ||
81+
this.host.requestedSource !== null ||
82+
(target !== null && target === this.currentTarget())
83+
) {
84+
return;
85+
}
86+
// Session events omit placement. Resolve it before comparing; unchanged updates keep live input.
87+
this.onTargetChange(target);
88+
}
89+
}
Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import type { DesktopSource, EnvironmentSummary } from "@openclaw/gateway-protocol";
2-
import type { GatewaySessionRow } from "../../api/types.ts";
3-
import { resolveChatPaneDesktopTarget } from "../../pages/chat/chat-pane-placement.ts";
42

53
export function desktopSourceForEnvironment(
64
environment: Pick<EnvironmentSummary, "id">,
@@ -13,14 +11,3 @@ export function desktopSourceForEnvironment(
1311
}
1412
return { kind: "environment", environmentId: environment.id };
1513
}
16-
17-
/**
18-
* Lives beside the lazily loaded panel rather than in the route module: the chat placement
19-
* owner pulls the chat page's dependency tree, which must stay out of the startup chunk.
20-
*/
21-
export function resolveDesktopDocumentTarget(
22-
options: { source: string | null; session: string | null },
23-
session: GatewaySessionRow | undefined,
24-
): string | null {
25-
return options.source ?? (options.session ? resolveChatPaneDesktopTarget(session) : null);
26-
}

‎ui/src/e2e/desktop-document-mode.e2e.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,32 @@ suite.define(() => {
342342
control: false,
343343
});
344344
await panel.locator("[data-test-remote-desktop='true']").waitFor();
345+
await gateway.setMethodResponse("sessions.describe", {
346+
session: {
347+
key: sessionKey,
348+
kind: "direct",
349+
updatedAt: 2,
350+
...scenario.session,
351+
placement: { state: "reclaimed" },
352+
},
353+
});
354+
await gateway.setMethodResponse("environments.list", {
355+
environments: [gatewayEnvironment, { ...scenario.environment, desktop: true }],
356+
});
357+
await gateway.emitGatewayEvent("sessions.changed", { sessionKey, reason: "reclaim" });
358+
await panel.getByText("Desktop sources", { exact: true }).waitFor();
359+
expect(await panel.locator("[data-test-remote-desktop='true']").count()).toBe(0);
360+
expect(await gateway.getRequests("desktop.observe")).toHaveLength(1);
361+
362+
await gateway.setMethodResponse("sessions.describe", {
363+
session: { key: sessionKey, kind: "direct", updatedAt: 3, ...scenario.session },
364+
});
365+
await gateway.emitGatewayEvent("sessions.changed", { sessionKey, reason: "placement" });
366+
await panel.locator("[data-test-remote-desktop='true']").waitFor();
367+
expect((await gateway.getRequests("desktop.observe")).at(-1)?.params).toEqual({
368+
source: scenario.source,
369+
control: false,
370+
});
345371
await mkdir(artifactDirectory, { recursive: true });
346372
await page.screenshot({
347373
path: path.join(

0 commit comments

Comments
 (0)