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

workerd-cloudflare-watchdog.spec.ts

143 lines4.1 KB

1/**
2 * Exempt from the aimock policy: the harness overrides `buildRunStream` with a
3 * local never-resolving stream and never reaches an LLM provider's HTTP layer,
4 * so there is nothing to mock.
5 */
6import { fileURLToPath } from 'node:url'
7import { expect, test } from '@playwright/test'
8import { Miniflare } from 'miniflare'
9import { build } from 'vite'
10​
11const AGENT_DIST = fileURLToPath(
12 new URL(
13 '../../../packages/ai-sandbox-cloudflare/dist/esm/agent.js',
14 import.meta.url,
15 ),
17const RUN_ID = 'watchdog-e2e'
18const STALL_MS = 250
19const POLL_TIMEOUT_MS = 15_000
20const WATCHDOG_ERROR = 'run watchdog: no progress; orchestrator presumed dead'
21​
22const harness = `
23import { SandboxCoordinator } from './agent.js'
24const RUN_ID = '${RUN_ID}'
25export class TestCoordinator extends SandboxCoordinator {
26 constructor(ctx, env) {
27 super(ctx, env, Number(env.STALL_TIMEOUT_MS))
28 }
29 buildRunStream() {
30 return (async function* () { await new Promise(() => {}) })()
31 }
32 async handleRoute(_request, parts) {
33 if (parts[0] === 'start') {
34 const result = await this.startRun({
35 runId: RUN_ID, threadId: 'thread-e2e', messages: [],
36 })
37 return this.jsonResponse(result)
38 }
39 if (parts[0] === 'state') {
40 const record = await this.status(RUN_ID)
41 const events = []
42 if (record && record.status !== 'running') {
43 for await (const event of this.log.read(RUN_ID)) events.push(event.chunk)
44 }
45 return this.jsonResponse({ record, events })
46 }
47 return new Response('not found', { status: 404 })
48 }
50export default {
51 fetch(request, env) {
52 const id = env.COORDINATOR.idFromName('singleton')
53 return env.COORDINATOR.get(id).fetch(request)
54 },
57​
58async function buildWorkerModules() {
59 const result = await build({
60 configFile: false,
61 logLevel: 'silent',
62 build: {
63 write: false,
64 rollupOptions: {
65 input: { agent: AGENT_DIST },
66 external: ['cloudflare:workers'],
67 preserveEntrySignatures: 'strict',
68 output: {
69 format: 'es',
70 entryFileNames: '[name].js',
71 chunkFileNames: '[name].js',
72 },
73 },
74 },
75 })
76 if (Array.isArray(result) || !('output' in result)) {
77 throw new Error('expected one Vite bundle')
78 }
79 return [
80 { type: 'ESModule' as const, path: 'worker.js', contents: harness },
81 ...result.output.flatMap((output) =>
82 output.type === 'chunk'
83 ? [
84 {
85 type: 'ESModule' as const,
86 path: output.fileName,
87 contents: output.code,
88 },
89 ]
90 : [],
91 ),
92 ]
94​
95/** Narrows the harness `state` route body: `{ record, events }`. */
96function readState(body: unknown) {
97 if (
98 typeof body !== 'object' ||
99 body === null ||
100 !('record' in body) ||
101 !('events' in body)
102 ) {
103 throw new Error(`unexpected state body: ${JSON.stringify(body)}`)
104 }
105 const { record, events } = body
106 const hasRecord = typeof record === 'object' && record !== null
107 return {
108 status: hasRecord && 'status' in record ? record.status : undefined,
109 error: hasRecord && 'error' in record ? record.error : undefined,
110 events,
111 }
113​
114test('a real alarm fails a stalled Cloudflare coordinator run', async () => {
115 test.setTimeout(60_000)
116 const mf = new Miniflare({
117 modules: await buildWorkerModules(),
118 compatibilityDate: '2025-01-01',
119 compatibilityFlags: ['nodejs_compat'],
120 bindings: { STALL_TIMEOUT_MS: String(STALL_MS) },
121 durableObjects: { COORDINATOR: 'TestCoordinator' },
122 })
123 const dispatch = (route: string) =>
124 mf.dispatchFetch(`http://localhost/${route}`)
125 const state = async () => readState(await (await dispatch('state')).json())
126​
127 try {
128 expect(await (await dispatch('start')).json()).toEqual({ runId: RUN_ID })
129 await expect
130 .poll(async () => (await state()).status, {
131 timeout: POLL_TIMEOUT_MS,
132 })
133 .toBe('failed')
134​
135 const final = await state()
136 expect(final.error).toEqual({ message: WATCHDOG_ERROR })
137 expect(final.events).toEqual([
138 { type: 'RUN_ERROR', message: WATCHDOG_ERROR },
139 ])
140 } finally {
141 await mf.dispose()
142 }
143})