Open History to see the last commit
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: {} },
66}
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>`
71}
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: '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 { name: 'happy-oyster' },
125 ],
126 }),
127 { status: 200, headers: { 'content-type': 'application/json' } },
128 ),
129 )
130 }) as typeof fetch
131 try {
132 const result = await provider.listModels({})
133 expect(result.skipped).toBeUndefined()
134 const ids = result.models.map((m) => m.rawId)
135 expect(ids).toContain('reactor/helios')
136 expect(ids).toContain('x2')
137 expect(ids).not.toContain('reactor/happy-oyster')
138 expect(ids).toContain('reactor/happy-oyster-adventure')
139 expect(new Set(ids).size).toBe(ids.length)
140 expect(result.models.every((m) => m.activity === 'video')).toBe(true)
141 expect(
142 result.models.find((m) => m.rawId === 'reactor/helios')?.pricing,
143 ).toBeUndefined()
144 expect(
145 result.models.find((m) => m.rawId === 'x2')?.pricing,
146 ).toMatchObject({
147 price: { '*': [{ var: 'video_seconds' }, 0.0017] },
148 })
149 } finally {
150 globalThis.fetch = original
151 }
152 })
153
154 it('falls back to the curated catalog when /pricing fails', async () => {
155 const original = globalThis.fetch
156 globalThis.fetch = () =>
157 Promise.resolve(new Response('nope', { status: 500 }))
158 try {
159 const result = await provider.listModels({})
160 expect(result.skipped).toBeUndefined()
161 expect(result.models.map((m) => m.rawId)).toEqual(
162 expect.arrayContaining([
163 'reactor/helios',
164 'reactor/fast-h3',
165 'x2',
166 'reactor/happy-oyster-director',
167 ]),
168 )
169 } finally {
170 globalThis.fetch = original
171 }
172 })
173})
174
175describe('reactor fetchSpec', () => {
176 it('extracts upstream OpenAPI from model API pages and namespaces paths', async () => {
177 const original = globalThis.fetch
178 const calls: Array<string> = []
179 globalThis.fetch = ((url: string) => {
180 const href = String(url)
181 calls.push(href)
182 if (href === modelApiPageUrl('helios')) {
183 return Promise.resolve(
184 new Response(htmlWithSpec(MINI_SPEC), {
185 status: 200,
186 headers: { 'content-type': 'text/html' },
187 }),
188 )
189 }
190 return Promise.resolve(new Response('not found', { status: 404 }))
191 }) as typeof fetch
192 try {
193 const fetched = await provider.fetchSpec({})
194 expect(calls).toContain(modelApiPageUrl('helios'))
195 expect(calls).toContain(modelApiPageUrl('ltx'))
196 expect(fetched.outputStrategy).toBe('post-200')
197 expect(fetched.warnings?.length).toBeGreaterThan(0)
198
199 const heliosSource = fetched.sources.find((s) =>
200 s.url.includes('helios/api#reactor/helios'),
201 )
202 expect(heliosSource?.hash).toMatch(/^[0-9a-f]{64}$/)
203
204 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
205 expect(warnings).toEqual([])
206 const byId = new Map(endpoints.map((e) => [e.dbId, e]))
207 expect(byId.get('reactor/reactor/helios')?.activity).toBe('video')
208 expect(
209 byId.get('reactor/reactor/helios/events/set_prompt')?.activity,
210 ).toBe('video')
211 expect(byId.get('reactor/reactor/helios/events/start')?.activity).toBe(
212 'video',
213 )
214 expect(endpoints.every((e) => e.derivation === 'upstream-spec')).toBe(
215 true,
216 )
217
218 for (const endpoint of endpoints) {
219 expect(endpoint.input ?? endpoint.output, endpoint.dbId).toBeDefined()
220 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
221 if (endpoint.output) {
222 expect(findDanglingRefs(endpoint.output)).toEqual([])
223 }
224 }
225
226 const setPrompt = byId.get('reactor/reactor/helios/events/set_prompt')
227 expect(setPrompt?.input?.required).toEqual(['prompt'])
228
229 const envelope = byId.get('reactor/reactor/helios')
230 expect(Array.isArray(envelope?.input?.oneOf)).toBe(true)
231 } finally {
232 globalThis.fetch = original
233 }
234 })
235
236 it('hashes the extracted OpenAPI, not the surrounding HTML', async () => {
237 const original = globalThis.fetch
238 let n = 0
239 globalThis.fetch = ((url: string) => {
240 if (String(url) !== modelApiPageUrl('helios')) {
241 return Promise.resolve(new Response('not found', { status: 404 }))
242 }
243 n += 1
244 const html = htmlWithSpec(MINI_SPEC) + `<!-- ${String(n)} -->`
245 return Promise.resolve(new Response(html, { status: 200 }))
246 }) as typeof fetch
247 try {
248 const a = await provider.fetchSpec({})
249 const b = await provider.fetchSpec({})
250 const hashA = a.sources.find((s) => s.url.includes('helios'))?.hash
251 const hashB = b.sources.find((s) => s.url.includes('helios'))?.hash
252 expect(hashA).toBe(hashB)
253 } finally {
254 globalThis.fetch = original
255 }
256 })
257})
258
259describe('reactor POST /tokens', () => {
260 it('documents the session JWT call and leaves command paths out of it', () => {
261 expect(provider.realtimeCommands).toBe(true)
262 const post = reactorPlatformOperations(undefined)['/tokens']?.post
263 if (!post) throw new Error('missing POST /tokens')
264 expect(post.parameters).toEqual([
265 expect.objectContaining({
266 name: 'Reactor-API-Key',
267 in: 'header',
268 required: true,
269 }),
270 ])
271 const body = sessionTokenRequestSchema()
272 expect(body.required).toEqual(['authorization_details'])
273 const details = (
274 body.properties as {
275 authorization_details: { items: { required: Array<string> } }
276 }
277 ).authorization_details
278 expect(details.items.required).toEqual(['type', 'resources'])
279 const response = (
280 post.responses as {
281 '200': {
282 content: {
283 'application/json': { schema: { required: Array<string> } }
284 }
285 }
286 }
287 )['200']
288 expect(response.content['application/json'].schema.required).toEqual([
289 'jwt',
290 'expires_at',
291 ])
292 const pinned = reactorPlatformOperations('reactor/helios')['/tokens']?.post
293 expect(JSON.stringify(pinned)).toContain('"enum":["reactor/helios"]')
294 })
295})
296
297describe('reactor seed metadata', () => {
298 it('exports the isolation-required fields', () => {
299 expect(provider.id).toBe('reactor')
300 expect(provider.displayName).toBe('Reactor')
301 expect(provider.authEnvVar).toBe('REACTOR_API_KEY')
302 expect(provider.defaultDerivation).toBe('upstream-spec')
303 expect(provider.specGrain).toBe('model')
304 expect(provider.specSourceUrl).toMatch(/^https:\/\//)
305 expect(provider.modelsEndpoint).toBe(REACTOR_PRICING_URL)
306 })
307})