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

computer-use-loop.test.ts

304 lines8.5 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: 'gpt-6.1-sol',
22 status: 'in_progress',
23 },
24 },
25 {
26 type: 'response.completed',
27 response: {
28 id: 'resp_1',
29 model: 'gpt-6.1-sol',
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 computerTool = computerUseTool({ type: 'computer' })
67​
68const screenshot = [
69 {
70 type: 'image',
71 source: { type: 'data', value: 'iVBORw0KGgo=', mimeType: 'image/png' },
72 },
74​
75/** The user message that gives the model the reason for a failed call. */
76function failureMessage(text: string) {
77 return {
78 type: 'message',
79 role: 'user',
80 content: [{ type: 'input_text', text }],
81 }
83​
84async function runLoop(
85 execute: (input: unknown) => Promise<unknown>,
86 {
87 computer = computerTool,
88 calls = [clickCall],
89 }: { computer?: Tool; calls?: Array<Record<string, unknown>> } = {},
90) {
91 const create = vi.fn()
92 for (const call of calls) create.mockResolvedValueOnce(completed([call]))
93 create.mockResolvedValueOnce(completed([answer]))
94 const client = {
95 responses: { create: (params: unknown) => create(params) },
96 } as unknown as OpenAI
97 const adapter = new TestAdapter('gpt-6.1-sol', 'openai', client)
98 const tool = { ...computer, execute: vi.fn(execute) }
99 const chunks: Array<StreamChunk> = []
100 for await (const chunk of chat({
101 threadId: 'thread-1',
102 adapter,
103 messages: [{ role: 'user', content: 'Click the button.' }],
104 tools: [tool],
105 })) {
106 chunks.push(chunk)
107 }
108 return { create, execute: tool.execute, chunks }
110​
111describe('computer use loop', () => {
112 it('runs the computer call and sends the screenshot back', async () => {
113 const { create, execute } = await runLoop(async () => screenshot)
114​
115 expect(execute).toHaveBeenCalledOnce()
116 expect(execute.mock.calls[0]?.[0]).toEqual({
117 action: { type: 'click', button: 'left', x: 10, y: 20 },
118 pending_safety_checks: [safetyCheck],
119 })
120 expect(create).toHaveBeenCalledTimes(2)
121 expect(create.mock.calls[1]?.[0].input).toEqual(
122 expect.arrayContaining([
123 {
124 type: 'computer_call',
125 id: 'cu_1',
126 call_id: 'call_cu',
127 status: 'completed',
128 action: { type: 'click', button: 'left', x: 10, y: 20 },
129 pending_safety_checks: [safetyCheck],
130 },
131 {
132 type: 'computer_call_output',
133 call_id: 'call_cu',
134 output: {
135 type: 'computer_screenshot',
136 image_url: 'data:image/png;base64,iVBORw0KGgo=',
137 detail: 'original',
138 },
139 acknowledged_safety_checks: [safetyCheck],
140 },
141 ]),
142 )
143 })
144​
145 it('runs the batched actions of the computer tool', async () => {
146 const actions = [
147 { type: 'click', button: 'left', x: 10, y: 20 },
148 { type: 'type', text: 'hello' },
149 ]
150 const { create, execute } = await runLoop(async () => screenshot, {
151 calls: [
152 {
153 type: 'computer_call',
154 id: 'cu_2',
155 call_id: 'call_batch',
156 status: 'completed',
157 actions,
158 pending_safety_checks: [],
159 },
160 ],
161 })
162​
163 expect(execute.mock.calls[0]?.[0]).toEqual({
164 actions,
165 pending_safety_checks: [],
166 })
167 const [first, second] = create.mock.calls.map(([params]) => params)
168 expect(first.tools).toEqual([{ type: 'computer' }])
169 expect(second.input).toEqual(
170 expect.arrayContaining([
171 {
172 type: 'computer_call',
173 id: 'cu_2',
174 call_id: 'call_batch',
175 status: 'completed',
176 actions,
177 pending_safety_checks: [],
178 },
179 {
180 type: 'computer_call_output',
181 call_id: 'call_batch',
182 output: {
183 type: 'computer_screenshot',
184 image_url: 'data:image/png;base64,iVBORw0KGgo=',
185 detail: 'original',
186 },
187 },
188 ]),
189 )
190 })
191​
192 it('reads no screenshot from the result of another app tool', async () => {
193 const create = vi.fn().mockResolvedValueOnce(completed([answer]))
194 const client = {
195 responses: { create: (params: unknown) => create(params) },
196 } as unknown as OpenAI
197 // OpenAI takes file sources, but not a file from another provider, so a
198 // screenshot read of this result would throw.
199 const adapter = new FileAdapter('gpt-5.5', 'openai', client)
200 for await (const _ of chat({
201 threadId: 'thread-1',
202 adapter,
203 messages: [
204 {
205 role: 'assistant',
206 content: null,
207 toolCalls: [
208 {
209 id: 'call_sh',
210 type: 'function',
211 function: {
212 name: 'local_shell',
213 arguments: JSON.stringify({ command: ['ls'] }),
214 },
215 metadata: { openaiUserTool: 'local_shell', itemId: 'ls_1' },
216 },
217 ],
218 },
219 {
220 role: 'tool',
221 toolCallId: 'call_sh',
222 content: [
223 {
224 type: 'image',
225 source: { type: 'file', value: 'file_1', provider: 'gemini' },
226 },
227 ],
228 },
229 ],
230 })) {
231 // Drain the stream.
232 }
233​
234 expect(create.mock.calls[0]?.[0].input).toContainEqual(
235 expect.objectContaining({ type: 'local_shell_call_output' }),
236 )
237 })
238​
239 it('fails the run when a computer result has no screenshot', async () => {
240 const { create, chunks } = await runLoop(async () => 'clicked')
241​
242 expect(create).toHaveBeenCalledOnce()
243 expect(chunks).toContainEqual(
244 expect.objectContaining({
245 type: 'RUN_ERROR',
246 message: expect.stringContaining(
247 'The computer tool result has no screenshot.',
248 ),
249 }),
250 )
251 })
252​
253 it('does not acknowledge the safety checks of a failed call', async () => {
254 const { create } = await runLoop(async () => {
255 throw new Error('A person did not allow the click.')
256 })
257​
258 const input: Array<Record<string, unknown>> =
259 create.mock.calls[1]?.[0].input
260 expect(input.slice(-2)).toEqual([
261 {
262 type: 'computer_call_output',
263 call_id: 'call_cu',
264 output: { type: 'computer_screenshot' },
265 },
266 failureMessage(
267 'Computer call call_cu failed: A person did not allow the click.',
268 ),
269 ])
270 })
271​
272 it('sends the newest screenshot and the reason for a failed call', async () => {
273 const secondCall = {
274 ...clickCall,
275 id: 'cu_2',
276 call_id: 'call_cu_2',
277 pending_safety_checks: [],
278 }
279 const execute = vi
280 .fn()
281 .mockResolvedValueOnce(screenshot)
282 .mockRejectedValueOnce(new Error('The page has no button there.'))
283 const { create } = await runLoop(execute, {
284 calls: [clickCall, secondCall],
285 })
286​
287 const input: Array<Record<string, unknown>> =
288 create.mock.calls[2]?.[0].input
289 expect(input.slice(-2)).toEqual([
290 {
291 type: 'computer_call_output',
292 call_id: 'call_cu_2',
293 output: {
294 type: 'computer_screenshot',
295 image_url: 'data:image/png;base64,iVBORw0KGgo=',
296 detail: 'original',
297 },
298 },
299 failureMessage(
300 'Computer call call_cu_2 failed: The page has no button there.',
301 ),
302 ])
303 })
304})