Skip to content

Commit 6a084c3

Browse files
committed
fix(cua): defer native driver loading
1 parent f63d092 commit 6a084c3

4 files changed

Lines changed: 237 additions & 48 deletions

File tree

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

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({
1212
shutdown: vi.fn(async () => {}),
1313
}));
1414

15-
vi.mock("@trycua/cua-driver", () => ({
15+
const sdk = {
1616
CaptureScope: { Desktop: "desktop" },
1717
ClickButton: { Left: 0, Right: 1, Middle: 2 },
1818
CuaDriver: { create: mocks.create, createConfigured: mocks.createConfigured },
@@ -21,7 +21,7 @@ vi.mock("@trycua/cua-driver", () => ({
2121
ScrollDirection: { Up: 0, Down: 1, Left: 2, Right: 3 },
2222
SessionPermissionMode: { Unrestricted: "unrestricted" },
2323
createTrustedSession: mocks.createTrustedSession,
24-
}));
24+
};
2525

2626
import { createCuaDriver } from "./driver-client.js";
2727

@@ -49,8 +49,9 @@ describe("CUA Driver direct session", () => {
4949
});
5050

5151
it("uses configured creation and one fixed trusted OpenClaw session", async () => {
52-
const driver = createCuaDriver();
52+
const driver = createCuaDriver({ loadSdk: () => sdk as never });
5353

54+
expect(driver.isAvailable()).toBe(true);
5455
expect(mocks.create).not.toHaveBeenCalled();
5556
expect(mocks.createConfigured).toHaveBeenCalledWith({
5657
claudeCodeCompatibility: false,
@@ -73,10 +74,10 @@ describe("CUA Driver direct session", () => {
7374
});
7475

7576
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];
77+
const driver = createCuaDriver({ loadSdk: () => sdk as never });
7878

7979
await Promise.all([driver.getDesktopState(), driver.getDesktopState()]);
80+
const sessionOptions = mocks.createTrustedSession.mock.calls[0]?.[1];
8081

8182
expect(mocks.startSession).toHaveBeenCalledOnce();
8283
expect(mocks.startSession).toHaveBeenCalledWith(
@@ -91,4 +92,23 @@ describe("CUA Driver direct session", () => {
9192
await driver.dispose();
9293
expect(mocks.endSession).toHaveBeenCalledWith({ session: sessionOptions.publicSession });
9394
});
95+
96+
it("keeps a missing native desktop library behind command availability", async () => {
97+
const loadSdk = vi.fn(() => {
98+
throw new Error("libX11.so.6: cannot open shared object file");
99+
});
100+
const driver = createCuaDriver({ loadSdk });
101+
102+
expect(loadSdk).not.toHaveBeenCalled();
103+
expect(driver.isAvailable()).toBe(false);
104+
expect(loadSdk).toHaveBeenCalledOnce();
105+
await expect(driver.getScreenSize()).rejects.toThrow(
106+
"COMPUTER_DRIVER_UNAVAILABLE: failed to load CUA Driver SDK: libX11.so.6",
107+
);
108+
109+
driver.resetAvailabilityCache();
110+
expect(driver.isAvailable()).toBe(false);
111+
expect(loadSdk).toHaveBeenCalledTimes(2);
112+
await driver.dispose();
113+
});
94114
});

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

Lines changed: 179 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,39 @@
11
import { randomUUID } from "node:crypto";
2-
import {
3-
CaptureScope,
4-
ClickButton,
5-
CuaDriver,
6-
DesktopScope,
7-
ScrollBy,
8-
ScrollDirection,
9-
SessionPermissionMode,
10-
createTrustedSession,
11-
type CuaDriverLike,
12-
type CuaDriverSessionLike,
13-
type ToolResult,
14-
} from "@trycua/cua-driver";
15-
16-
export type CuaToolResult = ToolResult;
2+
import { createRequire } from "node:module";
3+
4+
type DriverClickButton = import("@trycua/cua-driver").ClickButton;
5+
type CuaDriverLike = import("@trycua/cua-driver").CuaDriverLike;
6+
type CuaDriverSessionLike = import("@trycua/cua-driver").CuaDriverSessionLike;
7+
type DriverScrollDirection = import("@trycua/cua-driver").ScrollDirection;
8+
type CuaDriverSdk = Pick<
9+
typeof import("@trycua/cua-driver"),
10+
| "CaptureScope"
11+
| "CuaDriver"
12+
| "DesktopScope"
13+
| "ScrollBy"
14+
| "SessionPermissionMode"
15+
| "createTrustedSession"
16+
>;
17+
18+
export type CuaToolResult = import("@trycua/cua-driver").ToolResult;
19+
20+
// These numeric values are part of the pinned 0.14.1 SDK contract and are also
21+
// frozen in driver-contract-fixtures. Keeping them local avoids loading the
22+
// native library while OpenClaw is only registering the bundled plugin.
23+
export const ClickButton = {
24+
Left: 0 as DriverClickButton,
25+
Right: 1 as DriverClickButton,
26+
Middle: 2 as DriverClickButton,
27+
} as const;
28+
export type ClickButton = (typeof ClickButton)[keyof typeof ClickButton];
29+
30+
export const ScrollDirection = {
31+
Up: 0 as DriverScrollDirection,
32+
Down: 1 as DriverScrollDirection,
33+
Left: 2 as DriverScrollDirection,
34+
Right: 3 as DriverScrollDirection,
35+
} as const;
36+
export type ScrollDirection = (typeof ScrollDirection)[keyof typeof ScrollDirection];
1737

1838
export interface CuaDriverSession {
1939
readonly generation: string;
@@ -42,17 +62,6 @@ export interface CuaDriverSession {
4262
dispose(): Promise<void>;
4363
}
4464

45-
// This is an OpenClaw-owned ceiling, not plugin configuration or tool input.
46-
// The model can request only computer.act actions; it cannot select a session
47-
// or widen this authorization after the node host starts.
48-
const CUA_DRIVER_AUTHORIZATION = {
49-
allowedModes: [SessionPermissionMode.Unrestricted],
50-
compatibilityMode: SessionPermissionMode.Unrestricted,
51-
unrestrictedAcknowledged: true,
52-
maxSessionTtlSeconds: 3_600n,
53-
maxIdleTtlSeconds: 300n,
54-
};
55-
5665
function asyncOptions(signal?: AbortSignal) {
5766
return signal ? { signal } : undefined;
5867
}
@@ -66,18 +75,28 @@ class DirectCuaDriverSession implements CuaDriverSession {
6675
private started = false;
6776
private disposed = false;
6877

69-
constructor() {
78+
constructor(private readonly sdk: CuaDriverSdk) {
79+
const unrestricted = sdk.SessionPermissionMode.Unrestricted;
80+
// This is an OpenClaw-owned ceiling, not plugin configuration or tool input.
81+
// The model cannot select a session or widen this authorization after start.
82+
const authorization = {
83+
allowedModes: [unrestricted],
84+
compatibilityMode: unrestricted,
85+
unrestrictedAcknowledged: true,
86+
maxSessionTtlSeconds: 3_600n,
87+
maxIdleTtlSeconds: 300n,
88+
};
7089
// Never use CuaDriver.create(): configured creation fixes the authorization
7190
// ceiling before a single trusted OpenClaw session is admitted.
72-
this.runtime = CuaDriver.createConfigured({
91+
this.runtime = sdk.CuaDriver.createConfigured({
7392
claudeCodeCompatibility: false,
74-
authorization: { ...CUA_DRIVER_AUTHORIZATION },
93+
authorization,
7594
});
76-
this.session = createTrustedSession(this.runtime, {
95+
this.session = sdk.createTrustedSession(this.runtime, {
7796
publicSession: this.publicSession,
78-
mode: SessionPermissionMode.Unrestricted,
79-
ttlSeconds: CUA_DRIVER_AUTHORIZATION.maxSessionTtlSeconds,
80-
idleTtlSeconds: CUA_DRIVER_AUTHORIZATION.maxIdleTtlSeconds,
97+
mode: unrestricted,
98+
ttlSeconds: authorization.maxSessionTtlSeconds,
99+
idleTtlSeconds: authorization.maxIdleTtlSeconds,
81100
});
82101
}
83102

@@ -88,7 +107,7 @@ class DirectCuaDriverSession implements CuaDriverSession {
88107
if (!this.startPromise) {
89108
const start = this.session
90109
.startSession(
91-
{ session: this.publicSession, captureScope: CaptureScope.Desktop },
110+
{ session: this.publicSession, captureScope: this.sdk.CaptureScope.Desktop },
92111
asyncOptions(signal),
93112
)
94113
.then(() => {
@@ -131,20 +150,23 @@ class DirectCuaDriverSession implements CuaDriverSession {
131150
signal?: AbortSignal,
132151
) {
133152
return await this.invoke(signal, () =>
134-
this.session.click({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
153+
this.session.click({ ...input, scope: this.sdk.DesktopScope.Desktop }, asyncOptions(signal)),
135154
);
136155
}
137156
async drag(
138157
input: { fromX: number; fromY: number; toX: number; toY: number; durationMs?: bigint },
139158
signal?: AbortSignal,
140159
) {
141160
return await this.invoke(signal, () =>
142-
this.session.drag({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
161+
this.session.drag({ ...input, scope: this.sdk.DesktopScope.Desktop }, asyncOptions(signal)),
143162
);
144163
}
145164
async moveCursor(input: { x: number; y: number }, signal?: AbortSignal) {
146165
return await this.invoke(signal, () =>
147-
this.session.moveCursor({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
166+
this.session.moveCursor(
167+
{ ...input, scope: this.sdk.DesktopScope.Desktop },
168+
asyncOptions(signal),
169+
),
148170
);
149171
}
150172
async scroll(
@@ -153,19 +175,26 @@ class DirectCuaDriverSession implements CuaDriverSession {
153175
) {
154176
return await this.invoke(signal, () =>
155177
this.session.scroll(
156-
{ ...input, scope: DesktopScope.Desktop, by: ScrollBy.Line },
178+
{
179+
...input,
180+
scope: this.sdk.DesktopScope.Desktop,
181+
by: this.sdk.ScrollBy.Line,
182+
},
157183
asyncOptions(signal),
158184
),
159185
);
160186
}
161187
async typeText(text: string, signal?: AbortSignal) {
162188
return await this.invoke(signal, () =>
163-
this.session.typeText({ text, scope: DesktopScope.Desktop }, asyncOptions(signal)),
189+
this.session.typeText({ text, scope: this.sdk.DesktopScope.Desktop }, asyncOptions(signal)),
164190
);
165191
}
166192
async pressKey(input: { key: string; modifiers: string[] }, signal?: AbortSignal) {
167193
return await this.invoke(signal, () =>
168-
this.session.pressKey({ ...input, scope: DesktopScope.Desktop }, asyncOptions(signal)),
194+
this.session.pressKey(
195+
{ ...input, scope: this.sdk.DesktopScope.Desktop },
196+
asyncOptions(signal),
197+
),
169198
);
170199
}
171200

@@ -212,8 +241,115 @@ class DirectCuaDriverSession implements CuaDriverSession {
212241
}
213242
}
214243

215-
export function createCuaDriver(): CuaDriverSession {
216-
return new DirectCuaDriverSession();
244+
const require = createRequire(import.meta.url);
245+
246+
function loadCuaDriverSdk(): CuaDriverSdk {
247+
return require("@trycua/cua-driver") as CuaDriverSdk;
248+
}
249+
250+
function unavailableError(failure: unknown): Error {
251+
const detail = failure instanceof Error ? failure.message : String(failure);
252+
return new Error(`COMPUTER_DRIVER_UNAVAILABLE: failed to load CUA Driver SDK: ${detail}`, {
253+
cause: failure,
254+
});
217255
}
218256

219-
export { ClickButton, ScrollDirection };
257+
class LazyCuaDriverSession implements CuaDriverSession {
258+
private readonly unloadedGeneration = randomUUID();
259+
private runtime: DirectCuaDriverSession | undefined;
260+
private loadFailure: unknown;
261+
private hasLoadFailure = false;
262+
private disposed = false;
263+
264+
constructor(private readonly loadSdk: () => CuaDriverSdk) {}
265+
266+
get generation(): string {
267+
return this.runtime?.generation ?? this.unloadedGeneration;
268+
}
269+
270+
private resolveRuntime(): DirectCuaDriverSession | undefined {
271+
if (this.disposed || this.hasLoadFailure) {
272+
return undefined;
273+
}
274+
if (this.runtime) {
275+
return this.runtime;
276+
}
277+
try {
278+
this.runtime = new DirectCuaDriverSession(this.loadSdk());
279+
return this.runtime;
280+
} catch (error) {
281+
this.loadFailure = error;
282+
this.hasLoadFailure = true;
283+
return undefined;
284+
}
285+
}
286+
287+
private requireRuntime(): DirectCuaDriverSession {
288+
const runtime = this.resolveRuntime();
289+
if (runtime) {
290+
return runtime;
291+
}
292+
throw unavailableError(
293+
this.disposed ? new Error("cua-computer is stopping") : this.loadFailure,
294+
);
295+
}
296+
297+
isAvailable(): boolean {
298+
return this.resolveRuntime()?.isAvailable() ?? false;
299+
}
300+
301+
resetAvailabilityCache(): void {
302+
if (this.runtime) {
303+
this.runtime.resetAvailabilityCache();
304+
} else if (!this.disposed) {
305+
this.loadFailure = undefined;
306+
this.hasLoadFailure = false;
307+
}
308+
}
309+
310+
async getDesktopState(signal?: AbortSignal) {
311+
return await this.requireRuntime().getDesktopState(signal);
312+
}
313+
async getScreenSize(signal?: AbortSignal) {
314+
return await this.requireRuntime().getScreenSize(signal);
315+
}
316+
async click(
317+
input: { x: number; y: number; button: ClickButton; count: number },
318+
signal?: AbortSignal,
319+
) {
320+
return await this.requireRuntime().click(input, signal);
321+
}
322+
async drag(
323+
input: { fromX: number; fromY: number; toX: number; toY: number; durationMs?: bigint },
324+
signal?: AbortSignal,
325+
) {
326+
return await this.requireRuntime().drag(input, signal);
327+
}
328+
async moveCursor(input: { x: number; y: number }, signal?: AbortSignal) {
329+
return await this.requireRuntime().moveCursor(input, signal);
330+
}
331+
async scroll(
332+
input: { x: number; y: number; direction: ScrollDirection; amount: bigint },
333+
signal?: AbortSignal,
334+
) {
335+
return await this.requireRuntime().scroll(input, signal);
336+
}
337+
async typeText(text: string, signal?: AbortSignal) {
338+
return await this.requireRuntime().typeText(text, signal);
339+
}
340+
async pressKey(input: { key: string; modifiers: string[] }, signal?: AbortSignal) {
341+
return await this.requireRuntime().pressKey(input, signal);
342+
}
343+
344+
async dispose(): Promise<void> {
345+
if (this.disposed) {
346+
return;
347+
}
348+
this.disposed = true;
349+
await this.runtime?.dispose();
350+
}
351+
}
352+
353+
export function createCuaDriver(options: { loadSdk?: () => CuaDriverSdk } = {}): CuaDriverSession {
354+
return new LazyCuaDriverSession(options.loadSdk ?? loadCuaDriverSdk);
355+
}

‎scripts/e2e/lib/bundled-plugin-install-uninstall/runtime-smoke.mjs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,6 +1082,7 @@ async function smokePlugin(pluginId, pluginDir, requiresConfig, pluginIndex, plu
10821082
});
10831083
try {
10841084
await waitForReady({ child, port, logPath });
1085+
assertPluginLoaded(logPath, pluginId);
10851086
await assertBaseGatewayProbes({
10861087
entrypoint,
10871088
port,
@@ -1259,6 +1260,19 @@ export function assertGatewayLogNotTruncated(logPath) {
12591260
}
12601261
}
12611262

1263+
export function assertPluginLoaded(logPath, pluginId) {
1264+
let text;
1265+
try {
1266+
text = fs.readFileSync(logPath, "utf8");
1267+
} catch {
1268+
return;
1269+
}
1270+
const failurePrefix = `[plugins] ${pluginId} failed to load`;
1271+
if (text.includes(failurePrefix)) {
1272+
throw new Error(`${failurePrefix}: ${tailText(text)}`);
1273+
}
1274+
}
1275+
12621276
export function assertNoPostReadyRuntimeDepsWork(logPath, readyOffset) {
12631277
let stat;
12641278
try {

0 commit comments

Comments
 (0)