Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { fakeText } from '@tanstack/ai/testing'
3import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
4import { mediaIdOf } from '@tanstack/ai-harness/media'
5import { permissions } from '@tanstack/ai-harness/plugins'
6import { memoryPersistence } from '@tanstack/ai-persistence'
7import { computerUse, keepNewestScreenshots } from '../src/harness'
8import type { ModelMessage, TextOptions } from '@tanstack/ai'
9import type { FakeResponse } from '@tanstack/ai/testing'
10import type { HarnessHost, HarnessSession } from '@tanstack/ai-harness'
11import type { ComputerDriver } from '../src/types'
12
13const PNG_BYTES = new Uint8Array([137, 80, 78, 71])
14const PNG_BASE64 = 'iVBORw=='
15const CLICK = { action: { type: 'click', x: 10, y: 20, button: 'left' } }
16const CHECK = { id: 'sc_1', code: 'malicious_instructions', message: 'Look.' }
17
18const hosts: Array<HarnessHost> = []
19afterEach(async () => {
20 await Promise.all(hosts.splice(0).map((host) => host.close()))
21})
22
23/** A driver that counts its clicks. */
24function createDriver() {
25 const clicks: Array<string> = []
26 const noop = async () => {}
27 const driver: ComputerDriver = {
28 display: { width: 1024, height: 768 },
29 environment: 'browser',
30 screenshot: async () => PNG_BYTES,
31 click: async () => {
32 clicks.push('click')
33 },
34 move: noop,
35 mouseDown: noop,
36 mouseUp: noop,
37 scroll: noop,
38 keyDown: noop,
39 keyUp: noop,
40 press: noop,
41 type: noop,
42 }
43 return { driver, clicks }
44}
45
46/** A session whose model plays `answers`, then says `ok`. */
47async function open(
48 answers: Array<FakeResponse>,
49 options: { permissions?: boolean } = {},
50) {
51 const { driver, clicks } = createDriver()
52 const requests: Array<TextOptions> = []
53 const fake = fakeText()
54 const steps = [...answers, { text: 'ok' }]
55 fake.setResponses(
56 steps.map((answer) => ({ request }: { request: TextOptions }) => {
57 requests.push(request)
58 return answer
59 }),
60 )
61 const plugin = computerUse({ driver, screenshotDelay: 0 })
62 const harness = defineHarness({
63 name: 'test/computer-use',
64 adapter: fake,
65 plugins: () => (options.permissions ? [permissions(), plugin] : [plugin]),
66 })
67 const host = createHarnessHost({ persistence: memoryPersistence() })
68 hosts.push(host)
69 const session = await host.open(harness, { threadId: 't' })
70 return { session, requests, clicks }
71}
72
73const toolMessages = (messages: ReadonlyArray<ModelMessage>) =>
74 messages.filter((message) => message.role === 'tool')
75
76/** Wait for the one open approval, answer it, and wait for the turn that resumes. */
77async function answer(session: HarnessSession, value: unknown) {
78 await vi.waitFor(() =>
79 expect(session.snapshot().pendingWaits).toHaveLength(1),
80 )
81 const [wait] = session.snapshot().pendingWaits
82 if (!wait) throw new Error('No approval.')
83 const inputId = `answer:${wait.waitId}`
84 await session.resolve({
85 resume: [{ interruptId: wait.waitId, status: 'resolved', payload: value }],
86 inputId,
87 })
88 await session.settled({ inputId })
89 return wait.message ?? ''
90}
91
92describe('keepNewestScreenshots', () => {
93 const image = (value: string) => ({
94 type: 'image' as const,
95 source: { type: 'data' as const, value, mimeType: 'image/png' },
96 })
97 const step = (id: string, name = 'computer'): Array<ModelMessage> => [
98 {
99 role: 'assistant',
100 content: null,
101 toolCalls: [
102 { id, type: 'function', function: { name, arguments: '{}' } },
103 ],
104 },
105 { role: 'tool', toolCallId: id, content: [image(id)] },
106 ]
107
108 it('swaps all but the newest screenshots for a 1x1 image', () => {
109 const messages = [...step('a'), ...step('b'), ...step('c', 'read_file')]
110 const kept = keepNewestScreenshots(messages, new Set(['computer']), 1)
111
112 const values = toolMessages(kept).map((message) =>
113 JSON.stringify(message.content),
114 )
115 expect(values[0]).not.toContain('"a"')
116 expect(values[1]).toContain('"b"')
117 // Another tool keeps its image.
118 expect(values[2]).toContain('"c"')
119 // The transcript is not changed.
120 expect(JSON.stringify(messages)).toContain('"a"')
121 })
122
123 it('gives the same array when no screenshot is too old', () => {
124 const messages = [...step('a'), ...step('b')]
125 expect(keepNewestScreenshots(messages, new Set(['computer']), 2)).toBe(
126 messages,
127 )
128 })
129})
130
131describe('computerUse', () => {
132 it('stores the screenshot in the media store, and the model gets its bytes', async () => {
133 const { session, requests, clicks } = await open([
134 { toolCalls: [{ name: 'computer', input: CLICK }] },
135 ])
136
137 await session.send('click')
138
139 expect(clicks).toEqual(['click'])
140 const [result] = toolMessages(await session.transcript())
141 const [part] = Array.isArray(result?.content) ? result.content : []
142 expect(mediaIdOf(part)).toBeDefined()
143 expect(JSON.stringify(requests[1]?.messages)).toContain(PNG_BASE64)
144 })
145
146 it('asks before a call with safety checks, and runs it after a yes', async () => {
147 const { session, clicks } = await open(
148 [
149 {
150 toolCalls: [
151 {
152 name: 'computer',
153 input: { ...CLICK, pending_safety_checks: [CHECK] },
154 },
155 ],
156 },
157 ],
158 { permissions: true },
159 )
160
161 await session.send('click')
162 const message = await answer(session, { answer: 'once' })
163
164 expect(message).toContain('Allow computer')
165 expect(clicks).toEqual(['click'])
166 })
167
168 it('asks before a call with safety checks, and skips it after a no', async () => {
169 const { session, clicks } = await open(
170 [
171 {
172 toolCalls: [
173 {
174 name: 'computer',
175 input: { ...CLICK, pending_safety_checks: [CHECK] },
176 },
177 ],
178 },
179 ],
180 { permissions: true },
181 )
182
183 await session.send('click')
184 await answer(session, { answer: 'reject' })
185
186 expect(clicks).toEqual([])
187 })
188
189 it('runs a call with no safety checks without a question', async () => {
190 const { session, clicks } = await open(
191 [{ toolCalls: [{ name: 'computer', input: CLICK }] }],
192 { permissions: true },
193 )
194
195 await session.send('click')
196
197 expect(session.snapshot().pendingWaits).toEqual([])
198 expect(clicks).toEqual(['click'])
199 })
200
201 it('refuses a click in plan mode', async () => {
202 const { session, requests, clicks } = await open(
203 [{ toolCalls: [{ name: 'computer', input: CLICK }] }],
204 { permissions: true },
205 )
206 await session.runCommand({ name: 'mode', input: 'plan' })
207
208 await session.send('click')
209
210 expect(clicks).toEqual([])
211 expect(JSON.stringify(requests[1]?.messages)).toContain(
212 'This tool is not allowed in plan mode.',
213 )
214 })
215
216 it('refuses a call with safety checks without permissions()', async () => {
217 const { session, requests, clicks } = await open([
218 {
219 toolCalls: [
220 {
221 name: 'computer',
222 input: { ...CLICK, pending_safety_checks: [CHECK] },
223 },
224 ],
225 },
226 ])
227
228 await session.send('click')
229
230 expect(clicks).toEqual([])
231 expect(JSON.stringify(requests[1]?.messages)).toContain(
232 'Add permissions() to the plugins of the harness.',
233 )
234 })
235})