File size: 30,430 Bytes
c7d34c1
 
 
 
e445b51
81587dd
3e8ea5d
e445b51
c7d34c1
 
704e84f
c7d34c1
704e84f
c7d34c1
704e84f
c7d34c1
704e84f
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704e84f
c7d34c1
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
81587dd
f9a28cd
 
 
81587dd
f9a28cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81587dd
 
 
 
 
 
96bdf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81587dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
f9a28cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
6c12d18
11486ce
 
 
 
 
 
 
 
 
 
6c12d18
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
81587dd
 
 
 
 
 
 
 
 
96bdf6c
81587dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
import {
    PNG_BASE64,
    imageFormRequest,
    readSseEvents,
    startHangingImagesStreamUpstream,
    startImagesAcceptedTaskStreamFallbackUpstream,
    startImagesJsonUpstream,
    startImagesStreamFallbackUpstream,
    startStreamingImageUpstream
} from './route-test-helpers';
import { registerRouteTestLifecycle } from './route-test-setup';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

registerRouteTestLifecycle();

describe('POST /api/images Images API streaming', { concurrency: false }, () => {
    it('normalizes OtokAPI image stream events into the stable client SSE contract', async () => {
        const { POST } = await import('./route');
        let upstreamBody = '';
        const upstream = await startStreamingImageUpstream(async (body) => {
            upstreamBody = body;
            return [
                {
                    event: 'image.generation.chunk',
                    data: { b64_json: 'partial-base64' }
                },
                {
                    event: 'image.generation.result',
                    data: {
                        data: [{ b64_json: PNG_BASE64 }],
                        usage: { input_tokens: 1, output_tokens: 2, total_tokens: 3 }
                    }
                }
            ];
        });

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    stream: true
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.equal(events.length, 3);
            assert.equal(events[0].type, 'partial_image');
            assert.equal(events[0].b64_json, 'partial-base64');
            assert.equal(events[1].type, 'completed');
            assert.equal(events[1].b64_json, PNG_BASE64);
            assert.equal(events[1].output_format, 'png');
            assert.equal(events[2].type, 'done');
            assert.equal((events[2].images as Array<Record<string, unknown>>)[0].b64_json, PNG_BASE64);

            const upstreamJson = JSON.parse(upstreamBody) as Record<string, unknown>;
            assert.equal(upstreamJson.stream, true);
            assert.equal(upstreamJson.partial_images, 2);
        } finally {
            await upstream.close();
        }
    });

    it('uses a non-streaming channel request mode when page auto streaming has no SSE channel', async () => {
        const { POST } = await import('./route');
        const upstreamBodies: string[] = [];
        let observedIdempotencyKey: string | string[] | undefined;
        const upstream = await startImagesJsonUpstream(async (body, _url, request) => {
            if (request.method === 'POST') {
                upstreamBodies.push(body);
                observedIdempotencyKey = request.headers['idempotency-key'];
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'json-only';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';

        try {
            const response = await POST(
                imageFormRequest({
                    streamMode: 'auto'
                })
            );

            assert.equal(response.status, 200);
            assert.notEqual(response.headers.get('content-type'), 'text/event-stream');
            assert.equal(upstreamBodies.length, 1);
            const upstreamJson = JSON.parse(upstreamBodies[0] || '{}') as Record<string, unknown>;
            assert.equal(upstreamJson.stream, false);
            assert.equal(Object.hasOwn(upstreamJson, 'partial_images'), false);
            assert.equal(observedIdempotencyKey, 'client-route-stream');
        } finally {
            await upstream.close();
        }
    });

    it('passes force_request through page generation and lets upstream decide small sizes', async () => {
        const { POST } = await import('./route');
        const upstreamBodies: string[] = [];
        const upstream = await startImagesJsonUpstream(async (body, _url, request) => {
            if (request.method === 'POST') {
                upstreamBodies.push(body);
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'json-force';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';

        try {
            const response = await POST(
                imageFormRequest({
                    streamMode: 'auto',
                    size: '512x512',
                    forceRequest: 'true',
                    clientRequestId: 'force-small-size'
                })
            );

            assert.equal(response.status, 200);
            assert.equal(upstreamBodies.length, 1);
            const upstreamJson = JSON.parse(upstreamBodies[0] || '{}') as Record<string, unknown>;
            assert.equal(upstreamJson.size, '512x512');
        } finally {
            await upstream.close();
        }
    });

    it('uses the lower-cost non-streaming channel request mode for page auto streaming by default', async () => {
        const { POST } = await import('./route');
        const upstreamBodies: string[] = [];
        const upstream = await startImagesJsonUpstream(async (body, _url, request) => {
            if (request.method === 'POST') {
                upstreamBodies.push(body);
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'mixed';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream,images-sse';

        try {
            const response = await POST(
                imageFormRequest({
                    streamMode: 'auto'
                })
            );

            assert.equal(response.status, 200);
            assert.notEqual(response.headers.get('content-type'), 'text/event-stream');
            assert.equal(upstreamBodies.length, 1);
            const upstreamJson = JSON.parse(upstreamBodies[0] || '{}') as Record<string, unknown>;
            assert.equal(upstreamJson.stream, false);
            assert.equal(Object.hasOwn(upstreamJson, 'partial_images'), false);
        } finally {
            await upstream.close();
        }
    });

    it('retries accepted async image tasks with the same upstream idempotency key', async () => {
        const { POST } = await import('./route');
        const observedIdempotencyKeys: Array<string | string[] | undefined> = [];
        let upstreamCalls = 0;
        const upstream = await startImagesJsonUpstream(async (_body, _url, request) => {
            if (request.method !== 'POST') {
                return { data: [{ b64_json: PNG_BASE64 }] };
            }
            upstreamCalls += 1;
            observedIdempotencyKeys.push(request.headers['idempotency-key']);
            if (upstreamCalls === 1) {
                return {
                    object: 'image.task',
                    status: 'pending',
                    task_id: 'sync-gen-task',
                    poll_url: '/api/image-tasks?ids=sync-gen-task'
                };
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'json-task';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';

        try {
            const response = await POST(
                imageFormRequest({
                    streamMode: 'auto',
                    clientRequestId: 'accepted-task-retry-key'
                })
            );

            assert.equal(response.status, 200);
            assert.notEqual(response.headers.get('content-type'), 'text/event-stream');
            assert.equal(upstreamCalls, 2);
            assert.deepEqual(observedIdempotencyKeys, ['accepted-task-retry-key', 'accepted-task-retry-key']);
        } finally {
            await upstream.close();
        }
    });

    it('retries accepted async edit tasks with the same upstream idempotency key', async () => {
        const { POST } = await import('./route');
        const observedIdempotencyKeys: Array<string | string[] | undefined> = [];
        let upstreamCalls = 0;
        const upstream = await startImagesJsonUpstream(async (_body, _url, request) => {
            if (request.method !== 'POST') {
                return { data: [{ b64_json: PNG_BASE64 }] };
            }
            upstreamCalls += 1;
            observedIdempotencyKeys.push(request.headers['idempotency-key']);
            if (upstreamCalls === 1) {
                return {
                    object: 'image.task',
                    status: 'pending',
                    task_id: 'sync-edit-task',
                    poll_url: '/api/image-tasks?ids=sync-edit-task'
                };
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'json-edit-task';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';

        try {
            const response = await POST(
                imageFormRequest({
                    mode: 'edit',
                    streamMode: 'auto',
                    clientRequestId: 'accepted-edit-task-retry-key'
                })
            );

            assert.equal(response.status, 200);
            assert.notEqual(response.headers.get('content-type'), 'text/event-stream');
            assert.equal(upstreamCalls, 2);
            assert.deepEqual(observedIdempotencyKeys, ['accepted-edit-task-retry-key', 'accepted-edit-task-retry-key']);
        } finally {
            await upstream.close();
        }
    });

    it('fails explicit page stream requests instead of falling back to non-streaming request modes', async () => {
        const { POST } = await import('./route');
        const upstreamBodies: string[] = [];
        const upstream = await startImagesJsonUpstream(async (body, _url, request) => {
            if (request.method === 'POST') {
                upstreamBodies.push(body);
            }
            return { data: [{ b64_json: PNG_BASE64 }] };
        });
        process.env.OPENAI_CHANNEL_1_ID = 'json-only';
        process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
        process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
        process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';

        try {
            const response = await POST(
                imageFormRequest({
                    streamMode: 'stream',
                    imageStreamingStrategy: 'openai-sse'
                })
            );

            assert.equal(response.status, 503);
            const body = (await response.json()) as { error?: string };
            assert.match(body.error || '', /images-sse/);
            assert.equal(upstreamBodies.length, 0);
        } finally {
            await upstream.close();
        }
    });

    it('keeps the stable SSE contract for SDK-parsed multi-image results without partial events', async () => {
        const { POST } = await import('./route');
        const upstream = await startStreamingImageUpstream(async () => [
            {
                data: {
                    data: [{ b64_json: PNG_BASE64 }, { b64_json: PNG_BASE64 }]
                }
            }
        ]);

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    stream: true
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.deepEqual(
                events.map((event) => event.type),
                ['completed', 'completed', 'done']
            );
            assert.equal((events[2].images as Array<Record<string, unknown>>).length, 2);
        } finally {
            await upstream.close();
        }
    });

    it('normalizes JSON Images responses returned to stream requests into the stable SSE contract', async () => {
        const { POST } = await import('./route');
        let upstreamBody = '';
        const upstream = await startImagesJsonUpstream(async (body) => {
            if (!body) return { ok: true };
            upstreamBody = body;
            return { data: [{ b64_json: PNG_BASE64 }] };
        });

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    stream: true,
                    imageStreamingStrategy: 'newapi-keepalive-sse'
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.deepEqual(
                events.map((event) => event.type),
                ['completed', 'done']
            );
            assert.equal(events[0].b64_json, PNG_BASE64);
            assert.equal((events[1].images as Array<Record<string, unknown>>)[0].b64_json, PNG_BASE64);

            const upstreamJson = JSON.parse(upstreamBody) as Record<string, unknown>;
            assert.equal(upstreamJson.stream, true);
            assert.equal(upstreamJson.partial_images, 2);
        } finally {
            await upstream.close();
        }
    });

    it('allows Matsca-compatible Images API streams to request four partial images', async () => {
        let upstreamBody = '';
        let upstreamAppId: string | string[] | undefined;
        let upstreamAppSecret: string | string[] | undefined;
        const upstream = await startStreamingImageUpstream(async (body, _url, request) => {
            upstreamBody = body;
            upstreamAppId = request.headers['x-app-id'];
            upstreamAppSecret = request.headers['x-app-secret'];
            return [
                {
                    event: 'image.generation.result',
                    data: {
                        data: [{ b64_json: PNG_BASE64 }]
                    }
                }
            ];
        });

        try {
            process.env.OPENAI_CHANNEL_1_ID = 'matsca';
            process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
            process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
            process.env.OPENAI_CHANNEL_1_UPSTREAM_PROFILE = 'matsca';
            process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream,images-sse';
            process.env.OPENAI_CHANNEL_1_MATSCA_APP_ID = 'app-id';
            process.env.OPENAI_CHANNEL_1_MATSCA_APP_SECRET = 'app-secret';
            process.env.OPENAI_CHANNEL_RECOVERY_PROBE_ENABLED = 'false';
            process.env.OPENAI_CHANNEL_REQUIRE_PROBE_FOR_RECOVERY = 'false';
            const { resetServerChannelStateForTests } = await import('@/lib/server-channel-router');
            resetServerChannelStateForTests();
            const { POST } = await import('./route');

            const response = await POST(
                imageFormRequest({
                    stream: true,
                    partialImages: '4'
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            await readSseEvents(response);

            const upstreamJson = JSON.parse(upstreamBody) as Record<string, unknown>;
            assert.equal(upstreamJson.partial_images, 4);
            assert.equal(upstreamAppId, 'app-id');
            assert.equal(upstreamAppSecret, 'app-secret');
        } finally {
            await upstream.close();
        }
    });

    it('keeps same-credential page SSE requests queued until the active stream is released', async () => {
        const upstream = await startHangingImagesStreamUpstream();

        try {
            process.env.OPENAI_CHANNEL_1_ID = 'official';
            process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
            process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
            process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream,images-sse';
            process.env.OPENAI_CHANNEL_RECOVERY_PROBE_ENABLED = 'false';
            process.env.OPENAI_CHANNEL_REQUIRE_PROBE_FOR_RECOVERY = 'false';
            process.env.OPENAI_MAX_STREAMS_PER_CREDENTIAL = '1';
            process.env.OPENAI_CHANNEL_QUEUE_MAX_WAIT_MS = '1000';
            const { resetServerChannelStateForTests } = await import('@/lib/server-channel-router');
            resetServerChannelStateForTests();
            const { POST } = await import('./route');

            const firstResponse = await POST(
                imageFormRequest({
                    stream: true,
                    clientRequestId: 'client-route-queue-1'
                })
            );
            await upstream.waitForStreamRequest();
            assert.equal(upstream.calls.length, 1);

            const secondPromise = POST(
                imageFormRequest({
                    stream: true,
                    clientRequestId: 'client-route-queue-2'
                })
            );
            await new Promise((resolve) => setTimeout(resolve, 50));
            assert.equal(upstream.calls.length, 1);

            await firstResponse.body?.cancel();
            const secondResponse = await secondPromise;
            assert.equal(secondResponse.status, 200);
            assert.equal(secondResponse.headers.get('X-Channel-Queue-Queued'), 'true');
            assert.equal(upstream.calls.length, 2);
            await secondResponse.body?.cancel();
        } finally {
            await upstream.close();
        }
    });

    it('allows Matsca-compatible JSON generation fields through server channels', async () => {
        let upstreamBody = '';
        let upstreamAppId: string | string[] | undefined;
        let upstreamAppSecret: string | string[] | undefined;
        const upstream = await startImagesJsonUpstream(async (body, _url, request) => {
            if (request.method === 'POST' && request.url?.endsWith('/images/generations')) {
                upstreamBody = body;
                upstreamAppId = request.headers['x-app-id'];
                upstreamAppSecret = request.headers['x-app-secret'];
            }
            return {
                data: [{ b64_json: PNG_BASE64 }]
            };
        });

        try {
            process.env.OPENAI_CHANNEL_1_ID = 'matsca';
            process.env.OPENAI_CHANNEL_1_API_KEYS = 'test-key';
            process.env.OPENAI_CHANNEL_1_BASE_URL = upstream.baseUrl;
            process.env.OPENAI_CHANNEL_1_UPSTREAM_PROFILE = 'matsca';
            process.env.OPENAI_CHANNEL_1_REQUEST_MODES = 'images-non-stream';
            process.env.OPENAI_CHANNEL_1_MATSCA_APP_ID = 'app-id';
            process.env.OPENAI_CHANNEL_1_MATSCA_APP_SECRET = 'app-secret';
            process.env.OPENAI_CHANNEL_RECOVERY_PROBE_ENABLED = 'false';
            process.env.OPENAI_CHANNEL_REQUIRE_PROBE_FOR_RECOVERY = 'false';
            const { resetServerChannelStateForTests } = await import('@/lib/server-channel-router');
            resetServerChannelStateForTests();
            const { POST } = await import('./route');

            const response = await POST(
                imageFormRequest({
                    streamMode: 'non_stream',
                    n: '4',
                    size: '123x456',
                    background: 'transparent'
                })
            );

            assert.equal(response.status, 200);
            const upstreamJson = JSON.parse(upstreamBody) as Record<string, unknown>;
            assert.equal(upstreamJson.n, 4);
            assert.equal(upstreamJson.size, '123x456');
            assert.equal(upstreamJson.background, 'transparent');
            assert.equal(upstreamAppId, 'app-id');
            assert.equal(upstreamAppSecret, 'app-secret');
        } finally {
            await upstream.close();
        }
    });

    it('returns upstream diagnostics when JSON Images responses omit image data', async () => {
        const { POST } = await import('./route');
        const upstream = await startImagesJsonUpstream(async () => ({ data: [{ status: 'done' }] }));

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'non_stream'
                })
            );

            assert.equal(response.status, 502);
            const body = (await response.json()) as {
                error?: string;
                diagnostics?: { category?: string; structure?: unknown };
            };
            assert.match(body.error || '', /不是 OpenAI Images 格式/);
            assert.equal(body.diagnostics?.category, 'unknown_response_format');
            assert.equal(JSON.stringify(body.diagnostics).includes('test-key'), false);
        } finally {
            await upstream.close();
        }
    });

    it('falls back from force-sse auto streaming without a final image and skips streaming for the same mark', async () => {
        const { POST } = await import('./route');
        const { getServerChannelState } = await import('@/lib/server-channel-router');
        const upstream = await startImagesStreamFallbackUpstream();
        const otherUpstream = await startImagesStreamFallbackUpstream();

        try {
            const first = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'auto',
                    imageStreamingStrategy: 'force-sse',
                    clientRequestId: 'client-route-auto-fallback-1'
                })
            );

            assert.equal(first.status, 200);
            assert.equal(first.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(first);
            assert.deepEqual(
                events.map((event) => event.type),
                ['partial_image', 'completed', 'done']
            );
            assert.equal(events[2].fallback_used, true);
            assert.deepEqual(
                upstream.calls.map((call) => call.stream),
                [true, false]
            );
            assert.equal(getServerChannelState().streamingAvailability.summary().mark_count, 1);

            const second = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'auto',
                    imageStreamingStrategy: 'force-sse',
                    clientRequestId: 'client-route-auto-fallback-2'
                })
            );

            assert.equal(second.status, 200);
            assert.notEqual(second.headers.get('content-type'), 'text/event-stream');
            const body = (await second.json()) as { images?: Array<Record<string, unknown>> };
            assert.equal(body.images?.[0]?.b64_json, PNG_BASE64);
            assert.deepEqual(
                upstream.calls.map((call) => call.stream),
                [true, false, false]
            );

            const third = await POST(
                imageFormRequest({
                    apiBaseUrl: otherUpstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'auto',
                    imageStreamingStrategy: 'force-sse',
                    clientRequestId: 'client-route-auto-fallback-3'
                })
            );

            assert.equal(third.status, 200);
            assert.equal(third.headers.get('content-type'), 'text/event-stream');
            await readSseEvents(third);
            assert.deepEqual(
                otherUpstream.calls.map((call) => call.stream),
                [true, false]
            );
        } finally {
            await upstream.close();
            await otherUpstream.close();
        }
    });

    it('retries accepted async image tasks after force-sse auto stream fallback with the same idempotency key', async () => {
        const { POST } = await import('./route');
        const upstream = await startImagesAcceptedTaskStreamFallbackUpstream();

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'auto',
                    imageStreamingStrategy: 'force-sse',
                    clientRequestId: 'client-route-auto-fallback-task'
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.deepEqual(
                events.map((event) => event.type),
                ['partial_image', 'completed', 'done']
            );
            assert.equal(events[2].fallback_used, true);
            assert.deepEqual(
                upstream.calls.map((call) => call.stream),
                [true, false, false]
            );
            assert.deepEqual(
                upstream.calls.map((call) => call.idempotencyKey),
                [
                    'client-route-auto-fallback-task',
                    'client-route-auto-fallback-task',
                    'client-route-auto-fallback-task'
                ]
            );
        } finally {
            await upstream.close();
        }
    });

    it('does not mark force-sse auto streaming unavailable when the page SSE request is aborted', async () => {
        const { POST } = await import('./route');
        const { getServerChannelState } = await import('@/lib/server-channel-router');
        const upstream = await startHangingImagesStreamUpstream();
        const abortController = new AbortController();

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    streamMode: 'auto',
                    imageStreamingStrategy: 'force-sse',
                    clientRequestId: 'client-route-auto-abort',
                    signal: abortController.signal
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const reader = response.body?.getReader();
            assert.ok(reader);
            await upstream.waitForStreamRequest();
            abortController.abort();
            await reader.cancel();
            await new Promise((resolve) => setTimeout(resolve, 25));

            assert.deepEqual(
                upstream.calls.map((call) => call.stream),
                [true]
            );
            assert.equal(getServerChannelState().streamingAvailability.summary().mark_count, 0);
        } finally {
            abortController.abort();
            await upstream.close();
        }
    });

    it('returns an explicit SSE error when the upstream completed event has no image payload', async () => {
        const { POST } = await import('./route');
        const upstream = await startStreamingImageUpstream(async () => [
            {
                event: 'image.generation.result',
                data: {
                    data: [{ status: 'done' }]
                }
            }
        ]);

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    stream: true
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.equal(events.length, 1);
            assert.equal(events[0].type, 'error');
            assert.match(String(events[0].error), /b64_json/);
        } finally {
            await upstream.close();
        }
    });

    it('turns upstream stream failures into the stable SSE error contract', async () => {
        const { POST } = await import('./route');
        const upstream = await startStreamingImageUpstream(async () => [
            {
                event: 'image.generation.chunk',
                data: { b64_json: 'partial-before-failure' }
            },
            { abortAfter: true, data: { status: 'upstream connection closed' } }
        ]);

        try {
            const response = await POST(
                imageFormRequest({
                    apiBaseUrl: upstream.baseUrl,
                    apiKey: 'test-key',
                    stream: true
                })
            );

            assert.equal(response.status, 200);
            assert.equal(response.headers.get('content-type'), 'text/event-stream');
            const events = await readSseEvents(response);
            assert.deepEqual(
                events.map((event) => event.type),
                ['partial_image', 'error']
            );
            assert.match(String(events[1].error), /terminated|aborted|closed|stream/i);
        } finally {
            await upstream.close();
        }
    });
});