Open History to see the last commit
1import { test, expect } from '@playwright/test'
2import {
3 EventType,
4 INTERRUPT_PAYLOAD_METADATA_KEY,
5 chat,
6 genericInterruptContinuationFromDescriptor,
7 wrapGenericInterruptContinuation,
8} from '@tanstack/ai'
9import { createAnthropicChat } from '@tanstack/ai-anthropic'
10import { createComputerUse } from '@tanstack/ai-computer-use'
11import {
12 createPlaywrightComputerDriver,
13 playwrightComputer,
14} from '@tanstack/ai-computer-playwright'
15import { localComputer } from '@tanstack/ai-computer-local'
16import { createOpenaiChat } from '@tanstack/ai-openai'
17import type { Browser, BrowserContext, Locator, Page } from '@playwright/test'
18import type { ModelMessage, StreamChunk } from '@tanstack/ai'
19import type { RobotLike } from '@tanstack/ai-computer-local'
20
21/**
22 * Computer use from end to end. A real Playwright page is the computer.
23 * `createComputerUse` with the Playwright driver runs the actions on it.
24 * `playwrightComputer` makes one page for each thread from the `browser`
25 * fixture. `localComputer` runs on a fake robot, because CI has no desktop.
26 *
27 * `chat()` runs in the spec process. A mock `fetch` sends the model streams
28 * and keeps each request body. No app server and no API key are used.
29 */
30
31const PAGE_HTML = `
32 <button id="go" onclick="document.getElementById('status').textContent = 'clicked'">Go</button>
33 <p id="status">idle</p>
34 <input id="name" />
35`
36
37const START_URL = 'https://computer.test/start'
38const FORM_URL = 'https://computer.test/form'
39
40const USER_MESSAGE: ModelMessage = { role: 'user', content: 'Fill the form.' }
41
42const SAFETY_CHECK = {
43 id: 'sc_e2e',
44 code: 'malicious_instructions',
45 message: 'The page asks the model to do something else.',
46}
47
48/** The `navigate` function tool in an OpenAI request body. */
49const OPENAI_NAVIGATE_TOOL = { type: 'function', name: 'navigate' }
50
51type MockModel = ReturnType<typeof mockModel>
52type ComputerUse = ReturnType<typeof createComputerUse>
53
54/** A mock `fetch` that sends one stream per request, in order. */
55function mockModel(streams: Array<() => ReadableStream<Uint8Array>>) {
56 const bodies: Array<unknown> = []
57 const fetch: typeof globalThis.fetch = async (input, init) => {
58 const request = input instanceof Request ? input : new Request(input, init)
59 bodies.push(JSON.parse(await request.text()))
60 const stream = streams[bodies.length - 1]
61 if (!stream)
62 throw new Error(`No model response for request ${bodies.length}`)
63 return new Response(stream(), {
64 status: 200,
65 headers: { 'Content-Type': 'text/event-stream' },
66 })
67 }
68 return { fetch, bodies }
69}
70
71function sse(lines: Array<string>) {
72 const encoder = new TextEncoder()
73 return new ReadableStream<Uint8Array>({
74 start(controller) {
75 for (const line of lines) controller.enqueue(encoder.encode(line))
76 controller.close()
77 },
78 })
79}
80
81/** An OpenAI Responses stream that completes with `output`. */
82function openaiStream(id: string, output: Array<unknown>) {
83 const events = [
84 {
85 type: 'response.created',
86 response: { id, object: 'response', status: 'in_progress', output: [] },
87 },
88 {
89 type: 'response.completed',
90 response: {
91 id,
92 object: 'response',
93 status: 'completed',
94 output,
95 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
96 },
97 },
98 ]
99 return () =>
100 sse([
101 ...events.map((event) => `data: ${JSON.stringify(event)}\n\n`),
102 'data: [DONE]\n\n',
103 ])
104}
105
106/** An OpenAI `computer_call` item with one action and no safety checks. */
107function computerCall(
108 name: string,
109 action: { type: string; [field: string]: unknown },
110) {
111 return {
112 type: 'computer_call',
113 id: `cu_${name}`,
114 call_id: `call_cu_${name}`,
115 status: 'completed',
116 action,
117 pending_safety_checks: [],
118 }
119}
120
121const OPENAI_ANSWER = {
122 type: 'message',
123 id: 'msg_cu_e2e',
124 role: 'assistant',
125 status: 'completed',
126 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
127}
128
129/** An Anthropic Messages stream. */
130function anthropicStream(events: Array<{ type: string }>) {
131 return () =>
132 sse(
133 events.map(
134 (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
135 ),
136 )
137}
138
139const ANTHROPIC_START = {
140 type: 'message_start',
141 message: {
142 id: 'msg_cu_e2e',
143 type: 'message',
144 role: 'assistant',
145 content: [],
146 model: 'claude-opus-5-5',
147 stop_reason: null,
148 stop_sequence: null,
149 usage: { input_tokens: 5, output_tokens: 0 },
150 },
151}
152
153function anthropicEnd(stopReason: string) {
154 return [
155 {
156 type: 'message_delta',
157 delta: { stop_reason: stopReason, stop_sequence: null },
158 usage: { output_tokens: 1 },
159 },
160 { type: 'message_stop' },
161 ]
162}
163
164/** The blocks of one toolset call of the `computer` toolset. */
165function toolsetCall(index: number, id: string, name: string, input: unknown) {
166 return [
167 {
168 type: 'content_block_start',
169 index,
170 content_block: {
171 type: 'tool_use',
172 id,
173 name,
174 toolset_name: 'computer',
175 input: {},
176 },
177 },
178 {
179 type: 'content_block_delta',
180 index,
181 delta: { type: 'input_json_delta', partial_json: JSON.stringify(input) },
182 },
183 { type: 'content_block_stop', index },
184 ]
185}
186
187async function openForm(page: Page) {
188 await page.setContent(PAGE_HTML)
189 return {
190 button: await centerOf(page.locator('#go')),
191 input: await centerOf(page.locator('#name')),
192 }
193}
194
195async function centerOf(locator: Locator) {
196 const box = await locator.boundingBox()
197 if (!box) throw new Error('The element has no bounding box.')
198 return {
199 x: Math.round(box.x + box.width / 2),
200 y: Math.round(box.y + box.height / 2),
201 }
202}
203
204function computerUseFor(page: Page) {
205 return createComputerUse({
206 driver: createPlaywrightComputerDriver({ page }),
207 screenshotDelay: 0,
208 })
209}
210
211/**
212 * Computer use with `playwrightComputer` on the `browser` fixture. Each new
213 * context serves `PAGE_HTML` for every `https://computer.test` URL. The
214 * contexts stay in `contexts` in the order the threads open them.
215 */
216function routedComputerUse(browser: Browser) {
217 const contexts: Array<BrowserContext> = []
218 const computerUse = createComputerUse({
219 driver: playwrightComputer({
220 startUrl: START_URL,
221 browser: {
222 async newContext(options) {
223 const context = await browser.newContext(options)
224 await context.route('https://computer.test/**', (route) =>
225 route.fulfill({ contentType: 'text/html', body: PAGE_HTML }),
226 )
227 contexts.push(context)
228 return context
229 },
230 close: () => browser.close(),
231 },
232 }),
233 screenshotDelay: 0,
234 })
235 return { computerUse, contexts }
236}
237
238/** The one page that the factory opens in a context. */
239function pageOf(context: BrowserContext) {
240 const [page] = context.pages()
241 if (!page) throw new Error('The context has no page.')
242 return page
243}
244
245function openaiAdapter(model: MockModel) {
246 return createOpenaiChat('gpt-6.1-sol', 'sk-e2e-dummy', {
247 fetch: model.fetch,
248 })
249}
250
251/** Run one OpenAI chat with computer use in a thread, to the end. */
252function runOpenai(
253 computerUse: ComputerUse,
254 model: MockModel,
255 threadId: string,
256) {
257 return drain(
258 chat({
259 adapter: openaiAdapter(model),
260 messages: [USER_MESSAGE],
261 threadId,
262 tools: computerUse.tools,
263 middleware: [computerUse.middleware],
264 interrupts: [computerUse.interrupt],
265 }),
266 )
267}
268
269async function drain(stream: AsyncIterable<StreamChunk>) {
270 const chunks: Array<StreamChunk> = []
271 for await (const chunk of stream) chunks.push(chunk)
272 return chunks
273}
274
275/** The assistant message with the tool calls of a paused run. */
276function assistantFromChunks(chunks: Array<StreamChunk>): ModelMessage {
277 const toolCalls = chunks.flatMap((chunk) => {
278 if (chunk.type !== EventType.TOOL_CALL_START) return []
279 const end = chunks.find(
280 (item) =>
281 item.type === EventType.TOOL_CALL_END &&
282 item.toolCallId === chunk.toolCallId,
283 )
284 const input = end?.type === EventType.TOOL_CALL_END ? end.input : {}
285 return [
286 {
287 id: chunk.toolCallId,
288 type: 'function' as const,
289 function: {
290 name: chunk.toolCallName,
291 arguments: JSON.stringify(input),
292 },
293 metadata: chunk.metadata,
294 },
295 ]
296 })
297 return { role: 'assistant', content: null, toolCalls }
298}
299
300function interruptOutcome(chunks: Array<StreamChunk>) {
301 const finished = chunks.find((chunk) => chunk.type === EventType.RUN_FINISHED)
302 const outcome =
303 finished?.type === EventType.RUN_FINISHED ? finished.outcome : undefined
304 if (outcome?.type !== 'interrupt') {
305 throw new Error('The run did not end with an interrupt.')
306 }
307 return outcome.interrupts
308}
309
310test.describe('computer use with a Playwright page', () => {
311 test('openai computer tool runs a batch of actions on the page', async ({
312 page,
313 }) => {
314 const { button, input } = await openForm(page)
315 const computerUse = computerUseFor(page)
316 const model = mockModel([
317 openaiStream('resp_cu_1', [
318 {
319 type: 'computer_call',
320 id: 'cu_batch',
321 call_id: 'call_cu_batch',
322 status: 'completed',
323 actions: [
324 { type: 'click', button: 'left', ...button },
325 { type: 'click', button: 'left', ...input },
326 { type: 'type', text: 'hello' },
327 ],
328 pending_safety_checks: [],
329 },
330 ]),
331 openaiStream('resp_cu_2', [OPENAI_ANSWER]),
332 ])
333
334 await runOpenai(computerUse, model, 'thread-cu-batch')
335
336 await expect(page.locator('#status')).toHaveText('clicked')
337 await expect(page.locator('#name')).toHaveValue('hello')
338 expect(model.bodies).toHaveLength(2)
339 // The Playwright driver can navigate, so the `navigate` tool goes too.
340 expect(model.bodies[0]).toMatchObject({
341 tools: [{ type: 'computer' }, OPENAI_NAVIGATE_TOOL],
342 })
343 expect(model.bodies[1]).toMatchObject({
344 input: expect.arrayContaining([
345 expect.objectContaining({
346 type: 'computer_call_output',
347 call_id: 'call_cu_batch',
348 output: expect.objectContaining({
349 type: 'computer_screenshot',
350 image_url: expect.stringMatching(/^data:image\/png;base64,./),
351 }),
352 }),
353 ]),
354 })
355 })
356
357 test('anthropic computer toolset runs each call on the page', async ({
358 page,
359 }) => {
360 const { button, input } = await openForm(page)
361 const computerUse = computerUseFor(page)
362 const model = mockModel([
363 anthropicStream([
364 ANTHROPIC_START,
365 ...toolsetCall(0, 'toolu_button', 'left_click', {
366 coordinate: [button.x, button.y],
367 }),
368 ...toolsetCall(1, 'toolu_input', 'left_click', {
369 coordinate: [input.x, input.y],
370 }),
371 ...toolsetCall(2, 'toolu_type', 'type', { text: 'hello' }),
372 ...anthropicEnd('tool_use'),
373 ]),
374 anthropicStream([ANTHROPIC_START, ...anthropicEnd('end_turn')]),
375 ])
376
377 await drain(
378 chat({
379 adapter: createAnthropicChat('claude-opus-5-5', 'sk-ant-e2e-dummy', {
380 fetch: model.fetch,
381 }),
382 messages: [USER_MESSAGE],
383 threadId: 'thread-cu-toolset',
384 tools: computerUse.tools,
385 middleware: [computerUse.middleware],
386 interrupts: [computerUse.interrupt],
387 }),
388 )
389
390 await expect(page.locator('#status')).toHaveText('clicked')
391 await expect(page.locator('#name')).toHaveValue('hello')
392 expect(model.bodies).toHaveLength(2)
393 // The Playwright driver has zoom and no cursor position. It can
394 // navigate, so the `navigate` tool goes too, as a custom tool.
395 expect(model.bodies[0]).toMatchObject({
396 tools: [
397 {
398 type: 'computer_toolset_20260801',
399 configs: {
400 zoom: { enabled: true },
401 cursor_position: { enabled: false },
402 },
403 },
404 { type: 'custom', name: 'navigate' },
405 ],
406 })
407 const screenshotResult = (toolUseId: string) =>
408 expect.objectContaining({
409 type: 'tool_result',
410 tool_use_id: toolUseId,
411 content: expect.arrayContaining([
412 expect.objectContaining({
413 type: 'image',
414 source: expect.objectContaining({
415 type: 'base64',
416 data: expect.stringMatching(/^./),
417 }),
418 }),
419 ]),
420 })
421 expect(model.bodies[1]).toMatchObject({
422 messages: expect.arrayContaining([
423 expect.objectContaining({
424 role: 'user',
425 content: expect.arrayContaining([
426 screenshotResult('toolu_button'),
427 screenshotResult('toolu_input'),
428 screenshotResult('toolu_type'),
429 ]),
430 }),
431 ]),
432 })
433 })
434
435 test('openai safety check pauses the action until a person approves it', async ({
436 page,
437 }) => {
438 const { button } = await openForm(page)
439 const computerUse = computerUseFor(page)
440 const click = { type: 'click', button: 'left', ...button }
441 const model = mockModel([
442 openaiStream('resp_cu_1', [
443 {
444 ...computerCall('checked', click),
445 pending_safety_checks: [SAFETY_CHECK],
446 },
447 ]),
448 openaiStream('resp_cu_2', [OPENAI_ANSWER]),
449 ])
450 const adapter = openaiAdapter(model)
451 // `createComputerUse` keeps the approvals per thread. So both runs use
452 // the same thread.
453 const threadId = 'thread-cu-safety'
454
455 // Run 1 ends with the safety-check interrupt. The click waits.
456 const first = await drain(
457 chat({
458 adapter,
459 messages: [USER_MESSAGE],
460 tools: computerUse.tools,
461 middleware: [computerUse.middleware],
462 interrupts: [computerUse.interrupt],
463 threadId,
464 runId: 'run-cu-safety-1',
465 }),
466 )
467 const [paused, ...others] = interruptOutcome(first)
468 expect(others).toEqual([])
469 if (!paused) throw new Error('No interrupt in the outcome.')
470 expect(paused.metadata?.[INTERRUPT_PAYLOAD_METADATA_KEY]).toEqual({
471 checks: [SAFETY_CHECK],
472 action: click,
473 })
474 await expect(page.locator('#status')).toHaveText('idle')
475 expect(model.bodies).toHaveLength(1)
476
477 const continuation = genericInterruptContinuationFromDescriptor(paused)
478 if (!continuation) throw new Error('The interrupt has no continuation.')
479 expect(continuation).toMatchObject({
480 definitionId: 'computer-safety-check',
481 key: 'call_cu_checked',
482 })
483
484 // Run 2 approves the check. The click runs, and the model gets the result.
485 await drain(
486 chat({
487 adapter,
488 messages: [USER_MESSAGE, assistantFromChunks(first)],
489 tools: computerUse.tools,
490 middleware: [computerUse.middleware],
491 interrupts: [computerUse.interrupt],
492 threadId,
493 runId: 'run-cu-safety-2',
494 parentRunId: 'run-cu-safety-1',
495 resume: [
496 {
497 interruptId: paused.id,
498 status: 'resolved',
499 payload: { approved: true },
500 metadata: wrapGenericInterruptContinuation(continuation),
501 },
502 ],
503 }),
504 )
505
506 await expect(page.locator('#status')).toHaveText('clicked')
507 expect(model.bodies).toHaveLength(2)
508 expect(model.bodies[1]).toMatchObject({
509 input: expect.arrayContaining([
510 expect.objectContaining({
511 type: 'computer_call',
512 call_id: 'call_cu_checked',
513 action: click,
514 }),
515 expect.objectContaining({
516 type: 'computer_call_output',
517 call_id: 'call_cu_checked',
518 output: expect.objectContaining({
519 image_url: expect.stringMatching(/^data:image\/png;base64,./),
520 }),
521 acknowledged_safety_checks: [SAFETY_CHECK],
522 }),
523 ]),
524 })
525 })
526})
527
528test.describe('computer use with playwrightComputer', () => {
529 test('playwrightComputer navigates, then clicks', async ({
530 browser,
531 page,
532 }) => {
533 // The fixture page has the same HTML and width as the factory pages.
534 // So the button has the same center there.
535 const { button } = await openForm(page)
536 const { computerUse, contexts } = routedComputerUse(browser)
537 const model = mockModel([
538 openaiStream('resp_cu_1', [
539 {
540 type: 'function_call',
541 id: 'fc_cu_navigate',
542 call_id: 'call_cu_navigate',
543 name: 'navigate',
544 arguments: JSON.stringify({ url: FORM_URL }),
545 status: 'completed',
546 },
547 ]),
548 openaiStream('resp_cu_2', [
549 computerCall('click', { type: 'click', button: 'left', ...button }),
550 ]),
551 openaiStream('resp_cu_3', [OPENAI_ANSWER]),
552 ])
553
554 await runOpenai(computerUse, model, 'thread-cu-navigate')
555
556 expect(contexts).toHaveLength(1)
557 const [formPage] = contexts.map(pageOf)
558 expect(formPage.url()).toBe(FORM_URL)
559 await expect(formPage.locator('#status')).toHaveText('clicked')
560 expect(model.bodies).toHaveLength(3)
561 expect(model.bodies[0]).toMatchObject({
562 tools: [{ type: 'computer' }, OPENAI_NAVIGATE_TOOL],
563 })
564 expect(model.bodies[1]).toMatchObject({
565 input: expect.arrayContaining([
566 expect.objectContaining({
567 type: 'function_call_output',
568 call_id: 'call_cu_navigate',
569 output: [
570 expect.objectContaining({
571 type: 'input_image',
572 image_url: expect.stringMatching(/^data:image\/png;base64,./),
573 }),
574 ],
575 }),
576 ]),
577 })
578
579 await computerUse.close()
580 })
581
582 test('two threads get two pages', async ({ browser, page }) => {
583 const { button } = await openForm(page)
584 const { computerUse, contexts } = routedComputerUse(browser)
585 // Thread A clicks Go. Thread B only takes a screenshot.
586 const clickModel = mockModel([
587 openaiStream('resp_cu_a1', [
588 computerCall('click', { type: 'click', button: 'left', ...button }),
589 ]),
590 openaiStream('resp_cu_a2', [OPENAI_ANSWER]),
591 ])
592 const lookModel = mockModel([
593 openaiStream('resp_cu_b1', [
594 computerCall('look', { type: 'screenshot' }),
595 ]),
596 openaiStream('resp_cu_b2', [OPENAI_ANSWER]),
597 ])
598
599 await runOpenai(computerUse, clickModel, 'a')
600 await runOpenai(computerUse, lookModel, 'b')
601
602 expect(contexts).toHaveLength(2)
603 const [pageA, pageB] = contexts.map(pageOf)
604 await expect(pageA.locator('#status')).toHaveText('clicked')
605 await expect(pageB.locator('#status')).toHaveText('idle')
606
607 // `close('a')` closes the context of thread A. Thread B keeps its page.
608 await computerUse.close('a')
609 expect(pageA.isClosed()).toBe(true)
610 expect(pageB.isClosed()).toBe(false)
611
612 await computerUse.close()
613 expect(pageB.isClosed()).toBe(true)
614 })
615})
616
617/** A fake robot on a 2560 x 1600 screen. Each call adds one line to `calls`. */
618function fakeRobot() {
619 const screen = { width: 2560, height: 1600 }
620 const calls: Array<string> = []
621 const record =
622 (name: string) =>
623 (...args: Array<string | number | boolean | undefined>) => {
624 calls.push([name, ...args].join(' ').trim())
625 }
626 const robot: RobotLike = {
627 getScreenSize: () => screen,
628 getMousePos: () => ({ x: 0, y: 0 }),
629 moveMouse: record('moveMouse'),
630 mouseClick: record('mouseClick'),
631 mouseToggle: record('mouseToggle'),
632 scrollMouse: record('scrollMouse'),
633 keyToggle: record('keyToggle'),
634 typeString: record('typeString'),
635 screen: {
636 capture: () => ({
637 ...screen,
638 byteWidth: screen.width * 4,
639 bytesPerPixel: 4,
640 image: new Uint8Array(screen.width * screen.height * 4),
641 }),
642 },
643 }
644 return { robot, calls }
645}
646
647/** The size of the first PNG screenshot in a request body. */
648function screenshotSize(body: unknown) {
649 const match = /data:image\/png;base64,([A-Za-z0-9+/=]+)/.exec(
650 JSON.stringify(body),
651 )
652 if (!match?.[1]) throw new Error('The request has no PNG screenshot.')
653 const png = Buffer.from(match[1], 'base64')
654 return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) }
655}
656
657test.describe('computer use with localComputer', () => {
658 test('localComputer clicks on the screen and sends a display-size screenshot', async () => {
659 const { robot, calls } = fakeRobot()
660 const computerUse = createComputerUse({
661 driver: localComputer({ robot }),
662 screenshotDelay: 0,
663 })
664 const model = mockModel([
665 openaiStream('resp_cu_1', [
666 {
667 type: 'computer_call',
668 id: 'cu_local',
669 call_id: 'call_cu_local',
670 status: 'completed',
671 actions: [
672 { type: 'click', button: 'left', x: 640, y: 400 },
673 { type: 'type', text: 'hello' },
674 ],
675 pending_safety_checks: [],
676 },
677 ]),
678 openaiStream('resp_cu_2', [OPENAI_ANSWER]),
679 ])
680
681 await runOpenai(computerUse, model, 'thread-cu-local')
682
683 // The 2560 x 1600 screen fits in 1280 x 800, so each point doubles.
684 expect(calls).toEqual([
685 'moveMouse 1280 800',
686 'mouseClick left',
687 'typeString hello',
688 ])
689 expect(model.bodies).toHaveLength(2)
690 // A desktop has no address, so the `navigate` tool does not go.
691 expect(model.bodies[0]).toMatchObject({ tools: [{ type: 'computer' }] })
692 expect(screenshotSize(model.bodies[1])).toEqual({
693 width: 1280,
694 height: 800,
695 })
696 })
697})