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 abort() {},
193 retry() {},
194 emitCustomEvent() {},
195 context: undefined,
196 defer() {},
197 activity: 'chat',
198 provider: 'openai',
199 model: 'gpt-6.1-sol',
200 source: 'server',
201 streaming: true,
202 systemPrompts: [],
203 messageCount: messages.length,
204 hasTools: true,
205 currentMessageId: null,
206 accumulatedContent: '',
207 messages,
208 createId: (prefix) => prefix,
209 capabilities: new CapabilityRegistry(),
210 get: () => {
211 throw new Error('unused')
212 },
213 getOptional: () => undefined,
214 provide() {},
215 }
217​
218function toolCall(id: string, input: unknown, name = 'computer') {
219 return {
220 id,
221 type: 'function' as const,
222 function: { name, arguments: JSON.stringify(input) },
223 }
225​
226/** Run the boundary hook at `beforeTools` with one assistant tool-call message. */
227function boundary(
228 computer: Computer,
229 toolCalls: Array<ReturnType<typeof toolCall>>,
230 threadId = THREAD,
231) {
232 const messages: Array<ModelMessage> = [
233 { role: 'user', content: 'Click the button.' },
234 { role: 'assistant', content: null, toolCalls },
235 ]
236 return computer.middleware.onInterruptBoundary?.({
237 ...createContext('beforeTools', messages, threadId),
238 phase: 'beforeTools',
239 })
241​
242function beforeModel(computer: Computer, threadId = THREAD) {
243 return computer.middleware.onConfig?.(
244 createContext('beforeModel', [], threadId),
245 { messages: [], systemPrompts: [], tools: [] },
246 )
248​
249type Resolution = GenericInterruptResolution<typeof computerSafetyCheck>
250​
251function safetyRequest(key: string) {
252 return computerSafetyCheck.interrupt({
253 key,
254 reason: 'computer-safety-check',
255 message: 'Look.',
256 payload: { checks: [CHECK], action: CLICK.action },
257 })
259​
260function answer(key: string, approved: boolean): Resolution {
261 return {
262 request: safetyRequest(key),
263 status: 'resolved',
264 response: { approved },
265 }
267​
268function cancelled(key: string): Resolution {
269 return { request: safetyRequest(key), status: 'cancelled' }
271​
272function resolve(
273 computer: Computer,
274 items: Array<Resolution>,
275 threadId = THREAD,
276) {
277 const collection: InterruptResolutionCollection<typeof computerSafetyCheck> =
278 {
279 // TypeScript cannot tie a generic return to one definition. The chat
280 // engine uses the same cast.
281 for: () => items as never,
282 all: () => items,
283 }
284 return computer.middleware.onInterruptResolution?.(
285 createContext('init', [], threadId),
286 collection,
287 )
289​
290/** Wait for a macrotask, so that every pending promise step runs. */
291function settle() {
292 return new Promise((done) => setTimeout(done, 0))
294​
295afterEach(() => {
296 vi.useRealTimers()
297})
298​
299describe('createComputerUse tool', () => {
300 it('is the computer tool with the driver metadata', () => {
301 const {
302 tools: [tool],
303 interrupt,
304 } = setup({ zoom: true })
305​
306 expect(tool.name).toBe('computer')
307 expect(tool.metadata).toEqual({
308 __kind: 'computer_use',
309 display: { width: 1024, height: 768 },
310 environment: 'browser',
311 capabilities: { zoom: true, cursorPosition: false },
312 })
313 expect(interrupt).toBe(computerSafetyCheck)
314 })
315​
316 it('gives the cursorPosition capability from the driver', () => {
317 const {
318 tools: [tool],
319 } = setup({ cursor: true })
320​
321 expect(tool.metadata?.capabilities).toEqual({
322 zoom: false,
323 cursorPosition: true,
324 })
325 })
326​
327 it('takes the metadata from the factory before any machine exists', () => {
328 const { factory, created } = createFactory({ cursor: true })
329 const {
330 tools: [tool],
331 } = setupWith(factory)
332​
333 expect(tool.metadata).toEqual({
334 __kind: 'computer_use',
335 display: { width: 1280, height: 800 },
336 environment: 'linux',
337 capabilities: { zoom: false, cursorPosition: true },
338 })
339 expect(created).toEqual([])
340 })
341​
342 it('returns a screenshot after an action', async () => {
343 const computer = setup()
344​
345 await expect(computer.execute(CLICK)).resolves.toEqual(
346 screenshotOf(PNG_BASE64),
347 )
348 expect(computer.calls).toEqual(['click:start', 'click:end', 'screenshot'])
349 })
350​
351 it('sends only the screenshot bytes when the driver returns a small Node Buffer', async () => {
352 // Node puts a small Buffer in a shared pool, so its ArrayBuffer holds other data too.
353 const computer = setup({ screenshot: Buffer.from(PNG_BYTES) })
354​
355 await expect(computer.execute(CLICK)).resolves.toEqual(
356 screenshotOf(PNG_BASE64),
357 )
358 })
359​
360 it('returns the zoom image and the cursor position as text', async () => {
361 const computer = setup({ zoom: true, cursor: true })
362​
363 await expect(
364 computer.execute({ action: 'zoom', region: [0, 0, 10, 10] }),
365 ).resolves.toEqual(screenshotOf(ZOOM_BASE64))
366 await expect(computer.execute({ action: 'cursor_position' })).resolves.toBe(
367 'X=7,Y=9',
368 )
369 expect(computer.calls).toEqual([])
370 })
371​
372 it('takes the screenshot only after screenshotDelay', async () => {
373 vi.useFakeTimers()
374 const computer = setup({ screenshotDelay: 500 })
375​
376 const result = computer.execute(CLICK)
377 await vi.advanceTimersByTimeAsync(499)
378 expect(computer.calls).toEqual(['click:start', 'click:end'])
379 await vi.advanceTimersByTimeAsync(1)
380​
381 await expect(result).resolves.toEqual(screenshotOf(PNG_BASE64))
382 expect(computer.calls).toEqual(['click:start', 'click:end', 'screenshot'])
383 })
384​
385 it('runs concurrent calls one at a time, in call order', async () => {
386 const { gate, open } = createGate()
387 const computer = setup({ clickGate: gate })
388​
389 const first = computer.execute(CLICK, 'call_1')
390 const second = computer.execute(TYPE, 'call_2')
391 await vi.waitFor(() => expect(computer.calls).toEqual(['click:start']))
392 open()
393 await Promise.all([first, second])
394​
395 expect(computer.calls).toEqual([
396 'click:start',
397 'click:end',
398 'screenshot',
399 'type',
400 'screenshot',
401 ])
402 })
403})
404​
405describe('createComputerUse failed turn', () => {
406 it('stops the turn after a failed action until the next model call', async () => {
407 let isBroken = true
408 const computer = setup({ failClick: () => isBroken })
409​
410 await expect(computer.execute(CLICK, 'call_1')).rejects.toThrow(
411 'click failed',
412 )
413 await expect(computer.execute(TYPE, 'call_2')).rejects.toThrow(NOT_EXECUTED)
414 isBroken = false
415 await beforeModel(computer)
416​
417 await expect(computer.execute(CLICK, 'call_3')).resolves.toEqual(
418 screenshotOf(PNG_BASE64),
419 )
420 expect(computer.calls).toEqual([
421 'click:start',
422 'click:start',
423 'click:end',
424 'screenshot',
425 ])
426 })
427})
428​
429describe('createComputerUse safety checks', () => {
430 it('refuses a call with checks that nobody approved', async () => {
431 const computer = setup()
432​
433 await expect(computer.execute(CHECKED_CLICK)).rejects.toThrow('Refused')
434 expect(computer.calls).toEqual([])
435 })
436​
437 it('refuses a call whose checks do not parse', async () => {
438 const computer = setup()
439​
440 await expect(
441 computer.execute({ ...CLICK, pending_safety_checks: [{ code: 'x' }] }),
442 ).rejects.toThrow('Refused')
443 expect(computer.calls).toEqual([])
444 })
445​
446 it('emits one interrupt per computer call with checks', async () => {
447 const computer = setup()
448​
449 const result = await boundary(computer, [
450 toolCall('call_1', CHECKED_CLICK),
451 toolCall('call_2', CLICK),
452 toolCall('call_3', CHECKED_CLICK, 'search'),
453 ])
454​
455 expect(result?.interrupts).toEqual([
456 expect.objectContaining({
457 definition: computerSafetyCheck,
458 key: 'call_1',
459 payload: { checks: [CHECK], action: CLICK.action },
460 }),
461 ])
462 })
463​
464 it('sends the OpenAI actions list as the action', async () => {
465 const computer = setup()
466 const actions = [CLICK.action, TYPE.action]
467​
468 const result = await boundary(computer, [
469 toolCall('call_1', { actions, pending_safety_checks: [CHECK] }),
470 ])
471​
472 expect(result?.interrupts[0]?.payload).toEqual({
473 checks: [CHECK],
474 action: actions,
475 })
476 })
477​
478 it('emits nothing outside beforeTools', async () => {
479 const computer = setup()
480​
481 const result = await computer.middleware.onInterruptBoundary?.({
482 ...createContext('afterTools', [
483 {
484 role: 'assistant',
485 content: null,
486 toolCalls: [toolCall('c', CHECKED_CLICK)],
487 },
488 ]),
489 phase: 'afterTools',
490 })
491​
492 expect(result).toBeUndefined()
493 })
494​
495 it('runs an approved call and does not ask again', async () => {
496 const computer = setup()
497​
498 expect(await resolve(computer, [answer('call_1', true)])).toEqual({
499 toolResume: 'continue',
500 })
501 expect(
502 await boundary(computer, [toolCall('call_1', CHECKED_CLICK)]),
503 ).toBeUndefined()
504 await expect(computer.execute(CHECKED_CLICK, 'call_1')).resolves.toEqual(
505 screenshotOf(PNG_BASE64),
506 )
507 })
508​
509 it('cancels a declined call and does not ask again', async () => {
510 const computer = setup()
511​
512 expect(await resolve(computer, [answer('call_1', false)])).toEqual({
513 toolResume: 'cancel',
514 })
515 expect(
516 await boundary(computer, [toolCall('call_1', CHECKED_CLICK)]),
517 ).toBeUndefined()
518 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
519 'Refused',
520 )
521 })
522​
523 it('cancels the batch when one answer is cancelled', async () => {
524 const computer = setup()
525​
526 const result = await resolve(computer, [
527 answer('call_1', true),
528 cancelled('call_2'),
529 ])
530​
531 expect(result).toEqual({ toolResume: 'cancel' })
532 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
533 'Refused',
534 )
535 })
536​
537 it('does not unlock a call with an approval for another call', async () => {
538 const computer = setup()
539​
540 await resolve(computer, [answer('call_2', true)])
541​
542 await expect(computer.execute(CHECKED_CLICK, 'call_1')).rejects.toThrow(
543 'Refused',
544 )
545 expect(computer.calls).toEqual([])
546 })
547​
548 it('has no opinion without safety-check answers', async () => {
549 const computer = setup()
550​
551 expect(await resolve(computer, [])).toBeUndefined()
552 })
553})
554​
555describe('createComputerUse threads', () => {
556 it('gives each thread its own machine from the factory', async () => {
557 const { factory, created, machines } = createFactory()
558 const computer = setupWith(factory)
559​
560 await computer.execute(CLICK, 'call_1', 'a')
561 await computer.execute(TYPE, 'call_2', 'b')
562​
563 expect(created).toEqual(['a', 'b'])
564 expect(machines.get('a')).toEqual([
565 'click:start',
566 'click:end',
567 'screenshot',
568 ])
569 expect(machines.get('b')).toEqual(['type', 'screenshot'])
570 })
571​
572 it('runs two threads one at a time on a shared driver', async () => {
573 const { gate, open } = createGate()
574 const { driver, calls } = createDriver({ clickGate: gate })
575 const computer = setupWith(driver)
576 const first = computer.execute(CLICK, 'call_1', 'a')
577 const second = computer.execute(CLICK, 'call_2', 'b')
578 await new Promise((done) => setTimeout(done, 0))
579​
580 expect(calls).toEqual(['click:start'])
581 open()
582 await Promise.all([first, second])
583 expect(calls).toEqual([
584 'click:start',
585 'click:end',
586 'screenshot',
587 'click:start',
588 'click:end',
589 'screenshot',
590 ])
591 })
592​
593 it('runs two factory threads at the same time', async () => {
594 const { gate, open } = createGate()
595 const { factory, machines } = createFactory({ clickGate: gate })
596 const computer = setupWith(factory)
597 const first = computer.execute(CLICK, 'call_1', 'a')
598 const second = computer.execute(CLICK, 'call_2', 'b')
599 await new Promise((done) => setTimeout(done, 0))
600​
601 expect(machines.get('a')).toEqual(['click:start'])
602 expect(machines.get('b')).toEqual(['click:start'])
603 open()
604 await Promise.all([first, second])
605 })
606​
607 it('creates one machine for two calls at once on a new thread', async () => {
608 const { factory, created, machines } = createFactory()
609 const computer = setupWith(factory)
610​
611 await Promise.all([
612 computer.execute(CLICK, 'call_1', 'a'),
613 computer.execute(TYPE, 'call_2', 'a'),
614 ])
615​
616 expect(created).toEqual(['a'])
617 expect(machines.get('a')).toEqual([
618 'click:start',
619 'click:end',
620 'screenshot',
621 'type',
622 'screenshot',
623 ])
624 })
625​
626 it('uses one shared thread for calls with no threadId', async () => {
627 const { factory, created } = createFactory()
628 const {
629 tools: [tool],
630 } = setupWith(factory)
631 const context = { emitCustomEvent() {} }
632​
633 await tool.execute?.(CLICK, context)
634 await tool.execute?.(TYPE, context)
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})