Skip to content

Commit 1b236df

Browse files
authored
fix(ui): retain desktop viewer through control handoff (#134903)
* fix(ui): retain desktop viewer through control handoff * docs: leave desktop release notes to release generation * test: resume Code Mode lifecycle through waiting results * test(ui): await authenticated fullscreen handoff
1 parent aacaee7 commit 1b236df

10 files changed

Lines changed: 388 additions & 52 deletions

‎src/agents/code-mode.bridge.lifecycle.test.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
resultDetails,
2323
runUntilCompleted,
2424
testing,
25+
waitUntilCompleted,
2526
} from "./code-mode.test-support.js";
2627
import { buildEmbeddedRunPayloads } from "./embedded-agent-runner/run/payloads.js";
2728
import { emitAssistantTextDeltaAndEnd } from "./embedded-agent-subscribe.e2e-harness.js";
@@ -437,12 +438,10 @@ describe("Code Mode subscribed bridge lifecycle", () => {
437438
);
438439
expect(suspended).toMatchObject({ status: "waiting", reason: "yield" });
439440

440-
const completed = resultDetails(
441-
await expectDefined(harness.tools[1], "Code Mode wait test invariant").execute(
442-
`code-wait-stage-${stage}`,
443-
{ runId: suspended.runId },
444-
),
445-
);
441+
const completed = await waitUntilCompleted({
442+
details: suspended,
443+
waitTool: expectDefined(harness.tools[1], "Code Mode wait test invariant"),
444+
});
446445
expect(completed).toMatchObject({ status: "completed", value: { finished: true } });
447446
expect(countActiveToolExecutions(harness.runId)).toBe(0);
448447
}

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* @vitest-environment jsdom */
22

33
import { describe, expect, it, vi } from "vitest";
4+
import { createDeferred } from "../../../../test/helpers/promise.js";
45
import { DesktopClient } from "./desktop-client.ts";
56

67
type RfbConstructor = NonNullable<ConstructorParameters<typeof DesktopClient>[0]>;
@@ -36,6 +37,44 @@ function createFakeRfb() {
3637
}
3738

