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

computer-use-generic.test.ts

214 lines6.3 KB

1import { describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { OpenAIBaseChatCompletionsTextAdapter } from '../src/adapters/chat-completions-text'
4import { OpenAIBaseResponsesTextAdapter } from '../src/adapters/responses-text'
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: { id: 'resp_1', model: 'm', status: 'in_progress' },
20 },
21 {
22 type: 'response.completed',
23 response: {
24 id: 'resp_1',
25 model: 'm',
26 status: 'completed',
27 output,
28 usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
29 },
30 },
31 ]
33​
34const answer = {
35 type: 'message',
36 id: 'msg_1',
37 role: 'assistant',
38 status: 'completed',
39 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
41​
42const screenshot = [
43 {
44 type: 'image',
45 source: { type: 'data', value: 'iVBORw0KGgo=', mimeType: 'image/png' },
46 },
48​
49const screenshotOutput = {
50 type: 'computer_screenshot',
51 image_url: 'data:image/png;base64,iVBORw0KGgo=',
52 detail: 'original',
54​
55// The stub clients below implement only the one SDK method the adapter calls.
56// A full OpenAI client is too large to build, so they are cast.
57​
58// The OpenAI adapter sends provider tools in their native shape.
59class TestAdapter extends OpenAIBaseResponsesTextAdapter<string> {
60 protected override convertTools(tools: Array<Tool>) {
61 return convertToolsToProviderFormat(tools)
62 }
64​
65// The portable tool, as `@tanstack/ai-computer-use` builds it.
66function genericComputerTool() {
67 return {
68 name: 'computer',
69 description: 'Use the computer.',
70 metadata: {
71 __kind: 'computer_use',
72 display: { width: 1280, height: 800 },
73 environment: 'linux',
74 capabilities: { zoom: false, cursorPosition: true },
75 },
76 execute: vi.fn(async (_input: unknown) => screenshot),
77 } satisfies Tool
79​
80async function runLoop(model: string, call: Record<string, unknown>) {
81 const create = vi
82 .fn()
83 .mockResolvedValueOnce(completed([call]))
84 .mockResolvedValueOnce(completed([answer]))
85 const client = {
86 responses: { create: (params: unknown) => create(params) },
87 } as unknown as OpenAI
88 const tool = genericComputerTool()
89 for await (const _ of chat({
90 threadId: 'thread-1',
91 adapter: new TestAdapter(model, 'openai', client),
92 messages: [{ role: 'user', content: 'Click the button.' }],
93 tools: [tool],
94 })) {
95 // Drain the stream.
96 }
97 const [first, second] = create.mock.calls.map(([params]) => params)
98 return { first, second, execute: tool.execute }
100​
101describe('portable computer tool on the Responses API', () => {
102 it('sends computer_use_preview to computer-use-preview and runs the single action', async () => {
103 const action = { type: 'click', button: 'left', x: 10, y: 20 }
104 const { first, second, execute } = await runLoop('computer-use-preview', {
105 type: 'computer_call',
106 id: 'cu_1',
107 call_id: 'call_cu',
108 status: 'completed',
109 action,
110 pending_safety_checks: [safetyCheck],
111 })
112​
113 expect(first.tools).toEqual([
114 {
115 type: 'computer_use_preview',
116 display_width: 1280,
117 display_height: 800,
118 environment: 'linux',
119 },
120 ])
121 expect(execute.mock.calls[0]?.[0]).toEqual({
122 action,
123 pending_safety_checks: [safetyCheck],
124 })
125 expect(second.input).toContainEqual({
126 type: 'computer_call_output',
127 call_id: 'call_cu',
128 output: screenshotOutput,
129 acknowledged_safety_checks: [safetyCheck],
130 })
131 })
132​
133 it('sends the computer tool to other models and runs the batch', async () => {
134 const actions = [
135 { type: 'click', button: 'left', x: 10, y: 20 },
136 { type: 'type', text: 'hello' },
137 ]
138 const { first, second, execute } = await runLoop('gpt-6.1-sol', {
139 type: 'computer_call',
140 id: 'cu_2',
141 call_id: 'call_batch',
142 status: 'completed',
143 actions,
144 pending_safety_checks: [safetyCheck],
145 })
146​
147 expect(first.tools).toEqual([{ type: 'computer' }])
148 expect(execute.mock.calls[0]?.[0]).toEqual({
149 actions,
150 pending_safety_checks: [safetyCheck],
151 })
152 expect(second.input).toContainEqual({
153 type: 'computer_call_output',
154 call_id: 'call_batch',
155 output: screenshotOutput,
156 acknowledged_safety_checks: [safetyCheck],
157 })
158 })
159​
160 it('keeps safety checks that do not parse on the tool input', async () => {
161 const action = { type: 'click', button: 'left', x: 10, y: 20 }
162 const badChecks = [{ code: 'x' }]
163 const { second, execute } = await runLoop('gpt-6.1-sol', {
164 type: 'computer_call',
165 id: 'cu_bad',
166 call_id: 'call_bad',
167 status: 'completed',
168 action,
169 pending_safety_checks: badChecks,
170 })
171​
172 expect(execute.mock.calls[0]?.[0]).toEqual({
173 action,
174 pending_safety_checks: badChecks,
175 })
176 expect(second.input).toContainEqual({
177 type: 'computer_call_output',
178 call_id: 'call_bad',
179 output: screenshotOutput,
180 })
181 expect(JSON.stringify(second.input)).not.toContain(
182 'acknowledged_safety_checks',
183 )
184 })
185})
186​
187class TestChatCompletionsAdapter extends OpenAIBaseChatCompletionsTextAdapter<string> {}
188​
189describe('portable computer tool on the Chat Completions API', () => {
190 it('fails before any request', async () => {
191 const create = vi.fn()
192 const client = {
193 chat: { completions: { create } },
194 } as unknown as OpenAI
195 const chunks: Array<StreamChunk> = []
196 for await (const chunk of chat({
197 threadId: 'thread-1',
198 adapter: new TestChatCompletionsAdapter('gpt-6.1-sol', 'openai', client),
199 messages: [{ role: 'user', content: 'Click the button.' }],
200 tools: [genericComputerTool()],
201 })) {
202 chunks.push(chunk)
203 }
204​
205 expect(create).not.toHaveBeenCalled()
206 expect(chunks).toContainEqual(
207 expect.objectContaining({
208 type: 'RUN_ERROR',
209 message:
210 'Computer use needs the Responses API. The Chat Completions API has no computer tool.',
211 }),
212 )
213 })
214})