Open History to see the last commit
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 },
29}
30
31function jsonResponse(body: unknown, status = 200): Response {
32 return new Response(JSON.stringify(body), {
33 status,
34 headers: { 'Content-Type': 'application/json' },
35 })
36}
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 )
46}
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))
54}
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 })
64}
65
66function imagePart(value: string): ImagePart<MediaInputMetadata> {
67 return { type: 'image', source: { type: 'url', value } }
68}
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 }) }
84}
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')
89}
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 billed: { quantity: 1, unit: 'images' },
505 unitsBilled: 1,
506 })
507 })
508
509 it('maps b64_json results', async () => {
510 const fetchMock = mockFetch(() =>
511 jsonResponse({
512 model: 'seedream-4-0-250828',
513 data: [{ b64_json: 'QUJD', size: '1024x1024' }],
514 }),
515 )
516 const result = await adapterWithFetch(fetchMock).generateImages({
517 model: 'seedream-4-0-250828',
518 prompt: 'a guitar',
519 modelOptions: { response_format: 'b64_json' },
520 logger: testLogger,
521 })
522
523 expect(result.images).toEqual([{ b64Json: 'QUJD' }])
524 expect(result.usage).toBeUndefined()
525 })
526
527 it('maps every image of a group-image response', async () => {
528 const fetchMock = mockFetch(() =>
529 jsonResponse({
530 model: 'seedream-4-0-250828',
531 data: [{ url: 'https://example.com/1.png' }, { b64_json: 'QUJD' }],
532 usage: { generated_images: 2, output_tokens: 100, total_tokens: 100 },
533 }),
534 )
535 const result = await adapterWithFetch(fetchMock).generateImages({
536 model: 'seedream-4-0-250828',
537 prompt: 'a guitar',
538 numberOfImages: 2,
539 logger: testLogger,
540 })
541
542 expect(result.images).toEqual([
543 { url: 'https://example.com/1.png' },
544 { b64Json: 'QUJD' },
545 ])
546 expect(result.usage?.unitsBilled).toBe(2)
547 expect(result.usage?.billed).toEqual({ quantity: 2, unit: 'images' })
548 })
549
550 it('keeps the successes when part of a group fails, and reports the rest', async () => {
551 const { spy, logger } = capturingLogger()
552 const fetchMock = mockFetch(() =>
553 jsonResponse({
554 model: 'seedream-4-0-250828',
555 data: [
556 { url: 'https://example.com/1.png', size: '1024x1024' },
557 {
558 error: {
559 code: 'OutputImageSensitiveContentDetected',
560 message: 'The output image may contain sensitive information.',
561 },
562 },
563 { error: { code: 'InternalServiceError', message: 'try again' } },
564 ],
565 usage: { generated_images: 1, output_tokens: 1000, total_tokens: 1000 },
566 }),
567 )
568
569 const result = await adapterWithFetch(fetchMock).generateImages({
570 model: 'seedream-4-0-250828',
571 prompt: 'four seasons of one courtyard',
572 numberOfImages: 4,
573 logger,
574 })
575
576 // The one good image survives rather than the whole call failing.
577 expect(result.images).toEqual([{ url: 'https://example.com/1.png' }])
578
579 // The two failures are reported with their provider codes.
580 const errorLog = messages(spy.error)
581 expect(errorLog).toContain('dropped 2 failed image(s)')
582 expect(errorLog).toContain('OutputImageSensitiveContentDetected')
583 expect(errorLog).toContain('InternalServiceError')
584
585 // And the shortfall against numberOfImages is surfaced separately.
586 expect(messages(spy.warn)).toContain('requested 4 images, received 1')
587 })
588
589 it('warns when the model returns fewer images than requested', async () => {
590 const { spy, logger } = capturingLogger()
591 const fetchMock = mockFetch(() =>
592 jsonResponse({
593 model: 'seedream-4-0-250828',
594 data: [{ url: 'https://example.com/1.png' }],
595 usage: { generated_images: 1, output_tokens: 10, total_tokens: 10 },
596 }),
597 )
598
599 await adapterWithFetch(fetchMock).generateImages({
600 model: 'seedream-4-0-250828',
601 prompt: 'a guitar',
602 numberOfImages: 3,
603 logger,
604 })
605
606 // No per-image failure here — just a model that decided one was enough.
607 expect(spy.error).not.toHaveBeenCalled()
608 expect(messages(spy.warn)).toContain('requested 3 images, received 1')
609 })
610
611 it('does not warn when the count is met', async () => {
612 const { spy, logger } = capturingLogger()
613 const fetchMock = mockFetch(() => jsonResponse(successBody))
614 await adapterWithFetch(fetchMock).generateImages({
615 model: 'seedream-4-0-250828',
616 prompt: 'a guitar',
617 numberOfImages: 1,
618 logger,
619 })
620 expect(spy.warn).not.toHaveBeenCalled()
621 })
622
623 it('surfaces per-image codes when every image fails', async () => {
624 const fetchMock = mockFetch(() =>
625 jsonResponse({
626 model: 'seedream-4-0-250828',
627 data: [
628 { error: { code: 'OutputImageSensitiveContentDetected' } },
629 { error: { code: 'InternalServiceError', message: 'try again' } },
630 ],
631 }),
632 )
633 await expect(
634 adapterWithFetch(fetchMock).generateImages({
635 model: 'seedream-4-0-250828',
636 prompt: 'a guitar',
637 numberOfImages: 2,
638 logger: testLogger,
639 }),
640 ).rejects.toThrow(
641 /returned no images: OutputImageSensitiveContentDetected; InternalServiceError: try again/,
642 )
643 })
644
645 // Ark's OpenAPI document describes a second, nested `data[]` item form, so
646 // an item matching none of b64_json / url / error is a live possibility. It
647 // used to be dropped without even being counted, which turned provider drift
648 // into a bare "returned no images" with nothing to act on.
649 it('reports unrecognized data items rather than dropping them', async () => {
650 const { spy, logger } = capturingLogger()
651 const fetchMock = mockFetch(() =>
652 jsonResponse({
653 model: 'seedream-4-0-250828',
654 data: [{ imagecontent: [{ image_url: 'https://example.com/1.png' }] }],
655 }),
656 )
657
658 await expect(
659 adapterWithFetch(fetchMock).generateImages({
660 model: 'seedream-4-0-250828',
661 prompt: 'a guitar',
662 logger,
663 }),
664 ).rejects.toThrow(/1 unrecognized response item/)
665 expect(messages(spy.error)).toContain(
666 'matched none of b64_json / url / error',
667 )
668 })
669
670 it('carries the raw body into the unrecognized-item error', async () => {
671 const fetchMock = mockFetch(() =>
672 jsonResponse({
673 model: 'seedream-4-0-250828',
674 data: [{ imagecontent: [{ image_url: 'https://example.com/1.png' }] }],
675 }),
676 )
677
678 await expect(
679 adapterWithFetch(fetchMock).generateImages({
680 model: 'seedream-4-0-250828',
681 prompt: 'a guitar',
682 logger: testLogger,
683 }),
684 ).rejects.toThrow(/imagecontent/)
685 })
686
687 // `readJsonBody` returns the raw text for a non-JSON body — an HTML error
688 // page from a proxy in front of the API, served with a 200.
689 it.each([
690 ['an empty body', new Response('', { status: 200 })],
691 [
692 'an HTML page',
693 new Response('<html>502 Bad Gateway</html>', {
694 status: 200,
695 headers: { 'Content-Type': 'text/html' },
696 }),
697 ],
698 ])('throws with the body in hand for %s', async (_label, response) => {
699 await expect(
700 adapterWithFetch(mockFetch(() => response)).generateImages({
701 model: 'seedream-4-0-250828',
702 prompt: 'a guitar',
703 logger: testLogger,
704 }),
705 ).rejects.toThrow(/non-object body/)
706 })
707
708 // A partial group failure returns successfully with a short array. The
709 // `numberOfImages` warning only fires when the count was set explicitly, so
710 // without this one a caller who omitted it gets no signal at all.
711 it('warns on a partial failure even when numberOfImages is unset', async () => {
712 const { spy, logger } = capturingLogger()
713 const fetchMock = mockFetch(() =>
714 jsonResponse({
715 model: 'seedream-4-0-250828',
716 data: [
717 { url: 'https://example.com/1.png' },
718 { error: { code: 'InternalServiceError', message: 'try again' } },
719 ],
720 usage: { generated_images: 1, output_tokens: 10, total_tokens: 10 },
721 }),
722 )
723
724 const result = await adapterWithFetch(fetchMock).generateImages({
725 model: 'seedream-4-0-250828',
726 prompt: 'a guitar',
727 logger,
728 })
729
730 expect(result.images).toHaveLength(1)
731 expect(messages(spy.warn)).toContain('1 of 2 images failed to generate')
732 })
733
734 it('throws with the response error when no image comes back', async () => {
735 const fetchMock = mockFetch(() =>
736 jsonResponse({
737 model: 'seedream-4-0-250828',
738 data: [],
739 error: {
740 code: 'OutputImageSensitiveContentDetected',
741 message:
742 'The request failed because the output image may contain sensitive information.',
743 },
744 }),
745 )
746 await expect(
747 adapterWithFetch(fetchMock).generateImages({
748 model: 'seedream-4-0-250828',
749 prompt: 'a guitar',
750 logger: testLogger,
751 }),
752 ).rejects.toThrow(
753 /returned no images: OutputImageSensitiveContentDetected: The request failed/,
754 )
755 })
756})
757
758describe('error handling', () => {
759 it('surfaces the Ark error envelope', async () => {
760 const fetchMock = mockFetch(() =>
761 jsonResponse(
762 {
763 error: {
764 code: 'InputTextSensitiveContentDetected',
765 message:
766 'The request failed because the input text may contain sensitive information.',
767 },
768 },
769 400,
770 ),
771 )
772 await expect(
773 adapterWithFetch(fetchMock).generateImages({
774 model: 'seedream-4-0-250828',
775 prompt: 'a guitar',
776 logger: testLogger,
777 }),
778 ).rejects.toThrow(
779 /BytePlus Ark image generation failed \(400 InputTextSensitiveContentDetected\)/,
780 )
781 })
782
783 it('logs the failure through logger.errors before rethrowing', async () => {
784 const { spy, logger } = capturingLogger()
785 const fetchMock = mockFetch(() =>
786 jsonResponse(
787 { error: { code: 'QuotaExceeded', message: 'slow down' } },
788 429,
789 ),
790 )
791
792 await expect(
793 adapterWithFetch(fetchMock).generateImages({
794 model: 'seedream-4-0-250828',
795 prompt: 'a guitar',
796 logger,
797 }),
798 ).rejects.toThrow(/QuotaExceeded/)
799
800 expect(messages(spy.error)).toContain('byteplus.generateImages fatal')
801 const meta = spy.error.mock.calls[0]?.[1]
802 expect(meta).toMatchObject({ source: 'byteplus.generateImages' })
803 })
804
805 it('falls back to the raw body for a non-JSON failure', async () => {
806 const fetchMock = mockFetch(
807 () =>
808 new Response('<html>Bad Gateway</html>', {
809 status: 502,
810 headers: { 'Content-Type': 'text/html' },
811 }),
812 )
813 await expect(
814 adapterWithFetch(fetchMock).generateImages({
815 model: 'seedream-4-0-250828',
816 prompt: 'a guitar',
817 logger: testLogger,
818 }),
819 ).rejects.toThrow(/failed \(502\): <html>Bad Gateway<\/html>/)
820 })
821})
822
823describe('core generateImage() integration', () => {
824 it('drives the adapter through the core entry point', async () => {
825 const fetchMock = mockFetch(() => jsonResponse(successBody))
826 const result = await generateImage({
827 adapter: adapterWithFetch(fetchMock),
828 // Reference images are part of the prompt at the call site: the
829 // adapter's modality map has to admit image parts for this to compile.
830 prompt: [
831 { type: 'text', content: 'put this guitar on a beach' },
832 imagePart('https://example.com/guitar.png'),
833 ],
834 size: '2K',
835 modelOptions: { watermark: false },
836 debug: false,
837 })
838
839 expect(result.images).toEqual([{ url: IMAGE_URL }])
840 expect(sentRequest(fetchMock)).toMatchObject({
841 model: 'seedream-4-0-250828',
842 size: '2K',
843 watermark: false,
844 image: ['https://example.com/guitar.png'],
845 })
846 })
847})
848
849describe('parseBytePlusImageSize', () => {
850 it('accepts the documented forms', () => {
851 expect(parseBytePlusImageSize('1K')).toEqual({ kind: 'token', value: '1K' })
852 expect(parseBytePlusImageSize('4k')).toEqual({ kind: 'token', value: '4K' })
853 expect(parseBytePlusImageSize('2048x2048')).toEqual({
854 kind: 'pixels',
855 width: 2048,
856 height: 2048,
857 })
858 })
859
860 it('rejects everything else', () => {
861 for (const invalid of [
862 '3K',
863 '2K_1024',
864 '1024',
865 '1024x',
866 '0x1024',
867 '',
868 // Internal whitespace is not a documented form.
869 '2048 x 2048',
870 '2048x 2048',
871 // The docs render the separator as U+00D7, which the API rejects.
872 '2048×2048',
873 // Mixing the two forms.
874 '2K x 1024',
875 ]) {
876 expect(parseBytePlusImageSize(invalid)).toBeUndefined()
877 }
878 })
879
880 it('still trims surrounding whitespace', () => {
881 expect(parseBytePlusImageSize(' 2K ')).toEqual({
882 kind: 'token',
883 value: '2K',
884 })
885 expect(parseBytePlusImageSize(' 2048x2048 ')).toEqual({
886 kind: 'pixels',
887 width: 2048,
888 height: 2048,
889 })
890 })
891})