Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

create-computer-use.test.ts

933 lines27.1 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { CapabilityRegistry } from '@tanstack/ai'
3import { createComputerUse } from '../src/create-computer-use'
4import { computerSafetyCheck } from '../src/safety-check'
5import type {
6 ChatMiddlewareContext,
7 GenericInterruptResolution,
8 InterruptResolutionCollection,
9 ModelMessage,
10} from '@tanstack/ai'
11import type { ComputerDriver, ComputerDriverFactory } from '../src/types'
12​
13const PNG_BYTES = new Uint8Array([137, 80, 78, 71])
14const PNG_BASE64 = 'iVBORw=='
15const ZOOM_BYTES = new Uint8Array([1, 2, 3])
16const ZOOM_BASE64 = 'AQID'
17​
18const THREAD = 'thread'
19const CLICK = { action: { type: 'click', x: 10, y: 20, button: 'left' } }
20const TYPE = { action: { type: 'type', text: 'hi' } }
21const CHECK = { id: 'sc_1', code: 'malicious_instructions', message: 'Look.' }
22const CHECKED_CLICK = { ...CLICK, pending_safety_checks: [CHECK] }
23const NOT_EXECUTED =
24 'Not executed: an earlier computer action in this turn failed.'
25const FULL_URL = 'a full URL that starts with https:// or http://'
26​
27function screenshotOf(base64: string) {
28 return [
29 {
30 type: 'image',
31 source: { type: 'data', value: base64, mimeType: 'image/png' },
32 },
33 ]
35​
36/** A gate that holds an action until the test opens it. */
37function createGate() {
38 let open = () => {}
39 const gate = new Promise<void>((resolve) => {
40 open = resolve
41 })
42 return { gate, open }
44​
45interface DriverOptions {
46 zoom?: boolean
47 cursor?: boolean
48 navigate?: boolean
49 /** `click` throws while this returns true. */
50 failClick?: () => boolean
51 /** `click` waits for this promise. */
52 clickGate?: Promise<void>
53 /** The bytes that `screenshot` returns. The default is `PNG_BYTES`. */
54 screenshot?: Uint8Array
56​
57/** A driver that records its calls in order. */
58function createDriver(options: DriverOptions = {}) {
59 const calls: Array<string> = []
60 const record = (name: string) => async () => {
61 calls.push(name)
62 }
63 const driver: ComputerDriver = {
64 display: { width: 1024, height: 768 },
65 environment: 'browser',
66 screenshot: async () => {
67 calls.push('screenshot')
68 return options.screenshot ?? PNG_BYTES
69 },
70 click: async () => {
71 calls.push('click:start')
72 await options.clickGate
73 if (options.failClick?.()) throw new Error('click failed')
74 calls.push('click:end')
75 },
76 move: record('move'),
77 mouseDown: record('mouseDown'),
78 mouseUp: record('mouseUp'),
79 scroll: record('scroll'),
80 keyDown: record('keyDown'),
81 keyUp: record('keyUp'),
82 press: record('press'),
83 type: record('type'),
84 close: record('close'),
85 }
86 if (options.zoom) driver.zoom = async () => ZOOM_BYTES
87 if (options.cursor) driver.cursorPosition = async () => ({ x: 7, y: 9 })
88 if (options.navigate) {
89 driver.navigate = async (url) => {
90 calls.push(`navigate:${url}`)
91 }
92 }
93 return { driver, calls }
95​
96interface FactoryOptions extends DriverOptions {
97 /** `create` throws while this returns true. */
98 failCreate?: () => boolean
99 /** `close` throws while this returns true. */
100 failClose?: () => boolean
102​
103/** A factory that records each created machine and each close. */
104function createFactory(options: FactoryOptions = {}) {
105 const created: Array<string> = []
106 const closed: Array<string> = []
107 const machines = new Map<string, Array<string>>()
108 const factory: ComputerDriverFactory = {
109 display: { width: 1280, height: 800 },
110 environment: 'linux',
111 capabilities: {
112 zoom: options.zoom ?? false,
113 cursorPosition: options.cursor ?? false,
114 navigate: options.navigate ?? false,
115 },
116 async create({ threadId }) {
117 created.push(threadId)
118 if (options.failCreate?.()) throw new Error('create failed')
119 const { driver, calls } = createDriver(options)
120 driver.close = async () => {
121 closed.push(threadId)
122 if (options.failClose?.()) throw new Error('close failed')
123 }
124 machines.set(threadId, calls)
125 return driver
126 },
127 async close() {
128 closed.push('factory')
129 },
130 }
131 return { factory, created, closed, machines }
133​
134interface SetupOptions {
135 screenshotDelay?: number
136 idleTimeout?: number | false
138​
139/** `createComputerUse`, plus helpers that call its tools as `chat()` does. */
140function setupWith(
141 driver: ComputerDriver | ComputerDriverFactory,
142 options: SetupOptions = {},
143) {
144 const computer = createComputerUse({
145 driver,
146 screenshotDelay: options.screenshotDelay ?? 0,
147 idleTimeout: options.idleTimeout,
148 })
149 const [computerTool, navigateTool] = computer.tools
150 const execute = (
151 input: unknown,
152 toolCallId = 'call_1',
153 threadId = THREAD,
154 ) => {
155 if (!computerTool.execute) throw new Error('The tool has no execute.')
156 return computerTool.execute(input, {
157 toolCallId,
158 threadId,
159 emitCustomEvent() {},
160 })
161 }
162 const navigate = (url: string, threadId = THREAD) => {
163 if (!navigateTool?.execute) throw new Error('There is no navigate tool.')
164 return navigateTool.execute(
165 { url },
166 { toolCallId: 'call_nav', threadId, emitCustomEvent() {} },
167 )
168 }
169 return { ...computer, execute, navigate }
171​
172function setup(options: DriverOptions & SetupOptions = {}) {
173 const { driver, calls } = createDriver(options)
174 return { ...setupWith(driver, options), calls }
176​
177type Computer = ReturnType<typeof createComputerUse>
178​
179function createContext(
180 phase: ChatMiddlewareContext['phase'],
181 messages: Array<ModelMessage> = [],
182 threadId = THREAD,
183): ChatMiddlewareContext {
184 return {
185 requestId: 'request',
186 streamId: 'stream',
187 runId: 'run',
188 threadId,
189 phase,
190 iteration: 0,
191 chunkIndex: 0,
192 callMetadata: {},
193 abort() {},
194 retry() {},
195 emitCustomEvent() {},
196 context: undefined,
197 defer() {},
198 activity: 'chat',
199 provider: 'openai',
200 model: 'gpt-6.1-sol',
201 source: 'server',
202 streaming: true,
203 systemPrompts: [],
204 messageCount: messages.length,
205 hasTools: true,
206 currentMessageId: null,
207 accumulatedContent: '',
208 messages,
209 createId: (prefix) => prefix,
210 capabilities: new CapabilityRegistry(),
211 get: () => {
212 throw new Error('unused')
213 },
214 getOptional: () => undefined,
215 provide() {},
216 }
218​
219function toolCall(id: string, input: unknown, name = 'computer') {
220 return {
221 id,
222 type: 'function' as const,
223 function: { name, arguments: JSON.stringify(input) },
224 }
226​
227/** Run the boundary hook at `beforeTools` with one assistant tool-call message. */
228function boundary(
229 computer: Computer,
230 toolCalls: Array<ReturnType<typeof toolCall>>,
231 threadId = THREAD,
232) {
233 const messages: Array<ModelMessage> = [
234 { role: 'user', content: 'Click the button.' },
235 { role: 'assistant', content: null, toolCalls },
236 ]
237 return computer.middleware.onInterruptBoundary?.({
238 ...createContext('beforeTools', messages, threadId),
239 phase: 'beforeTools',
240 })
242​
243function beforeModel(computer: Computer, threadId = THREAD) {
244 return computer.middleware.onConfig?.(
245 createContext('beforeModel', [], threadId),
246 { messages: [], systemPrompts: [], tools: [] },
247 )
249​
250type Resolution = GenericInterruptResolution<typeof computerSafetyCheck>
251​
252function safetyRequest(key: string) {
253 return computerSafetyCheck.interrupt({
254 key,
255 reason: 'computer-safety-check',
256 message: 'Look.',
257 payload: { checks: [CHECK], action: CLICK.action },
258 })
260​
261function answer(key: string, approved: boolean): Resolution {
262 return {
263 request: safetyRequest(key),
264 status: 'resolved',
265 response: { approved },
266 }
268​
269function cancelled(key: string): Resolution {
270 return { request: safetyRequest(key), status: 'cancelled' }
272​
273function resolve(
274 computer: Computer,
275 items: Array<Resolution>,
276 threadId = THREAD,
277) {
278 const collection: InterruptResolutionCollection<typeof computerSafetyCheck> =
279 {
280 // TypeScript cannot tie a generic return to one definition. The chat
281 // engine uses the same cast.
282 for: () => items as never,
283 all: () => items,
284 }
285 return computer.middleware.onInterruptResolution?.(
286 createContext('init', [], threadId),
287 collection,
288 )
290​
291/** Wait for a macrotask, so that every pending promise step runs. */
292function settle() {
293 return new Promise((done) => setTimeout(done, 0))
295​
296afterEach(() => {
297 vi.useRealTimers()
298})
299​
300describe('createComputerUse tool', () => {
301 it('is the computer tool with the driver metadata', () => {
302 const {
303 tools: [tool],
304 interrupt,
305 } = setup({ zoom: true })
306​
307 expect(tool.name).toBe('computer')
308 expect(tool.metadata).toEqual({
309 __kind: 'computer_use',
310 display: { width: 1024, height: 768 },
311 environment: 'browser',
312 capabilities: { zoom: true, cursorPosition: false },
313 })
314 expect(interrupt).toBe(computerSafetyCheck)
315 })
316​
317 it('gives the cursorPosition capability from the driver', () => {
318 const {
319 tools: [tool],
320 } = setup({ cursor: true })
321​
322 expect(tool.metadata?.capabilities).toEqual({
323 zoom: false,
324 cursorPosition: true,
325 })
326 })
327​
328 it('takes the metadata from the factory before any machine exists', () => {
329 const { factory, created } = createFactory({ cursor: true })
330 const {
331 tools: [tool],
332 } = setupWith(factory)
333​
334 expect(tool.metadata).toEqual({
335 __kind: 'computer_use',
336 display: { width: 1280, height: 800 },
337 environment: 'linux',
338 capabilities: { zoom: false, cursorPosition: true },
339 })
340 expect(created).toEqual([])
341 })
342​
343 it('returns a screenshot after an action', async () => {
344 const computer = setup()
345​
346 await expect(computer.execute(CLICK)).resolves.toEqual(
347 screenshotOf(PNG_BASE64),
348 )
349 expect(computer.calls).toEqual(['click:start', 'click:end', 'screenshot'])
350 })
351​
352 it('sends only the screenshot bytes when the driver returns a small Node Buffer', async () => {
353 // Node puts a small Buffer in a shared pool, so its ArrayBuffer holds other data too.
354 const computer = setup({ screenshot: Buffer.from(PNG_BYTES) })
355​
356 await expect(computer.execute(CLICK)).resolves.toEqual(
357 screenshotOf(PNG_BASE64),
358 )
359 })
360​
361 it('returns the zoom image and the cursor position as text', async () => {
362 const computer = setup({ zoom: true, cursor: true })
363​
364 await expect(
365 computer.execute({ action: 'zoom', region: [0, 0, 10, 10] }),
366 ).resolves.toEqual(screenshotOf(ZOOM_BASE64))
367 await expect(computer.execute({ action: 'cursor_position' })).resolves.toBe(
368 'X=7,Y=9',
369 )
370 expect(computer.calls).toEqual([])
371 })
372​
373 it('takes the screenshot only after screenshotDelay', async () => {
374 vi.useFakeTimers()
375 const computer = setup({ screenshotDelay: 500 })
376​
377 const result = computer.execute(CLICK)
378 await vi.advanceTimersByTimeAsync(499)
379 expect(computer.calls).toEqual(['click:start', 'click:end'])
380 await vi.advanceTimersByTimeAsync(1)
381​
382 await expect(result).resolves.toEqual(screenshotOf(PNG_BASE64))
383 expect(computer.calls).toEqual(['click:start', 'click:end', 'screenshot'])
384 })
385​
386 it('runs concurrent calls one at a time, in call order', async () => {
387 const { gate, open } = createGate()
388 const computer = setup({ clickGate: gate })
389​
390 const first = computer.execute(CLICK, 'call_1')
391 const second = computer.execute(TYPE, 'call_2')
392 await vi.waitFor(() => expect(computer.calls).toEqual(['click:start']))
393 open()
394 await Promise.all([first, second])
395​
396 expect(computer.calls).toEqual([
397 'click:start',
398 'click:end',
399 'screenshot',
400 'type',
401 'screenshot',
402 ])
403 })
404})
405​
406describe('createComputerUse failed turn', () => {
407 it('stops the turn after a failed action until the next model call', async () => {
408 let isBroken = true
409 const computer = setup({ failClick: () => isBroken })
410​
411 await expect(computer.execute(CLICK, 'call_1')).rejects.toThrow(
412 'click failed',
413 )
414 await expect(computer.execute(TYPE, 'call_2')).rejects.toThrow(NOT_EXECUTED)
415 isBroken = false
416 await beforeModel(computer)
417​
418 await expect(computer.execute(CLICK, 'call_3')).resolves.toEqual(
419 screenshotOf(PNG_BASE64),
420 )
421 expect(computer.calls).toEqual([
422 'click:start',
423 'click:start',
424 'click:end',
425 'screenshot',
426 ])
427 })
428})
429​
430describe('createComputerUse safety checks', () => {
431 it('refuses a call with checks that nobody approved', async () => {
432 const computer = setup()
433​
434 await expect(computer.execute(CHECKED_CLICK)).rejects.toThrow('Refused')
435 expect(computer.calls).toEqual([])
436 })
437​
438 it('refuses a call whose checks do not parse', async () => {
439 const computer = setup()
440​
441 await expect(
442 computer.execute({ ...CLICK, pending_safety_checks: [{ code: 'x' }] }),
443 ).rejects.toThrow('Refused')
444 expect(computer.calls).toEqual([])
445 })
446​
447 it('emits one interrupt per computer call with checks', async () => {
448 const computer = setup()
449​
450 const result = await boundary(computer, [
451 toolCall('call_1', CHECKED_CLICK),
452 toolCall('call_2', CLICK),
453 toolCall('call_3', CHECKED_CLICK, 'search'),
454 ])
455​
456 expect(result?.interrupts).toEqual([
457 expect.objectContaining({
458 definition: computerSafetyCheck,
459 key: 'call_1',
460 payload: { checks: [CHECK], action: CLICK.action },
461 }),
462 ])
463 })
464​
465 it('sends the OpenAI actions list as the action', async () => {
466 const computer = setup()
467 const actions = [CLICK.action, TYPE.action]
468​
469 const result = await boundary(computer, [
470 toolCall('call_1', { actions, pending_safety_checks: [CHECK] }),
471 ])
472​
473 expect(result?.interrupts[0]?.payload).toEqual({
474 checks: [CHECK],
475 action: actions,
476 })
477 })
478​
479 it('emits nothing outside beforeTools', async () => {
480 const computer = setup()
481​
482 const result = await computer.middleware.onInterruptBoundary?.({
483 ...createContext('afterTools', [
484 {
485 role: 'assistant',
486 content: null,
487 toolCalls: [toolCall('c', CHECKED_CLICK)],
488 },
489 ]),
490 phase: 'afterTools',
491 })
492​
493 expect(result).toBeUndefined()
494 })
495​
496 it('runs an approved call and does not ask again', async () => {
497 const computer = setup()
498​
499 expect(await resolve(computer, [answer('call_1', true)])).toEqual({
500 toolResume: 'continue',
501 })
502 expect(
503 await boundary(computer, [toolCall('call_1', CHECKED_CLICK)]),
504 ).toBeUndefined()
505 await expect(computer.execute(CHECKED_CLICK, 'call_1')).resolves.toEqual(
506 screenshotOf(PNG_BASE64),
507 )
508 })
509​
510 it('cancels a declined call and does not ask again', async () => {
511 const computer = setup()
512​
513 expect(await resolve(computer, [answer('call_1', false)])).toEqual({
514 toolResume: 'cancel',
515 })
516 expect(
517 await boundary(computer, [toolCall('call_1', CHECKED_CLICK)]),
518 ).toBeUndefined()
519 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
520 'Refused',
521 )
522 })
523​
524 it('cancels the batch when one answer is cancelled', async () => {
525 const computer = setup()
526​
527 const result = await resolve(computer, [
528 answer('call_1', true),
529 cancelled('call_2'),
530 ])
531​
532 expect(result).toEqual({ toolResume: 'cancel' })
533 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
534 'Refused',
535 )
536 })
537​
538 it('does not unlock a call with an approval for another call', async () => {
539 const computer = setup()
540​
541 await resolve(computer, [answer('call_2', true)])
542​
543 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
544 'Refused',
545 )
546 expect(computer.calls).toEqual([])
547 })
548​
549 it('has no opinion without safety-check answers', async () => {
550 const computer = setup()
551​
552 expect(await resolve(computer, [])).toBeUndefined()
553 })
554})
555​
556describe('createComputerUse threads', () => {
557 it('gives each thread its own machine from the factory', async () => {
558 const { factory, created, machines } = createFactory()
559 const computer = setupWith(factory)
560​
561 await computer.execute(CLICK, 'call_1', 'a')
562 await computer.execute(TYPE, 'call_2', 'b')
563​
564 expect(created).toEqual(['a', 'b'])
565 expect(machines.get('a')).toEqual([
566 'click:start',
567 'click:end',
568 'screenshot',
569 ])
570 expect(machines.get('b')).toEqual(['type', 'screenshot'])
571 })
572​
573 it('runs two threads one at a time on a shared driver', async () => {
574 const { gate, open } = createGate()
575 const { driver, calls } = createDriver({ clickGate: gate })
576 const computer = setupWith(driver)
577 const first = computer.execute(CLICK, 'call_1', 'a')
578 const second = computer.execute(CLICK, 'call_2', 'b')
579 await new Promise((done) => setTimeout(done, 0))
580​
581 expect(calls).toEqual(['click:start'])
582 open()
583 await Promise.all([first, second])
584 expect(calls).toEqual([
585 'click:start',
586 'click:end',
587 'screenshot',
588 'click:start',
589 'click:end',
590 'screenshot',
591 ])
592 })
593​
594 it('runs two factory threads at the same time', async () => {
595 const { gate, open } = createGate()
596 const { factory, machines } = createFactory({ clickGate: gate })
597 const computer = setupWith(factory)
598 const first = computer.execute(CLICK, 'call_1', 'a')
599 const second = computer.execute(CLICK, 'call_2', 'b')
600 await new Promise((done) => setTimeout(done, 0))
601​
602 expect(machines.get('a')).toEqual(['click:start'])
603 expect(machines.get('b')).toEqual(['click:start'])
604 open()
605 await Promise.all([first, second])
606 })
607​
608 it('creates one machine for two calls at once on a new thread', async () => {
609 const { factory, created, machines } = createFactory()
610 const computer = setupWith(factory)
611​
612 await Promise.all([
613 computer.execute(CLICK, 'call_1', 'a'),
614 computer.execute(TYPE, 'call_2', 'a'),
615 ])
616​
617 expect(created).toEqual(['a'])
618 expect(machines.get('a')).toEqual([
619 'click:start',
620 'click:end',
621 'screenshot',
622 'type',
623 'screenshot',
624 ])
625 })
626​
627 it('uses one shared thread for calls with no context', async () => {
628 const { factory, created } = createFactory()
629 const {
630 tools: [tool],
631 } = setupWith(factory)
632​
633 await tool.execute?.(CLICK)
634 await tool.execute?.(TYPE)
635​
636 expect(created).toHaveLength(1)
637 })
638​
639 it('keeps the approvals per thread', async () => {
640 const computer = setup()
641​
642 await resolve(computer, [answer('call_1', true)], 'a')
643 const otherThread = await boundary(
644 computer,
645 [toolCall('call_1', CHECKED_CLICK)],
646 'b',
647 )
648​
649 expect(otherThread?.interrupts).toHaveLength(1)
650 await expect(
651 computer.execute(CHECKED_CLICK, 'call_1', 'b'),
652 ).rejects.toThrow('Refused')
653 await expect(
654 computer.execute(CHECKED_CLICK, 'call_1', 'a'),
655 ).resolves.toEqual(screenshotOf(PNG_BASE64))
656 })
657​
658 it('keeps the failed-turn flag per thread', async () => {
659 const computer = setup({ failClick: () => true })
660​
661 await expect(computer.execute(CLICK, 'call_1', 'a')).rejects.toThrow(
662 'click failed',
663 )
664 await expect(computer.execute(TYPE, 'call_2', 'b')).resolves.toEqual(
665 screenshotOf(PNG_BASE64),
666 )
667 await beforeModel(computer, 'b')
668​
669 await expect(computer.execute(TYPE, 'call_3', 'a')).rejects.toThrow(
670 NOT_EXECUTED,
671 )
672 })
673​
674 it('calls create again after it rejects', async () => {
675 let isBroken = true
676 const { factory, created } = createFactory({ failCreate: () => isBroken })
677 const computer = setupWith(factory)
678​
679 await expect(computer.execute(CLICK, 'call_1', 'a')).rejects.toThrow(
680 'create failed',
681 )
682 isBroken = false
683 await beforeModel(computer, 'a')
684​
685 await expect(computer.execute(CLICK, 'call_2', 'a')).resolves.toEqual(
686 screenshotOf(PNG_BASE64),
687 )
688 expect(created).toEqual(['a', 'a'])
689 })
690})
691​
692describe('createComputerUse close', () => {
693 it('closes the machine of one thread with close(threadId)', async () => {
694 const { factory, created, closed } = createFactory()
695 const computer = setupWith(factory)
696 await computer.execute(CLICK, 'call_1', 'a')
697 await computer.execute(CLICK, 'call_2', 'b')
698​
699 await computer.close('a')
700 await computer.execute(CLICK, 'call_3', 'a')
701​
702 expect(closed).toEqual(['a'])
703 expect(created).toEqual(['a', 'b', 'a'])
704 })
705​
706 it('closes every thread, then the factory, with close()', async () => {
707 const { factory, closed } = createFactory()
708 const computer = setupWith(factory)
709 await computer.execute(CLICK, 'call_1', 'a')
710 await computer.execute(CLICK, 'call_2', 'b')
711​
712 await computer.close()
713​
714 expect(closed).toEqual(['a', 'b', 'factory'])
715 })
716​
717 it('closes the factory when a thread close fails, then throws', async () => {
718 const { factory, closed } = createFactory()
719 const create = factory.create
720 factory.create = async (context) => {
721 const driver = await create(context)
722 if (context.threadId === 'a') {
723 driver.close = async () => {
724 throw new Error('close failed')
725 }
726 }
727 return driver
728 }
729 const computer = setupWith(factory)
730 await computer.execute(CLICK, 'call_1', 'a')
731 await computer.execute(CLICK, 'call_2', 'b')
732​
733 await expect(computer.close()).rejects.toThrow('close failed')
734 expect(closed).toEqual(['b', 'factory'])
735 })
736​
737 it('does not throw for a closed or an unknown thread', async () => {
738 const { factory, closed } = createFactory()
739 const computer = setupWith(factory)
740 await computer.execute(CLICK, 'call_1', 'a')
741​
742 await computer.close('a')
743 await computer.close('a')
744 await computer.close('unknown')
745​
746 expect(closed).toEqual(['a'])
747 })
748​
749 it('waits for the running action before it closes the thread', async () => {
750 const { gate, open } = createGate()
751 const { factory, closed, machines } = createFactory({ clickGate: gate })
752 const computer = setupWith(factory)
753 const result = computer.execute(CLICK, 'call_1', 'a')
754 await vi.waitFor(() => expect(machines.get('a')).toEqual(['click:start']))
755​
756 const closing = computer.close('a')
757 await settle()
758 expect(closed).toEqual([])
759 open()
760 await closing
761​
762 expect(closed).toEqual(['a'])
763 await expect(result).resolves.toEqual(screenshotOf(PNG_BASE64))
764 expect(machines.get('a')).toEqual([
765 'click:start',
766 'click:end',
767 'screenshot',
768 ])
769 })
770​
771 it('never closes a driver that the app passed in', async () => {
772 vi.useFakeTimers()
773 let isBroken = true
774 const computer = setup({ idleTimeout: 1000, failClick: () => isBroken })
775 await expect(computer.execute(CLICK, 'call_1')).rejects.toThrow(
776 'click failed',
777 )
778 isBroken = false
779​
780 await vi.advanceTimersByTimeAsync(1000)
781 const next = computer.execute(TYPE, 'call_2')
782 await vi.advanceTimersByTimeAsync(0)
783 await computer.close(THREAD)
784 await computer.close()
785​
786 // The idle timeout dropped the failed turn of the thread.
787 await expect(next).resolves.toEqual(screenshotOf(PNG_BASE64))
788 expect(computer.calls).not.toContain('close')
789 })
790})
791​
792describe('createComputerUse idle timeout', () => {
793 it('closes and drops a thread after idleTimeout', async () => {
794 vi.useFakeTimers()
795 const { factory, created, closed } = createFactory()
796 const computer = setupWith(factory, { idleTimeout: 1000 })
797 const first = computer.execute(CLICK, 'call_1', 'a')
798 await vi.advanceTimersByTimeAsync(0)
799 await first
800​
801 await vi.advanceTimersByTimeAsync(999)
802 expect(closed).toEqual([])
803 await vi.advanceTimersByTimeAsync(1)
804 expect(closed).toEqual(['a'])
805​
806 const second = computer.execute(CLICK, 'call_2', 'a')
807 await vi.advanceTimersByTimeAsync(0)
808 await second
809 expect(created).toEqual(['a', 'a'])
810 })
811​
812 it('starts the idle time only after a long action ends', async () => {
813 vi.useFakeTimers()
814 const { gate, open } = createGate()
815 const { factory, closed } = createFactory({ clickGate: gate })
816 const computer = setupWith(factory, { idleTimeout: 1000 })
817 const result = computer.execute(CLICK, 'call_1', 'a')
818​
819 await vi.advanceTimersByTimeAsync(5000)
820 expect(closed).toEqual([])
821 open()
822 await vi.advanceTimersByTimeAsync(0)
823 await result
824 await vi.advanceTimersByTimeAsync(999)
825 expect(closed).toEqual([])
826 await vi.advanceTimersByTimeAsync(1)
827​
828 expect(closed).toEqual(['a'])
829 })
830​
831 it('logs a close error when the idle timeout closes a thread', async () => {
832 vi.useFakeTimers()
833 const error = vi.spyOn(console, 'error').mockImplementation(() => {})
834 const { factory, closed } = createFactory({ failClose: () => true })
835 const computer = setupWith(factory, { idleTimeout: 1000 })
836 const first = computer.execute(CLICK, 'call_1', 'a')
837 await vi.advanceTimersByTimeAsync(0)
838 await first
839​
840 await vi.advanceTimersByTimeAsync(1000)
841​
842 expect(closed).toEqual(['a'])
843 expect(error).toHaveBeenCalledWith(
844 'Failed to close the idle computer thread a.',
845 expect.any(Error),
846 )
847 error.mockRestore()
848 })
849​
850 it('never closes a thread with idleTimeout false', async () => {
851 vi.useFakeTimers()
852 const { factory, created, closed } = createFactory()
853 const computer = setupWith(factory, { idleTimeout: false })
854 const first = computer.execute(CLICK, 'call_1', 'a')
855 await vi.advanceTimersByTimeAsync(0)
856 await first
857​
858 await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000)
859 const second = computer.execute(CLICK, 'call_2', 'a')
860 await vi.advanceTimersByTimeAsync(0)
861 await second
862​
863 expect(closed).toEqual([])
864 expect(created).toEqual(['a'])
865 })
866})
867​
868describe('createComputerUse navigate', () => {
869 it('has no navigate tool for a driver without navigate', () => {
870 const { tools } = setup()
871​
872 expect(tools.map((tool) => tool.name)).toEqual(['computer'])
873 })
874​
875 it('has a navigate tool for a factory that can navigate', () => {
876 const { factory } = createFactory({ navigate: true })
877 const { tools } = setupWith(factory)
878​
879 expect(tools.map((tool) => tool.name)).toEqual(['computer', 'navigate'])
880 })
881​
882 it('goes to the URL on the machine of the thread and returns a screenshot', async () => {
883 const { factory, machines } = createFactory({ navigate: true })
884 const computer = setupWith(factory)
885​
886 await expect(
887 computer.navigate('https://tanstack.com', 'a'),
888 ).resolves.toEqual(screenshotOf(PNG_BASE64))
889 expect(machines.get('a')).toEqual([
890 'navigate:https://tanstack.com',
891 'screenshot',
892 ])
893 })
894​
895 it('asks for a full URL when the URL has no scheme', async () => {
896 const computer = setup({ navigate: true })
897​
898 await expect(computer.navigate('tanstack.com')).rejects.toThrow(FULL_URL)
899 expect(computer.calls).toEqual([])
900 })
901​
902 it.each(['file:///etc/passwd', 'javascript:alert(1)'])(
903 'refuses %s',
904 async (url) => {
905 const computer = setup({ navigate: true })
906​
907 await expect(computer.navigate(url)).rejects.toThrow(FULL_URL)
908 expect(computer.calls).toEqual([])
909 },
910 )
911​
912 it('stops the turn after a refused navigate', async () => {
913 const computer = setup({ navigate: true })
914​
915 await expect(computer.navigate('file:///etc/passwd')).rejects.toThrow(
916 FULL_URL,
917 )
918​
919 await expect(computer.execute(CLICK)).rejects.toThrow(NOT_EXECUTED)
920 })
921​
922 it('fails when the factory says navigate but its driver has none', async () => {
923 const { factory } = createFactory()
924 const computer = setupWith({
925 ...factory,
926 capabilities: { ...factory.capabilities, navigate: true },
927 })
928​
929 await expect(computer.navigate('https://tanstack.com')).rejects.toThrow(
930 'no navigate method',
931 )
932 })
933})