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

ant-ling.test.ts

726 lines23.7 KB

1import type { BrowserRunContentOptions } from '@cloudflare/workers-types'
2import { Validator } from '@cfworker/json-schema'
3import { afterEach, expect, it } from 'vitest'
4import { cardCurrency, price } from '@modelschemas/rate-card'
5import { classifyAndBundle } from '../../ingest/sync.ts'
6import fixtures from '../fixtures/ant-ling-docs.json'
7import sourceFailure from '../fixtures/ant-ling-native-source-failure.json'
8import seriesThinking from '../fixtures/ant-ling-openai-series-thinking.json'
9import reasoningEffort from '../fixtures/ant-ling-openai-reasoning-effort.json'
10import noEffort from '../fixtures/ant-ling-openai-no-effort.json'
11import {
12 ANT_OPENAI,
13 ANT_PRICE,
14 nativePrices,
15 nativeRequest,
16} from '../ant-ling-docs.ts'
17import { provider } from './ant-ling.ts'
18import { sha256Text } from '../types.ts'
19import type { ProviderEnvironment } from '../types.ts'
20​
21const native = fixtures as Record<string, string>
22const originalFetch = globalThis.fetch
23let nativeEnv: ProviderEnvironment = {}
24function serve(overrides: Record<string, string> = {}) {
25 const urls: Array<string> = []
26 nativeEnv = {
27 BROWSER: {
28 quickAction: async (action: string, options: { url?: string }) => {
29 if (action !== 'content' || !options.url)
30 throw new Error('unexpected browser action')
31 const url = options.url
32 urls.push(url)
33 const body = overrides[url] ?? native[url]
34 if (body === undefined) throw new Error(`unexpected source ${url}`)
35 return Response.json({
36 success: true,
37 result: body,
38 meta: { status: 200, finalUrl: url, title: 'native fixture' },
39 })
40 },
41 } as unknown as Pick<BrowserRun, 'quickAction'>,
42 }
43 return urls
45afterEach(() => {
46 globalThis.fetch = originalFetch
47})
48it('refreshes direct IDs, CNY sale/free rates and hosted contexts without a key', async () => {
49 const urls = serve()
50 const fetched = await provider.listModels(nativeEnv)
51 expect(fetched.skipped).toBeUndefined()
52 expect(fetched.models).toHaveLength(8)
53 const flagship = fetched.models.find((m) => m.rawId === 'Ling-2.6-1T')
54 expect(flagship?.contextWindow).toBe(256000)
55 expect(flagship?.pricing).toMatchObject({
56 tables: {
57 rate: {
58 base: {
59 input_tokens: 4.5 / 1e6,
60 output_tokens: 18 / 1e6,
61 cache_read_tokens: 0.9 / 1e6,
62 },
63 },
64 },
65 })
66 const flash = fetched.models.find((m) => m.rawId === 'Ling-3.0-flash')
67 expect(
68 cardCurrency(flash?.pricing as Parameters<typeof cardCurrency>[0]),
69 ).toBe('CNY')
70 expect(flash?.pricing).toMatchObject({
71 tables: {
72 rate: {
73 base: {
74 input_tokens: 0.125 / 1e6,
75 output_tokens: 0.375 / 1e6,
76 cache_read_tokens: 0.025 / 1e6,
77 },
78 },
79 },
80 })
81 const free = fetched.models.find((m) => m.rawId === 'Ling-3.1-flash')
82 expect(price(free?.pricing as Parameters<typeof price>[0], {})).toBe(0)
83 expect(
84 fetched.models.find((m) => m.rawId === 'AntAngelMed')?.pricing,
85 ).toBeNull()
86 expect(
87 fetched.models.find((m) => m.rawId === 'Ling-3.0-tiny')?.contextWindow,
88 ).toBeNull()
89 expect(fetched.models.every((m) => m.maxOutput === null)).toBe(true)
90 expect(
91 urls.every((url) =>
92 url.startsWith('https://developer.ant-ling.com/en/docs/'),
93 ),
94 ).toBe(true)
95})
96it('keeps scoped native reasoning bodies and unknown max_tokens null', async () => {
97 serve()
98 const { models } = await provider.listModels(nativeEnv)
99 const ring = models.find((m) => m.rawId === 'Ring-2.6-1T')
100 expect(ring).toMatchObject({
101 reasoning: { mode: 'effort', mandatory: null, efforts: ['high', 'xhigh'] },
102 requestMap: {
103 thinking: {
104 on: { reasoning: { effort: 'high' } },
105 off: null,
106 levels: { high: 'high', xhigh: 'xhigh', medium: null },
107 },
108 maxTokensField: null,
109 },
110 })
111 const flash = models.find((m) => m.rawId === 'Ling-3.0-flash')
112 expect(flash?.requestMap?.thinking).toMatchObject({
113 on: { thinking: { type: 'enabled' } },
114 off: { thinking: { type: 'disabled' } },
115 })
116 expect(
117 models.find((m) => m.rawId === 'Ling-2.6-1T')?.requestMap?.thinking,
118 ).toBeNull()
119 expect(
120 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
121 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
122})
123it('binds the thinking toggle to every id in the series the page names', async () => {
124 serve({ [ANT_OPENAI]: seriesThinking.html })
125 const { models } = await provider.listModels(nativeEnv)
126 const toggle = {
127 on: { thinking: { type: 'enabled' } },
128 off: { thinking: { type: 'disabled' } },
129 levels: null,
130 }
131 for (const id of [
132 'Ling-3.1-flash',
133 'Ling-3.0-flash-VL',
134 'Ling-3.0-flash',
135 'Ling-3.0-tiny',
136 ]) {
137 const row = models.find((m) => m.rawId === id)
138 expect(row?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
139 expect(row?.requestMap?.thinking).toEqual(toggle)
140 }
141 for (const id of ['Ling-2.6-1T', 'Ling-2.6-flash', 'AntAngelMed']) {
142 const row = models.find((m) => m.rawId === id)
143 expect(row?.reasoning).toBeNull()
144 expect(row?.requestMap?.thinking).toBeNull()
145 }
146 expect(models.find((m) => m.rawId === 'Ring-2.6-1T')?.reasoning).toEqual({
147 mode: 'effort',
148 mandatory: null,
149 efforts: ['high', 'xhigh'],
150 })
151})
152it('reads the top-level reasoning_effort string the page replaced reasoning.effort with', async () => {
153 serve({ [ANT_OPENAI]: reasoningEffort.html })
154 const { models } = await provider.listModels(nativeEnv)
155 const ring = models.find((m) => m.rawId === 'Ring-2.6-1T')
156 expect(ring?.reasoning).toEqual({
157 mode: 'effort',
158 mandatory: null,
159 efforts: ['high', 'xhigh'],
160 })
161 expect(ring?.requestMap?.thinking).toMatchObject({
162 off: null,
163 levels: { high: 'high', xhigh: 'xhigh', medium: null },
164 })
165 expect(ring?.requestMap?.thinking?.on).toEqual({ reasoning_effort: 'high' })
166 for (const id of ['Ling-3.0-flash', 'Ling-3.1-flash'])
167 expect(models.find((m) => m.rawId === id)?.reasoning).toEqual({
168 mode: 'toggle',
169 mandatory: false,
170 })
171 expect(models.find((m) => m.rawId === 'Ling-2.6-1T')?.reasoning).toBeNull()
172 const input = nativeRequest(reasoningEffort.html)
173 expect(
174 (input.properties as Record<string, unknown>).reasoning_effort,
175 ).toMatchObject({ type: 'string', enum: ['high', 'xhigh'], default: 'high' })
176 const bundled = classifyAndBundle(
177 provider,
178 await provider.fetchSpec(nativeEnv),
179 )
180 expect(bundled.endpoints).toHaveLength(1)
181})
182it('reads a reference that dropped reasoning_effort with Ring as no effort model', async () => {
183 serve({ [ANT_OPENAI]: noEffort.html })
184 const { models } = await provider.listModels(nativeEnv)
185 for (const id of [
186 'Ling-3.1-flash',
187 'Ling-3.0-flash-VL',
188 'Ling-3.0-flash',
189 'Ling-3.0-tiny',
190 ]) {
191 const row = models.find((m) => m.rawId === id)
192 expect(row?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
193 expect(row?.requestMap?.thinking).toEqual({
194 on: { thinking: { type: 'enabled' } },
195 off: { thinking: { type: 'disabled' } },
196 levels: null,
197 })
198 }
199 expect(models.some((m) => m.reasoning?.mode === 'effort')).toBe(false)
200 expect(models.find((m) => m.rawId === 'Ring-2.6-1T')?.requestMap).toBeNull()
201 expect(
202 models.find((m) => m.rawId === 'Ming-3.0-audio-flash')?.modalities,
203 ).toEqual({ input: ['text', 'audio'], output: ['text'] })
204 expect(
205 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
206 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
207 expect(models.find((m) => m.rawId === 'Ling-3.0-flash')?.modalities).toEqual({
208 input: ['text'],
209 output: ['text'],
210 })
211})
212it('fails an input-modality statement it cannot read', async () => {
213 for (const html of [
214 noEffort.html.replace('accepts text and audio', 'accepts text and smell'),
215 noEffort.html.replace(
216 'the request accepts text, images, and videos',
217 'the request also accepts text, images, and videos',
218 ),
219 ]) {
220 expect(html).not.toBe(noEffort.html)
221 serve({ [ANT_OPENAI]: html })
222 await expect(provider.listModels(nativeEnv)).rejects.toThrow(
223 /unreadable native input modality smell|missing native multimodal applicability/,
224 )
225 }
226})
227it('fails a reasoning_effort it cannot scope or whose default is no option', async () => {
228 const detailDefault =
229 'default <code class="nextra-code" dir="ltr">high</code>'
230 const overviewDefault =
231 /(<td[^>]*>\s*)<code class="nextra-code" dir="ltr">high<\/code>/
232 const description =
233 'Controls how much reasoning depth Ring-2.6-1T applies when responding.'
234 const cases: Array<[string, RegExp]> = [
235 [
236 reasoningEffort.html.replace('(Ring-2.6-1T only)', ''),
237 /unreadable reasoning_effort applicability/,
238 ],
239 [
240 reasoningEffort.html.replace(
241 description,
242 'Only takes effect for Ring-3.0-1T.',
243 ),
244 /conflicting reasoning_effort applicability/,
245 ],
246 [
247 reasoningEffort.html.replace(
248 description,
249 'Controls reasoning depth. Supported by 2.6 series models.',
250 ),
251 /conflicting reasoning_effort applicability/,
252 ],
253 [
254 reasoningEffort.html.replace(
255 description,
256 'Controls how much reasoning depth Ring-3.0-1T applies when responding.',
257 ),
258 /conflicting reasoning_effort applicability/,
259 ],
260 [
261 reasoningEffort.html.replace(
262 detailDefault,
263 'default <code class="nextra-code" dir="ltr">max</code>',
264 ),
265 /reasoning_effort defaults disagree/,
266 ],
267 [
268 reasoningEffort.html.replace(detailDefault, ''),
269 /reasoning_effort default unstated/,
270 ],
271 [
272 reasoningEffort.html.replace(
273 description,
274 'Controls how much reasoning depth Ring-2.6-1T-mini applies when responding.',
275 ),
276 /conflicting reasoning_effort applicability/,
277 ],
278 [
279 reasoningEffort.html.replace(
280 overviewDefault,
281 '$1<code class="nextra-code" dir="ltr">xhigh</code>',
282 ),
283 /reasoning_effort defaults disagree/,
284 ],
285 [
286 reasoningEffort.html
287 .replace(
288 detailDefault,
289 'default <code class="nextra-code" dir="ltr">max</code>',
290 )
291 .replace(
292 overviewDefault,
293 '$1<code class="nextra-code" dir="ltr">max</code>',
294 ),
295 /unknown parameter default/,
296 ],
297 [
298 reasoningEffort.html.replace(
299 '<h3 id="thinking"',
300 '<h3 id="reasoning">reasoning</h3><ul><li><strong>Description</strong>: Only takes effect for Ring-2.6-1T.</li></ul><h4 id="reasoningeffort">reasoning.effort</h4><ul><li><strong>Type</strong>: <code>string</code></li></ul><h3 id="thinking"',
301 ),
302 /two native effort fields/,
303 ],
304 ]
305 const search = reasoningEffort.html
306 .replace(
307 /(<code class="nextra-code" dir="ltr">enable_search<\/code><\/td>(?:<td[^>]*>[\s\S]*?<\/td>){2}<td[^>]*>)<code class="nextra-code" dir="ltr">false<\/code>/,
308 '$1<code class="nextra-code" dir="ltr">auto</code>',
309 )
310 .replace(
311 'Whether to allow the model to use web search.</li>',
312 'Whether to allow the model to use web search.</li><li><strong>Options</strong>:<ul><li><code>auto</code></li></ul></li>',
313 )
314 expect(search).not.toBe(reasoningEffort.html)
315 expect(() => nativeRequest(search)).toThrow('unknown parameter default')
316 for (const [html, error] of cases) {
317 expect(html).not.toBe(reasoningEffort.html)
318 serve({ [ANT_OPENAI]: html })
319 await expect(provider.listModels(nativeEnv)).rejects.toThrow(error)
320 }
321})
322it('fails thinking scopes it cannot read as stated support', async () => {
323 const sentence = 'Supported by 3.0 series models and 3.1 series models.'
324 const cases: Array<[string, RegExp]> = [
325 [
326 seriesThinking.html.replace(
327 sentence,
328 'Supported by 3.0 series models and 4.0 series models.',
329 ),
330 /no native model in the 4\.0 series/,
331 ],
332 [
333 seriesThinking.html.replace(sentence, `Not s${sentence.slice(1)}`),
334 /unreadable thinking applicability/,
335 ],
336 [
337 seriesThinking.html.replace(
338 sentence,
339 `${sentence} Not supported by Ling-3.0-tiny.`,
340 ),
341 /unreadable thinking applicability/,
342 ],
343 [
344 seriesThinking.html.replace(
345 '3.0 series models and 3.1 series models enable reasoning',
346 '3.0 series models enable reasoning',
347 ),
348 /thinking\.type names other models than thinking/,
349 ],
350 [
351 seriesThinking.html.replaceAll(
352 '3.0 series models and 3.1 series models',
353 '2.6 series models',
354 ),
355 /a model has both native reasoning controls/,
356 ],
357 ]
358 for (const [html, error] of cases) {
359 serve({ [ANT_OPENAI]: html })
360 await expect(provider.listModels(nativeEnv)).rejects.toThrow(error)
361 }
362})
363it('derives native parameter tables and nested constraints without borrowing a schema', async () => {
364 serve()
365 const fetched = await provider.fetchSpec(nativeEnv)
366 const bundled = classifyAndBundle(provider, fetched)
367 expect(bundled.endpoints).toHaveLength(1)
368 expect(bundled.endpoints[0]?.input).toBeTruthy()
369 expect(bundled.endpoints[0]?.output).toBeUndefined()
370 const input = nativeRequest(native[ANT_OPENAI] ?? '')
371 expect(
372 (input.properties as Record<string, Record<string, unknown>>).model?.[
373 'x-source-options'
374 ],
375 ).toContain('Ring-2.6-1T')
376 expect(input).toMatchObject({
377 required: ['model', 'messages'],
378 properties: {
379 temperature: { type: 'number', minimum: 0, maximum: 1 },
380 top_p: { exclusiveMinimum: 0, maximum: 1 },
381 messages: {
382 items: {
383 required: ['role', 'content'],
384 properties: { role: { enum: ['system', 'user', 'assistant'] } },
385 },
386 },
387 },
388 })
389 expect(
390 (input.properties as Record<string, { enum?: unknown }>).model?.enum,
391 ).toBeUndefined()
392 expect(
393 (input.properties as Record<string, unknown>).max_tokens,
394 ).toBeUndefined()
395})
396it('ignores all reseller USD rows, including conflicting later rates', () => {
397 const prices = nativePrices(native[ANT_PRICE] ?? '')
398 expect(prices.get('Ling-2.6-1T')?.rates.input_tokens).toBe(4.5 / 1e6)
399 expect(
400 nativePrices((native[ANT_PRICE] ?? '').replace('$0.30', '$999999')).get(
401 'Ling-2.6-1T',
402 ),
403 ).toEqual(prices.get('Ling-2.6-1T'))
404})
405it('fails missing sale amounts, missing price sections and changed field types', () => {
406 const source = native[ANT_PRICE] ?? ''
407 expect(() =>
408 nativePrices(
409 source.replace('<span>¥0.14</span>', '<span>unreadable</span>'),
410 ),
411 ).toThrow('unreadable current CNY price')
412 expect(() =>
413 nativePrices(source.replace('id="model-pricing"', 'id="changed-pricing"')),
414 ).toThrow('missing model-pricing')
415 expect(() =>
416 nativeRequest(
417 (native[ANT_OPENAI] ?? '').replace(
418 '<code>double</code>',
419 '<code>unknown-unit</code>',
420 ),
421 ),
422 ).toThrow('unknown native field type')
423})
424it('fails an empty native catalog instead of silently retiring stored rows', async () => {
425 serve({
426 [ANT_OPENAI]: '<article><h2 id="request-body">Request Body</h2></article>',
427 })
428 await expect(provider.listModels(nativeEnv)).rejects.toThrow('missing native')
429})
430​
431it('refreshes newly published model IDs and changes free rows to paid from source', async () => {
432 serve({
433 [ANT_OPENAI]: (native[ANT_OPENAI] ?? '').replaceAll(
434 'AntAngelMed',
435 'Native-New-ID',
436 ),
437 })
438 const { models } = await provider.listModels(nativeEnv)
439 expect(models.some((m) => m.rawId === 'Native-New-ID')).toBe(true)
440 expect(models.some((m) => m.rawId === 'AntAngelMed')).toBe(false)
441 const quotes = nativePrices(
442 (native[ANT_PRICE] ?? '').replaceAll('¥0.00', '¥1.00'),
443 )
444 expect(quotes.get('Ling-3.1-flash')).toEqual({
445 free: false,
446 rates: {
447 input_tokens: 1 / 1e6,
448 output_tokens: 1 / 1e6,
449 cache_read_tokens: 1 / 1e6,
450 },
451 })
452})
453​
454it('keeps conflicting content shape unknown without fabricating block schemas', () => {
455 const schema = nativeRequest(native[ANT_OPENAI] ?? '')
456 const props = schema.properties as Record<string, Record<string, unknown>>
457 const message = props.messages!.items as Record<string, unknown>
458 const content = (
459 message.properties as Record<string, Record<string, unknown>>
460 ).content!
461 expect(content.type).toBeUndefined()
462 expect(content['x-source-type']).toBeNull()
463 expect(content['x-source-declared-type']).toBe('string')
464 expect(content['x-source-conflicting-statement']).toContain(
465 'the request accepts text, images, and videos',
466 )
467 expect(content.items).toBeUndefined()
468 const result = new Validator(schema).validate({
469 model: 'Ling-3.0-flash-VL',
470 messages: [
471 {
472 role: 'user',
473 content: [
474 {
475 type: 'image_url',
476 image_url: { url: 'data:image/png;base64,example' },
477 },
478 { type: 'text', text: 'Describe' },
479 ],
480 },
481 ],
482 })
483 expect(result.valid).toBe(true)
484})
485it('clears missing native prices and binds only API-documented models', async () => {
486 serve()
487 const models = (await provider.listModels(nativeEnv)).models
488 expect(models).toHaveLength(8)
489 for (const id of ['AntAngelMed', 'Ling-3.0-tiny']) {
490 const m = models.find((candidate) => candidate.rawId === id)
491 expect(m?.pricing).toBeNull()
492 expect(m?.absent?.pricing).toBe('cleared')
493 }
494 const newlyPriced = models.find((m) => m.rawId === 'Ling-3.1-flash')
495 expect(newlyPriced?.pricing).not.toBeNull()
496 expect(newlyPriced?.activity).toBeNull()
497 expect(newlyPriced?.schemaEndpointId).toBeNull()
498 expect(newlyPriced?.requestMap).toBeNull()
499 expect(newlyPriced?.factSources?.schemaEndpointId).toBeUndefined()
500 const published = models.find((m) => m.rawId === 'Ling-3.0-flash-VL')
501 expect(published?.schemaEndpointId).toBe('v1/chat/completions')
502 expect(published?.factSources?.schemaEndpointId).toMatchObject({
503 sourceUrl: ANT_OPENAI,
504 path: 'Request Address + model.Options',
505 })
506 expect(provider.generationEndpointId).toBeUndefined()
507 expect(provider.bindSyncedRoutesOnly).toBe(true)
508})
509​
510function docsKv(initial: Record<string, string> = {}) {
511 const stored = new Map(Object.entries(initial))
512 const writes: Array<string> = []
513 const kv = {
514 get: async (key: string) => stored.get(key) ?? null,
515 put: async (key: string, value: string) => {
516 writes.push(key)
517 stored.set(key, value)
518 },
519 } as unknown as KVNamespace
520 return { kv, stored, writes }
522it('rejects the actual production captcha before caching and retries native docs', async () => {
523 const { kv, writes } = docsKv()
524 serve(
525 Object.fromEntries(
526 Object.keys(native).map((url) => [url, sourceFailure.html]),
527 ),
528 )
529 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
530 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
531 )
532 expect(writes).toEqual([])
533 serve()
534 expect((await provider.listModels(nativeEnv, kv)).models).toHaveLength(8)
535 expect(writes).toHaveLength(5)
536 expect(
537 writes.every((key) => key.includes('#cloudflare-browser-content-v1')),
538 ).toBe(true)
539})
540it('validates cached articles and never serves a cached blocked document', async () => {
541 const writes: Array<string> = []
542 const reads: Array<string> = []
543 const kv = {
544 get: async (key: string) => {
545 reads.push(key)
546 return JSON.stringify({
547 html: sourceFailure.html,
548 hash: 'cached-source-hash',
549 })
550 },
551 put: async (key: string) => {
552 writes.push(key)
553 },
554 } as unknown as KVNamespace
555 serve(
556 Object.fromEntries(
557 Object.keys(native).map((url) => [url, sourceFailure.html]),
558 ),
559 )
560 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
561 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
562 )
563 expect(writes).toEqual([])
564 expect(reads).toHaveLength(1)
565 expect(
566 reads.every((key) => key.endsWith('#cloudflare-browser-content-v1')),
567 ).toBe(true)
568})
569it('reports malformed native HTML with its URL before it can enter the cache', async () => {
570 const { kv, writes } = docsKv()
571 serve(
572 Object.fromEntries(
573 Object.keys(native).map((url) => [
574 url,
575 '<html><body>upstream unavailable</body></html>',
576 ]),
577 ),
578 )
579 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
580 `ant-ling: native source ${ANT_OPENAI}: ant-ling: missing native article`,
581 )
582 expect(writes).toEqual([])
583})
584​
585it('requires the browser binding even if documents are cached', async () => {
586 const { kv, writes } = docsKv()
587 await expect(provider.listModels({}, kv)).rejects.toThrow(
588 `ant-ling: native source ${ANT_OPENAI}: Cloudflare Browser Rendering BROWSER binding is required`,
589 )
590 await expect(provider.fetchSpec({})).rejects.toThrow(
591 'BROWSER binding is required',
592 )
593 expect(writes).toEqual([])
594})
595it.each([
596 [
597 'service failure',
598 () => new Response('unavailable', { status: 503 }),
599 'request failed: HTTP 503',
600 ],
601 [
602 'invalid JSON',
603 () => new Response('<html>bad wrapper</html>'),
604 'native source',
605 ],
606 [
607 'unsuccessful result',
608 () => Response.json({ success: false, errors: [] }),
609 'unreadable',
610 ],
611 [
612 'array result',
613 () =>
614 Response.json({
615 success: true,
616 result: [],
617 meta: { status: 200, finalUrl: ANT_OPENAI },
618 }),
619 'unreadable',
620 ],
621 [
622 'missing meta',
623 () => Response.json({ success: true, result: native[ANT_OPENAI] }),
624 'unreadable',
625 ],
626 [
627 'native HTTP error',
628 () =>
629 Response.json({
630 success: true,
631 result: native[ANT_OPENAI],
632 meta: { status: 403, finalUrl: ANT_OPENAI },
633 }),
634 'native page failed',
635 ],
636 [
637 'unreadable native status',
638 () =>
639 Response.json({
640 success: true,
641 result: native[ANT_OPENAI],
642 meta: { status: '200', finalUrl: ANT_OPENAI },
643 }),
644 'native page failed',
645 ],
646 [
647 'wrong native host',
648 () =>
649 Response.json({
650 success: true,
651 result: native[ANT_OPENAI],
652 meta: {
653 status: 200,
654 finalUrl: 'https://other.example/en/docs/api-reference/openai/',
655 },
656 }),
657 'URL mismatch',
658 ],
659 [
660 'wrong native page',
661 () =>
662 Response.json({
663 success: true,
664 result: native[ANT_OPENAI],
665 meta: { status: 200, finalUrl: ANT_PRICE },
666 }),
667 'URL mismatch',
668 ],
669 [
670 'missing final URL',
671 () =>
672 Response.json({
673 success: true,
674 result: native[ANT_OPENAI],
675 meta: { status: 200 },
676 }),
677 'URL mismatch',
678 ],
679] as const)(
680 'rejects browser %s without direct-fetch recovery or caching',
681 async (_name, response, error) => {
682 let directFetches = 0
683 globalThis.fetch = async () => {
684 directFetches++
685 throw new Error('direct fetch must not recover browser errors')
686 }
687 const browser = { quickAction: async () => response() } as unknown as Pick<
688 BrowserRun,
689 'quickAction'
690 >
691 const { kv, writes } = docsKv()
692 await expect(provider.listModels({ BROWSER: browser }, kv)).rejects.toThrow(
693 error,
694 )
695 expect(writes).toEqual([])
696 expect(directFetches).toBe(0)
697 },
699it('hashes the rendered native HTML and bounds browser source reads sequentially', async () => {
700 const urls = serve()
701 let active = 0
702 let peak = 0
703 const browser = nativeEnv.BROWSER!
704 const originalAction = browser.quickAction.bind(browser)
705 browser.quickAction = (async (action: string, options: { url?: string }) => {
706 active++
707 peak = Math.max(peak, active)
708 try {
709 await Promise.resolve()
710 return await originalAction(
711 action as 'content',
712 options as BrowserRunContentOptions,
713 )
714 } finally {
715 active--
716 }
717 }) as typeof browser.quickAction
718 const { models } = await provider.listModels(nativeEnv)
719 expect(models).toHaveLength(8)
720 expect(urls).toHaveLength(5)
721 expect(peak).toBe(1)
722 const spec = await provider.fetchSpec(nativeEnv)
723 expect(spec.sources).toEqual([
724 { url: ANT_OPENAI, hash: await sha256Text(native[ANT_OPENAI]!) },
725 ])
726})