3839
describe("DesktopClient", () => {
40+
it.each([false, true])(
41+
"opens a socket after the RFB loader only while the operation remains current (%s)",
42+
async (remainsCurrent) => {
43+
const { Rfb, instances } = createFakeRfb();
44+
const loaded = createDeferred<RfbConstructor>();
45+
const createSocket = vi.fn((url: string) => new FakeSocket(url) as unknown as WebSocket);
46+
const client = new DesktopClient(undefined, createSocket, () => loaded.promise);
47+
let current = true;
48+
const pending = client.connect({
49+
wsUrl: "ws://control.example.test/desktop/observe",
50+
viewOnly: false,
51+
target: document.createElement("div"),
52+
isCurrent: () => current,
53+
});
54+
const result = pending.then(
55+
(handle) => ({ handle, error: undefined }),
56+
(error: unknown) => ({ handle: undefined, error }),
57+
);
58+
try {
59+
expect(createSocket).not.toHaveBeenCalled();
60+
current = remainsCurrent;
61+
loaded.resolve(Rfb);
62+
const outcome = await result;
63+
expect(createSocket).toHaveBeenCalledTimes(remainsCurrent ? 1 : 0);
64+
if (remainsCurrent) {
65+
expect(outcome.error).toBeUndefined();
66+
expect(instances).toHaveLength(1);
67+
} else {
68+
expect(outcome.error).toMatchObject({ name: "AbortError" });
69+
expect(instances).toHaveLength(0);
70+
}
71+
} finally {
72+
loaded.resolve(Rfb);
73+
(await result).handle?.disconnect();
74+
}
75+
},
76+
);
77+
3978
it.each([
4079
["http://control.example.test/chat", "ws://control.example.test/desktop/observe?token=abc"],
4180
["https://control.example.test/chat", "wss://control.example.test/desktop/observe?token=abc"],
@@ -51,6 +90,7 @@ describe("DesktopClient", () => {
5190

5291
await client.connect({
5392
gatewayUrl,
93+
isCurrent: () => true,
5494
wsUrl: "/desktop/observe?token=abc",
5595
credentials: { password: "secret" },
5696
viewOnly: true,
@@ -74,6 +114,7 @@ describe("DesktopClient", () => {
74114

75115
const handle = await client.connect({
76116
gatewayUrl: "ws://control.example.test",
117+
isCurrent: () => true,
77118
wsUrl: "/desktop/observe",
78119
credentials: { username: "operator", password: "secret" },
79120
background: "rgb(8, 8, 8)",
@@ -100,6 +141,8 @@ describe("DesktopClient", () => {
100141
["k", "m", "Backspace"],
101142
);
102143

144+
handle.disableInput();
145+
expect(instances[0]?.viewOnly).toBe(true);
103146
handle.disconnect();
104147
expect(instances[0]?.disconnect).toHaveBeenCalledOnce();
105148
});
@@ -112,6 +155,7 @@ describe("DesktopClient", () => {
112155

113156
await client.connect({
114157
wsUrl: "ws://control.example.test/desktop/observe",
158+
isCurrent: () => true,
115159
viewOnly: true,
116160
target: document.createElement("div"),
117161
onDisconnect,

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type DesktopConnectOptions = {
1212
background?: string;
1313
credentials?: { username?: string; password?: string };
1414
gatewayUrl?: string;
15+
isCurrent: () => boolean;
1516
onConnect?: () => void;
1617
onDisconnect?: (detail: DesktopDisconnectDetail) => void;
1718
onSecurityFailure?: (detail: DesktopSecurityFailureDetail) => void;
@@ -23,6 +24,7 @@ type DesktopConnectOptions = {
2324

2425
export type DesktopConnectionHandle = {
2526
disconnect(): void;
27+
disableInput(): void;
2628
sendBackspace?(): void;
2729
sendKeyboardEvent?(event: KeyboardEvent): void;
2830
sendText?(text: string): void;
@@ -82,6 +84,10 @@ export class DesktopClient {
8284
async connect(options: DesktopConnectOptions): Promise<DesktopConnectionHandle> {
8385
const Rfb = this.rfbConstructor ?? (await this.loadRfb());
8486
const wsUrl = resolveDesktopWebSocketUrl(options.wsUrl, options.gatewayUrl);
87+
// The socket claims control before RFB authentication; canceled lazy loads must not open it.
88+
if (!options.isCurrent()) {
89+
throw new DOMException("Desktop connection is no longer current", "AbortError");
90+
}
8591
const socket = this.createWebSocket(wsUrl);
8692
let closeDetail: DesktopDisconnectDetail = {};
8793
socket.addEventListener("close", (event) => {
@@ -123,6 +129,9 @@ export class DesktopClient {
123129
});
124130
return {
125131
disconnect: () => rfb.disconnect(),
132+
disableInput: () => {
133+
rfb.viewOnly = true;
134+
},
126135
setScaleViewport: (enabled) => {
127136
rfb.scaleViewport = enabled;
128137
},

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DesktopObserveResult, WorkerDesktopAppId } from "@openclaw/gateway-protocol";
2+
import type { DesktopConnectionHandle } from "./desktop-client.ts";
23

34
export type DesktopAppId = WorkerDesktopAppId;
45
export type DesktopCredentials = { username?: string; password?: string };
@@ -13,3 +14,46 @@ export type PendingDesktopConnection = {
1314
export type ObservedDesktopConnection = PendingDesktopConnection & {
1415
observed: DesktopObserveResult;
1516
};
17+
18+
/** Keeps a same-source viewer alive until its replacement finishes RFB authentication. */
19+
export class DesktopConnectionHandoff {
20+
private current: DesktopConnectionHandle | null = null;
21+
private retained: DesktopConnectionHandle | null = null;
22+
private connected = false;
23+
24+
get handle(): DesktopConnectionHandle | null {
25+
return this.connected ? this.current : null;
26+
}
27+
28+
begin(retainViewer: boolean): void {
29+
const retained = retainViewer ? (this.connected ? this.current : this.retained) : null;
30+
const current = this.current;
31+
const previous = this.retained;
32+
this.current = null;
33+
this.retained = retained;
34+
this.connected = false;
35+
if (current !== retained) {
36+
current?.disconnect();
37+
}
38+
if (previous !== retained) {
39+
previous?.disconnect();
40+
}
41+
retained?.disableInput();
42+
}
43+
44+
attach(handle: DesktopConnectionHandle): void {
45+
this.current = handle;
46+
}
47+
48+
markConnected(): void {
49+
// A returned handle or observe result is not the RFB authentication boundary.
50+
this.connected = true;
51+
const retained = this.retained;
52+
this.retained = null;
53+
retained?.disconnect();
54+
}
55+
56+
disconnect(): void {
57+
this.begin(false);
58+
}
59+
}

0 commit comments

Comments
 (0)