Repository navigation
Expand file tree
/
Copy pathnative.test.js
More file actions
589 lines (553 loc) · 33.7 KB
/
Copy pathnative.test.js
File metadata and controls
589 lines (553 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
const test = require('node:test');
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
test('Linux public inventory and window selectors use the trusted adapter', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const calls = [], writes = [];
const apps = ['22', '18446744073709551615'].map(id => ({
id: `linux-window:${id}`, displayName: 'editor', title: 'Document', focused: true, isRunning: true,
}));
globalThis.nodeRepl = { write: value => writes.push(value), rpc: async (_, request) => {
calls.push(request);
return request.method === 'list_apps' ? apps : { accessibility_tree: [] };
}};
try {
const cua = installLinuxComputerUse({
listWindows: () => assert.fail('upstream missing method must be replaced'),
getState: () => assert.fail('upstream state still uses the unsupported Sky proxy'),
listBrowsers: async options => {
assert.equal(options.emit, false);
return [{ id: 'iab' }];
},
listTabs: async options => {
assert.deepEqual(options, { browser: 'iab', emit: false });
return [{ id: 'tab-1' }];
},
});
const windows = await cua.listWindows({ emit: false });
assert.deepEqual(windows.map(window => window.id), [22, '18446744073709551615']);
assert.equal(writes.length, 0);
assert.deepEqual(await cua.getState({ emit: false }), {
apps, browsers: [{ id: 'iab', tabs: [{ id: 'tab-1' }] }],
});
for (const window of windows) {
const app = await cua.getApp({ windowId: window.id });
await app.pressKey('ESC');
assert.equal(calls.at(-1).app, `linux-window:${window.id}`);
}
const before = calls.length;
for (const windowId of [null, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, '', '1e3', '18446744073709551616']) {
await assert.rejects(cua.getApp({ windowId }), /exact windowId/);
}
assert.equal(calls.length, before);
const failedBrowser = installLinuxComputerUse({
listBrowsers: async () => { throw new Error('extension disconnected'); },
});
assert.deepEqual(await failedBrowser.getState({ emit: false }), {
apps, browsers: [], errors: ['Browsers: Error: extension disconnected'],
});
} finally { globalThis.nodeRepl = original; }
});
test('native client preserves browser inventory and binds native actions to selected app', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const calls = [];
const original = globalThis.nodeRepl;
globalThis.nodeRepl = { write() {}, rpc: async (service, request) => {
calls.push([service, request]);
if (request.method === 'list_apps') return [{ id: 'org.example.Editor', isRunning: true }];
if (request.method === 'get_app_state') return { accessibility_tree: [{ name: 'Document' }] };
return { ok: true };
}};
try {
const cua = { listBrowsers: async () => [{ id: 'iab' }], listTabs: async () => [] };
installLinuxComputerUse(cua);
const expected = { apps: [{ id: 'org.example.Editor', isRunning: true }], browsers: [{ id: 'iab', tabs: [] }] };
assert.deepEqual(await cua.getState({ emit: false }), expected);
assert.deepEqual(await cua.initialize({ emit: false }), expected);
const app = await cua.getApp('org.example.Editor');
await app.click([2, 3]);
assert.deepEqual(calls.at(-1), ['sky', { method: 'click', app: 'org.example.Editor', params: { x: 2, y: 3, button: 'left', click_count: 1, relative: true } }]);
const before = calls.length;
await assert.rejects(app.drag({ x: 1, y: 2 }, { x: 3, y: 4 }), /not supported/);
await assert.rejects(app.paste('x', { format: 'html' }), /not supported/);
assert.equal(calls.length, before);
} finally { globalThis.nodeRepl = original; }
});
test('trusted service validates requests before backend launch', async () => {
const { handleRpc } = await import('./native-service.mjs');
await assert.rejects(handleRpc({ method: 'drag', app: 'editor', params: {} }), /not supported/);
await assert.rejects(handleRpc({ method: 'click', app: 'editor', params: { window_id: 22 } }), /parameter/);
for (const params of [
{max_nodes:0}, {max_nodes:10001}, {max_depth:-1}, {max_depth:65},
{max_width:0}, {max_height:4097}, {max_bytes:1023}, {max_bytes:4194305},
{scale:0}, {scale:1.1}, {format:'webp'}, {quality:0}, {quality:96},
]) {
const method = Object.keys(params)[0].startsWith('max_n') || Object.hasOwn(params, 'max_depth') ? 'get_app_state' : 'screenshot';
await assert.rejects(handleRpc({method, app:'editor', params}), /Invalid native/);
}
});
test('trusted service answers the official Linux Sky setup handshake without launching the backend', async () => {
const { createNativeService } = await import('./native-service.mjs');
const service = createNativeService({ connect: () => assert.fail('setup must not connect to the host bridge') });
assert.deepEqual(await service.handleRpc({ type: 'setup' }), {
target: 'linux',
methods: [],
});
});
test('trusted service uses the native-pipe host bridge and accepts fragmented responses', async () => {
const { createNativeService } = await import('./native-service.mjs');
class FakeConnection extends EventEmitter {
writes = [];
ended = false;
write(data) {
this.writes.push(Buffer.from(data));
const request = JSON.parse(Buffer.from(data).toString('utf8'));
const response = Buffer.from(`${JSON.stringify({ id: request.id, result: [{ id: 'linux-window:22', isRunning: true }] })}\n`);
queueMicrotask(() => {
this.emit('data', response.subarray(0, 7));
this.emit('data', response.subarray(7));
});
}
end() { this.ended = true; }
}
const connection = new FakeConnection();
const service = createNativeService({ connect: async () => connection, timeoutMs: 1000 });
const apps = await service.handleRpc({ method: 'list_apps' });
assert.deepEqual(apps, [{ id: 'linux-window:22', isRunning: true }]);
assert.deepEqual(JSON.parse(Buffer.concat(connection.writes).toString('utf8')).input, { method: 'list_apps' });
service.shutdown();
assert.equal(connection.ended, true);
});
test('default trusted service reads only the privileged NodeREPL socket context', async () => {
const { createNativeService } = await import('./native-service.mjs');
const original = globalThis.nodeRepl;
const connection = new EventEmitter();
connection.end = () => {};
connection.write = data => {
const { id } = JSON.parse(Buffer.from(data).toString('utf8'));
queueMicrotask(() => connection.emit('data', Buffer.from(`${JSON.stringify({ id, result: [] })}\n`)));
};
let requestedPath;
globalThis.nodeRepl = {
env: { CODEX_LINUX_CUA_HOST_SOCKET: '/run/user/1000/codex-desktop/computer-use-native.sock' },
nativePipe: { createConnection: async value => { requestedPath = value; return connection; } },
};
try {
assert.deepEqual(await createNativeService().handleRpc({ method: 'list_apps' }), []);
assert.equal(requestedPath, globalThis.nodeRepl.env.CODEX_LINUX_CUA_HOST_SOCKET);
} finally { globalThis.nodeRepl = original; }
});
const { mkdtemp, writeFile, readFile, rm } = require('node:fs/promises');
const { tmpdir } = require('node:os');
const { join } = require('node:path');
async function fixture(t, { windowId, structured = false, capture = false, captureError = false, captureMalformed } = {}) {
const dir = await mkdtemp(join(tmpdir(), 'native-mcp-'));
const script = join(dir, 'backend.cjs');
const log = join(dir, 'requests.jsonl');
await writeFile(script, `
const readline = require('node:readline');
let initialized = false, focused = false;
readline.createInterface({ input: process.stdin }).on('line', line => {
const r = JSON.parse(line);
const reply = result => process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result})+'\\n');
if(r.method === 'initialize') return reply({protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'fixture',version:'1'}});
if(r.method === 'notifications/initialized') { initialized=true; return; }
if(!initialized) process.exit(9);
const {name,arguments:a} = r.params;
// The host pages a tree from the backend's cache; that read is not a desktop call.
if(name === 'get_tree_page') return reply({structuredContent:{nodes:[],offset:a.offset,next_offset:null,node_count:1,message:''},content:[]});
require('node:fs').appendFileSync(${JSON.stringify(log)}, line+'\\n');
if (${capture}) {
if(name === 'get_app_state') return reply({content:[{type:'text',text:JSON.stringify({accessibility_tree:[{name:'Document'}],window_context:{focused},...(a.include_screenshot ? {screenshot_error:'requested window is not focused'} : {})})}]});
if(name === 'screenshot') {
if(${captureError}) return reply({isError:true,content:[{type:'text',text:'requested window could not be focused exactly'}]});
focused = true;
return reply({content:[{type:'image',mimeType:'image/png',data:'AQID'},{type:'text',text:JSON.stringify({width:100,height:50,coordinate_width:200,coordinate_height:100,cropped_to_window:${captureMalformed !== 'uncropped'},scale:0.5})}].filter(item => !(${captureMalformed === 'missing-image'} && item.type === 'image'))});
}
return reply({isError:true,content:[{type:'text',text:'unexpected operation'}]});
}
if(a.text === 'exit') process.exit(7);
if(a.text === 'tool-error') return reply({isError:true,content:[{type:'text',text:'denied by backend'}]});
if(a.window_id === 99) return reply({structuredContent:{window_error:'window no longer exists',accessibility_tree:[]},content:[]});
if(a.text === 'malformed') return process.stdout.write('garbage\\n');
if(a.text === 'hang') return;
if(a.text === 'action-error') return reply({structuredContent:{ok:false,message:'focus changed'},content:[]});
const windowId = ${JSON.stringify(windowId ?? null)};
if(windowId !== null) {
// Construct numeric tokens from strings so the fixture cannot round them.
const raw = name === 'list_windows'
? '{"windows":[{"window_id":'+windowId+',"title":"Document","app_id":"editor","focused":true}]}'
: '{"ok":true,"window_id":'+windowId+',"received":'+JSON.stringify(line)+'}';
if(${structured}) return process.stdout.write('{"jsonrpc":"2.0","id":'+r.id+',"result":{"structuredContent":'+raw+'}}'+'\\n');
return reply({content:[{type:'text',text:raw}]});
}
let data = name === 'list_windows' ? {windows:[{window_id:22,title:'Document',app_id:'editor',focused:true}]} : {ok:true,name,arguments:a};
reply({content:[{type:'text',text:JSON.stringify(data)}]});
});
`);
const { createNativeBackendService } = await import('./native-backend-service.mjs');
const service = createNativeBackendService({ command: process.execPath, args: [script], timeoutMs: 1000 });
t.after(async () => { service.shutdown(); await rm(dir, {recursive:true,force:true}); });
return { ...service, readCalls: async () => (await readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line, (key, value, context) => key === 'window_id' ? context.source : value).params) };
}
test('MCP initialization, exact window IDs, targeted inputs and desktop inputs', async t => {
const service = await fixture(t);
assert.deepEqual(await service.handleRpc({method:'list_apps'}), [{id:'linux-window:22',displayName:'editor',title:'Document',isRunning:true,focused:true}]);
const result = await service.handleRpc({method:'click',app:'linux-window:22',params:{x:2,y:3,relative:true}});
assert.deepEqual(result.arguments, {x:2,y:3,relative:true,window_id:22});
const zero = await service.handleRpc({method:'click',app:'linux-window:0',params:{x:2,y:3}});
assert.equal(zero.arguments.window_id, 0);
const desktop = await service.handleRpc({method:'press_key',params:{key:'ESC'}});
assert.deepEqual(desktop.arguments, {key:'ESC'});
});
test('trusted service forwards bounded observation options exactly', async t => {
const stateService = await fixture(t);
const state = await stateService.handleRpc({method:'get_app_state',app:'editor',params:{include_screenshot:true,max_nodes:20,max_depth:5,max_width:800,max_height:600,max_bytes:65536,scale:0.5,format:'jpeg',quality:70}});
assert.deepEqual(state.arguments, {include_screenshot:true,max_nodes:20,max_depth:5,max_width:800,max_height:600,max_bytes:65536,scale:0.5,format:'jpeg',quality:70,app_id:'editor'});
const captureService = await fixture(t, {capture:true});
await captureService.handleRpc({method:'screenshot',app:'editor',params:{max_width:800,max_height:600,max_bytes:65536,scale:0.5,format:'jpeg',quality:70}});
const calls = await captureService.readCalls();
assert.deepEqual(calls.at(-1).arguments, {max_width:800,max_height:600,max_bytes:65536,scale:0.5,format:'jpeg',quality:70,app_id:'editor'});
});
test('native client compacts and suppresses repeated large accessibility observations', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const calls = [], writes = [];
const tree = Array.from({length:237}, (_, index) => ({
index,
parent_index:index ? index - 1 : null,
depth:index,
object_ref:`:1.234/org/a11y/atspi/accessible/${'metadata'.repeat(8)}/${index}`,
role:index === 236 ? 'button' : 'section',
name:index === 236 ? 'Save' : null,
description:null,
child_count:index === 236 ? 0 : 1,
bounds:index === 236 ? {x:40,y:50,width:80,height:30} : null,
states:['enabled','sensitive','showing','visible','focusable',...(index === 236 ? ['focused','selected'] : [])],
actions:[{index:0,name:index === 236 ? 'click' : '',description:'',keybinding:''}],
value:null,
text:{character_count:1,caret_offset:0,content:' \uFFFC ',truncated:false,selections:[]},
supports_editable_text:true,
}));
let response = {accessibility_tree:tree,window_context:{focused:true}};
globalThis.nodeRepl = {
write:value=>writes.push(value),
rpc:async (_, request)=>{calls.push(request); return response;},
};
try {
const app = await installLinuxComputerUse({}).getApp('editor');
const initial = writes.find(value => typeof value === 'string' && value.startsWith('{'));
const compact = JSON.parse(initial);
const button = compact.accessibility_tree.at(-1);
assert.ok(initial.length < JSON.stringify(response).length / 2);
assert.equal(button.index,236);
assert.equal(button.parent_index,235);
assert.deepEqual(button.bounds,{x:40,y:50,width:80,height:30});
assert.equal(button.states,'enabled sensitive showing visible focusable focused selected');
assert.deepEqual(button.actions,['click']);
assert.equal(button.actionable,true);
assert.equal(button.editable,true);
assert.equal(button.object_ref,undefined);
assert.equal(button.text.content,undefined);
const repeated = JSON.parse(await app.getAXState({emit:false,maxNodes:20,maxDepth:5}));
assert.deepEqual(repeated,{accessibility_tree_unchanged:true});
assert.deepEqual(calls.at(-1).params,{include_screenshot:false,max_nodes:20,max_depth:5});
const refreshed = JSON.parse(await app.getAXState({emit:false,disableDiffing:true,max_nodes:21,max_depth:6}));
assert.equal(refreshed.accessibility_tree.length,237);
assert.deepEqual(calls.at(-1).params,{include_screenshot:false,max_nodes:21,max_depth:6});
const full = JSON.parse(await app.getAXState({emit:false,compact:false}));
assert.match(full.accessibility_tree[0].object_ref,/org\/a11y/);
assert.deepEqual(calls.at(-1).params,{include_screenshot:false,verbose:true});
response = {...response,accessibility_tree:tree.map((node,index) => index === 236
? {...node,states:node.states.filter(state => state !== 'enabled' && state !== 'showing')}
: node)};
const disabled = JSON.parse(await app.getAXState({emit:false}));
assert.doesNotMatch(disabled.accessibility_tree.at(-1).states,/enabled|showing/);
response = {...response,window_context:{focused:false}};
const changed = JSON.parse(await app.getAXState({emit:false}));
assert.equal(changed.window_context.focused,false);
await assert.rejects(app.getAXState({maxNodes:20,max_nodes:21}),/Conflicting maxNodes/);
} finally { globalThis.nodeRepl=original; }
});
test('native client keeps action names from compact backend nodes', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
globalThis.nodeRepl = {
write(){},
rpc:async () => ({accessibility_tree:[{
index:0, depth:0, object_ref:':1.234/org/a11y/atspi/accessible/0', role:'push button',
name:'Save', states:['enabled','focusable'], actions:['click','press'],
}]}),
};
try {
const app = await installLinuxComputerUse({}).getApp('editor');
const [button] = JSON.parse(await app.getAXState({emit:false,disableDiffing:true})).accessibility_tree;
assert.deepEqual(button.actions,['click','press']);
assert.equal(button.actionable,true);
} finally { globalThis.nodeRepl=original; }
});
test('native verbose is a boolean get_app_state parameter', async () => {
const { validateNativeRequest } = await import('./native-protocol.mjs');
assert.doesNotThrow(() => validateNativeRequest({method:'get_app_state', params:{verbose:true}}));
assert.throws(() => validateNativeRequest({method:'get_app_state', params:{verbose:'yes'}}), /Invalid native verbose/);
assert.throws(() => validateNativeRequest({method:'screenshot', app:'editor', params:{verbose:true}}), /Unsupported native operation parameter/);
});
test('native client routes screenshot limits separately from accessibility limits', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const calls = [];
globalThis.nodeRepl = {
write(){},
emitImage:async()=>{},
rpc:async (_, request) => {
calls.push(request);
return request.method === 'screenshot'
? {screenshot:{data_url:'data:image/png;base64,AQID',width:100,height:50,coordinate_width:100,coordinate_height:50}}
: {accessibility_tree:[]};
},
};
try {
const app = await installLinuxComputerUse({}).getApp('editor');
await app.getAXStateAndScreenshot({
emit:false, disableDiffing:true, maxNodes:40, maxDepth:7,
maxWidth:800, maxHeight:600, maxBytes:65536, scale:0.5, format:'jpeg', quality:70,
});
const [capture, state] = calls.slice(-2);
assert.deepEqual(capture.params,{max_width:800,max_height:600,max_bytes:65536,scale:0.5,format:'jpeg',quality:70});
assert.deepEqual(state.params,{include_screenshot:false,max_nodes:40,max_depth:7});
} finally { globalThis.nodeRepl=original; }
});
for (const structured of [false, true]) {
for (const windowId of ['1017417960236020624', '18446744073709551615']) {
test(`u64 window IDs round trip exactly through ${structured ? 'structuredContent' : 'text JSON'}: ${windowId}`, async t => {
const service = await fixture(t, { windowId, structured });
const apps = await service.handleRpc({ method: 'list_apps' });
assert.equal(apps[0].id, `linux-window:${windowId}`);
const result = await service.handleRpc({ method: 'click', app: apps[0].id, params: { x: 2, y: 3 } });
// Match the wire token, not JSON.parse's rounded interpretation of it.
assert.match(result.received, new RegExp(`"window_id":${windowId}(?=[,}])`));
assert.equal(result.window_id, windowId);
assert.deepEqual(JSON.parse(JSON.stringify(result)), result);
assert.deepEqual(structuredClone(result), result);
});
}
}
test('invalid and out-of-range window IDs are rejected before backend dispatch', async t => {
const { createNativeBackendService } = await import('./native-backend-service.mjs');
const service = createNativeBackendService({ command: '/nonexistent/native-backend' });
t.after(() => service.shutdown());
for (const id of ['', '-1', '1.5', '1e3', ' 22', '+22', '18446744073709551616']) {
await assert.rejects(service.handleRpc({ method: 'click', app: `linux-window:${id}`, params: { x: 2, y: 3 } }), /Invalid native window id/);
}
});
test('backend errors surface and an exited backend is never silently replayed or restarted', async t => {
const service = await fixture(t);
await assert.rejects(service.handleRpc({method:'type_text',params:{text:'tool-error'}}), /denied by backend/);
await assert.rejects(service.handleRpc({method:'type_text',params:{text:'action-error'}}), /focus changed/);
await assert.rejects(service.handleRpc({method:'type_text',params:{text:'exit'}}), /exited/);
await assert.rejects(service.handleRpc({method:'list_apps'}), /exited/);
});
test('missing targets, shutdown and malformed protocol fail without replay', async t => {
const service = await fixture(t);
await assert.rejects(service.handleRpc({method:'get_app_state',app:'linux-window:99'}), /window no longer exists/);
await assert.rejects(service.handleRpc({method:'type_text',params:{text:'malformed'}}), /invalid JSON/);
await assert.rejects(service.handleRpc({method:'list_apps'}), /invalid JSON/);
const stopped = await fixture(t);
stopped.shutdown();
await assert.rejects(stopped.handleRpc({method:'list_apps'}), /shut down/);
});
test('timed-out input poisons the transport rather than allowing replay', async t => {
const service = await fixture(t);
await assert.rejects(service.handleRpc({method:'type_text',params:{text:'hang'}}), /timed out/);
await assert.rejects(service.handleRpc({method:'list_apps'}), /timed out/);
});
test('native observations return image bytes and expose screenshot errors and coordinate space', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const images = [];
const window = { x: 300, y: 200, width: 200, height: 100 };
const tree = [{name:'Button',bounds:{x:350,y:250,width:20,height:10}}];
let response = {accessibility_tree:tree,window_context:window,screenshot:{data_url:'data:image/png;base64,AQID',width:100,height:50,coordinate_width:200,coordinate_height:100}};
globalThis.nodeRepl = {write(){},emitImage:async value=>images.push(value),rpc:async()=>response};
try {
const app=await installLinuxComputerUse({}).getApp('linux-window:22');
const observed=await app.getAXStateAndScreenshot({emit:false,disableDiffing:true});
assert.deepEqual([...observed.screenshot],[1,2,3]);
const state = JSON.parse(observed.state);
assert.deepEqual(state.accessibility_tree, tree);
assert.deepEqual(state.window_context, window);
assert.equal(state.coordinates.accessibility_bounds, 'screen');
assert.match(state.coordinates.input, /window-relative/);
assert.match(state.coordinates.guidance, /Do not pass accessibility bounds directly/);
assert.equal(images.length,0);
await app.getScreenshot();
assert.equal(images.length,1);
response={accessibility_tree:[],screenshot_error:'capture unavailable'};
await assert.rejects(app.getScreenshot(),/capture unavailable/);
assert.match((await app.getAXStateAndScreenshot({emit:false})).state,/capture unavailable/);
await assert.rejects(async()=>app.click(3),/element-index.*not supported/);
} finally { globalThis.nodeRepl=original; }
});
for (const api of ['getScreenshot', 'getAXStateAndScreenshot']) {
test(`${api} captures a background exact u64 target through client and service`, async t => {
const service = await fixture(t, { capture: true });
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const images = [], writes = [];
globalThis.nodeRepl = { write: value => writes.push(value), emitImage: async value => images.push(value), rpc: (_, request) => service.handleRpc(request) };
try {
const app = await installLinuxComputerUse({}).getApp('linux-window:18446744073709551615');
assert.equal(JSON.parse(await app.getAXState({emit:false,disableDiffing:true})).window_context.focused, false);
const result = await app[api](api === 'getAXStateAndScreenshot' ? {disableDiffing:true} : {});
assert.deepEqual([...(api === 'getScreenshot' ? result : result.screenshot)], [1,2,3]);
assert.deepEqual(images, ['data:image/png;base64,AQID']);
assert.deepEqual(writes.find(value => value?.screenshot)?.screenshot, {width:100,height:50,coordinate_width:200,coordinate_height:100});
if (api === 'getAXStateAndScreenshot') {
const state = JSON.parse(result.state);
assert.equal(state.window_context.focused, true);
assert.deepEqual(state.accessibility_tree, [{name:'Document'}]);
assert.equal(state.screenshot.coordinate_width, 200);
}
const calls = await service.readCalls();
assert.equal(calls.filter(call => call.name === 'screenshot').length, 1);
assert.ok(calls.every(call => call.arguments.window_id === '18446744073709551615'));
assert.ok(calls.filter(call => call.name === 'get_app_state').every(call => call.arguments.include_screenshot === false));
} finally { globalThis.nodeRepl = original; }
});
test(`${api} exposes failed exact activation without capture fallback or replay`, async t => {
const service = await fixture(t, {capture:true, captureError:true});
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
globalThis.nodeRepl = {write(){}, emitImage: async () => assert.fail('failed capture emitted an image'), rpc: (_, request) => service.handleRpc(request)};
try {
const app = await installLinuxComputerUse({}).getApp('editor');
if(api === 'getScreenshot') await assert.rejects(app[api]({emit:false}), /could not be focused exactly/);
else {
const result = await app[api]({emit:false});
assert.match(JSON.parse(result.state).screenshot_error, /could not be focused exactly/);
assert.equal(result.screenshot, undefined);
}
const calls = await service.readCalls();
assert.equal(calls.filter(call => call.name === 'screenshot').length, 1);
assert.ok(calls.every(call => call.arguments.app_id === 'editor'));
assert.ok(calls.every(call => call.name === 'screenshot' || (call.name === 'get_app_state' && call.arguments.include_screenshot === false)));
} finally { globalThis.nodeRepl = original; }
});
}
test('screenshot service requires a target and rejects desktop or focus overrides before launch', async t => {
const { createNativeBackendService } = await import('./native-backend-service.mjs');
const service = createNativeBackendService({command:'/nonexistent/native-backend'});
t.after(() => service.shutdown());
await assert.rejects(service.handleRpc({method:'screenshot'}), /app id is required/);
for (const params of [{full_screen:true}, {raise_window:false}, {window_id:22}]) {
await assert.rejects(service.handleRpc({method:'screenshot',app:'editor',params}), /parameter/);
}
});
for (const captureMalformed of ['missing-image', 'uncropped']) {
test(`screenshot service rejects ${captureMalformed} backend capture`, async t => {
const service = await fixture(t, {capture:true, captureMalformed});
await assert.rejects(service.handleRpc({method:'screenshot',app:'editor'}), /targeted screenshot/);
});
}
// Like the real backend: a large tree comes back as its leading nodes, the whole tree
// stays cached, and get_tree_page pages it. Each snapshot replaces the cache.
async function spillFixture(t, { nodes = 500, spill = true, nameBytes = 20, treeBudgetBytes, replaceOnPage } = {}) {
const { mkdtemp, writeFile: write, rm: remove } = await import('node:fs/promises');
const { tmpdir: tmp } = await import('node:os');
const { join: joinPath } = await import('node:path');
const dir = await mkdtemp(joinPath(tmp(), 'cul-spill-native-'));
const script = joinPath(dir, 'backend.cjs');
await write(script, `
let cache = [], sequence = 0, id = '', pages = 0;
require('node:readline').createInterface({input:process.stdin}).on('line', line => {
const r = JSON.parse(line);
const reply = result => process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result})+'\\n');
if (r.method === 'initialize') return reply({protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'fixture',version:'1'}});
if (r.method === 'notifications/initialized') return;
const {name, arguments: a} = r.params;
if (name === 'get_tree_page') {
// Another caller's snapshot replaces the cache before this page.
if (++pages === ${replaceOnPage ?? 0}) {
cache = Array.from({length:${nodes}}, (_, index) => ({index, role:'push button', name:'Node '+index+' of call replaced'}));
id = 'fixture-replaced';
}
if (a.snapshot_id !== undefined && a.snapshot_id !== id)
return reply({structuredContent:{nodes:[], offset:a.offset ?? 0, next_offset:null, node_count:0, message:'snapshot_id is not the cached snapshot'}, content:[]});
const start = Math.min(a.offset ?? 0, cache.length), end = Math.min(start + 100, cache.length);
return reply({structuredContent:{snapshot_id:id, nodes:cache.slice(start, end), offset:start, next_offset:end < cache.length ? end : null, node_count:cache.length, message:''}, content:[]});
}
const call = sequence++;
id = 'fixture-' + call;
cache = Array.from({length:${nodes}}, (_, index) => ({index, role:'push button', name:'Node '+index+' of call '+call+' '+'x'.repeat(${nameBytes})}));
// A failed spill write: no accessibility_tree_spill, only the leading nodes.
reply({structuredContent:{snapshot_id:id, accessibility_tree:cache.slice(0, 3), accessibility_tree_truncated:false,
...(${spill} ? {accessibility_tree_spill:{path:'/run/user/1000/codex-computer-use-linux/trees/tree-1-2-'+call+'.json', node_count:cache.length, bytes:1, inline_node_count:3}} : {})}, content:[]});
});
`);
const { createNativeBackendService } = await import('./native-backend-service.mjs');
const service = createNativeBackendService({ command: process.execPath, args: [script], timeoutMs: 5000, ...(treeBudgetBytes ? {treeBudgetBytes} : {}) });
t.after(async () => { service.shutdown(); await remove(dir, {recursive:true, force:true}); });
return service;
}
test('a large tree reaches the agent whole, and concurrent snapshots each get their own', async t => {
const service = await spillFixture(t);
const state = await service.handleRpc({method:'get_app_state', app:'editor', params:{max_nodes:10000}});
assert.equal(state.accessibility_tree.length, 500);
assert.equal(state.accessibility_tree.at(-1).index, 499);
assert.match(state.accessibility_tree.at(-1).name, /^Node 499 of call 0 /);
assert.equal(state.accessibility_tree_spill, undefined);
assert.equal(state.accessibility_tree_note, undefined);
// Each snapshot replaces the cache; calls are serialized, so each pages its own.
const [a, b] = await Promise.all([
service.handleRpc({method:'get_app_state', app:'editor', params:{}}),
service.handleRpc({method:'get_app_state', app:'editor', params:{}}),
]);
assert.ok(a.accessibility_tree.every(node => node.name.includes('of call 1 ')));
assert.ok(b.accessibility_tree.every(node => node.name.includes('of call 2 ')));
assert.equal(a.accessibility_tree.length, 500);
});
test('a tree replaced while it is paged comes back partial instead of mixed', async t => {
const service = await spillFixture(t, {replaceOnPage:3});
const state = await service.handleRpc({method:'get_app_state', app:'editor', params:{}});
assert.equal(state.snapshot_id, 'fixture-0');
// The leading 3 nodes and two 100-node pages, all from the first snapshot.
assert.equal(state.accessibility_tree.length, 203);
assert.ok(state.accessibility_tree.every(node => node.name.includes('of call 0 ')));
assert.equal(state.accessibility_tree_truncated, true);
assert.match(state.accessibility_tree_note, /203 of 500 nodes; a newer snapshot replaced this one/);
});
test('a tree the backend could not spill to a file is still returned whole', async t => {
const service = await spillFixture(t, {spill:false});
const state = await service.handleRpc({method:'get_app_state', app:'editor', params:{}});
assert.equal(state.accessibility_tree.length, 500);
});
test('a tree larger than the bridge comes back partial and says so', async t => {
const service = await spillFixture(t, {nameBytes:1000, treeBudgetBytes:200_000});
const state = await service.handleRpc({method:'get_app_state', app:'editor', params:{}});
assert.ok(state.accessibility_tree.length > 3 && state.accessibility_tree.length < 500, String(state.accessibility_tree.length));
assert.ok(Buffer.byteLength(JSON.stringify(state)) <= 200_000 + 4096);
assert.equal(state.accessibility_tree_truncated, true);
assert.match(state.accessibility_tree_note, new RegExp(`${state.accessibility_tree.length} of 500 nodes`));
});
test('the native client passes the partial-tree marker to the agent', async () => {
const { installLinuxComputerUse } = await import('./native-client.mjs');
const original = globalThis.nodeRepl;
const writes = [];
const response = {accessibility_tree:[{index:0,role:'frame',states:[],actions:[]}], window_context:{focused:true},
accessibility_tree_truncated:true, accessibility_tree_note:'Partial tree: 1 of 9 nodes fit the host bridge.'};
globalThis.nodeRepl = { write:value=>writes.push(value), rpc:async () => response };
try {
const app = await installLinuxComputerUse({}).getApp('editor');
const state = JSON.parse(await app.getAXState({emit:false, disableDiffing:true}));
assert.equal(state.accessibility_tree_truncated, true);
assert.match(state.accessibility_tree_note, /1 of 9 nodes/);
} finally {
globalThis.nodeRepl = original;
}
});
test('native max_nodes accepts the backend cap of 10000', async () => {
const { validateNativeRequest } = await import('./native-protocol.mjs');
assert.doesNotThrow(() => validateNativeRequest({method:'get_app_state', params:{max_nodes:10000}}));
assert.throws(() => validateNativeRequest({method:'get_app_state', params:{max_nodes:10001}}), /Invalid native max_nodes/);
});