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

worker.test.ts

395 lines13.6 KB

1import { describe, expect, it } from 'vitest'
2import { generateToolWrappers, wrapCode } from '../src/worker/wrap-code'
3import type {
4 ExecuteResponse,
5 ToolResultPayload,
6 ToolSchema,
7} from '../src/types'
8import workerModule from '../src/worker/index'
9​
10/**
11 * Error envelope returned by the outer worker for invalid requests (e.g.
12 * non-POST methods or missing `code`). Not part of `ExecuteResponse` — these
13 * are short-circuit responses produced before `executeCode` is called.
14 */
15interface SimpleErrorResponse {
16 error: string
18​
19/**
20 * Single trust-boundary cast: the Fetch API types `Response.json()` as
21 * `Promise<unknown>`, but tests know the worker's response shape from the
22 * source. This helper is the ONLY place where we assert that shape; all
23 * callers get a properly typed value back without sprinkling `as` casts at
24 * each call site.
25 */
26async function readJson<T>(response: Response): Promise<T> {
27 // Trust boundary: Response.json() returns unknown; tests own the shape.
28 return (await response.json()) as T
30​
31const worker = workerModule as {
32 fetch: (
33 request: Request,
34 env: {
35 LOADER?: {
36 load: (options: {
37 compatibilityDate: string
38 mainModule: string
39 modules: Record<string, string>
40 globalOutbound?: unknown
41 env?: Record<string, unknown>
42 }) => {
43 getEntrypoint: (name?: string) => {
44 fetch: (request: Request) => Promise<Response>
45 }
46 }
47 }
48 },
49 ctx: ExecutionContext,
50 ) => Promise<Response>
52​
53const mockExecutionContext = {
54 waitUntil: () => {},
55 passThroughOnException: () => {},
56} as unknown as ExecutionContext
57​
58describe('generateToolWrappers', () => {
59 const tools: Array<ToolSchema> = [
60 {
61 name: 'add',
62 description: 'Add numbers',
63 inputSchema: { type: 'object' },
64 },
65 { name: 'fetchData', description: 'Fetch data', inputSchema: {} },
66 ]
67​
68 it('generates first-pass wrappers that collect tool calls when toolResults is undefined', () => {
69 const code = generateToolWrappers(tools)
70 expect(code).toContain('async function add(input)')
71 expect(code).toContain('__pendingToolCalls.push')
72 expect(code).toContain('__ToolCallNeeded')
73 expect(code).toContain('async function fetchData(input)')
74 expect(code).not.toContain('__toolResults')
75 })
76​
77 it('generates second-pass wrappers that return cached results when toolResults is provided', () => {
78 const toolResults: Record<string, ToolResultPayload> = {
79 add_1: { success: true, value: 5 },
80 fetchData_1: { success: false, error: 'Failed' },
81 }
82 const code = generateToolWrappers(tools, toolResults)
83 expect(code).toContain('async function add(input)')
84 expect(code).toContain('__toolResults[callId]')
85 expect(code).toContain('result.success')
86 expect(code).toContain('result.error')
87 expect(code).toContain('return result.value')
88 })
89​
90 it('rejects tool names that would break out of the function identifier', () => {
91 const malicious: ToolSchema = {
92 name: "foo'); process.exit(1); (function bar() {",
93 description: '',
94 inputSchema: {},
95 }
96 expect(() => generateToolWrappers([malicious])).toThrow(/Invalid tool name/)
97 })
98​
99 it('rejects tool names containing whitespace, quotes, or backticks', () => {
100 const cases = [
101 'has space',
102 'with`backtick',
103 "with'quote",
104 'with"quote',
105 'with;semi',
106 'with\nnewline',
107 ]
108 for (const name of cases) {
109 expect(() =>
110 generateToolWrappers([{ name, description: '', inputSchema: {} }]),
111 ).toThrow(/Invalid tool name/)
112 }
113 })
114​
115 it('rejects tool names that start with a digit', () => {
116 expect(() =>
117 generateToolWrappers([
118 { name: '123tool', description: '', inputSchema: {} },
119 ]),
120 ).toThrow(/Invalid tool name/)
121 })
122​
123 it('rejects reserved JS keywords that would pass the regex but break eval', () => {
124 const reserved = ['return', 'class', 'function', 'if', 'await', 'import']
125 for (const name of reserved) {
126 expect(
127 () =>
128 generateToolWrappers([{ name, description: '', inputSchema: {} }]),
129 `should reject reserved: ${name}`,
130 ).toThrow(/reserved JavaScript keyword/)
131 }
132 })
133​
134 it('accepts conventional identifiers (camelCase, snake_case, $_)', () => {
135 const valid = ['camelCase', 'snake_case', '_leading_underscore', '$dollar']
136 for (const name of valid) {
137 expect(() =>
138 generateToolWrappers([{ name, description: '', inputSchema: {} }]),
139 ).not.toThrow()
140 }
141 })
142})
143​
144describe('wrapCode', () => {
145 const tools: Array<ToolSchema> = [
146 { name: 'greet', description: 'Greet', inputSchema: {} },
147 ]
148​
149 it('wraps user code in async IIFE with __pendingToolCalls and __toolResults when no toolResults', () => {
150 const wrapped = wrapCode('return 1 + 1', tools)
151 expect(wrapped).toContain('(async function()')
152 expect(wrapped).toContain('const __pendingToolCalls = []')
153 expect(wrapped).toContain('const __toolResults = {}')
154 expect(wrapped).toContain('return 1 + 1')
155 expect(wrapped).toContain("status: 'done'")
156 expect(wrapped).toContain("status: 'need_tools'")
157 expect(wrapped).toContain('async function greet(input)')
158 })
159​
160 it('includes toolResults JSON when toolResults provided', () => {
161 const toolResults: Record<string, ToolResultPayload> = {
162 greet_1: { success: true, value: 'Hi' },
163 }
164 const wrapped = wrapCode('return await greet({})', tools, toolResults)
165 expect(wrapped).toContain('"greet_1"')
166 expect(wrapped).toContain('"success":true')
167 expect(wrapped).toContain('"value":"Hi"')
168 })
169​
170 it('includes console capture and __logs', () => {
171 const wrapped = wrapCode('console.log("x")', [])
172 expect(wrapped).toContain('const console =')
173 expect(wrapped).toContain('__logs.push')
174 expect(wrapped).toContain('logs: __logs')
175 })
176})
177​
178describe('Worker fetch handler', () => {
179 it('returns CORS headers for OPTIONS preflight', async () => {
180 const request = new Request('https://worker.test/', { method: 'OPTIONS' })
181 const response = await worker.fetch(request, {}, mockExecutionContext)
182​
183 expect(response.status).toBe(200)
184 expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*')
185 expect(response.headers.get('Access-Control-Allow-Methods')).toContain(
186 'POST',
187 )
188 expect(response.headers.get('Access-Control-Allow-Headers')).toContain(
189 'Content-Type',
190 )
191 })
192​
193 it('returns 405 for non-POST methods', async () => {
194 const request = new Request('https://worker.test/', { method: 'GET' })
195 const response = await worker.fetch(request, {}, mockExecutionContext)
196​
197 expect(response.status).toBe(405)
198 const json = await readJson<SimpleErrorResponse>(response)
199 expect(json).toHaveProperty('error', 'Method not allowed')
200 expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*')
201 })
202​
203 it('returns 400 when body has no code', async () => {
204 const request = new Request('https://worker.test/', {
205 method: 'POST',
206 headers: { 'Content-Type': 'application/json' },
207 body: JSON.stringify({ tools: [] }),
208 })
209 const response = await worker.fetch(request, {}, mockExecutionContext)
210​
211 expect(response.status).toBe(400)
212 const json = await readJson<SimpleErrorResponse>(response)
213 expect(json).toHaveProperty('error', 'Code is required')
214 })
215​
216 it('returns 200 with WorkerLoaderNotAvailable when env has no LOADER', async () => {
217 const request = new Request('https://worker.test/', {
218 method: 'POST',
219 headers: { 'Content-Type': 'application/json' },
220 body: JSON.stringify({
221 code: 'return 1',
222 tools: [],
223 }),
224 })
225 const response = await worker.fetch(request, {}, mockExecutionContext)
226​
227 expect(response.status).toBe(200)
228 const json =
229 await readJson<Extract<ExecuteResponse, { status: 'error' }>>(response)
230 expect(json.status).toBe('error')
231 expect(json.error.name).toBe('WorkerLoaderNotAvailable')
232 expect(json.error.message).toContain('LOADER')
233 expect(json.error.message).toContain('worker_loaders')
234 expect(json.error.message).toContain('wrangler.toml')
235 })
236​
237 it('exercises the LOADER.load → getEntrypoint → fetch chain on the happy path', async () => {
238 // Capture mock state for post-fetch assertions. Asserting inside the
239 // synchronous `load()` mock would be swallowed by the outer worker's
240 // try/catch and surface as a generic 500, masking the real failure.
241 let loadCalled = false
242 type LoadOptions = {
243 compatibilityDate: string
244 mainModule: string
245 modules: Record<string, string>
246 globalOutbound?: unknown
247 env?: Record<string, unknown>
248 }
249 let capturedOptions: LoadOptions | null = null
250 const env = {
251 LOADER: {
252 load: (options: LoadOptions) => {
253 loadCalled = true
254 capturedOptions = options
255 return {
256 getEntrypoint: () => ({
257 fetch: (_req: Request) =>
258 Promise.resolve(
259 new Response(
260 JSON.stringify({
261 status: 'done',
262 success: true,
263 value: 42,
264 logs: ['hello from sandbox'],
265 }),
266 { headers: { 'Content-Type': 'application/json' } },
267 ),
268 ),
269 }),
270 }
271 },
272 },
273 }
274​
275 const request = new Request('https://worker.test/', {
276 method: 'POST',
277 headers: { 'Content-Type': 'application/json' },
278 body: JSON.stringify({ code: 'return 42', tools: [], timeout: 5000 }),
279 })
280 const response = await worker.fetch(request, env, mockExecutionContext)
281​
282 expect(loadCalled).toBe(true)
283 expect(capturedOptions).not.toBeNull()
284 expect(capturedOptions!.mainModule).toBe('main.js')
285 expect(capturedOptions!.modules).toHaveProperty('main.js')
286 expect(capturedOptions!.modules['main.js']).toContain('export default')
287 expect(capturedOptions!.globalOutbound).toBeNull()
288 expect(response.status).toBe(200)
289 const json =
290 await readJson<Extract<ExecuteResponse, { status: 'done' }>>(response)
291 expect(json.status).toBe('done')
292 expect(json.success).toBe(true)
293 expect(json.value).toBe(42)
294 expect(json.logs).toEqual(['hello from sandbox'])
295 })
296​
297 it('forwards need_tools status from the loaded Worker back to the driver', async () => {
298 const env = {
299 LOADER: {
300 load: () => ({
301 getEntrypoint: () => ({
302 fetch: async () =>
303 new Response(
304 JSON.stringify({
305 status: 'need_tools',
306 toolCalls: [{ id: 'tc_0', name: 'fetchData', args: {} }],
307 logs: [],
308 }),
309 { headers: { 'Content-Type': 'application/json' } },
310 ),
311 }),
312 }),
313 },
314 }
315​
316 const request = new Request('https://worker.test/', {
317 method: 'POST',
318 headers: { 'Content-Type': 'application/json' },
319 body: JSON.stringify({
320 code: 'return await fetchData({})',
321 tools: [{ name: 'fetchData', description: 'd', inputSchema: {} }],
322 }),
323 })
324 const response = await worker.fetch(request, env, mockExecutionContext)
325​
326 expect(response.status).toBe(200)
327 const json =
328 await readJson<Extract<ExecuteResponse, { status: 'need_tools' }>>(
329 response,
330 )
331 expect(json.status).toBe('need_tools')
332 expect(json.toolCalls).toHaveLength(1)
333 expect(json.toolCalls[0]!.name).toBe('fetchData')
334 expect(typeof json.continuationId).toBe('string')
335 })
336​
337 it('returns TimeoutError when entrypoint.fetch exceeds timeout', async () => {
338 // Capture the AbortSignal seen by the loaded Worker so we can assert that
339 // the outer worker's AbortController actually fires `abort` on timeout.
340 // (Request.signal is always non-null per spec, so `not.toBeNull()` would
341 // be trivially true and prove nothing.)
342 let receivedSignal: AbortSignal | null = null
343 const env = {
344 LOADER: {
345 load: () => ({
346 getEntrypoint: () => ({
347 fetch: (req: Request) =>
348 new Promise<Response>((_resolve, reject) => {
349 receivedSignal = req.signal
350 req.signal.addEventListener('abort', () => {
351 reject(new Error('aborted'))
352 })
353 // Never resolves on its own; relies on AbortSignal.
354 }),
355 }),
356 }),
357 },
358 }
359​
360 const request = new Request('https://worker.test/', {
361 method: 'POST',
362 headers: { 'Content-Type': 'application/json' },
363 body: JSON.stringify({
364 code: 'while(true){}',
365 tools: [],
366 timeout: 50,
367 }),
368 })
369 const response = await worker.fetch(request, env, mockExecutionContext)
370 expect(receivedSignal).not.toBeNull()
371 expect(receivedSignal!.aborted).toBe(true)
372​
373 expect(response.status).toBe(200)
374 const json =
375 await readJson<Extract<ExecuteResponse, { status: 'error' }>>(response)
376 expect(json.status).toBe('error')
377 expect(json.error.name).toBe('TimeoutError')
378 expect(json.error.message).toContain('50ms')
379 })
380​
381 it('returns 500 with RequestError when body is invalid JSON', async () => {
382 const request = new Request('https://worker.test/', {
383 method: 'POST',
384 headers: { 'Content-Type': 'application/json' },
385 body: 'not json',
386 })
387 const response = await worker.fetch(request, {}, mockExecutionContext)
388​
389 expect(response.status).toBe(500)
390 const json =
391 await readJson<Extract<ExecuteResponse, { status: 'error' }>>(response)
392 expect(json.status).toBe('error')
393 expect(json.error.name).toBe('RequestError')
394 })
395})