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

computer-use-loop.test.ts

310 lines8.7 KB

1import { describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { OpenAIBaseResponsesTextAdapter } from '../src/adapters/responses-text'
4import { computerUseTool } from '../src/tools/computer-use-tool'
5import { convertToolsToProviderFormat } from '../src/tools/tool-converter'
6import type OpenAI from 'openai'
7import type { StreamChunk, Tool } from '@tanstack/ai'
8​
9const safetyCheck = {
10 id: 'sc_1',
11 code: 'malicious_instructions',
12 message: 'The page asks the model to do something else.',
14​
15async function* completed(output: Array<Record<string, unknown>>) {
16 yield* [
17 {
18 type: 'response.created',
19 response: {
20 id: 'resp_1',
21 model: 'computer-use-preview',
22 status: 'in_progress',
23 },
24 },
25 {
26 type: 'response.completed',
27 response: {
28 id: 'resp_1',
29 model: 'computer-use-preview',
30 status: 'completed',
31 output,
32 usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
33 },
34 },
35 ]
37​
38const clickCall = {
39 type: 'computer_call',
40 id: 'cu_1',
41 call_id: 'call_cu',
42 status: 'completed',
43 action: { type: 'click', button: 'left', x: 10, y: 20 },
44 pending_safety_checks: [safetyCheck],
46​
47const answer = {
48 type: 'message',
49 id: 'msg_1',
50 role: 'assistant',
51 status: 'completed',
52 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
54​
55// The OpenAI adapter sends provider tools in their native shape.
56class TestAdapter extends OpenAIBaseResponsesTextAdapter<string> {
57 protected override convertTools(tools: Array<Tool>) {
58 return convertToolsToProviderFormat(tools)
59 }
61​
62class FileAdapter extends TestAdapter {
63 override readonly supportsFileSources = true
65​
66const previewTool = computerUseTool({
67 type: 'computer_use_preview',
68 display_width: 1024,
69 display_height: 768,
70 environment: 'browser',
71})
72​
73const screenshot = [
74 {
75 type: 'image',
76 source: { type: 'data', value: 'iVBORw0KGgo=', mimeType: 'image/png' },
77 },
79​
80/** The user message that gives the model the reason for a failed call. */
81function failureMessage(text: string) {
82 return {
83 type: 'message',
84 role: 'user',
85 content: [{ type: 'input_text', text }],
86 }
88​
89async function runLoop(
90 execute: (input: unknown) => Promise<unknown>,
91 {
92 computer = previewTool,
93 calls = [clickCall],
94 }: { computer?: Tool; calls?: Array<Record<string, unknown>> } = {},
95) {
96 const create = vi.fn()
97 for (const call of calls) create.mockResolvedValueOnce(completed([call]))
98 create.mockResolvedValueOnce(completed([answer]))
99 const client = {
100 responses: { create: (params: unknown) => create(params) },
101 } as unknown as OpenAI
102 const adapter = new TestAdapter('computer-use-preview', 'openai', client)
103 const tool = { ...computer, execute: vi.fn(execute) }
104 const chunks: Array<StreamChunk> = []
105 for await (const chunk of chat({
106 threadId: 'thread-1',
107 adapter,
108 messages: [{ role: 'user', content: 'Click the button.' }],
109 tools: [tool],
110 })) {
111 chunks.push(chunk)
112 }
113 return { create, execute: tool.execute, chunks }
115​
116describe('computer use loop', () => {
117 it('runs the computer call and sends the screenshot back', async () => {
118 const { create, execute } = await runLoop(async () => screenshot)
119​
120 expect(execute).toHaveBeenCalledOnce()
121 expect(execute.mock.calls[0]?.[0]).toEqual({
122 action: { type: 'click', button: 'left', x: 10, y: 20 },
123 pending_safety_checks: [safetyCheck],
124 })
125 expect(create).toHaveBeenCalledTimes(2)
126 expect(create.mock.calls[1]?.[0].input).toEqual(
127 expect.arrayContaining([
128 {
129 type: 'computer_call',
130 id: 'cu_1',
131 call_id: 'call_cu',
132 status: 'completed',
133 action: { type: 'click', button: 'left', x: 10, y: 20 },
134 pending_safety_checks: [safetyCheck],
135 },
136 {
137 type: 'computer_call_output',
138 call_id: 'call_cu',
139 output: {
140 type: 'computer_screenshot',
141 image_url: 'data:image/png;base64,iVBORw0KGgo=',
142 detail: 'original',
143 },
144 acknowledged_safety_checks: [safetyCheck],
145 },
146 ]),
147 )
148 })
149​
150 it('runs the batched actions of the computer tool', async () => {
151 const actions = [
152 { type: 'click', button: 'left', x: 10, y: 20 },
153 { type: 'type', text: 'hello' },
154 ]
155 const { create, execute } = await runLoop(async () => screenshot, {
156 computer: computerUseTool({ type: 'computer' }),
157 calls: [
158 {
159 type: 'computer_call',
160 id: 'cu_2',
161 call_id: 'call_batch',
162 status: 'completed',
163 actions,
164 pending_safety_checks: [],
165 },
166 ],
167 })
168​
169 expect(execute.mock.calls[0]?.[0]).toEqual({
170 actions,
171 pending_safety_checks: [],
172 })
173 const [first, second] = create.mock.calls.map(([params]) => params)
174 expect(first.tools).toEqual([{ type: 'computer' }])
175 expect(second.input).toEqual(
176 expect.arrayContaining([
177 {
178 type: 'computer_call',
179 id: 'cu_2',
180 call_id: 'call_batch',
181 status: 'completed',
182 actions,
183 pending_safety_checks: [],
184 },
185 {
186 type: 'computer_call_output',
187 call_id: 'call_batch',
188 output: {
189 type: 'computer_screenshot',
190 image_url: 'data:image/png;base64,iVBORw0KGgo=',
191 detail: 'original',
192 },
193 },
194 ]),
195 )
196 })
197​
198 it('reads no screenshot from the result of another app tool', async () => {
199 const create = vi.fn().mockResolvedValueOnce(completed([answer]))
200 const client = {
201 responses: { create: (params: unknown) => create(params) },
202 } as unknown as OpenAI
203 // OpenAI takes file sources, but not a file from another provider, so a
204 // screenshot read of this result would throw.
205 const adapter = new FileAdapter('gpt-5.5', 'openai', client)
206 for await (const _ of chat({
207 threadId: 'thread-1',
208 adapter,
209 messages: [
210 {
211 role: 'assistant',
212 content: null,
213 toolCalls: [
214 {
215 id: 'call_sh',
216 type: 'function',
217 function: {
218 name: 'local_shell',
219 arguments: JSON.stringify({ command: ['ls'] }),
220 },
221 metadata: { openaiUserTool: 'local_shell', itemId: 'ls_1' },
222 },
223 ],
224 },
225 {
226 role: 'tool',
227 toolCallId: 'call_sh',
228 content: [
229 {
230 type: 'image',
231 source: { type: 'file', value: 'file_1', provider: 'gemini' },
232 },
233 ],
234 },
235 ],
236 })) {
237 // Drain the stream.
238 }
239​
240 expect(create.mock.calls[0]?.[0].input).toContainEqual(
241 expect.objectContaining({ type: 'local_shell_call_output' }),
242 )
243 })
244​
245 it('fails the run when a computer result has no screenshot', async () => {
246 const { create, chunks } = await runLoop(async () => 'clicked')
247​
248 expect(create).toHaveBeenCalledOnce()
249 expect(chunks).toContainEqual(
250 expect.objectContaining({
251 type: 'RUN_ERROR',
252 message: expect.stringContaining(
253 'The computer tool result has no screenshot.',
254 ),
255 }),
256 )
257 })
258​
259 it('does not acknowledge the safety checks of a failed call', async () => {
260 const { create } = await runLoop(async () => {
261 throw new Error('A person did not allow the click.')
262 })
263​
264 const input: Array<Record<string, unknown>> =
265 create.mock.calls[1]?.[0].input
266 expect(input.slice(-2)).toEqual([
267 {
268 type: 'computer_call_output',
269 call_id: 'call_cu',
270 output: { type: 'computer_screenshot' },
271 },
272 failureMessage(
273 'Computer call call_cu failed: A person did not allow the click.',
274 ),
275 ])
276 })
277​
278 it('sends the newest screenshot and the reason for a failed call', async () => {
279 const secondCall = {
280 ...clickCall,
281 id: 'cu_2',
282 call_id: 'call_cu_2',
283 pending_safety_checks: [],
284 }
285 const execute = vi
286 .fn()
287 .mockResolvedValueOnce(screenshot)
288 .mockRejectedValueOnce(new Error('The page has no button there.'))
289 const { create } = await runLoop(execute, {
290 calls: [clickCall, secondCall],
291 })
292​
293 const input: Array<Record<string, unknown>> =
294 create.mock.calls[2]?.[0].input
295 expect(input.slice(-2)).toEqual([
296 {
297 type: 'computer_call_output',
298 call_id: 'call_cu_2',
299 output: {
300 type: 'computer_screenshot',
301 image_url: 'data:image/png;base64,iVBORw0KGgo=',
302 detail: 'original',
303 },
304 },
305 failureMessage(
306 'Computer call call_cu_2 failed: The page has no button there.',
307 ),
308 ])
309 })
310})