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

video.test.ts

1,240 lines40.2 KB

1import { describe, expect, expectTypeOf, it, vi } from 'vitest'
2import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
3import {
4 BytePlusVideoAdapter,
5 byteplusVideo,
6 createBytePlusVideo,
7} from '../src/adapters/video'
8import { isKnownBytePlusVideoModel } from '../src/model-meta'
9import type {
10 BytePlusVideoSize,
11 ResolveBytePlusVideoSize,
12} from '../src/model-meta'
13import type {
14 BytePlusVideoCreateRequest,
15 BytePlusVideoTask,
16} from '../src/video/wire-types'
17import type { BytePlusVideoModel } from '../src/model-meta'
18import type { MediaPromptPart, VideoGenerationOptions } from '@tanstack/ai'
19import type { BytePlusVideoProviderOptions } from '../src/video/video-provider-options'
20​
21const logger = resolveDebugOption(false)
22​
23const VIDEO_URL =
24 'https://ark-content-generation-v2-ap-southeast-1.tos-ap-southeast-1.volces.com/seedance/x.mp4'
25​
26/** Task id shape returned by a live `flex` create call (2026-07-31). */
27const JOB_ID = 'cgt-batch-20260731174311-zmz5s'
28​
29function jsonResponse(body: unknown, status = 200): Response {
30 return new Response(JSON.stringify(body), {
31 status,
32 headers: { 'Content-Type': 'application/json' },
33 })
35​
36/**
37 * A `vi.fn` fetch stub with the real fetch parameter list, so call assertions
38 * (`mock.calls[0]`) stay typed as `[input, init?]`.
39 */
40function mockFetch(handler: () => Response) {
41 return vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
42 handler(),
43 )
45​
46function adapterWithFetch<TModel extends BytePlusVideoModel>(
47 fetchMock: ReturnType<typeof mockFetch>,
48 model: TModel,
49) {
50 return createBytePlusVideo(model, 'ark-test-key', { fetch: fetchMock })
52​
53/** Reads the JSON body the adapter sent on its first request. */
54function sentRequest(
55 fetchMock: ReturnType<typeof mockFetch>,
56): BytePlusVideoCreateRequest {
57 return JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
59​
60function createOptions(
61 overrides: Partial<
62 VideoGenerationOptions<BytePlusVideoProviderOptions, string, number>
63 > = {},
64): VideoGenerationOptions<BytePlusVideoProviderOptions, any, any> {
65 return {
66 model: 'seedance-1-0-pro-fast-251015',
67 prompt: 'a guitar being played in a store',
68 logger,
69 ...overrides,
70 }
72​
73function imagePart(url: string, role?: string): MediaPromptPart {
74 return {
75 type: 'image',
76 source: { type: 'url', value: url },
77 ...(role && { metadata: { role: role as 'start_frame' } }),
78 }
80​
81/** A succeeded task as documented by the Get action's response example. */
82function succeededTask(overrides: Partial<BytePlusVideoTask> = {}) {
83 return {
84 id: JOB_ID,
85 model: 'seedance-1-0-pro-fast-251015',
86 status: 'succeeded',
87 created_at: 1_718_049_470,
88 updated_at: 1_718_053_070,
89 content: { video_url: VIDEO_URL },
90 usage: { completion_tokens: 35800, total_tokens: 35800 },
91 ...overrides,
92 } satisfies BytePlusVideoTask
94​
95describe('factories', () => {
96 it('creates an adapter with the provided API key', () => {
97 const adapter = createBytePlusVideo(
98 'seedance-1-0-pro-fast-251015',
99 'ark-test-key',
100 )
101 expect(adapter).toBeInstanceOf(BytePlusVideoAdapter)
102 expect(adapter.kind).toBe('video')
103 expect(adapter.name).toBe('byteplus')
104 expect(adapter.model).toBe('seedance-1-0-pro-fast-251015')
105 })
106​
107 it('byteplusVideo reads ARK_API_KEY from the environment', () => {
108 vi.stubEnv('ARK_API_KEY', 'env-key')
109 try {
110 expect(byteplusVideo('dreamina-seedance-2-0-260128')).toBeInstanceOf(
111 BytePlusVideoAdapter,
112 )
113 } finally {
114 vi.unstubAllEnvs()
115 }
116 })
117​
118 it('byteplusVideo names ARK_API_KEY when it is missing', () => {
119 vi.stubEnv('ARK_API_KEY', '')
120 vi.stubEnv('BYTEPLUS_API_KEY', '')
121 try {
122 expect(() => byteplusVideo('seedance-1-5-pro-251215')).toThrow(
123 /ARK_API_KEY/,
124 )
125 } finally {
126 vi.unstubAllEnvs()
127 }
128 })
129})
130​
131describe('createVideoJob', () => {
132 it('posts to the Seedance task endpoint with Ark auth', async () => {
133 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
134 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
135​
136 const result = await adapter.createVideoJob(createOptions())
137​
138 expect(result).toEqual({
139 jobId: JOB_ID,
140 model: 'seedance-1-0-pro-fast-251015',
141 })
142 const [url, init] = fetchMock.mock.calls[0] ?? []
143 expect(url).toBe(
144 'https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks',
145 )
146 expect(init?.method).toBe('POST')
147 expect(init?.headers).toMatchObject({
148 Authorization: 'Bearer ark-test-key',
149 'Content-Type': 'application/json',
150 })
151 })
152​
153 it('merges configured defaultHeaders into the request', async () => {
154 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
155 const adapter = createBytePlusVideo(
156 'seedance-1-0-pro-250528',
157 'ark-test-key',
158 { fetch: fetchMock, defaultHeaders: { 'X-Test-Id': 'video-1' } },
159 )
160​
161 await adapter.createVideoJob(createOptions())
162​
163 expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({
164 Authorization: 'Bearer ark-test-key',
165 'X-Test-Id': 'video-1',
166 })
167 })
168​
169 it('honours a custom baseURL, trailing slashes and all', async () => {
170 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
171 const adapter = createBytePlusVideo(
172 'seedance-1-0-pro-250528',
173 'ark-test-key',
174 { fetch: fetchMock, baseURL: 'https://proxy.example.com/api/v3//' },
175 )
176​
177 await adapter.createVideoJob(createOptions())
178​
179 expect(fetchMock.mock.calls[0]?.[0]).toBe(
180 'https://proxy.example.com/api/v3/contents/generations/tasks',
181 )
182 })
183​
184 it('splits the size template into ratio and resolution', async () => {
185 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
186 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
187​
188 await adapter.createVideoJob(
189 createOptions({ size: '21:9_1080p', duration: 6 }),
190 )
191​
192 expect(sentRequest(fetchMock)).toMatchObject({
193 model: 'seedance-1-5-pro-251215',
194 ratio: '21:9',
195 resolution: '1080p',
196 duration: 6,
197 content: [{ type: 'text', text: 'a guitar being played in a store' }],
198 })
199 })
200​
201 it('accepts a bare ratio with no resolution suffix', async () => {
202 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
203 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
204​
205 await adapter.createVideoJob(createOptions({ size: 'adaptive' }))
206​
207 const request = sentRequest(fetchMock)
208 expect(request.ratio).toBe('adaptive')
209 expect(request.resolution).toBeUndefined()
210 })
211​
212 it('lowercases the resolution, which the API matches case-insensitively', async () => {
213 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
214 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
215​
216 await adapter.createVideoJob(
217 createOptions({ size: '16:9_4K' as '16:9_4k' }),
218 )
219​
220 expect(sentRequest(fetchMock).resolution).toBe('4k')
221 })
222​
223 it('rejects a resolution the model does not offer', async () => {
224 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
225 // 4k is exclusive to the 2.0 flagship (live-probed).
226 const adapter = adapterWithFetch(
227 fetchMock,
228 'dreamina-seedance-2-0-fast-260128',
229 )
230​
231 await expect(
232 adapter.createVideoJob(createOptions({ size: '16:9_4k' as '16:9_720p' })),
233 ).rejects.toThrow(/resolution "4k" is not supported.*480p, 720p/s)
234 expect(fetchMock).not.toHaveBeenCalled()
235 })
236​
237 it('keeps Authorization when defaultHeaders tries to override it', async () => {
238 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
239 const adapter = createBytePlusVideo(
240 'seedance-1-0-pro-250528',
241 'ark-test-key',
242 {
243 fetch: fetchMock,
244 defaultHeaders: { Authorization: 'Bearer not-the-real-key' },
245 },
246 )
247​
248 await adapter.createVideoJob(createOptions())
249​
250 expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({
251 Authorization: 'Bearer ark-test-key',
252 })
253 })
254​
255 // Live-probed 2026-07-31 and contradicting the BytePlus docs, which list
256 // this model as 480p/720p. Guards the cell most likely to be "corrected"
257 // back by someone reading the docs.
258 it('accepts 1080p on seedance-1-0-pro-fast-251015', async () => {
259 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
260 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
261​
262 await adapter.createVideoJob(createOptions({ size: '16:9_1080p' }))
263​
264 expect(sentRequest(fetchMock).resolution).toBe('1080p')
265 })
266​
267 // No Seedance model has a 2K tier, including the 2.0 flagship whose docs
268 // advertise "up to 4K". The cast mimics a caller who trusted the docs.
269 it('rejects a 2k resolution on every model', async () => {
270 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
271 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
272​
273 await expect(
274 adapter.createVideoJob(
275 createOptions({ size: '16:9_2k' as '16:9_1080p' }),
276 ),
277 ).rejects.toThrow(/resolution "2k" is not supported/)
278 expect(fetchMock).not.toHaveBeenCalled()
279 })
280​
281 it('validates a resolution that modelOptions introduced', async () => {
282 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
283 // 4k is exclusive to the 2.0 flagship; overriding a valid size with it
284 // must fail locally rather than reaching Ark.
285 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
286​
287 await expect(
288 adapter.createVideoJob(
289 createOptions({
290 size: '16:9_720p',
291 modelOptions: { resolution: '4k' as '1080p' },
292 }),
293 ),
294 ).rejects.toThrow(/resolution "4k" is not supported.*480p, 720p, 1080p/s)
295 expect(fetchMock).not.toHaveBeenCalled()
296 })
297​
298 it('rejects a malformed size template', async () => {
299 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
300 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
301​
302 await expect(
303 adapter.createVideoJob(createOptions({ size: '720p' as '16:9' })),
304 ).rejects.toThrow(/is not supported by model/)
305 })
306​
307 it('snaps the generic duration into the model range', async () => {
308 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
309 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
310​
311 await adapter.createVideoJob(createOptions({ duration: 99 }))
312​
313 expect(sentRequest(fetchMock).duration).toBe(12)
314 })
315​
316 it('lets modelOptions override the derived fields', async () => {
317 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
318 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
319​
320 await adapter.createVideoJob(
321 createOptions({
322 size: '16:9_720p',
323 duration: 5,
324 modelOptions: {
325 resolution: '1080p',
326 // -1 (model picks the length) is only reachable through
327 // modelOptions, which is why it is not snapped.
328 duration: -1,
329 service_tier: 'flex',
330 draft: true,
331 },
332 }),
333 )
334​
335 expect(sentRequest(fetchMock)).toMatchObject({
336 ratio: '16:9',
337 resolution: '1080p',
338 duration: -1,
339 service_tier: 'flex',
340 draft: true,
341 })
342 })
343​
344 it('surfaces an Ark error envelope', async () => {
345 const fetchMock = mockFetch(() =>
346 jsonResponse(
347 {
348 error: {
349 code: 'InvalidParameter',
350 message: 'the parameter duration is not valid',
351 type: 'BadRequest',
352 },
353 },
354 400,
355 ),
356 )
357 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
358​
359 await expect(adapter.createVideoJob(createOptions())).rejects.toThrow(
360 /video task creation failed \(400 InvalidParameter\): the parameter duration is not valid/,
361 )
362 })
363​
364 it('fails when the response carries no task id', async () => {
365 const fetchMock = mockFetch(() => jsonResponse({}))
366 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
367​
368 await expect(adapter.createVideoJob(createOptions())).rejects.toThrow(
369 /returned no task id/,
370 )
371 })
372})
373​
374describe('createVideoJob content roles', () => {
375 it('sends an un-roled image as the opening frame', async () => {
376 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
377 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
378​
379 await adapter.createVideoJob(
380 createOptions({
381 prompt: [
382 { type: 'text', content: 'the guitarist starts playing' },
383 imagePart('https://example.com/shop.jpg'),
384 ],
385 }),
386 )
387​
388 expect(sentRequest(fetchMock).content).toEqual([
389 { type: 'text', text: 'the guitarist starts playing' },
390 {
391 type: 'image_url',
392 image_url: { url: 'https://example.com/shop.jpg' },
393 role: 'first_frame',
394 },
395 ])
396 })
397​
398 it('maps start_frame and end_frame onto first_frame and last_frame', async () => {
399 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
400 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
401​
402 await adapter.createVideoJob(
403 createOptions({
404 prompt: [
405 imagePart('https://example.com/open.jpg', 'start_frame'),
406 imagePart('https://example.com/close.jpg', 'end_frame'),
407 ],
408 }),
409 )
410​
411 expect(sentRequest(fetchMock).content).toEqual([
412 {
413 type: 'image_url',
414 image_url: { url: 'https://example.com/open.jpg' },
415 role: 'first_frame',
416 },
417 {
418 type: 'image_url',
419 image_url: { url: 'https://example.com/close.jpg' },
420 role: 'last_frame',
421 },
422 ])
423 })
424​
425 it('maps reference and character images onto reference_image', async () => {
426 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
427 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
428​
429 await adapter.createVideoJob(
430 createOptions({
431 prompt: [
432 imagePart('https://example.com/a.jpg', 'reference'),
433 imagePart('https://example.com/b.jpg', 'character'),
434 ],
435 }),
436 )
437​
438 expect(sentRequest(fetchMock).content).toEqual([
439 {
440 type: 'image_url',
441 image_url: { url: 'https://example.com/a.jpg' },
442 role: 'reference_image',
443 },
444 {
445 type: 'image_url',
446 image_url: { url: 'https://example.com/b.jpg' },
447 role: 'reference_image',
448 },
449 ])
450 })
451​
452 it('maps video and audio parts onto reference_video and reference_audio', async () => {
453 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
454 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
455​
456 await adapter.createVideoJob(
457 createOptions({
458 prompt: [
459 { type: 'text', content: 'match this camera move' },
460 { type: 'video', source: { type: 'url', value: 'https://x/v.mp4' } },
461 { type: 'audio', source: { type: 'url', value: 'https://x/a.mp3' } },
462 ],
463 }),
464 )
465​
466 expect(sentRequest(fetchMock).content).toEqual([
467 { type: 'text', text: 'match this camera move' },
468 {
469 type: 'video_url',
470 video_url: { url: 'https://x/v.mp4' },
471 role: 'reference_video',
472 },
473 {
474 type: 'audio_url',
475 audio_url: { url: 'https://x/a.mp3' },
476 role: 'reference_audio',
477 },
478 ])
479 })
480​
481 it('sends base64 image sources as data URIs', async () => {
482 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
483 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
484​
485 await adapter.createVideoJob(
486 createOptions({
487 prompt: [
488 {
489 type: 'image',
490 source: { type: 'data', value: 'AAAA', mimeType: 'image/PNG' },
491 },
492 ],
493 }),
494 )
495​
496 expect(sentRequest(fetchMock).content).toEqual([
497 {
498 type: 'image_url',
499 image_url: { url: 'data:image/png;base64,AAAA' },
500 role: 'first_frame',
501 },
502 ])
503 })
504​
505 it('rejects mixing frame roles with reference roles', async () => {
506 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
507 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
508​
509 await expect(
510 adapter.createVideoJob(
511 createOptions({
512 prompt: [
513 imagePart('https://example.com/open.jpg', 'start_frame'),
514 imagePart('https://example.com/ref.jpg', 'reference'),
515 ],
516 }),
517 ),
518 ).rejects.toThrow(/cannot be combined with reference media/)
519 expect(fetchMock).not.toHaveBeenCalled()
520 })
521​
522 it('reports the mode mix, not the audio rule, for a frame plus audio', async () => {
523 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
524 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
525​
526 await expect(
527 adapter.createVideoJob(
528 createOptions({
529 prompt: [
530 imagePart('https://example.com/open.jpg', 'start_frame'),
531 {
532 type: 'audio',
533 source: { type: 'url', value: 'https://x/a.mp3' },
534 },
535 ],
536 }),
537 ),
538 // Advising the caller to add another reference would still fail — the
539 // real defect is the frame/reference mix.
540 ).rejects.toThrow(/cannot be combined with reference media/)
541 })
542​
543 it('rejects more than one opening frame', async () => {
544 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
545 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
546​
547 await expect(
548 adapter.createVideoJob(
549 createOptions({
550 prompt: [
551 imagePart('https://example.com/a.jpg'),
552 imagePart('https://example.com/b.jpg', 'start_frame'),
553 ],
554 }),
555 ),
556 ).rejects.toThrow(/at most one opening frame; received 2/)
557 expect(fetchMock).not.toHaveBeenCalled()
558 })
559​
560 it('rejects a closing frame with no opening frame', async () => {
561 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
562 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
563​
564 await expect(
565 adapter.createVideoJob(
566 createOptions({
567 prompt: [imagePart('https://example.com/close.jpg', 'end_frame')],
568 }),
569 ),
570 ).rejects.toThrow(/closing frame needs an opening frame/)
571 expect(fetchMock).not.toHaveBeenCalled()
572 })
573​
574 it('rejects a reference audio that is the only reference input on 2.0', async () => {
575 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
576 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
577​
578 await expect(
579 adapter.createVideoJob(
580 createOptions({
581 prompt: [
582 { type: 'text', content: 'use this score' },
583 {
584 type: 'audio',
585 source: { type: 'url', value: 'https://x/a.mp3' },
586 },
587 ],
588 }),
589 ),
590 ).rejects.toThrow(/cannot be the only reference/)
591 })
592​
593 it('accepts audio-only reference input on Seedance 2.5', async () => {
594 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
595 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-5-260628')
596​
597 await adapter.createVideoJob(
598 createOptions({
599 prompt: [
600 { type: 'text', content: 'use this score' },
601 {
602 type: 'audio',
603 source: { type: 'url', value: 'https://x/a.mp3' },
604 },
605 ],
606 }),
607 )
608​
609 expect(sentRequest(fetchMock).content).toEqual(
610 expect.arrayContaining([
611 expect.objectContaining({
612 type: 'audio_url',
613 role: 'reference_audio',
614 }),
615 ]),
616 )
617 })
618​
619 it('accepts 1080p on Seedance 2.5', async () => {
620 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
621 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-5-260628')
622​
623 await adapter.createVideoJob(createOptions({ size: '16:9_1080p' }))
624​
625 expect(sentRequest(fetchMock).resolution).toBe('1080p')
626 })
627​
628 it('rejects 4k on Seedance 2.5', async () => {
629 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
630 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-5-260628')
631​
632 await expect(
633 adapter.createVideoJob(
634 createOptions({ size: '16:9_4k' as '16:9_1080p' }),
635 ),
636 ).rejects.toThrow(/resolution "4k" is not supported.*480p, 720p, 1080p/s)
637 expect(fetchMock).not.toHaveBeenCalled()
638 })
639​
640 it('forwards output_format on Seedance 2.5', async () => {
641 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
642 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-5-260628')
643​
644 await adapter.createVideoJob(
645 createOptions({
646 modelOptions: { output_format: 'mov' },
647 }),
648 )
649​
650 expect(sentRequest(fetchMock).output_format).toBe('mov')
651 })
652​
653 it('rejects reference images on a model without reference mode', async () => {
654 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
655 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
656​
657 await expect(
658 adapter.createVideoJob(
659 createOptions({
660 prompt: [imagePart('https://example.com/ref.jpg', 'reference')],
661 }),
662 ),
663 ).rejects.toThrow(/does not support reference images/)
664 })
665​
666 it('rejects a closing frame on seedance-1-0-pro-fast', async () => {
667 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
668 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
669​
670 await expect(
671 adapter.createVideoJob(
672 createOptions({
673 prompt: [
674 imagePart('https://example.com/open.jpg', 'start_frame'),
675 imagePart('https://example.com/close.jpg', 'end_frame'),
676 ],
677 }),
678 ),
679 ).rejects.toThrow(/does not support a closing frame/)
680 })
681​
682 // The per-model modality map makes these compile errors; the casts stand in
683 // for JS callers and for a prompt built from untyped data.
684 it('rejects video prompt parts on a 1.x model', async () => {
685 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
686 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
687​
688 await expect(
689 adapter.createVideoJob(
690 createOptions({
691 prompt: [
692 {
693 type: 'video',
694 source: { type: 'url', value: 'https://x/v.mp4' },
695 },
696 ] as Array<MediaPromptPart>,
697 }),
698 ),
699 ).rejects.toThrow(/does not accept video prompt parts/)
700 expect(fetchMock).not.toHaveBeenCalled()
701 })
702​
703 it('rejects audio prompt parts on a 1.x model', async () => {
704 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
705 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
706​
707 await expect(
708 adapter.createVideoJob(
709 createOptions({
710 prompt: [
711 {
712 type: 'audio',
713 source: { type: 'url', value: 'https://x/a.mp3' },
714 },
715 ] as Array<MediaPromptPart>,
716 }),
717 ),
718 ).rejects.toThrow(/does not accept audio prompt parts/)
719 })
720​
721 // The create schema says maxItems: 5, but Ark accepted 7 live, so the
722 // adapter passes long prompts through rather than rejecting what the API
723 // would have taken.
724 it('does not cap the content array locally', async () => {
725 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
726 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
727​
728 await adapter.createVideoJob(
729 createOptions({
730 prompt: [
731 { type: 'text', content: 'blend these' },
732 imagePart('https://example.com/1.jpg', 'reference'),
733 imagePart('https://example.com/2.jpg', 'reference'),
734 imagePart('https://example.com/3.jpg', 'reference'),
735 imagePart('https://example.com/4.jpg', 'reference'),
736 imagePart('https://example.com/5.jpg', 'reference'),
737 ],
738 }),
739 )
740​
741 expect(sentRequest(fetchMock).content).toHaveLength(6)
742 })
743​
744 it('rejects mask and control roles Seedance has no channel for', async () => {
745 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
746 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
747​
748 await expect(
749 adapter.createVideoJob(
750 createOptions({
751 prompt: [imagePart('https://example.com/m.png', 'mask')],
752 }),
753 ),
754 ).rejects.toThrow(/has no 'mask' image input/)
755 })
756​
757 it('rejects an empty prompt', async () => {
758 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
759 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
760​
761 await expect(
762 adapter.createVideoJob(createOptions({ prompt: [] })),
763 ).rejects.toThrow(/must carry text or at least one media input/)
764 })
765})
766​
767describe('getVideoStatus', () => {
768 it.each([
769 ['queued', 'pending'],
770 ['running', 'processing'],
771 ['succeeded', 'completed'],
772 ['failed', 'failed'],
773 ['expired', 'failed'],
774 ['cancelled', 'failed'],
775 ] as const)('maps %s to %s', async (apiStatus, expected) => {
776 const fetchMock = mockFetch(() =>
777 jsonResponse({ id: JOB_ID, status: apiStatus }),
778 )
779 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
780​
781 const status = await adapter.getVideoStatus(JOB_ID)
782​
783 expect(status.status).toBe(expected)
784 expect(fetchMock.mock.calls[0]?.[0]).toBe(
785 `https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks/${JOB_ID}`,
786 )
787 })
788​
789 // Core's poll loop treats `processing` as "keep waiting", so a status it
790 // can't map must not answer `processing` — that turns a malformed or
791 // newly-added terminal state into a silent poll to `maxDuration` and a
792 // generic timeout, with what Ark actually sent never reaching the caller.
793 it.each([
794 ['a status Ark adds later', { id: JOB_ID, status: 'rejected' }],
795 ['a task with no status at all', { id: JOB_ID }],
796 ])('throws naming %s', async (_label, body) => {
797 const adapter = adapterWithFetch(
798 mockFetch(() => jsonResponse(body)),
799 'seedance-1-0-pro-fast-251015',
800 )
801​
802 await expect(adapter.getVideoStatus(JOB_ID)).rejects.toThrow(
803 /unrecognized Seedance task status/,
804 )
805 })
806​
807 it('names the offending status value in the error', async () => {
808 const adapter = adapterWithFetch(
809 mockFetch(() => jsonResponse({ id: JOB_ID, status: 'rejected' })),
810 'seedance-1-0-pro-fast-251015',
811 )
812​
813 await expect(adapter.getVideoStatus(JOB_ID)).rejects.toThrow(/"rejected"/)
814 })
815​
816 // `readJsonBody` returns `undefined` for an empty body and the raw text for
817 // a non-JSON one — both documented failure modes of these hosts (an HTML
818 // error page from a proxy). Casting either to a task hides the body.
819 it.each([
820 ['an empty body', new Response('', { status: 200 })],
821 [
822 'an HTML error page served with 200',
823 new Response('<html><body>502 Bad Gateway</body></html>', {
824 status: 200,
825 headers: { 'Content-Type': 'text/html' },
826 }),
827 ],
828 ])('throws with the body in hand for %s', async (_label, response) => {
829 const adapter = adapterWithFetch(
830 mockFetch(() => response),
831 'seedance-1-0-pro-fast-251015',
832 )
833​
834 await expect(adapter.getVideoStatus(JOB_ID)).rejects.toThrow(
835 /non-object body/,
836 )
837 })
838​
839 it('carries the raw HTML into the error so the failure stays diagnosable', async () => {
840 const adapter = adapterWithFetch(
841 mockFetch(
842 () =>
843 new Response('<html><body>502 Bad Gateway</body></html>', {
844 status: 200,
845 headers: { 'Content-Type': 'text/html' },
846 }),
847 ),
848 'seedance-1-0-pro-fast-251015',
849 )
850​
851 await expect(adapter.getVideoStatus(JOB_ID)).rejects.toThrow(
852 /502 Bad Gateway/,
853 )
854 })
855​
856 // Core does `throw new Error(statusResult.error || 'Video generation
857 // failed')`, so a failure with no `error` block must still carry something
858 // identifying or the caller gets an unattributable error.
859 it('describes a failed task that carries no error block', async () => {
860 const adapter = adapterWithFetch(
861 mockFetch(() =>
862 jsonResponse({
863 id: JOB_ID,
864 status: 'failed',
865 model: 'seedance-1-0-pro-fast-251015',
866 }),
867 ),
868 'seedance-1-0-pro-fast-251015',
869 )
870​
871 const status = await adapter.getVideoStatus(JOB_ID)
872​
873 expect(status.status).toBe('failed')
874 expect(status.error).toContain(JOB_ID)
875 expect(status.error).toContain('seedance-1-0-pro-fast-251015')
876 expect(status.error).toContain('no error detail')
877 })
878​
879 it('surfaces the error code and message of a failed task', async () => {
880 const fetchMock = mockFetch(() =>
881 jsonResponse({
882 id: JOB_ID,
883 status: 'failed',
884 error: {
885 code: 'OutputVideoSensitiveContentDetected',
886 message: 'The request failed because the output video may contain…',
887 },
888 }),
889 )
890 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
891​
892 expect(await adapter.getVideoStatus(JOB_ID)).toEqual({
893 jobId: JOB_ID,
894 status: 'failed',
895 error:
896 'OutputVideoSensitiveContentDetected: The request failed because the output video may contain…',
897 })
898 })
899​
900 it('explains an expired task, which carries no error block', async () => {
901 const fetchMock = mockFetch(() =>
902 jsonResponse({ id: JOB_ID, status: 'expired' }),
903 )
904 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
905​
906 const status = await adapter.getVideoStatus(JOB_ID)
907​
908 expect(status.error).toMatch(/expired before it finished/)
909 })
910​
911 it('reports a 404 as a failed job rather than throwing', async () => {
912 const fetchMock = mockFetch(() =>
913 jsonResponse(
914 { error: { code: 'NotFound', message: 'task not found' } },
915 404,
916 ),
917 )
918 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
919​
920 const result = await adapter.getVideoStatus(JOB_ID)
921 expect(result).toMatchObject({ jobId: JOB_ID, status: 'failed' })
922 // Ark's own code/message is kept: a 404 from a wrong baseURL or a proxy in
923 // front of the API is not an expired job id, and collapsing both to a bare
924 // "Job not found" points the caller at the wrong cause.
925 expect(result.error).toContain(JOB_ID)
926 expect(result.error).toContain('NotFound')
927 expect(result.error).toContain('task not found')
928 })
929​
930 it('propagates non-404 lookup failures', async () => {
931 const fetchMock = mockFetch(() =>
932 jsonResponse(
933 {
934 error: {
935 code: 'RateLimitExceeded.FoundationModelRPMExceeded',
936 message: 'RPM exceeded',
937 },
938 },
939 429,
940 ),
941 )
942 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
943​
944 await expect(adapter.getVideoStatus(JOB_ID)).rejects.toThrow(
945 /429 RateLimitExceeded.FoundationModelRPMExceeded/,
946 )
947 })
948})
949​
950describe('getVideoUrl', () => {
951 it('returns the URL, its 24h expiry and usage', async () => {
952 const task = succeededTask()
953 const fetchMock = mockFetch(() => jsonResponse(task))
954 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
955​
956 const result = await adapter.getVideoUrl(JOB_ID)
957​
958 expect(result.url).toBe(VIDEO_URL)
959 // Anchored on updated_at (when the output appeared), not created_at.
960 expect(result.expiresAt).toEqual(
961 new Date((task.updated_at + 24 * 60 * 60) * 1000),
962 )
963 expect(result.usage).toEqual({
964 promptTokens: 0,
965 completionTokens: 35800,
966 totalTokens: 35800,
967 billed: { quantity: 35800, unit: 'tokens' },
968 unitsBilled: 35800,
969 })
970 })
971​
972 it('falls back to created_at when the task has no updated_at', async () => {
973 const fetchMock = mockFetch(() =>
974 jsonResponse({
975 id: JOB_ID,
976 status: 'succeeded',
977 created_at: 1_718_049_470,
978 content: { video_url: VIDEO_URL },
979 }),
980 )
981 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-fast-251015')
982​
983 const result = await adapter.getVideoUrl(JOB_ID)
984​
985 expect(result.expiresAt).toEqual(
986 new Date((1_718_049_470 + 24 * 60 * 60) * 1000),
987 )
988 })
989​
990 it('coerces usage counts the schema types as strings', async () => {
991 const fetchMock = mockFetch(() =>
992 jsonResponse(
993 succeededTask({
994 usage: { completion_tokens: '35800', total_tokens: '35800' },
995 }),
996 ),
997 )
998 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
999​
1000 expect((await adapter.getVideoUrl(JOB_ID)).usage).toMatchObject({
1001 completionTokens: 35800,
1002 totalTokens: 35800,
1003 billed: { quantity: 35800, unit: 'tokens' },
1004 unitsBilled: 35800,
1005 })
1006 })
1007​
1008 it('omits usage when the task reports none', async () => {
1009 const fetchMock = mockFetch(() =>
1010 jsonResponse(succeededTask({ usage: undefined })),
1012 const adapter = adapterWithFetch(fetchMock, 'seedance-1-5-pro-251215')
1013​
1014 expect((await adapter.getVideoUrl(JOB_ID)).usage).toBeUndefined()
1015 })
1016​
1017 it('throws with the failure detail when the task failed', async () => {
1018 const fetchMock = mockFetch(() =>
1019 jsonResponse({
1020 id: JOB_ID,
1021 status: 'failed',
1022 error: {
1023 code: 'InputImageSensitiveContentDetected',
1024 message: 'input image may contain sensitive information',
1025 },
1026 }),
1028 const adapter = adapterWithFetch(fetchMock, 'dreamina-seedance-2-0-260128')
1029​
1030 await expect(adapter.getVideoUrl(JOB_ID)).rejects.toThrow(
1031 /Video generation failed: InputImageSensitiveContentDetected: input image may contain sensitive information/,
1033 })
1034​
1035 it('throws while the task is still running', async () => {
1036 const fetchMock = mockFetch(() =>
1037 jsonResponse({ id: JOB_ID, status: 'running' }),
1039 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
1040​
1041 await expect(adapter.getVideoUrl(JOB_ID)).rejects.toThrow(
1042 /not ready for download/,
1044 })
1045​
1046 it('throws a job-not-found error on 404', async () => {
1047 const fetchMock = mockFetch(() => jsonResponse({}, 404))
1048 const adapter = adapterWithFetch(fetchMock, 'seedance-1-0-pro-250528')
1049​
1050 await expect(adapter.getVideoUrl(JOB_ID)).rejects.toThrow(
1051 `Video job not found: ${JOB_ID}`,
1053 })
1055​
1056// The factories accept any string so an id BytePlus ships between package
1057// releases still works. Seedance 2.5 used to be this example; it is now a
1058// first-class known model. These cover the still-open unknown-id path.
1059describe('unknown model ids', () => {
1060 const FUTURE = 'dreamina-seedance-9-9-999999'
1061​
1062 it('accepts a bare string through the factories', async () => {
1063 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1064 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1065 fetch: fetchMock,
1066 })
1067​
1068 expect(adapter.model).toBe(FUTURE)
1069 expect(await adapter.createVideoJob(createOptions())).toEqual({
1070 jobId: JOB_ID,
1071 model: FUTURE,
1072 })
1073 })
1074​
1075 it('passes resolutions and ratios through without the per-model table', async () => {
1076 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1077 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1078 fetch: fetchMock,
1079 })
1080​
1081 // '8k' and '32:9' exist on no model today; a future model may have both.
1082 await adapter.createVideoJob(createOptions({ size: '32:9_8K' }))
1083​
1084 expect(sentRequest(fetchMock)).toMatchObject({
1085 ratio: '32:9',
1086 resolution: '8k',
1087 })
1088 })
1089​
1090 it('sends an unknown model duration verbatim rather than clamping it', async () => {
1091 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1092 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1093 fetch: fetchMock,
1094 })
1095​
1096 // 45s is outside every range shipping today; clamping to 30 would corrupt
1097 // a legitimate request for a model with a longer ceiling.
1098 await adapter.createVideoJob(createOptions({ duration: 45 }))
1099​
1100 expect(sentRequest(fetchMock).duration).toBe(45)
1101 })
1102​
1103 it('passes provider options through ungated', async () => {
1104 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1105 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1106 fetch: fetchMock,
1107 })
1108​
1109 // draft is 1.5-pro-only and priority is 2.x-only today; on an unknown
1110 // model neither is second-guessed.
1111 await adapter.createVideoJob(
1112 createOptions({ modelOptions: { draft: true, priority: 3 } }),
1114​
1115 expect(sentRequest(fetchMock)).toMatchObject({ draft: true, priority: 3 })
1116 })
1117​
1118 it('stands down the media-shape guards', async () => {
1119 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1120 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1121 fetch: fetchMock,
1122 })
1123​
1124 // Frame + reference is mutually exclusive on every known model. A future
1125 // model that relaxes it must not be blocked by today's tables.
1126 await adapter.createVideoJob(
1127 createOptions({
1128 prompt: [
1129 imagePart('https://example.com/open.jpg', 'start_frame'),
1130 imagePart('https://example.com/ref.jpg', 'reference'),
1131 ],
1132 }),
1134​
1135 expect(sentRequest(fetchMock).content).toEqual([
1137 type: 'image_url',
1138 image_url: { url: 'https://example.com/open.jpg' },
1139 role: 'first_frame',
1140 },
1142 type: 'image_url',
1143 image_url: { url: 'https://example.com/ref.jpg' },
1144 role: 'reference_image',
1145 },
1146 ])
1147 })
1148​
1149 it('still rejects roles the wire format cannot carry on any model', async () => {
1150 const fetchMock = mockFetch(() => jsonResponse({ id: JOB_ID }))
1151 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key', {
1152 fetch: fetchMock,
1153 })
1154​
1155 await expect(
1156 adapter.createVideoJob(
1157 createOptions({
1158 prompt: [imagePart('https://example.com/m.png', 'mask')],
1159 }),
1160 ),
1161 ).rejects.toThrow(/has no 'mask' image input/)
1162 })
1163​
1164 it('reports the union of known ranges as its duration hint', () => {
1165 const adapter = createBytePlusVideo(FUTURE, 'ark-test-key')
1166​
1167 expect(adapter.availableDurations()).toEqual({
1168 kind: 'range',
1169 min: 2,
1170 max: 30,
1171 step: 1,
1172 unit: 'seconds',
1173 })
1174 })
1175​
1176 it('knows which ids it has metadata for', () => {
1177 expect(isKnownBytePlusVideoModel('seedance-1-5-pro-251215')).toBe(true)
1178 expect(isKnownBytePlusVideoModel('dreamina-seedance-2-5-260628')).toBe(true)
1179 expect(isKnownBytePlusVideoModel(FUTURE)).toBe(false)
1180 })
1182​
1183describe('model id typing', () => {
1184 it('accepts a bare string while keeping known ids narrowed', () => {
1185 // A plain string compiles through both factories — the escape hatch's
1186 // whole point. `toBeCallableWith` checks the signature without running
1187 // byteplusVideo, which would need ARK_API_KEY.
1188 expectTypeOf(byteplusVideo).toBeCallableWith('dreamina-seedance-9-9-999999')
1189 const adapter = createBytePlusVideo('dreamina-seedance-9-9-999999', 'k')
1190 expectTypeOf(adapter.model).toEqualTypeOf<'dreamina-seedance-9-9-999999'>()
1191​
1192 // Known ids keep their probe-verified size union, so a tier the model
1193 // does not offer stays a compile error.
1194 expectTypeOf<
1195 ResolveBytePlusVideoSize<'dreamina-seedance-2-5-260628'>
1196 >().toEqualTypeOf<BytePlusVideoSize<'480p' | '720p' | '1080p'>>()
1197 expectTypeOf<
1198 ResolveBytePlusVideoSize<'dreamina-seedance-2-0-fast-260128'>
1199 >().toEqualTypeOf<BytePlusVideoSize<'480p' | '720p'>>()
1200 expectTypeOf<
1201 ResolveBytePlusVideoSize<'dreamina-seedance-2-0-260128'>
1202 >().toEqualTypeOf<BytePlusVideoSize<'480p' | '720p' | '1080p' | '4k'>>()
1203​
1204 // An unknown id widens instead.
1205 expectTypeOf<ResolveBytePlusVideoSize<'anything-else'>>().toEqualTypeOf<
1206 BytePlusVideoSize | (string & {})
1207 >()
1208 })
1210​
1211describe('durations', () => {
1212 it.each([
1213 ['dreamina-seedance-2-5-260628', 4, 30],
1214 ['dreamina-seedance-2-0-260128', 4, 15],
1215 ['dreamina-seedance-2-0-fast-260128', 4, 15],
1216 ['dreamina-seedance-2-0-mini-260615', 4, 15],
1217 ['seedance-1-5-pro-251215', 4, 12],
1218 ['seedance-1-0-pro-250528', 2, 12],
1219 ['seedance-1-0-pro-fast-251015', 2, 12],
1220 ] as const)('reports the %s range as %i–%i seconds', (model, min, max) => {
1221 const adapter = createBytePlusVideo(model, 'ark-test-key')
1222​
1223 expect(adapter.availableDurations()).toEqual({
1224 kind: 'range',
1225 min,
1226 max,
1227 step: 1,
1228 unit: 'seconds',
1229 })
1230 })
1231​
1232 it('snaps below, above and between the range', () => {
1233 const adapter = createBytePlusVideo('seedance-1-5-pro-251215', 'k')
1234​
1235 expect(adapter.snapDuration(1)).toBe(4)
1236 expect(adapter.snapDuration(6.4)).toBe(6)
1237 expect(adapter.snapDuration(6.6)).toBe(7)
1238 expect(adapter.snapDuration(30)).toBe(12)
1239 })