Open History to see the last commit
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.',
13}
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 ]
36}
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],
45}
46
47const answer = {
48 type: 'message',
49 id: 'msg_1',
50 role: 'assistant',
51 status: 'completed',
52 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
53}
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 }
60}
61
62class FileAdapter extends TestAdapter {
63 override readonly supportsFileSources = true
64}
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 },
78]
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 }
87}
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 adapter,
107 messages: [{ role: 'user', content: 'Click the button.' }],
108 tools: [tool],
109 })) {
110 chunks.push(chunk)
111 }
112 return { create, execute: tool.execute, chunks }
113}
114
115describe('computer use loop', () => {
116 it('runs the computer call and sends the screenshot back', async () => {
117 const { create, execute } = await runLoop(async () => screenshot)
118
119 expect(execute).toHaveBeenCalledOnce()
120 expect(execute.mock.calls[0]?.[0]).toEqual({
121 action: { type: 'click', button: 'left', x: 10, y: 20 },
122 pending_safety_checks: [safetyCheck],
123 })
124 expect(create).toHaveBeenCalledTimes(2)
125 expect(create.mock.calls[1]?.[0].input).toEqual(
126 expect.arrayContaining([
127 {
128 type: 'computer_call',
129 id: 'cu_1',
130 call_id: 'call_cu',
131 status: 'completed',
132 action: { type: 'click', button: 'left', x: 10, y: 20 },
133 pending_safety_checks: [safetyCheck],
134 },
135 {
136 type: 'computer_call_output',
137 call_id: 'call_cu',
138 output: {
139 type: 'computer_screenshot',
140 image_url: 'data:image/png;base64,iVBORw0KGgo=',
141 detail: 'original',
142 },
143 acknowledged_safety_checks: [safetyCheck],
144 },
145 ]),
146 )
147 })
148
149 it('runs the batched actions of the computer tool', async () => {
150 const actions = [
151 { type: 'click', button: 'left', x: 10, y: 20 },
152 { type: 'type', text: 'hello' },
153 ]
154 const { create, execute } = await runLoop(async () => screenshot, {
155 computer: computerUseTool({ type: 'computer' }),
156 calls: [
157 {
158 type: 'computer_call',
159 id: 'cu_2',
160 call_id: 'call_batch',
161 status: 'completed',
162 actions,
163 pending_safety_checks: [],
164 },
165 ],
166 })
167
168 expect(execute.mock.calls[0]?.[0]).toEqual({
169 actions,
170 pending_safety_checks: [],
171 })
172 const [first, second] = create.mock.calls.map(([params]) => params)
173 expect(first.tools).toEqual([{ type: 'computer' }])
174 expect(second.input).toEqual(
175 expect.arrayContaining([
176 {
177 type: 'computer_call',
178 id: 'cu_2',
179 call_id: 'call_batch',
180 status: 'completed',
181 actions,
182 pending_safety_checks: [],
183 },
184 {
185 type: 'computer_call_output',
186 call_id: 'call_batch',
187 output: {
188 type: 'computer_screenshot',
189 image_url: 'data:image/png;base64,iVBORw0KGgo=',
190 detail: 'original',
191 },
192 },
193 ]),
194 )
195 })
196
197 it('reads no screenshot from the result of another app tool', async () => {
198 const create = vi.fn().mockResolvedValueOnce(completed([answer]))
199 const client = {
200 responses: { create: (params: unknown) => create(params) },
201 } as unknown as OpenAI
202 // OpenAI takes file sources, but not a file from another provider, so a
203 // screenshot read of this result would throw.
204 const adapter = new FileAdapter('gpt-5.5', 'openai', client)
205 for await (const _ of chat({
206 adapter,
207 messages: [
208 {
209 role: 'assistant',
210 content: null,
211 toolCalls: [
212 {
213 id: 'call_sh',
214 type: 'function',
215 function: {
216 name: 'local_shell',
217 arguments: JSON.stringify({ command: ['ls'] }),
218 },
219 metadata: { openaiUserTool: 'local_shell', itemId: 'ls_1' },
220 },
221 ],
222 },
223 {
224 role: 'tool',
225 toolCallId: 'call_sh',
226 content: [
227 {
228 type: 'image',
229 source: { type: 'file', value: 'file_1', provider: 'gemini' },
230 },
231 ],
232 },
233 ],
234 })) {
235 // Drain the stream.
236 }
237
238 expect(create.mock.calls[0]?.[0].input).toContainEqual(
239 expect.objectContaining({ type: 'local_shell_call_output' }),
240 )
241 })
242
243 it('fails the run when a computer result has no screenshot', async () => {
244 const { create, chunks } = await runLoop(async () => 'clicked')
245
246 expect(create).toHaveBeenCalledOnce()
247 expect(chunks).toContainEqual(
248 expect.objectContaining({
249 type: 'RUN_ERROR',
250 message: expect.stringContaining(
251 'The computer tool result has no screenshot.',
252 ),
253 }),
254 )
255 })
256
257 it('does not acknowledge the safety checks of a failed call', async () => {
258 const { create } = await runLoop(async () => {
259 throw new Error('A person did not allow the click.')
260 })
261
262 const input: Array<Record<string, unknown>> =
263 create.mock.calls[1]?.[0].input
264 expect(input.slice(-2)).toEqual([
265 {
266 type: 'computer_call_output',
267 call_id: 'call_cu',
268 output: { type: 'computer_screenshot' },
269 },
270 failureMessage(
271 'Computer call call_cu failed: A person did not allow the click.',
272 ),
273 ])
274 })
275
276 it('sends the newest screenshot and the reason for a failed call', async () => {
277 const secondCall = {
278 ...clickCall,
279 id: 'cu_2',
280 call_id: 'call_cu_2',
281 pending_safety_checks: [],
282 }
283 const execute = vi
284 .fn()
285 .mockResolvedValueOnce(screenshot)
286 .mockRejectedValueOnce(new Error('The page has no button there.'))
287 const { create } = await runLoop(execute, {
288 calls: [clickCall, secondCall],
289 })
290
291 const input: Array<Record<string, unknown>> =
292 create.mock.calls[2]?.[0].input
293 expect(input.slice(-2)).toEqual([
294 {
295 type: 'computer_call_output',
296 call_id: 'call_cu_2',
297 output: {
298 type: 'computer_screenshot',
299 image_url: 'data:image/png;base64,iVBORw0KGgo=',
300 detail: 'original',
301 },
302 },
303 failureMessage(
304 'Computer call call_cu_2 failed: The page has no button there.',
305 ),
306 ])
307 })
308})