Skip to content

Commit 0c6628c

Browse files
committed
fix(cua-computer): start direct driver sessions
1 parent 45a6a82 commit 0c6628c

2 files changed

Lines changed: 117 additions & 20 deletions

File tree

‎extensions/cua-computer/src/driver-client.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,15 @@ const mocks = vi.hoisted(() => ({
55
create: vi.fn(),
66
createConfigured: vi.fn(),
77
createTrustedSession: vi.fn(),
8+
endSession: vi.fn(async () => ({})),
9+
getDesktopState: vi.fn(async () => ({})),
810
isAvailable: vi.fn(() => true),
11+
startSession: vi.fn(async () => ({})),
912
shutdown: vi.fn(async () => {}),
1013
}));
1114

1215
vi.mock("@trycua/cua-driver", () => ({
16+
CaptureScope: { Desktop: "desktop" },
1317
ClickButton: { Left: 0, Right: 1, Middle: 2 },
1418
CuaDriver: { create: mocks.create, createConfigured: mocks.createConfigured },
1519
DesktopScope: { Desktop: 0 },
@@ -36,7 +40,12 @@ describe("CUA Driver direct session", () => {
3640
isAvailable: mocks.isAvailable,
3741
shutdown: mocks.shutdown,
3842
});
39-
mocks.createTrustedSession.mockReturnValue({ close: mocks.close });
43+
mocks.createTrustedSession.mockReturnValue({
44+
close: mocks.close,
45+
endSession: mocks.endSession,
46+
getDesktopState: mocks.getDesktopState,
47+
startSession: mocks.startSession,
48+
});
4049
});
4150

4251
it("uses configured creation and one fixed trusted OpenClaw session", async () => {
@@ -62,4 +71,24 @@ describe("CUA Driver direct session", () => {
6271
expect(mocks.close).toHaveBeenCalledOnce();
6372
expect(mocks.shutdown).toHaveBeenCalledOnce();
6473
});
74+
75+
it("starts the fixed desktop capture session once before using driver tools", async () => {
76+
const driver = createCuaDriver();
77+
const sessionOptions = mocks.createTrustedSession.mock.calls[0]?.[1];
78+
79+
await Promise.all([driver.getDesktopState(), driver.getDesktopState()]);
80+
81+
expect(mocks.startSession).toHaveBeenCalledOnce();
82+
expect(mocks.startSession).toHaveBeenCalledWith(
83+
{
84+
session: sessionOptions.publicSession,
85+
captureScope: "desktop",
86+
},
87+
undefined,
88+
);
89+
expect(mocks.getDesktopState).toHaveBeenCalledTimes(2);
90+
91+
await driver.dispose();
92+
expect(mocks.endSession).toHaveBeenCalledWith({ session: sessionOptions.publicSession });
93+
});
6594
});

‎extensions/cua-computer/src/driver-client.ts‎

Lines changed: 87 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { randomUUID } from "node:crypto";
22
import {
3+
CaptureScope,
34
ClickButton,
45
CuaDriver,
56
DesktopScope,
@@ -60,6 +61,9 @@ class DirectCuaDriverSession implements CuaDriverSession {
6061
readonly generation = randomUUID();
6162
private readonly runtime: CuaDriverLike;
6263
private readonly session: CuaDriverSessionLike;
64+
private readonly publicSession = `openclaw-${randomUUID()}`;
65+
private startPromise: Promise<void> | undefined;
66+
private started = false;
6367
private disposed = false;
6468

6569
constructor() {
@@ -70,49 +74,99 @@ class DirectCuaDriverSession implements CuaDriverSession {
7074
authorization: { ...CUA_OPENCLAW_AUTHORIZATION },
7175
});
7276
this.session = createTrustedSession(this.runtime, {
73-
publicSession: `openclaw-${randomUUID()}`,
77+
publicSession: this.publicSession,
7478
mode: SessionPermissionMode.Unrestricted,
7579
ttlSeconds: CUA_OPENCLAW_AUTHORIZATION.maxSessionTtlSeconds,
7680
idleTtlSeconds: CUA_OPENCLAW_AUTHORIZATION.maxIdleTtlSeconds,
7781
});
7882
}
7983

84+
private async ensureStarted(signal?: AbortSignal): Promise<void> {
85+
if (this.disposed) {
86+
throw new Error("COMPUTER_DRIVER_UNAVAILABLE: cua-computer is stopping");
87+
}
88+
if (!this.startPromise) {
89+
const start = this.session
90+
.startSession(
91+
{ session: this.publicSession, captureScope: CaptureScope.Desktop },
92+
asyncOptions(signal),
93+
)
94+
.then(() => {
95+
this.started = true;
96+
});
97+
this.startPromise = start;
98+
try {
99+
await start;
100+
} catch (error) {
101+
if (this.startPromise === start) {
102+
this.startPromise = undefined;
103+
}
104+
throw error;
105+
}
106+
return;
107+
}
108+
await this.startPromise;
109+
}
110+
111+
private async invoke<T>(
112+
signal: AbortSignal | undefined,
113+
operation: () => Promise<T>,
114+
): Promise<T> {
115+
await this.ensureStarted(signal);
116+
return await operation();
117+
}
118+
80119
isAvailable(): boolean {
81120
return !this.disposed && this.runtime.isAvailable();
82121
}
83122
resetAvailabilityCache(): void {}
84-
getDesktopState(signal?: AbortSignal) {
85-
return this.session.getDesktopState({}, asyncOptions(signal));
123+
async getDesktopState(signal?: AbortSignal) {
124+
return await this.invoke(signal, () => this.session.getDesktopState({}, asyncOptions(signal)));
86125
}
87-
getScreenSize(signal?: AbortSignal) {
88-
return this.session.getScreenSize({}, asyncOptions(signal));
126+
async getScreenSize(signal?: AbortSignal) {
127+
return await this.invoke(signal, () => this.session.getScreenSize({}, asyncOptions(signal)));
89128
}
90-
click(input: { x: number; y: number; button: ClickButton; count: number }, signal?: AbortSignal) {
91-
return this.session.click({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal));
129+
async click(
130+
input: { x: number; y: number; button: ClickButton; count: number },
131+
signal?: AbortSignal,
132+
) {
133+
return await this.invoke(signal, () =>
134+
this.session.click({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
135+
);
92136
}
93-
drag(
137+
async drag(
94138
input: { fromX: number; fromY: number; toX: number; toY: number; durationMs?: bigint },
95139
signal?: AbortSignal,
96140
) {
97-
return this.session.drag({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal));
141+
return await this.invoke(signal, () =>
142+
this.session.drag({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
143+
);
98144
}
99-
moveCursor(input: { x: number; y: number }, signal?: AbortSignal) {
100-
return this.session.moveCursor({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal));
145+
async moveCursor(input: { x: number; y: number }, signal?: AbortSignal) {
146+
return await this.invoke(signal, () =>
147+
this.session.moveCursor({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
148+
);
101149
}
102-
scroll(
150+
async scroll(
103151
input: { x: number; y: number; direction: ScrollDirection; amount: bigint },
104152
signal?: AbortSignal,
105153
) {
106-
return this.session.scroll(
107-
{ ...input, scope: DesktopScope.Desktop, by: ScrollBy.Line },
108-
asyncOptions(signal),
154+
return await this.invoke(signal, () =>
155+
this.session.scroll(
156+
{ ...input, scope: DesktopScope.Desktop, by: ScrollBy.Line },
157+
asyncOptions(signal),
158+
),
109159
);
110160
}
111-
typeText(text: string, signal?: AbortSignal) {
112-
return this.session.typeText({ text, scope: DesktopScope.Desktop }, asyncOptions(signal));
161+
async typeText(text: string, signal?: AbortSignal) {
162+
return await this.invoke(signal, () =>
163+
this.session.typeText({ text, scope: DesktopScope.Desktop }, asyncOptions(signal)),
164+
);
113165
}
114-
pressKey(input: { key: string; modifiers: string[] }, signal?: AbortSignal) {
115-
return this.session.pressKey({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal));
166+
async pressKey(input: { key: string; modifiers: string[] }, signal?: AbortSignal) {
167+
return await this.invoke(signal, () =>
168+
this.session.pressKey({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
169+
);
116170
}
117171

118172
async dispose(): Promise<void> {
@@ -121,6 +175,20 @@ class DirectCuaDriverSession implements CuaDriverSession {
121175
}
122176
this.disposed = true;
123177
let failure: unknown;
178+
try {
179+
await this.startPromise;
180+
} catch (error) {
181+
failure = error;
182+
}
183+
if (this.started) {
184+
try {
185+
// End the native desktop session before revoking its trusted handle.
186+
// Closing only the handle can leave the started session behind on stop.
187+
await this.session.endSession({ session: this.publicSession });
188+
} catch (error) {
189+
failure ??= error;
190+
}
191+
}
124192
try {
125193
this.session.close();
126194
} catch (error) {

0 commit comments

Comments
 (0)