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

image.test.ts

889 lines28.3 KB

1import { describe, expect, it, vi } from 'vitest'
2import { generateImage } from '@tanstack/ai'
3import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
4import {
5 BytePlusImageAdapter,
6 byteplusImage,
7 createBytePlusImage,
8} from '../src/adapters/image'
9import { parseBytePlusImageSize } from '../src/image/image-provider-options'
10import type { BytePlusSeedream5ImageProviderOptions } from '../src/image/image-provider-options'
11import type { BytePlusImageGenerationRequest } from '../src/image/wire-types'
12import type {
13 ImagePart,
14 MediaInputMetadata,
15 MediaPromptPart,
16} from '@tanstack/ai'
17​
18const testLogger = resolveDebugOption(false)
19​
20const IMAGE_URL =
21 'https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedream/x.png'
22​
23/** Live-verified `seedream-4-0-250828` response body (2026-07-31). */
24const successBody = {
25 model: 'seedream-4-0-250828',
26 created: 1_754_000_000,
27 data: [{ url: IMAGE_URL, size: '1152x864' }],
28 usage: { generated_images: 1, output_tokens: 3888, total_tokens: 3888 },
30​
31function jsonResponse(body: unknown, status = 200): Response {
32 return new Response(JSON.stringify(body), {
33 status,
34 headers: { 'Content-Type': 'application/json' },
35 })
37​
38/**
39 * A `vi.fn` fetch stub with the real fetch parameter list, so call assertions
40 * (`mock.calls[0]`) stay typed as `[input, init?]`.
41 */
42function mockFetch(handler: () => Response) {
43 return vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
44 handler(),
45 )
47​
48/** Reads the JSON body the adapter sent on its first (only) request. */
49function sentRequest(
50 fetchMock: ReturnType<typeof mockFetch>,
51): BytePlusImageGenerationRequest {
52 const init = fetchMock.mock.calls[0]?.[1]
53 return JSON.parse(String(init?.body))
55​
56function adapterWithFetch(
57 fetchMock: ReturnType<typeof mockFetch>,
58 model:
59 | 'seedream-4-0-250828'
60 | 'seedream-5-0-lite-260128'
61 | 'dola-seedream-5-0-pro-260628' = 'seedream-4-0-250828',
62) {
63 return createBytePlusImage(model, 'ark-test-key', { fetch: fetchMock })
65​
66function imagePart(value: string): ImagePart<MediaInputMetadata> {
67 return { type: 'image', source: { type: 'url', value } }
69​
70/**
71 * A logger whose every level is captured. `resolveDebugOption` with a partial
72 * config turns all categories on, so `logger.errors()` and `logger.warn()`
73 * both reach the spy (the shared `testLogger` uses `false`, which silences
74 * everything including errors).
75 */
76function capturingLogger() {
77 const spy = {
78 debug: vi.fn(),
79 info: vi.fn(),
80 warn: vi.fn(),
81 error: vi.fn(),
82 }
83 return { spy, logger: resolveDebugOption({ logger: spy }) }
85​
86/** Joins every message a spy level received, for substring assertions. */
87function messages(level: ReturnType<typeof vi.fn>): string {
88 return level.mock.calls.map((call) => String(call[0])).join('\n')
90​
91describe('factories', () => {
92 it('creates an adapter with the provided API key', () => {
93 const adapter = createBytePlusImage('seedream-4-0-250828', 'ark-test-key')
94 expect(adapter).toBeInstanceOf(BytePlusImageAdapter)
95 expect(adapter.kind).toBe('image')
96 expect(adapter.name).toBe('byteplus')
97 expect(adapter.model).toBe('seedream-4-0-250828')
98 })
99​
100 it('byteplusImage reads ARK_API_KEY from the environment', () => {
101 vi.stubEnv('ARK_API_KEY', 'env-key')
102 try {
103 expect(byteplusImage('seedream-5-0-260128')).toBeInstanceOf(
104 BytePlusImageAdapter,
105 )
106 } finally {
107 vi.unstubAllEnvs()
108 }
109 })
110​
111 it('byteplusImage names ARK_API_KEY when it is missing', () => {
112 vi.stubEnv('ARK_API_KEY', '')
113 try {
114 expect(() => byteplusImage('seedream-5-0-260128')).toThrow(/ARK_API_KEY/)
115 } finally {
116 vi.unstubAllEnvs()
117 }
118 })
119})
120​
121describe('request shape', () => {
122 it('posts to the Ark images endpoint with a bearer token', async () => {
123 const fetchMock = mockFetch(() => jsonResponse(successBody))
124 await adapterWithFetch(fetchMock).generateImages({
125 model: 'seedream-4-0-250828',
126 prompt: 'a guitar in a sunlit workshop',
127 logger: testLogger,
128 })
129​
130 const [url, init] = fetchMock.mock.calls[0] ?? []
131 expect(url).toBe(
132 'https://ark.ap-southeast.bytepluses.com/api/v3/images/generations',
133 )
134 expect(init?.method).toBe('POST')
135 expect(init?.headers).toMatchObject({
136 Authorization: 'Bearer ark-test-key',
137 'Content-Type': 'application/json',
138 })
139 expect(sentRequest(fetchMock)).toEqual({
140 model: 'seedream-4-0-250828',
141 prompt: 'a guitar in a sunlit workshop',
142 })
143 })
144​
145 it('honours a custom base URL and merges configured default headers', async () => {
146 const fetchMock = mockFetch(() => jsonResponse(successBody))
147 const adapter = createBytePlusImage('seedream-4-0-250828', 'ark-test-key', {
148 // The trailing slash must not survive into the request path.
149 baseURL: 'https://ark.eu-west.bytepluses.com/api/v3/',
150 defaultHeaders: { 'X-Test-Id': 'abc', 'X-Dropped': null },
151 fetch: fetchMock,
152 })
153 await adapter.generateImages({
154 model: 'seedream-4-0-250828',
155 prompt: 'a guitar',
156 logger: testLogger,
157 })
158​
159 const [url, init] = fetchMock.mock.calls[0] ?? []
160 expect(url).toBe(
161 'https://ark.eu-west.bytepluses.com/api/v3/images/generations',
162 )
163 expect(init?.headers).toMatchObject({
164 Authorization: 'Bearer ark-test-key',
165 'X-Test-Id': 'abc',
166 })
167 // Null-valued entries are dropped rather than serialized as "null".
168 expect(init?.headers).not.toHaveProperty('X-Dropped')
169 })
170​
171 it('sends a size token unchanged and normalizes its case', async () => {
172 const fetchMock = mockFetch(() => jsonResponse(successBody))
173 await adapterWithFetch(fetchMock).generateImages({
174 model: 'seedream-4-0-250828',
175 prompt: 'a guitar',
176 // Lowercase tokens are normalized at runtime for JS callers; the type
177 // only advertises the canonical uppercase form.
178 size: '2k' as '2K',
179 logger: testLogger,
180 })
181 expect(sentRequest(fetchMock).size).toBe('2K')
182 })
183​
184 it('sends explicit pixel sizes', async () => {
185 const fetchMock = mockFetch(() => jsonResponse(successBody))
186 await adapterWithFetch(fetchMock).generateImages({
187 model: 'seedream-4-0-250828',
188 prompt: 'a guitar',
189 size: '2048x2048',
190 logger: testLogger,
191 })
192 expect(sentRequest(fetchMock).size).toBe('2048x2048')
193 })
194​
195 it('rejects a size that mixes the token and pixel forms', async () => {
196 const fetchMock = mockFetch(() => jsonResponse(successBody))
197 await expect(
198 adapterWithFetch(fetchMock).generateImages({
199 model: 'seedream-4-0-250828',
200 prompt: 'a guitar',
201 // Invalid at runtime and at compile time; the cast keeps the
202 // runtime-validation path reachable from the test.
203 size: '2K x 1024' as '2K',
204 logger: testLogger,
205 }),
206 ).rejects.toThrow(/never a mix of the two/)
207 expect(fetchMock).not.toHaveBeenCalled()
208 })
209​
210 it('maps prompt image parts to the image reference array', async () => {
211 const fetchMock = mockFetch(() => jsonResponse(successBody))
212 await adapterWithFetch(fetchMock).generateImages({
213 model: 'seedream-4-0-250828',
214 prompt: [
215 { type: 'text', content: 'put the guitar on a beach' },
216 imagePart('https://example.com/guitar.png'),
217 {
218 type: 'image',
219 source: { type: 'data', value: 'AAAA', mimeType: 'image/PNG' },
220 },
221 ],
222 logger: testLogger,
223 })
224​
225 const request = sentRequest(fetchMock)
226 expect(request.image).toEqual([
227 'https://example.com/guitar.png',
228 // BytePlus requires a lowercase format in the data URI.
229 'data:image/png;base64,AAAA',
230 ])
231 expect(request.prompt).toBe('put the guitar on a beach')
232 })
233​
234 it('enforces the per-model reference-image limit', async () => {
235 const fetchMock = mockFetch(() => jsonResponse(successBody))
236 const prompt: Array<MediaPromptPart> = [
237 { type: 'text', content: 'blend these' },
238 ...Array.from({ length: 11 }, (_, index) =>
239 imagePart(`https://example.com/${index}.png`),
240 ),
241 ]
242​
243 // 5.0 Pro caps references at 10; the other models accept 14.
244 await expect(
245 adapterWithFetch(
246 fetchMock,
247 'dola-seedream-5-0-pro-260628',
248 ).generateImages({
249 model: 'dola-seedream-5-0-pro-260628',
250 prompt,
251 logger: testLogger,
252 }),
253 ).rejects.toThrow(/at most 10 reference images; received 11/)
254​
255 await expect(
256 adapterWithFetch(fetchMock).generateImages({
257 model: 'seedream-4-0-250828',
258 prompt,
259 logger: testLogger,
260 }),
261 ).resolves.toMatchObject({ model: 'seedream-4-0-250828' })
262 })
263​
264 it('passes a data-URI image source through untouched', async () => {
265 const fetchMock = mockFetch(() => jsonResponse(successBody))
266 await adapterWithFetch(fetchMock).generateImages({
267 model: 'seedream-4-0-250828',
268 prompt: [
269 { type: 'text', content: 'restyle this' },
270 {
271 type: 'image',
272 source: {
273 type: 'data',
274 value: 'data:image/jpeg;base64,QUJD',
275 mimeType: 'image/jpeg',
276 },
277 },
278 ],
279 logger: testLogger,
280 })
281​
282 // Already a data URI: it must not be wrapped in a second `data:` prefix.
283 expect(sentRequest(fetchMock).image).toEqual([
284 'data:image/jpeg;base64,QUJD',
285 ])
286 })
287​
288 it('rejects roles outside the reference allow-list', async () => {
289 const fetchMock = mockFetch(() => jsonResponse(successBody))
290 await expect(
291 adapterWithFetch(fetchMock).generateImages({
292 model: 'seedream-4-0-250828',
293 prompt: [
294 { type: 'text', content: 'inpaint this' },
295 {
296 type: 'image',
297 source: { type: 'url', value: 'https://example.com/mask.png' },
298 metadata: { role: 'mask' },
299 },
300 ],
301 logger: testLogger,
302 }),
303 ).rejects.toThrow(/no mask input/)
304​
305 // Video-oriented roles must fail loudly rather than be flattened into a
306 // plain reference — that is the point of the allow-list.
307 await expect(
308 adapterWithFetch(fetchMock).generateImages({
309 model: 'seedream-4-0-250828',
310 prompt: [
311 { type: 'text', content: 'start from this' },
312 {
313 type: 'image',
314 source: { type: 'url', value: 'https://example.com/frame.png' },
315 metadata: { role: 'start_frame' },
316 },
317 ],
318 logger: testLogger,
319 }),
320 ).rejects.toThrow(/no start_frame input/)
321​
322 expect(fetchMock).not.toHaveBeenCalled()
323 })
324​
325 it('accepts the reference and character roles', async () => {
326 const fetchMock = mockFetch(() => jsonResponse(successBody))
327 await adapterWithFetch(fetchMock).generateImages({
328 model: 'seedream-4-0-250828',
329 prompt: [
330 { type: 'text', content: 'put @Image1 next to @Image2' },
331 {
332 type: 'image',
333 source: { type: 'url', value: 'https://example.com/a.png' },
334 metadata: { role: 'reference' },
335 },
336 {
337 type: 'image',
338 source: { type: 'url', value: 'https://example.com/b.png' },
339 metadata: { role: 'character' },
340 },
341 ],
342 logger: testLogger,
343 })
344​
345 expect(sentRequest(fetchMock).image).toEqual([
346 'https://example.com/a.png',
347 'https://example.com/b.png',
348 ])
349 })
350​
351 it('rejects video and audio prompt parts', async () => {
352 const fetchMock = mockFetch(() => jsonResponse(successBody))
353 await expect(
354 adapterWithFetch(fetchMock).generateImages({
355 model: 'seedream-4-0-250828',
356 prompt: [
357 { type: 'text', content: 'a still from this' },
358 {
359 type: 'video',
360 source: { type: 'url', value: 'https://example.com/clip.mp4' },
361 },
362 ],
363 logger: testLogger,
364 }),
365 ).rejects.toThrow(/does not support video \/ audio prompt parts/)
366 })
367​
368 it('requires prompt text even when editing', async () => {
369 const fetchMock = mockFetch(() => jsonResponse(successBody))
370 await expect(
371 adapterWithFetch(fetchMock).generateImages({
372 model: 'seedream-4-0-250828',
373 prompt: [imagePart('https://example.com/guitar.png')],
374 logger: testLogger,
375 }),
376 ).rejects.toThrow(/requires prompt text/)
377 })
378​
379 it('rejects a prompt longer than 600 words', async () => {
380 const fetchMock = mockFetch(() => jsonResponse(successBody))
381 await expect(
382 adapterWithFetch(fetchMock).generateImages({
383 model: 'seedream-4-0-250828',
384 prompt: Array.from({ length: 601 }, () => 'guitar').join(' '),
385 logger: testLogger,
386 }),
387 ).rejects.toThrow(/601 words/)
388 })
389​
390 it('passes watermark and output_format straight through', async () => {
391 const fetchMock = mockFetch(() => jsonResponse(successBody))
392 await adapterWithFetch(
393 fetchMock,
394 'seedream-5-0-lite-260128',
395 ).generateImages({
396 model: 'seedream-5-0-lite-260128',
397 prompt: 'a guitar',
398 modelOptions: {
399 watermark: false,
400 output_format: 'png',
401 response_format: 'b64_json',
402 },
403 logger: testLogger,
404 })
405​
406 expect(sentRequest(fetchMock)).toMatchObject({
407 watermark: false,
408 output_format: 'png',
409 response_format: 'b64_json',
410 })
411 })
412​
413 it('sends output_format on a 4.x model rather than rejecting it locally', async () => {
414 const fetchMock = mockFetch(() => jsonResponse(successBody))
415 // Seedream 4.x is documented as not reading output_format, so it is absent
416 // from that model's provider-options type. A caller who reuses a 5.0
417 // options object still gets the value sent — Ark decides, not us. Same
418 // policy as sequential_image_generation.
419 const fiveOhOptions: BytePlusSeedream5ImageProviderOptions = {
420 output_format: 'png',
421 }
422 await adapterWithFetch(fetchMock).generateImages({
423 model: 'seedream-4-0-250828',
424 prompt: 'a guitar',
425 modelOptions: fiveOhOptions,
426 logger: testLogger,
427 })
428​
429 expect(sentRequest(fetchMock).output_format).toBe('png')
430 })
431})
432​
433describe('numberOfImages', () => {
434 it('sends no group-image fields for a single image', async () => {
435 const fetchMock = mockFetch(() => jsonResponse(successBody))
436 await adapterWithFetch(fetchMock).generateImages({
437 model: 'seedream-4-0-250828',
438 prompt: 'a guitar',
439 numberOfImages: 1,
440 logger: testLogger,
441 })
442​
443 const request = sentRequest(fetchMock)
444 expect(request.sequential_image_generation).toBeUndefined()
445 expect(request.sequential_image_generation_options).toBeUndefined()
446 })
447​
448 it('maps more than one image onto group-image mode', async () => {
449 const fetchMock = mockFetch(() => jsonResponse(successBody))
450 await adapterWithFetch(fetchMock).generateImages({
451 model: 'seedream-4-0-250828',
452 prompt: 'four seasons of one courtyard',
453 numberOfImages: 4,
454 logger: testLogger,
455 })
456​
457 expect(sentRequest(fetchMock)).toMatchObject({
458 sequential_image_generation: 'auto',
459 sequential_image_generation_options: { max_images: 4 },
460 })
461 })
462​
463 it('lets explicit provider options override the derived mode', async () => {
464 const fetchMock = mockFetch(() => jsonResponse(successBody))
465 await adapterWithFetch(fetchMock).generateImages({
466 model: 'seedream-4-0-250828',
467 prompt: 'a guitar',
468 numberOfImages: 4,
469 modelOptions: { sequential_image_generation: 'disabled' },
470 logger: testLogger,
471 })
472 expect(sentRequest(fetchMock).sequential_image_generation).toBe('disabled')
473 })
474​
475 it('rejects counts outside the group-image range', async () => {
476 const fetchMock = mockFetch(() => jsonResponse(successBody))
477 await expect(
478 adapterWithFetch(fetchMock).generateImages({
479 model: 'seedream-4-0-250828',
480 prompt: 'a guitar',
481 numberOfImages: 16,
482 logger: testLogger,
483 }),
484 ).rejects.toThrow(/between 1 and 15/)
485 })
486})
487​
488describe('response mapping', () => {
489 it('maps url results and per-image usage', async () => {
490 const fetchMock = mockFetch(() => jsonResponse(successBody))
491 const result = await adapterWithFetch(fetchMock).generateImages({
492 model: 'seedream-4-0-250828',
493 prompt: 'a guitar',
494 logger: testLogger,
495 })
496​
497 expect(result.model).toBe('seedream-4-0-250828')
498 expect(result.id).toMatch(/^byteplus-/)
499 expect(result.images).toEqual([{ url: IMAGE_URL }])
500 expect(result.usage).toEqual({
501 promptTokens: 0,
502 completionTokens: 3888,
503 totalTokens: 3888,
504 unitsBilled: 1,
505 })
506 })
507​
508 it('maps b64_json results', async () => {
509 const fetchMock = mockFetch(() =>
510 jsonResponse({
511 model: 'seedream-4-0-250828',
512 data: [{ b64_json: 'QUJD', size: '1024x1024' }],
513 }),
514 )
515 const result = await adapterWithFetch(fetchMock).generateImages({
516 model: 'seedream-4-0-250828',
517 prompt: 'a guitar',
518 modelOptions: { response_format: 'b64_json' },
519 logger: testLogger,
520 })
521​
522 expect(result.images).toEqual([{ b64Json: 'QUJD' }])
523 expect(result.usage).toBeUndefined()
524 })
525​
526 it('maps every image of a group-image response', async () => {
527 const fetchMock = mockFetch(() =>
528 jsonResponse({
529 model: 'seedream-4-0-250828',
530 data: [{ url: 'https://example.com/1.png' }, { b64_json: 'QUJD' }],
531 usage: { generated_images: 2, output_tokens: 100, total_tokens: 100 },
532 }),
533 )
534 const result = await adapterWithFetch(fetchMock).generateImages({
535 model: 'seedream-4-0-250828',
536 prompt: 'a guitar',
537 numberOfImages: 2,
538 logger: testLogger,
539 })
540​
541 expect(result.images).toEqual([
542 { url: 'https://example.com/1.png' },
543 { b64Json: 'QUJD' },
544 ])
545 expect(result.usage?.unitsBilled).toBe(2)
546 })
547​
548 it('keeps the successes when part of a group fails, and reports the rest', async () => {
549 const { spy, logger } = capturingLogger()
550 const fetchMock = mockFetch(() =>
551 jsonResponse({
552 model: 'seedream-4-0-250828',
553 data: [
554 { url: 'https://example.com/1.png', size: '1024x1024' },
555 {
556 error: {
557 code: 'OutputImageSensitiveContentDetected',
558 message: 'The output image may contain sensitive information.',
559 },
560 },
561 { error: { code: 'InternalServiceError', message: 'try again' } },
562 ],
563 usage: { generated_images: 1, output_tokens: 1000, total_tokens: 1000 },
564 }),
565 )
566​
567 const result = await adapterWithFetch(fetchMock).generateImages({
568 model: 'seedream-4-0-250828',
569 prompt: 'four seasons of one courtyard',
570 numberOfImages: 4,
571 logger,
572 })
573​
574 // The one good image survives rather than the whole call failing.
575 expect(result.images).toEqual([{ url: 'https://example.com/1.png' }])
576​
577 // The two failures are reported with their provider codes.
578 const errorLog = messages(spy.error)
579 expect(errorLog).toContain('dropped 2 failed image(s)')
580 expect(errorLog).toContain('OutputImageSensitiveContentDetected')
581 expect(errorLog).toContain('InternalServiceError')
582​
583 // And the shortfall against numberOfImages is surfaced separately.
584 expect(messages(spy.warn)).toContain('requested 4 images, received 1')
585 })
586​
587 it('warns when the model returns fewer images than requested', async () => {
588 const { spy, logger } = capturingLogger()
589 const fetchMock = mockFetch(() =>
590 jsonResponse({
591 model: 'seedream-4-0-250828',
592 data: [{ url: 'https://example.com/1.png' }],
593 usage: { generated_images: 1, output_tokens: 10, total_tokens: 10 },
594 }),
595 )
596​
597 await adapterWithFetch(fetchMock).generateImages({
598 model: 'seedream-4-0-250828',
599 prompt: 'a guitar',
600 numberOfImages: 3,
601 logger,
602 })
603​
604 // No per-image failure here — just a model that decided one was enough.
605 expect(spy.error).not.toHaveBeenCalled()
606 expect(messages(spy.warn)).toContain('requested 3 images, received 1')
607 })
608​
609 it('does not warn when the count is met', async () => {
610 const { spy, logger } = capturingLogger()
611 const fetchMock = mockFetch(() => jsonResponse(successBody))
612 await adapterWithFetch(fetchMock).generateImages({
613 model: 'seedream-4-0-250828',
614 prompt: 'a guitar',
615 numberOfImages: 1,
616 logger,
617 })
618 expect(spy.warn).not.toHaveBeenCalled()
619 })
620​
621 it('surfaces per-image codes when every image fails', async () => {
622 const fetchMock = mockFetch(() =>
623 jsonResponse({
624 model: 'seedream-4-0-250828',
625 data: [
626 { error: { code: 'OutputImageSensitiveContentDetected' } },
627 { error: { code: 'InternalServiceError', message: 'try again' } },
628 ],
629 }),
630 )
631 await expect(
632 adapterWithFetch(fetchMock).generateImages({
633 model: 'seedream-4-0-250828',
634 prompt: 'a guitar',
635 numberOfImages: 2,
636 logger: testLogger,
637 }),
638 ).rejects.toThrow(
639 /returned no images: OutputImageSensitiveContentDetected; InternalServiceError: try again/,
640 )
641 })
642​
643 // Ark's OpenAPI document describes a second, nested `data[]` item form, so
644 // an item matching none of b64_json / url / error is a live possibility. It
645 // used to be dropped without even being counted, which turned provider drift
646 // into a bare "returned no images" with nothing to act on.
647 it('reports unrecognized data items rather than dropping them', async () => {
648 const { spy, logger } = capturingLogger()
649 const fetchMock = mockFetch(() =>
650 jsonResponse({
651 model: 'seedream-4-0-250828',
652 data: [{ imagecontent: [{ image_url: 'https://example.com/1.png' }] }],
653 }),
654 )
655​
656 await expect(
657 adapterWithFetch(fetchMock).generateImages({
658 model: 'seedream-4-0-250828',
659 prompt: 'a guitar',
660 logger,
661 }),
662 ).rejects.toThrow(/1 unrecognized response item/)
663 expect(messages(spy.error)).toContain(
664 'matched none of b64_json / url / error',
665 )
666 })
667​
668 it('carries the raw body into the unrecognized-item error', async () => {
669 const fetchMock = mockFetch(() =>
670 jsonResponse({
671 model: 'seedream-4-0-250828',
672 data: [{ imagecontent: [{ image_url: 'https://example.com/1.png' }] }],
673 }),
674 )
675​
676 await expect(
677 adapterWithFetch(fetchMock).generateImages({
678 model: 'seedream-4-0-250828',
679 prompt: 'a guitar',
680 logger: testLogger,
681 }),
682 ).rejects.toThrow(/imagecontent/)
683 })
684​
685 // `readJsonBody` returns the raw text for a non-JSON body — an HTML error
686 // page from a proxy in front of the API, served with a 200.
687 it.each([
688 ['an empty body', new Response('', { status: 200 })],
689 [
690 'an HTML page',
691 new Response('<html>502 Bad Gateway</html>', {
692 status: 200,
693 headers: { 'Content-Type': 'text/html' },
694 }),
695 ],
696 ])('throws with the body in hand for %s', async (_label, response) => {
697 await expect(
698 adapterWithFetch(mockFetch(() => response)).generateImages({
699 model: 'seedream-4-0-250828',
700 prompt: 'a guitar',
701 logger: testLogger,
702 }),
703 ).rejects.toThrow(/non-object body/)
704 })
705​
706 // A partial group failure returns successfully with a short array. The
707 // `numberOfImages` warning only fires when the count was set explicitly, so
708 // without this one a caller who omitted it gets no signal at all.
709 it('warns on a partial failure even when numberOfImages is unset', async () => {
710 const { spy, logger } = capturingLogger()
711 const fetchMock = mockFetch(() =>
712 jsonResponse({
713 model: 'seedream-4-0-250828',
714 data: [
715 { url: 'https://example.com/1.png' },
716 { error: { code: 'InternalServiceError', message: 'try again' } },
717 ],
718 usage: { generated_images: 1, output_tokens: 10, total_tokens: 10 },
719 }),
720 )
721​
722 const result = await adapterWithFetch(fetchMock).generateImages({
723 model: 'seedream-4-0-250828',
724 prompt: 'a guitar',
725 logger,
726 })
727​
728 expect(result.images).toHaveLength(1)
729 expect(messages(spy.warn)).toContain('1 of 2 images failed to generate')
730 })
731​
732 it('throws with the response error when no image comes back', async () => {
733 const fetchMock = mockFetch(() =>
734 jsonResponse({
735 model: 'seedream-4-0-250828',
736 data: [],
737 error: {
738 code: 'OutputImageSensitiveContentDetected',
739 message:
740 'The request failed because the output image may contain sensitive information.',
741 },
742 }),
743 )
744 await expect(
745 adapterWithFetch(fetchMock).generateImages({
746 model: 'seedream-4-0-250828',
747 prompt: 'a guitar',
748 logger: testLogger,
749 }),
750 ).rejects.toThrow(
751 /returned no images: OutputImageSensitiveContentDetected: The request failed/,
752 )
753 })
754})
755​
756describe('error handling', () => {
757 it('surfaces the Ark error envelope', async () => {
758 const fetchMock = mockFetch(() =>
759 jsonResponse(
760 {
761 error: {
762 code: 'InputTextSensitiveContentDetected',
763 message:
764 'The request failed because the input text may contain sensitive information.',
765 },
766 },
767 400,
768 ),
769 )
770 await expect(
771 adapterWithFetch(fetchMock).generateImages({
772 model: 'seedream-4-0-250828',
773 prompt: 'a guitar',
774 logger: testLogger,
775 }),
776 ).rejects.toThrow(
777 /BytePlus Ark image generation failed \(400 InputTextSensitiveContentDetected\)/,
778 )
779 })
780​
781 it('logs the failure through logger.errors before rethrowing', async () => {
782 const { spy, logger } = capturingLogger()
783 const fetchMock = mockFetch(() =>
784 jsonResponse(
785 { error: { code: 'QuotaExceeded', message: 'slow down' } },
786 429,
787 ),
788 )
789​
790 await expect(
791 adapterWithFetch(fetchMock).generateImages({
792 model: 'seedream-4-0-250828',
793 prompt: 'a guitar',
794 logger,
795 }),
796 ).rejects.toThrow(/QuotaExceeded/)
797​
798 expect(messages(spy.error)).toContain('byteplus.generateImages fatal')
799 const meta = spy.error.mock.calls[0]?.[1]
800 expect(meta).toMatchObject({ source: 'byteplus.generateImages' })
801 })
802​
803 it('falls back to the raw body for a non-JSON failure', async () => {
804 const fetchMock = mockFetch(
805 () =>
806 new Response('<html>Bad Gateway</html>', {
807 status: 502,
808 headers: { 'Content-Type': 'text/html' },
809 }),
810 )
811 await expect(
812 adapterWithFetch(fetchMock).generateImages({
813 model: 'seedream-4-0-250828',
814 prompt: 'a guitar',
815 logger: testLogger,
816 }),
817 ).rejects.toThrow(/failed \(502\): <html>Bad Gateway<\/html>/)
818 })
819})
820​
821describe('core generateImage() integration', () => {
822 it('drives the adapter through the core entry point', async () => {
823 const fetchMock = mockFetch(() => jsonResponse(successBody))
824 const result = await generateImage({
825 adapter: adapterWithFetch(fetchMock),
826 // Reference images are part of the prompt at the call site: the
827 // adapter's modality map has to admit image parts for this to compile.
828 prompt: [
829 { type: 'text', content: 'put this guitar on a beach' },
830 imagePart('https://example.com/guitar.png'),
831 ],
832 size: '2K',
833 modelOptions: { watermark: false },
834 debug: false,
835 })
836​
837 expect(result.images).toEqual([{ url: IMAGE_URL }])
838 expect(sentRequest(fetchMock)).toMatchObject({
839 model: 'seedream-4-0-250828',
840 size: '2K',
841 watermark: false,
842 image: ['https://example.com/guitar.png'],
843 })
844 })
845})
846​
847describe('parseBytePlusImageSize', () => {
848 it('accepts the documented forms', () => {
849 expect(parseBytePlusImageSize('1K')).toEqual({ kind: 'token', value: '1K' })
850 expect(parseBytePlusImageSize('4k')).toEqual({ kind: 'token', value: '4K' })
851 expect(parseBytePlusImageSize('2048x2048')).toEqual({
852 kind: 'pixels',
853 width: 2048,
854 height: 2048,
855 })
856 })
857​
858 it('rejects everything else', () => {
859 for (const invalid of [
860 '3K',
861 '2K_1024',
862 '1024',
863 '1024x',
864 '0x1024',
865 '',
866 // Internal whitespace is not a documented form.
867 '2048 x 2048',
868 '2048x 2048',
869 // The docs render the separator as U+00D7, which the API rejects.
870 '2048×2048',
871 // Mixing the two forms.
872 '2K x 1024',
873 ]) {
874 expect(parseBytePlusImageSize(invalid)).toBeUndefined()
875 }
876 })
877​
878 it('still trims surrounding whitespace', () => {
879 expect(parseBytePlusImageSize(' 2K ')).toEqual({
880 kind: 'token',
881 value: '2K',
882 })
883 expect(parseBytePlusImageSize(' 2048x2048 ')).toEqual({
884 kind: 'pixels',
885 width: 2048,
886 height: 2048,
887 })
888 })
889})