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

reactor.test.ts

323 lines10.5 KB

1import { describe, expect, it } from 'vitest'
2​
3import { findDanglingRefs } from '#/server/ingest/bundle.ts'
4import { classifyAndBundle } from '#/server/ingest/sync.ts'
5​
6import {
7 REACTOR_PRICING_URL,
8 extractOpenApiFromHtml,
9 modelApiPageUrl,
10 provider,
11 reactorPlatformOperations,
12 sessionTokenRequestSchema,
13} from './reactor.ts'
14​
15const MINI_SPEC = {
16 openapi: '3.1.0',
17 info: { title: 'helios', version: 'v1.0.1' },
18 paths: {
19 '/events/set_prompt': {
20 post: {
21 operationId: 'set_prompt',
22 summary: 'Set the prompt',
23 requestBody: {
24 required: true,
25 content: {
26 'application/json': {
27 schema: {
28 type: 'object',
29 required: ['prompt'],
30 properties: { prompt: { type: 'string' } },
31 },
32 },
33 },
34 },
35 responses: {
36 '200': {
37 description: 'ok',
38 content: {
39 'application/json': {
40 schema: {
41 type: 'object',
42 properties: { prompt: { type: 'string' } },
43 },
44 },
45 },
46 },
47 },
48 },
49 },
50 '/events/start': {
51 post: {
52 operationId: 'start',
53 requestBody: {
54 required: true,
55 content: {
56 'application/json': {
57 schema: { type: 'object', properties: {} },
58 },
59 },
60 },
61 responses: { '202': { description: 'accepted' } },
62 },
63 },
64 },
65 components: { schemas: {} },
67​
68function htmlWithSpec(spec: unknown): string {
69 const chunk = JSON.stringify(JSON.stringify(spec))
70 return `<!doctype html><script>self.__next_f.push([1,${chunk}])</script>`
72​
73describe('extractOpenApiFromHtml', () => {
74 it('reads the OpenAPI document out of a Next.js RSC string chunk', () => {
75 const extracted = extractOpenApiFromHtml(htmlWithSpec(MINI_SPEC))
76 expect(extracted?.info?.title).toBe('helios')
77 expect(extracted?.paths?.['/events/set_prompt']?.post).toBeDefined()
78 })
79​
80 it('returns null when the page has no spec chunk', () => {
81 expect(extractOpenApiFromHtml('<html>nope</html>')).toBeNull()
82 })
83})
84​
85describe('reactor classify', () => {
86 it('maps namespaced model command paths and drops platform', () => {
87 expect(provider.classify('/reactor/helios', {})).toBe('video')
88 expect(provider.classify('/reactor/helios/events/set_prompt', {})).toBe(
89 'video',
90 )
91 expect(provider.classify('/x2/events/set_prompt', {})).toBe('video')
92 expect(
93 provider.classify('/reactor/happy-oyster-adventure/create_world', {}),
94 ).toBe('video')
95 expect(provider.classify('/tokens', {})).toBeNull()
96 expect(provider.classify('/sessions', {})).toBeNull()
97 expect(provider.classify('/pricing', {})).toBeNull()
98 })
99})
100​
101describe('reactor listModels', () => {
102 it('does not skip when REACTOR_API_KEY is absent (GET /pricing is public)', async () => {
103 const original = globalThis.fetch
104 globalThis.fetch = ((url: string) => {
105 expect(String(url)).toBe(REACTOR_PRICING_URL)
106 return Promise.resolve(
107 new Response(
108 JSON.stringify({
109 models: [
110 {
111 id: 'helios-id',
112 name: 'helios',
113 rate: { amount_per_sec: 17, unit: 'credits' },
114 },
115 {
116 name: 'xmax/x2',
117 rate: {
118 amount_per_sec: 17,
119 amount_per_sec_usd: '0.0017',
120 currency_code: 'USD',
121 unit: 'credits',
122 },
123 },
124 {
125 name: 'reactor/xmax-x2-1',
126 rate: {
127 amount_per_sec: 17,
128 amount_per_sec_usd: '0.0017',
129 currency_code: 'USD',
130 unit: 'credits',
131 },
132 },
133 { name: 'happy-oyster' },
134 ],
135 }),
136 { status: 200, headers: { 'content-type': 'application/json' } },
137 ),
138 )
139 }) as typeof fetch
140 try {
141 const result = await provider.listModels({})
142 expect(result.skipped).toBeUndefined()
143 const ids = result.models.map((m) => m.rawId)
144 expect(ids).toContain('reactor/helios')
145 expect(ids).toContain('x2')
146 expect(ids).not.toContain('xmax/x2')
147 expect(ids).toContain('reactor/xmax-x2-1')
148 expect(ids).not.toContain('reactor/happy-oyster')
149 expect(ids).toContain('reactor/happy-oyster-adventure')
150 expect(new Set(ids).size).toBe(ids.length)
151 expect(result.models.every((m) => m.activity === 'video')).toBe(true)
152 expect(
153 result.models.find((m) => m.rawId === 'reactor/helios')?.pricing,
154 ).toBeUndefined()
155 const perSecond = {
156 price: { '*': [{ var: 'video_seconds' }, 0.0017] },
157 }
158 expect(
159 result.models.find((m) => m.rawId === 'x2')?.pricing,
160 ).toMatchObject(perSecond)
161 expect(
162 result.models.find((m) => m.rawId === 'reactor/xmax-x2-1')?.pricing,
163 ).toMatchObject(perSecond)
164 } finally {
165 globalThis.fetch = original
166 }
167 })
168​
169 it('throws when /pricing fails or lists no models', async () => {
170 const original = globalThis.fetch
171 const bodies = ['nope', 'not json', JSON.stringify({ settings: {} })]
172 try {
173 for (const body of bodies) {
174 globalThis.fetch = () =>
175 Promise.resolve(
176 new Response(body, {
177 status: body === 'nope' ? 500 : 200,
178 headers: { 'content-type': 'application/json' },
179 }),
180 )
181 await expect(provider.listModels({})).rejects.toThrow(/pricing|fetch/)
182 }
183 } finally {
184 globalThis.fetch = original
185 }
186 })
187})
188​
189describe('reactor fetchSpec', () => {
190 it('extracts upstream OpenAPI from model API pages and namespaces paths', async () => {
191 const original = globalThis.fetch
192 const calls: Array<string> = []
193 globalThis.fetch = ((url: string) => {
194 const href = String(url)
195 calls.push(href)
196 if (href === modelApiPageUrl('helios')) {
197 return Promise.resolve(
198 new Response(htmlWithSpec(MINI_SPEC), {
199 status: 200,
200 headers: { 'content-type': 'text/html' },
201 }),
202 )
203 }
204 return Promise.resolve(new Response('not found', { status: 404 }))
205 }) as typeof fetch
206 try {
207 const fetched = await provider.fetchSpec({})
208 expect(calls).toContain(modelApiPageUrl('helios'))
209 expect(calls).toContain(modelApiPageUrl('ltx'))
210 expect(fetched.outputStrategy).toBe('post-200')
211 expect(fetched.warnings?.length).toBeGreaterThan(0)
212​
213 const heliosSource = fetched.sources.find((s) =>
214 s.url.includes('helios/api#reactor/helios'),
215 )
216 expect(heliosSource?.hash).toMatch(/^[0-9a-f]{64}$/)
217​
218 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
219 expect(warnings).toEqual([])
220 const byId = new Map(endpoints.map((e) => [e.dbId, e]))
221 expect(byId.get('reactor/reactor/helios')?.activity).toBe('video')
222 expect(
223 byId.get('reactor/reactor/helios/events/set_prompt')?.activity,
224 ).toBe('video')
225 expect(byId.get('reactor/reactor/helios/events/start')?.activity).toBe(
226 'video',
227 )
228 expect(endpoints.every((e) => e.derivation === 'upstream-spec')).toBe(
229 true,
230 )
231​
232 for (const endpoint of endpoints) {
233 expect(endpoint.input ?? endpoint.output, endpoint.dbId).toBeDefined()
234 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
235 if (endpoint.output) {
236 expect(findDanglingRefs(endpoint.output)).toEqual([])
237 }
238 }
239​
240 const setPrompt = byId.get('reactor/reactor/helios/events/set_prompt')
241 expect(setPrompt?.input?.required).toEqual(['prompt'])
242​
243 const envelope = byId.get('reactor/reactor/helios')
244 expect(Array.isArray(envelope?.input?.oneOf)).toBe(true)
245 } finally {
246 globalThis.fetch = original
247 }
248 })
249​
250 it('hashes the extracted OpenAPI, not the surrounding HTML', async () => {
251 const original = globalThis.fetch
252 let n = 0
253 globalThis.fetch = ((url: string) => {
254 if (String(url) !== modelApiPageUrl('helios')) {
255 return Promise.resolve(new Response('not found', { status: 404 }))
256 }
257 n += 1
258 const html = htmlWithSpec(MINI_SPEC) + `<!-- ${String(n)} -->`
259 return Promise.resolve(new Response(html, { status: 200 }))
260 }) as typeof fetch
261 try {
262 const a = await provider.fetchSpec({})
263 const b = await provider.fetchSpec({})
264 const hashA = a.sources.find((s) => s.url.includes('helios'))?.hash
265 const hashB = b.sources.find((s) => s.url.includes('helios'))?.hash
266 expect(hashA).toBe(hashB)
267 } finally {
268 globalThis.fetch = original
269 }
270 })
271})
272​
273describe('reactor POST /tokens', () => {
274 it('documents the session JWT call and leaves command paths out of it', () => {
275 expect(provider.realtimeCommands).toBe(true)
276 const post = reactorPlatformOperations(undefined)['/tokens']?.post
277 if (!post) throw new Error('missing POST /tokens')
278 expect(post.parameters).toEqual([
279 expect.objectContaining({
280 name: 'Reactor-API-Key',
281 in: 'header',
282 required: true,
283 }),
284 ])
285 const body = sessionTokenRequestSchema()
286 expect(body.required).toEqual(['authorization_details'])
287 const details = (
288 body.properties as {
289 authorization_details: { items: { required: Array<string> } }
290 }
291 ).authorization_details
292 expect(details.items.required).toEqual(['type', 'resources'])
293 const response = (
294 post.responses as {
295 '200': {
296 content: {
297 'application/json': { schema: { required: Array<string> } }
298 }
299 }
300 }
301 )['200']
302 expect(response.content['application/json'].schema.required).toEqual([
303 'jwt',
304 'expires_at',
305 ])
306 const pinned = reactorPlatformOperations('reactor/helios')['/tokens']?.post
307 expect(JSON.stringify(pinned)).toContain('"enum":["reactor/helios"]')
308 const x2 = reactorPlatformOperations('x2')['/tokens']?.post
309 expect(JSON.stringify(x2)).toContain('"enum":["xmax/x2"]')
310 })
311})
312​
313describe('reactor seed metadata', () => {
314 it('exports the isolation-required fields', () => {
315 expect(provider.id).toBe('reactor')
316 expect(provider.displayName).toBe('Reactor')
317 expect(provider.authEnvVar).toBe('REACTOR_API_KEY')
318 expect(provider.defaultDerivation).toBe('upstream-spec')
319 expect(provider.specGrain).toBe('model')
320 expect(provider.specSourceUrl).toMatch(/^https:\/\//)
321 expect(provider.modelsEndpoint).toBe(REACTOR_PRICING_URL)
322 })
323})