@fungi.computer/darkroom 0.11.11 → 0.11.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +7 -1
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
@@ -0,0 +1,533 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ validateMediaGenerationSettings,
4
+ validateMediaVideoSelection,
5
+ mediaVideoSelectionSchema,
6
+ MediaSettingsError,
7
+ getMediaModel,
8
+ mediaVideoModelIdSchema,
9
+ estimateVideoMilliunits,
10
+ } from "../src/index.js";
11
+ import {
12
+ createMediaService,
13
+ generateMedia,
14
+ type MediaServiceHost,
15
+ } from "../src/server.js";
16
+ import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
17
+ import { generate } from "../src/cloudflare/provider.js";
18
+ import {
19
+ gatewayInput,
20
+ estimateGatewayMilliunits,
21
+ mediaUnits,
22
+ } from "../src/gateway-models.js";
23
+
24
+ const base = {
25
+ model: "bytedance/seedance-2.0",
26
+ prompt: "fern fronds unfurling",
27
+ width: 1280,
28
+ height: 720,
29
+ };
30
+ const image = (value: number) => ({
31
+ bytes: new Uint8Array([value]),
32
+ format: "png" as const,
33
+ width: 1,
34
+ height: 1,
35
+ });
36
+ const reference = (
37
+ role: "first-frame" | "last-frame" | "reference",
38
+ path: string = role,
39
+ ) => ({ computerId: "pictures", path, role });
40
+
41
+ describe("verified video catalog contract", () => {
42
+ it("retains every admitted frame and translates by role, independent of order", () => {
43
+ const settings = validateMediaGenerationSettings({
44
+ ...base,
45
+ references: [reference("last-frame"), reference("first-frame")],
46
+ });
47
+ expect(gatewayInput(settings, [image(2), image(1)])).toMatchObject({
48
+ image: "data:image/png;base64,AQ==",
49
+ last_frame_image: "data:image/png;base64,Ag==",
50
+ });
51
+ });
52
+ it("sends all four reference images using the provider reference mode", () => {
53
+ const settings = validateMediaGenerationSettings({
54
+ ...base,
55
+ references: [0, 1, 2, 3].map((index) =>
56
+ reference("reference", String(index)),
57
+ ),
58
+ });
59
+ expect(
60
+ gatewayInput(settings, [image(1), image(2), image(3), image(4)]),
61
+ ).toMatchObject({
62
+ reference_images: [
63
+ "data:image/png;base64,AQ==",
64
+ "data:image/png;base64,Ag==",
65
+ "data:image/png;base64,Aw==",
66
+ "data:image/png;base64,BA==",
67
+ ],
68
+ });
69
+ });
70
+ it("uses Veo's default audio price and string duration", () => {
71
+ const settings = validateMediaGenerationSettings({
72
+ ...base,
73
+ model: "google/veo-3.1-fast",
74
+ });
75
+ expect(gatewayInput(settings)).toEqual({
76
+ prompt: base.prompt,
77
+ duration: "6s",
78
+ resolution: "720p",
79
+ aspect_ratio: "16:9",
80
+ generate_audio: true,
81
+ });
82
+ expect(estimateGatewayMilliunits(settings, [])).toBe(60_000);
83
+ expect(mediaUnits(settings)).toEqual({ unit: "video_second", units: 6 });
84
+ expect(getMediaModel(settings.model)?.video?.defaultSeconds).toBe(6);
85
+ });
86
+ it("builds MiniMax H3 Max's documented content[] body and refuses an audio choice", () => {
87
+ const minimax = getMediaModel("minimax/h3-max")?.video;
88
+ if (!minimax) throw new Error("catalog missing minimax/h3-max");
89
+ const defaultFormat = minimax.formats.find(
90
+ (format) =>
91
+ format.resolution === minimax.defaultResolution &&
92
+ format.aspectRatio === minimax.defaultAspectRatio,
93
+ );
94
+ if (!defaultFormat) throw new Error("minimax default format missing");
95
+ const settings = validateMediaGenerationSettings({
96
+ model: "minimax/h3-max",
97
+ prompt: "A golden retriever runs along a beach at sunrise",
98
+ width: defaultFormat.width,
99
+ height: defaultFormat.height,
100
+ durationSeconds: 5,
101
+ });
102
+ expect(gatewayInput(settings)).toEqual({
103
+ content: [
104
+ {
105
+ type: "text",
106
+ text: "A golden retriever runs along a beach at sunrise",
107
+ },
108
+ ],
109
+ duration: 5,
110
+ resolution: "768P",
111
+ ratio: "16:9",
112
+ });
113
+ expect(() => gatewayInput({ ...settings, generateAudio: true })).toThrow(
114
+ "does not support an audio choice",
115
+ );
116
+ });
117
+ it("sends a MiniMax first-frame image as a data-URI content[] item", () => {
118
+ const settings = validateMediaGenerationSettings({
119
+ model: "minimax/h3-max",
120
+ prompt: "The camera slowly pans across the scene",
121
+ width: 854,
122
+ height: 480,
123
+ references: [reference("first-frame")],
124
+ });
125
+ expect(gatewayInput(settings, [image(1)])).toEqual({
126
+ content: [
127
+ { type: "text", text: "The camera slowly pans across the scene" },
128
+ {
129
+ type: "image_url",
130
+ image_url: { url: "data:image/png;base64,AQ==" },
131
+ role: "first_frame",
132
+ },
133
+ ],
134
+ duration: 5,
135
+ resolution: "480P",
136
+ ratio: "16:9",
137
+ });
138
+ });
139
+ });
140
+
141
+ describe("video refinements and provider prices", () => {
142
+ const select = (model = "bytedance/seedance-2.0", overrides = {}) =>
143
+ validateMediaVideoSelection(
144
+ mediaVideoSelectionSchema.parse({
145
+ model,
146
+ prompt: "fern fronds",
147
+ ...overrides,
148
+ }),
149
+ );
150
+ const hydrate = (selection: ReturnType<typeof select>) =>
151
+ validateMediaGenerationSettings({
152
+ ...selection,
153
+ references: selection.references?.map((reference) => ({
154
+ ...reference,
155
+ computerId: "pictures",
156
+ })),
157
+ audioReferences: selection.audioReferences?.map((reference) => ({
158
+ ...reference,
159
+ computerId: "pictures",
160
+ })),
161
+ });
162
+ it.each([
163
+ ["bytedance/seedance-2.0", "480p", false, 7_000],
164
+ ["bytedance/seedance-2.0", "720p", true, 15_000],
165
+ ["bytedance/seedance-2.0", "1080p", false, 37_000],
166
+ ["bytedance/seedance-2.0", "4k", true, 78_000],
167
+ ["bytedance/seedance-2.0-fast", "480p", true, 6_000],
168
+ ["bytedance/seedance-2.0-fast", "720p", false, 12_000],
169
+ ["bytedance/seedance-2.0-mini", "480p", false, 4_000],
170
+ ["bytedance/seedance-2.0-mini", "720p", true, 9_000],
171
+ ["google/veo-3.1", "720p", false, 20_000],
172
+ ["google/veo-3.1", "720p", true, 40_000],
173
+ ["google/veo-3.1", "1080p", false, 20_000],
174
+ ["google/veo-3.1", "1080p", true, 40_000],
175
+ ["google/veo-3.1-fast", "720p", false, 8_000],
176
+ ["google/veo-3.1-fast", "720p", true, 10_000],
177
+ ["google/veo-3.1-fast", "1080p", false, 10_000],
178
+ ["google/veo-3.1-fast", "1080p", true, 12_000],
179
+ ])(
180
+ "quotes %s/%s/audio=%s in provider milliunits per requested second",
181
+ (model, resolution, generateAudio, perSecond) => {
182
+ const settings = hydrate(
183
+ select(model, { resolution, generateAudio, durationSeconds: 4 }),
184
+ );
185
+ expect(estimateVideoMilliunits(settings)).toBe(perSecond * 4);
186
+ expect(
187
+ estimateVideoMilliunits(
188
+ select(model, { resolution, generateAudio, durationSeconds: 4 }),
189
+ ),
190
+ ).toBe(perSecond * 4);
191
+ expect(estimateGatewayMilliunits(settings, [])).toBe(perSecond * 4);
192
+ expect(mediaUnits(settings)).toEqual({ unit: "video_second", units: 4 });
193
+ },
194
+ );
195
+ it.each([
196
+ ["480p", false, 5_000],
197
+ ["480p", true, 5_000],
198
+ ["768p", false, 8_000],
199
+ ["768p", true, 8_000],
200
+ ])(
201
+ "quotes minimax/h3-max/%s/audio=%s at the same rate; no documented audio surcharge",
202
+ (resolution, generateAudio, perSecond) => {
203
+ const settings = hydrate(
204
+ select("minimax/h3-max", {
205
+ resolution,
206
+ generateAudio,
207
+ durationSeconds: 5,
208
+ }),
209
+ );
210
+ expect(estimateVideoMilliunits(settings)).toBe(perSecond * 5);
211
+ expect(estimateGatewayMilliunits(settings, [])).toBe(perSecond * 5);
212
+ expect(mediaUnits(settings)).toEqual({ unit: "video_second", units: 5 });
213
+ },
214
+ );
215
+ it("admits every verified duration, aspect and resolution combination from the catalog", () => {
216
+ for (const id of mediaVideoModelIdSchema.options) {
217
+ const video = getMediaModel(id)?.video;
218
+ expect(video).toBeDefined();
219
+ if (!video) throw new Error("catalog video missing");
220
+ for (const format of video.formats)
221
+ for (const durationSeconds of video.durations)
222
+ expect(
223
+ select(id, {
224
+ resolution: format.resolution,
225
+ aspectRatio: format.aspectRatio,
226
+ durationSeconds,
227
+ }),
228
+ ).toMatchObject({
229
+ width: format.width,
230
+ height: format.height,
231
+ durationSeconds,
232
+ });
233
+ }
234
+ });
235
+ it.each([
236
+ ["bytedance/seedance-2.0", { durationSeconds: 3 }],
237
+ ["bytedance/seedance-2.0", { durationSeconds: 13 }],
238
+ ["bytedance/seedance-2.0", { durationSeconds: 4.5 }],
239
+ ["google/veo-3.1", { durationSeconds: 5 }],
240
+ ["google/veo-3.1-fast", { resolution: "4k" }],
241
+ ["google/veo-3.1", { resolution: "480p" }],
242
+ ["google/veo-3.1", { aspectRatio: "4:3" }],
243
+ ["bytedance/seedance-2.0-fast", { resolution: "1080p" }],
244
+ [
245
+ "bytedance/seedance-2.0",
246
+ { references: [{ path: "last.png", role: "last-frame" }] },
247
+ ],
248
+ [
249
+ "bytedance/seedance-2.0",
250
+ {
251
+ references: [
252
+ { path: "first.png", role: "first-frame" },
253
+ { path: "reference.png", role: "reference" },
254
+ ],
255
+ },
256
+ ],
257
+ [
258
+ "bytedance/seedance-2.0",
259
+ {
260
+ references: [
261
+ { path: "a.png", role: "first-frame" },
262
+ { path: "b.png", role: "first-frame" },
263
+ ],
264
+ },
265
+ ],
266
+ [
267
+ "bytedance/seedance-2.0",
268
+ {
269
+ resolution: "1080p",
270
+ references: [{ path: "ref.png", role: "reference" }],
271
+ },
272
+ ],
273
+ [
274
+ "bytedance/seedance-2.0",
275
+ {
276
+ references: [0, 1, 2, 3, 4].map((index) => ({
277
+ path: `${String(index)}.png`,
278
+ role: "reference",
279
+ })),
280
+ },
281
+ ],
282
+ [
283
+ "google/veo-3.1",
284
+ {
285
+ references: [
286
+ { path: "a.png", role: "first-frame" },
287
+ { path: "b.png", role: "last-frame" },
288
+ ],
289
+ },
290
+ ],
291
+ [
292
+ "google/veo-3.1-fast",
293
+ { references: [{ path: "ref.png", role: "reference" }] },
294
+ ],
295
+ ["bytedance/seedance-2.0", { prompt: "x".repeat(10_001) }],
296
+ ["bytedance/seedance-2.0", { referenceVideo: "video.mp4" }],
297
+ [
298
+ "bytedance/seedance-2.0",
299
+ {
300
+ references: [
301
+ { path: "ref.png", role: "reference", computerId: "attacker" },
302
+ ],
303
+ },
304
+ ],
305
+ ["bytedance/seedance-2.0", { references: [{ path: "ref.png" }] }],
306
+ [
307
+ "bytedance/seedance-2.0",
308
+ { references: [{ path: "ref.png", role: "video" }] },
309
+ ],
310
+ ["bytedance/seedance-2.5", { durationSeconds: 31 }],
311
+ ["bytedance/seedance-2.5", { resolution: "1080p" }],
312
+ ["bytedance/seedance-2.5", { aspectRatio: "9:21" }],
313
+ ["bytedance/seedance-2.6", {}],
314
+ // MiniMax H3 Max: 5-15s, only 480p/768p, no 9:21, no audio choice.
315
+ ["minimax/h3-max", { durationSeconds: 4 }],
316
+ ["minimax/h3-max", { durationSeconds: 16 }],
317
+ ["minimax/h3-max", { resolution: "1080p" }],
318
+ ["minimax/h3-max", { aspectRatio: "9:21" }],
319
+ ])("refuses unsupported %s selection %j", (model, overrides) => {
320
+ expect(() => select(model, overrides)).toThrow();
321
+ });
322
+ it("returns the owner's typed refusal for unsupported combinations", () => {
323
+ expect(() =>
324
+ validateMediaVideoSelection({
325
+ model: "google/veo-3.1",
326
+ prompt: "x",
327
+ durationSeconds: 5,
328
+ }),
329
+ ).toThrow(MediaSettingsError);
330
+ expect(() =>
331
+ validateMediaGenerationSettings({ ...base, resolution: "480p" }),
332
+ ).toThrow(MediaSettingsError);
333
+ expect(() => mediaUnits({ ...base, durationSeconds: 13 })).toThrow(
334
+ MediaSettingsError,
335
+ );
336
+ expect(() =>
337
+ mediaUnits({ ...base, model: "bytedance/seedance-2.6" }),
338
+ ).toThrow(MediaSettingsError);
339
+ expect(() =>
340
+ estimateVideoMilliunits({
341
+ ...base,
342
+ model: "google/veo-3.1-fast",
343
+ durationSeconds: 5,
344
+ }),
345
+ ).toThrow(MediaSettingsError);
346
+ expect(() =>
347
+ validateMediaGenerationSettings({
348
+ ...base,
349
+ model: "@cf/black-forest-labs/flux-1-schnell",
350
+ generateAudio: true,
351
+ }),
352
+ ).toThrow(MediaSettingsError);
353
+ });
354
+ it("encodes a Veo first image as plain base64 and refuses lost resolved references", () => {
355
+ const settings = hydrate(
356
+ select("google/veo-3.1", {
357
+ references: [{ path: "first.png", role: "first-frame" }],
358
+ }),
359
+ );
360
+ expect(gatewayInput(settings, [image(1)])).toMatchObject({
361
+ image_input: "AQ==",
362
+ generate_audio: true,
363
+ });
364
+ expect(() => gatewayInput(settings, [])).toThrow(MediaSettingsError);
365
+ expect(() => gatewayInput(hydrate(select()), [image(1)])).toThrow(
366
+ MediaSettingsError,
367
+ );
368
+ });
369
+ it("keeps the existing Workflow single-image input as first-frame mode", () => {
370
+ const settings = validateMediaGenerationSettings({
371
+ ...base,
372
+ width: 720,
373
+ height: 720,
374
+ references: [{ computerId: "pictures", path: "panel.png" }],
375
+ });
376
+ expect(settings.references?.[0]?.role).toBe("first-frame");
377
+ expect(gatewayInput(settings, [image(1)])).toMatchObject({
378
+ image: "data:image/png;base64,AQ==",
379
+ aspect_ratio: "1:1",
380
+ duration: 5,
381
+ });
382
+ });
383
+ it.each(mediaVideoModelIdSchema.options)(
384
+ "fetches %s as bounded MP4 without the image decoder",
385
+ async (model) => {
386
+ const bytes = new Uint8Array([
387
+ 0, 0, 0, 24, 102, 116, 121, 112, 105, 115, 111, 109, 0, 0, 2, 0,
388
+ ]);
389
+ // MiniMax answers with its documented task wrapper, not the Unified
390
+ // gateway's {state, result} shape every other video model normalizes to.
391
+ const run = vi.fn(() =>
392
+ Promise.resolve(
393
+ getMediaModel(model)?.video?.provider === "minimax"
394
+ ? {
395
+ task: {
396
+ id: "1",
397
+ model,
398
+ status: "succeeded",
399
+ created_at: 0,
400
+ updated_at: 0,
401
+ content: { url: "https://results.example/clip.mp4" },
402
+ },
403
+ }
404
+ : {
405
+ state: "Completed",
406
+ result: { video: "https://results.example/clip.mp4" },
407
+ },
408
+ ),
409
+ );
410
+ const fetchResult = vi.fn<typeof fetch>(() =>
411
+ Promise.resolve(new Response(bytes)),
412
+ );
413
+ await expect(
414
+ generate(
415
+ { run },
416
+ hydrate(select(model)),
417
+ [],
418
+ undefined,
419
+ undefined,
420
+ fetchResult,
421
+ ),
422
+ ).resolves.toEqual({ bytes, format: "mp4" });
423
+ expect(run).toHaveBeenCalledOnce();
424
+ expect(fetchResult).toHaveBeenCalledOnce();
425
+ },
426
+ );
427
+ it("refuses a pending gateway answer before fetching output", async () => {
428
+ const fetchResult = vi.fn<typeof fetch>();
429
+ await expect(
430
+ generate(
431
+ {
432
+ run: () =>
433
+ Promise.resolve({
434
+ state: "Running",
435
+ result: { video: "https://results.example/clip.mp4" },
436
+ }),
437
+ },
438
+ hydrate(select()),
439
+ [],
440
+ undefined,
441
+ undefined,
442
+ fetchResult,
443
+ ),
444
+ ).rejects.toMatchObject({ stage: "normalization" });
445
+ expect(fetchResult).not.toHaveBeenCalled();
446
+ });
447
+ it("refuses video output without an explicit completion state", async () => {
448
+ const fetchResult = vi.fn<typeof fetch>();
449
+ await expect(
450
+ generate(
451
+ {
452
+ run: () =>
453
+ Promise.resolve({
454
+ result: { video: "https://results.example/clip.mp4" },
455
+ }),
456
+ },
457
+ hydrate(select()),
458
+ [],
459
+ undefined,
460
+ undefined,
461
+ fetchResult,
462
+ ),
463
+ ).rejects.toMatchObject({ stage: "normalization" });
464
+ expect(fetchResult).not.toHaveBeenCalled();
465
+ });
466
+ it.each([
467
+ { ...base, model: "google/veo-3.1", durationSeconds: 5 },
468
+ { ...base, model: "@cf/black-forest-labs/flux-1-schnell", width: 5040 },
469
+ ])(
470
+ "refuses unsupported settings through the service before billing or provider dispatch: %j",
471
+ async (invalidSettings) => {
472
+ const fixture = mediaOperationFixture();
473
+ try {
474
+ const admit = vi.fn(() => Promise.resolve({ priceMilliunits: 60_000 }));
475
+ const provider = vi.fn(() =>
476
+ Promise.resolve({ bytes: new Uint8Array([1]), format: "mp4" }),
477
+ );
478
+ const beforeAdmit = vi.fn();
479
+ const host = {
480
+ scope: {
481
+ actorId: "reader",
482
+ namespace: "studio",
483
+ owner: "prints",
484
+ destinationId: "pictures",
485
+ },
486
+ operations: { getByName: () => fixture.owner },
487
+ provider,
488
+ beforeAdmit,
489
+ metering: { admit, settle: () => Promise.resolve() },
490
+ refusalMessages: {
491
+ insufficient_credits: "refill",
492
+ denied: "denied",
493
+ daily_limit_reached: "daily limit",
494
+ },
495
+ destination: {
496
+ authorize: () => Promise.resolve(),
497
+ remove: () => Promise.resolve("absent" as const),
498
+ write: () => Promise.resolve(),
499
+ },
500
+ } satisfies MediaServiceHost;
501
+ const service = createMediaService(host);
502
+ await expect(
503
+ generateMedia(host, {
504
+ requestId: "invalid-video-promise",
505
+ path: "prints-invalid-video.mp4",
506
+ settings: invalidSettings,
507
+ }),
508
+ ).rejects.toBeInstanceOf(MediaSettingsError);
509
+ const response = await service.request("/generate", {
510
+ method: "POST",
511
+ headers: {
512
+ "Content-Type": "application/json",
513
+ "X-Request-Id": "invalid-video",
514
+ },
515
+ body: JSON.stringify({
516
+ path: "prints-invalid-video.mp4",
517
+ settings: invalidSettings,
518
+ }),
519
+ });
520
+ expect(response.status).toBe(400);
521
+ expect(await response.json()).toMatchObject({
522
+ code: "INVALID_ARGUMENT",
523
+ retryable: false,
524
+ });
525
+ expect(admit).not.toHaveBeenCalled();
526
+ expect(provider).not.toHaveBeenCalled();
527
+ expect(beforeAdmit).not.toHaveBeenCalled();
528
+ } finally {
529
+ fixture.close();
530
+ }
531
+ },
532
+ );
533
+ });
@@ -0,0 +1,177 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
3
+ import type { MediaProvider } from "../src/index.js";
4
+ import { createMediaService } from "../src/server.js";
5
+ import { readMediaFailure } from "../src/browser-failure.js";
6
+ import { MediaOperationOwner } from "../src/media-operation-owner.js";
7
+ import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
8
+ import {
9
+ readMediaBindingReply,
10
+ mediaBindingCallSchema,
11
+ } from "../src/media-binding.js";
12
+ import { mediaRequestIds } from "@fungi.computer/agar/media-request-id";
13
+
14
+ // A real admitted video request, served entirely by offline ports below.
15
+ const settings = {
16
+ model: "bytedance/seedance-2.0-mini",
17
+ prompt: "fern fronds unfurling",
18
+ width: 854,
19
+ height: 480,
20
+ durationSeconds: 4,
21
+ };
22
+
23
+ describe("background video diagnostic contract", () => {
24
+ it.each(["dispatch", "download", "safety", "credits"])(
25
+ "retains a %s diagnostic through alarm, restart and HTTP replay without redispatch",
26
+ async (failureKind) => {
27
+ const marker = "synthetic-private-background-video-details";
28
+ const failure = new Error(
29
+ failureKind === "credits"
30
+ ? `2021: AiError: insufficient credits ${marker}`
31
+ : failureKind === "safety"
32
+ ? `3031: AiError: Input prompt contains NSFW content. ${marker}`
33
+ : `3031: ${marker}`,
34
+ );
35
+ failure.name =
36
+ failureKind === "credits" ? "Error" : "InferenceUpstreamError";
37
+ const diagnostic =
38
+ failureKind === "download"
39
+ ? { category: "result_download", status: 503 }
40
+ : failureKind === "credits"
41
+ ? { category: "Error", code: 2021, reason: "credits_exhausted" }
42
+ : failureKind === "safety"
43
+ ? {
44
+ category: "InferenceUpstreamError",
45
+ code: 3031,
46
+ reason: "content_refused",
47
+ }
48
+ : { category: "InferenceUpstreamError", code: 3031 };
49
+ let dispatches = 0;
50
+ let downloads = 0;
51
+ let writes = 0;
52
+ const ai: MediaAiPort = {
53
+ run: () => {
54
+ dispatches++;
55
+ return failureKind !== "download"
56
+ ? Promise.reject(failure)
57
+ : Promise.resolve({
58
+ state: "Completed",
59
+ result: { video: "https://results.example/clip.mp4" },
60
+ });
61
+ },
62
+ };
63
+ const fetchResult: typeof fetch = () => {
64
+ downloads++;
65
+ return Promise.resolve(new Response(marker, { status: 503 }));
66
+ };
67
+ const provider: MediaProvider = (selection, references, signal, format) =>
68
+ generate(
69
+ ai,
70
+ selection,
71
+ references,
72
+ signal,
73
+ undefined,
74
+ fetchResult,
75
+ format,
76
+ );
77
+ const test = mediaOperationFixture();
78
+ let owner = new MediaOperationOwner(
79
+ test.context,
80
+ { APP_ARTIFACTS: test.bucket },
81
+ () => provider,
82
+ );
83
+ try {
84
+ const service = createMediaService({
85
+ scope: {
86
+ actorId: "actor-video",
87
+ namespace: "team-video",
88
+ owner: "installation-video",
89
+ destinationId: "computer-video",
90
+ },
91
+ operations: { getByName: () => owner },
92
+ provider,
93
+ metering: "unmetered",
94
+ destination: {
95
+ authorize: () => Promise.resolve(),
96
+ remove: () => Promise.resolve("absent" as const),
97
+ write: () => {
98
+ writes++;
99
+ return Promise.resolve();
100
+ },
101
+ },
102
+ });
103
+ const request = {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ "X-Request-Id": `video-${failureKind}`,
108
+ },
109
+ body: JSON.stringify({ settings, path: "generated/fern.mp4" }),
110
+ };
111
+ expect((await service.request("/generate", request)).status).toBe(202);
112
+ await owner.alarm();
113
+ owner = new MediaOperationOwner(
114
+ test.context,
115
+ { APP_ARTIFACTS: test.bucket },
116
+ () => provider,
117
+ );
118
+ const response = await service.request("/generate", request);
119
+ const status = failureKind === "safety" ? 400 : 503;
120
+ expect(response.status).toBe(status);
121
+ const replay = await service.request("/generate", request);
122
+ expect(replay.status).toBe(status);
123
+ expect(await replay.text()).not.toContain(marker);
124
+ await owner.alarm();
125
+ expect(dispatches).toBe(1);
126
+ expect(downloads).toBe(failureKind === "download" ? 1 : 0);
127
+ expect(writes).toBe(0);
128
+ const body = await response.text();
129
+ expect(body).not.toContain(marker);
130
+ const browserFailure = await readMediaFailure(
131
+ new Response(body, { status: response.status }),
132
+ );
133
+ expect(browserFailure).toMatchObject({
134
+ stage: failureKind === "download" ? "normalization" : "provider",
135
+ });
136
+ expect(browserFailure?.provider).toEqual(diagnostic);
137
+ const broker = await readMediaBindingReply(
138
+ mediaBindingCallSchema.parse({
139
+ operation: "generate",
140
+ input: {
141
+ kind: "video",
142
+ requestId: mediaRequestIds.request.generate(),
143
+ libraryPath: "/prints",
144
+ settings: {
145
+ model: settings.model,
146
+ prompt: settings.prompt,
147
+ resolution: "480p",
148
+ durationSeconds: settings.durationSeconds,
149
+ },
150
+ },
151
+ }),
152
+ "computer-video",
153
+ new Response(body, { status }),
154
+ );
155
+ expect(broker).toMatchObject({
156
+ error:
157
+ failureKind === "safety"
158
+ ? "SAFETY_FILTER_REFUSED"
159
+ : failureKind === "download"
160
+ ? "HOST_FAILURE"
161
+ : "MEDIA_PROVIDER_FAILURE",
162
+ retryable: false,
163
+ });
164
+ expect(broker).toHaveProperty("provider", diagnostic);
165
+ expect(JSON.stringify(broker)).not.toContain(marker);
166
+ const stored = test.storage.sql
167
+ .exec(
168
+ "SELECT failure_json FROM hub_media_provider_failure WHERE singleton=1",
169
+ )
170
+ .toArray();
171
+ expect(JSON.stringify(stored)).not.toContain(marker);
172
+ } finally {
173
+ test.close();
174
+ }
175
+ },
176
+ );
177
+ });